Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/bevy tiles 2d #3

Merged
merged 4 commits into from
Apr 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,4 @@ undocumented_unsafe_blocks = "deny"
all = "deny"

[workspace.lints.rust]
unused_imports = "warn"
unused_imports = "warn"
2 changes: 1 addition & 1 deletion crates/bevy_tiles/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "bevy_tiles"
version.workspace = true
version = "0.1.0"
edition.workspace = true
authors.workspace = true
license-file.workspace = true
Expand Down
23 changes: 11 additions & 12 deletions crates/bevy_tiles/examples/basic_2d.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use bevy::{prelude::*, sprite::SpriteBundle, DefaultPlugins};
use bevy_tiles::prelude::*;
use bevy_tiles::{commands::TileCommandExt, coords::CoordIterator, tiles_2d::*, TilesPlugin};

fn main() {
App::new()
Expand All @@ -25,7 +25,7 @@ fn spawn(mut commands: Commands, asset_server: Res<AssetServer>) {
let character = asset_server.load("character.png");

commands.spawn(Camera2dBundle::default());
let mut map = commands.spawn_map::<2>(16, GameLayer);
let mut map = commands.spawn_map(16, GameLayer);

let sprite_bundle = SpriteBundle {
texture: block,
Expand All @@ -43,7 +43,7 @@ fn spawn(mut commands: Commands, asset_server: Res<AssetServer>) {

// spawn a player
map.spawn_tile(
[0, 0],
IVec2::ZERO,
(
Character,
SpriteBundle {
Expand All @@ -64,23 +64,22 @@ fn move_character(
let map_id = map.single();
let walls = walls_maps.get_map(map_id).unwrap();

let x = keyboard_input.just_pressed(KeyCode::KeyD) as isize
- keyboard_input.just_pressed(KeyCode::KeyA) as isize;
let x = keyboard_input.just_pressed(KeyCode::KeyD) as i32
- keyboard_input.just_pressed(KeyCode::KeyA) as i32;

let y = keyboard_input.just_pressed(KeyCode::KeyW) as isize
- keyboard_input.just_pressed(KeyCode::KeyS) as isize;
let y = keyboard_input.just_pressed(KeyCode::KeyW) as i32
- keyboard_input.just_pressed(KeyCode::KeyS) as i32;

let char_c = character.get_single().unwrap();
let new_coord = [char_c[0] + x, char_c[1] + y];
let char_c = IVec2::from(*character.get_single().unwrap());
let new_coord = char_c + IVec2::new(x, y);

if (x != 0 || y != 0) && walls.get_at(new_coord).is_none() {
commands.move_tile(map_id, **char_c, new_coord);
commands.move_tile(map_id, char_c, new_coord);
}
}

fn sync_tile_transforms(mut tiles: Query<(&TileCoord, &mut Transform), Changed<TileCoord>>) {
for (tile_c, mut transform) in tiles.iter_mut() {
transform.translation.x = tile_c[0] as f32 * 16.0;
transform.translation.y = tile_c[1] as f32 * 16.0;
transform.translation = Vec3::from((Vec2::from(*tile_c) * Vec2::ONE * 16.0, 0.0));
}
}
24 changes: 12 additions & 12 deletions crates/bevy_tiles/examples/basic_3d.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::f32::consts::PI;

use bevy::{pbr::CascadeShadowConfigBuilder, prelude::*, DefaultPlugins};
use bevy_tiles::prelude::*;
use bevy_tiles::{commands::TileCommandExt, coords::CoordIterator, tiles_3d::*, TilesPlugin};

fn main() {
App::new()
Expand Down Expand Up @@ -56,7 +56,7 @@ fn spawn(
..Default::default()
};

let mut tile_commands = commands.spawn_map::<3>(16, GameLayer);
let mut tile_commands = commands.spawn_map(16, GameLayer);

// spawn a 10 * 10 room
tile_commands.spawn_tile_batch(
Expand All @@ -69,7 +69,7 @@ fn spawn(

// spawn a player
tile_commands.spawn_tile(
[0, 0, 0],
IVec3::ZERO,
(
Character,
PbrBundle {
Expand Down Expand Up @@ -108,20 +108,20 @@ fn move_character(
keyboard_input: Res<ButtonInput<KeyCode>>,
mut commands: Commands,
map: Query<Entity, With<GameLayer>>,
character: Query<&TileCoord<3>, With<Character>>,
walls_maps: TileMapQuery<(), With<Block>, 3>,
character: Query<&TileCoord, With<Character>>,
walls_maps: TileMapQuery<(), With<Block>>,
) {
let map_id = map.single();
let walls = walls_maps.get_map(map_id).unwrap();

let x = keyboard_input.just_pressed(KeyCode::KeyD) as isize
- keyboard_input.just_pressed(KeyCode::KeyA) as isize;
let x = keyboard_input.just_pressed(KeyCode::KeyD) as i32
- keyboard_input.just_pressed(KeyCode::KeyA) as i32;

let y = keyboard_input.just_pressed(KeyCode::ShiftLeft) as isize
- keyboard_input.just_pressed(KeyCode::ControlLeft) as isize;
let y = keyboard_input.just_pressed(KeyCode::ShiftLeft) as i32
- keyboard_input.just_pressed(KeyCode::ControlLeft) as i32;

let z = keyboard_input.just_pressed(KeyCode::KeyS) as isize
- keyboard_input.just_pressed(KeyCode::KeyW) as isize;
let z = keyboard_input.just_pressed(KeyCode::KeyS) as i32
- keyboard_input.just_pressed(KeyCode::KeyW) as i32;

let char_c = character.get_single().unwrap();
let new_coord = [char_c[0] + x, char_c[1] + y, char_c[2] + z];
Expand All @@ -131,7 +131,7 @@ fn move_character(
}
}

fn sync_tile_transforms(mut tiles: Query<(&TileCoord<3>, &mut Transform), Changed<TileCoord<3>>>) {
fn sync_tile_transforms(mut tiles: Query<(&TileCoord, &mut Transform), Changed<TileCoord>>) {
for (tile_c, mut transform) in tiles.iter_mut() {
transform.translation.x = tile_c[0] as f32;
transform.translation.y = tile_c[1] as f32;
Expand Down
8 changes: 4 additions & 4 deletions crates/bevy_tiles/examples/logo.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use bevy::{prelude::*, sprite::SpriteBundle, DefaultPlugins};
use bevy_tiles::prelude::*;
use bevy_tiles::{commands::TileCommandExt, tiles_2d::*, TilesPlugin};

fn main() {
App::new()
Expand All @@ -22,7 +22,7 @@ fn spawn(mut commands: Commands, asset_server: Res<AssetServer>) {
transform: Transform::from_translation(Vec3::new(480.0, 32.0, 0.0)),
..Default::default()
});
let mut map = commands.spawn_map::<2>(16, GameLayer);
let mut map = commands.spawn_map(16, GameLayer);

let sprite_bundle = SpriteBundle {
texture: block,
Expand All @@ -39,15 +39,15 @@ eeeee eeee e e e e eeee8 eeeee e eeee eeeee
let logo = logo.split('\n').enumerate().flat_map(|(y, line)| {
line.bytes().enumerate().filter_map(move |(x, byte)| {
if byte == 56 || byte == 101 {
Some([x as isize, 6 - y as isize])
Some([x as i32, 6 - y as i32])
} else {
None
}
})
});

// spawn a 10 * 10 room
map.spawn_tile_batch(logo.collect::<Vec<[isize; 2]>>(), move |_| {
map.spawn_tile_batch(logo.collect::<Vec<[i32; 2]>>(), move |_| {
(Block, sprite_bundle.clone())
});
}
Expand Down
14 changes: 10 additions & 4 deletions crates/bevy_tiles/examples/spatial.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,13 @@ use bevy::{
window::PrimaryWindow,
DefaultPlugins,
};
use bevy_tiles::prelude::*;
use bevy_tiles::{
commands::TileCommandExt,
coords::{calculate_chunk_coordinate, world_to_tile, CoordIterator},
maps::TileMap,
tiles_2d::*,
TilesPlugin,
};
use std::ops::{Deref, DerefMut};

fn main() {
Expand Down Expand Up @@ -54,7 +60,7 @@ fn spawn(mut commands: Commands, asset_server: Res<AssetServer>) {
},
..Default::default()
});
let mut tile_commands = commands.spawn_map::<2>(32, GameLayer);
let mut tile_commands = commands.spawn_map(32, GameLayer);

let sprite_bundle = SpriteBundle {
texture: block,
Expand Down Expand Up @@ -86,7 +92,7 @@ fn add_damage(
.cursor_position()
.and_then(|cursor| cam.viewport_to_world(cam_t, cursor.xy()))
.map(|ray| ray.origin.truncate())
.map(|pos| world_to_tile(pos.into(), 16.0));
.map(|pos| world_to_tile(pos, 16.0));

if let Some(damage_pos) = buttons
.just_pressed(MouseButton::Left)
Expand All @@ -109,7 +115,7 @@ fn add_damage(
.flatten()
{
let chunk_c = calculate_chunk_coordinate(damage_pos, map.get_chunk_size());
commands.tile_map::<2>(map_id).despawn_chunk(chunk_c);
commands.tile_map(map_id).despawn_chunk(chunk_c);
}
}

Expand Down
33 changes: 25 additions & 8 deletions crates/bevy_tiles/src/chunks.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use bevy::{
ecs::{component::Component, entity::Entity},
math::{IVec2, IVec3},
prelude::Deref,
};

Expand All @@ -8,19 +9,35 @@ mod chunk_query;
pub use chunk_query::*;

/// An relation on chunks that point towards the map they are a part of.
#[derive(Component, Deref, Debug)]
/// # Note:
/// It probably won't break anything to manually copy this
/// to put it on your own entities, but this is only accurate
/// when mutated by the plugin.
#[derive(Component, Clone, Copy, Deref, Debug)]
pub struct InMap(pub(crate) Entity);

/// The coordinate of a given chunk.
/// # Note
#[derive(Component, Clone, Copy, Deref, Debug, PartialEq, Eq, Hash)]
pub struct ChunkCoord<const N: usize = 2>(pub(crate) [isize; N]);
/// # Note:
/// It probably won't break anything to manually copy this
/// to put it on your own entities, but this is only accurate
/// when mutated by the plugin.
#[derive(Component, Deref, Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ChunkCoord<const N: usize>(pub(crate) [i32; N]);

impl From<IVec2> for ChunkCoord<2> {
fn from(value: IVec2) -> Self {
Self(value.into())
}
}

impl From<IVec3> for ChunkCoord<3> {
fn from(value: IVec3) -> Self {
Self(value.into())
}
}

/// Holds handles to all the tiles in a chunk.
/// # Note
/// Manually updating this value, adding it, or removing it from an entity may
/// cause issues, please only mutate chunk information via commands.
#[derive(Component, Deref, Debug)]
#[derive(Component, Debug)]
pub struct Chunk(pub(crate) Vec<Option<Entity>>);

impl Chunk {
Expand Down
32 changes: 21 additions & 11 deletions crates/bevy_tiles/src/chunks/chunk_query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ use bevy::{
};

use crate::{
chunks::ChunkCoord,
chunks::{Chunk, ChunkCoord, InMap},
coords::CoordIterator,
maps::TileMap,
prelude::{Chunk, CoordIterator, InMap},
};

/// Used to query chunks from any tile map.
Expand Down Expand Up @@ -81,8 +81,9 @@ where
#[inline]
pub fn get_at(
&self,
chunk_c: [isize; N],
chunk_c: impl Into<[i32; N]>,
) -> Option<<<Q as QueryData>::ReadOnly as WorldQuery>::Item<'_>> {
let chunk_c = chunk_c.into();
let chunk_id = self.map.get_from_chunk(ChunkCoord(chunk_c))?;

self.chunk_q.get(chunk_id).ok()
Expand All @@ -96,8 +97,9 @@ where
#[inline]
pub unsafe fn get_at_unchecked(
&self,
chunk_c: [isize; N],
chunk_c: impl Into<[i32; N]>,
) -> Option<<Q as WorldQuery>::Item<'_>> {
let chunk_c = chunk_c.into();
let chunk_id = self.map.get_from_chunk(ChunkCoord(chunk_c))?;

self.chunk_q.get_unchecked(chunk_id).ok()
Expand All @@ -110,9 +112,11 @@ where
#[inline]
pub fn iter_in(
&self,
corner_1: [isize; N],
corner_2: [isize; N],
corner_1: impl Into<[i32; N]>,
corner_2: impl Into<[i32; N]>,
) -> ChunkQueryIter<'_, 'a, C, N> {
let corner_1 = corner_1.into();
let corner_2 = corner_2.into();
ChunkQueryIter::new(self, corner_1, corner_2)
}
}
Expand All @@ -127,7 +131,11 @@ where
/// # Note
/// Coordinates are for these calls are in chunk coordinates.
#[inline]
pub fn get_at_mut(&mut self, chunk_c: [isize; N]) -> Option<<Q as WorldQuery>::Item<'_>> {
pub fn get_at_mut(
&mut self,
chunk_c: impl Into<[i32; N]>,
) -> Option<<Q as WorldQuery>::Item<'_>> {
let chunk_c = chunk_c.into();
let chunk_id = self.map.get_from_chunk(ChunkCoord(chunk_c))?;

self.chunk_q.get_mut(chunk_id).ok()
Expand All @@ -140,9 +148,11 @@ where
#[inline]
pub fn iter_in_mut(
&mut self,
corner_1: [isize; N],
corner_2: [isize; N],
corner_1: impl Into<[i32; N]>,
corner_2: impl Into<[i32; N]>,
) -> ChunkQueryIterMut<'_, 'a, C, N> {
let corner_1 = corner_1.into();
let corner_2 = corner_2.into();
ChunkQueryIterMut::new(self, corner_1, corner_2)
}
}
Expand All @@ -154,7 +164,7 @@ pub struct ChunkQueryIter<'i, 'a, C, const N: usize> {
}

impl<'i, 'a, C, const N: usize> ChunkQueryIter<'i, 'a, C, N> {
fn new(chunk_q: &'i ChunkQuery<'a, C, N>, corner_1: [isize; N], corner_2: [isize; N]) -> Self {
fn new(chunk_q: &'i ChunkQuery<'a, C, N>, corner_1: [i32; N], corner_2: [i32; N]) -> Self {
Self {
chunk_q,
coord_iter: CoordIterator::new(corner_1, corner_2),
Expand Down Expand Up @@ -191,7 +201,7 @@ pub struct ChunkQueryIterMut<'i, 'a, C, const N: usize> {
}

impl<'i, 'a, C, const N: usize> ChunkQueryIterMut<'i, 'a, C, N> {
fn new(chunk_q: &'i ChunkQuery<'a, C, N>, corner_1: [isize; N], corner_2: [isize; N]) -> Self {
fn new(chunk_q: &'i ChunkQuery<'a, C, N>, corner_1: [i32; N], corner_2: [i32; N]) -> Self {
Self {
chunk_q,
coord_iter: CoordIterator::new(corner_1, corner_2),
Expand Down
Loading
Loading