use bevy::prelude::*;
use crate::chunk::Chunk;
use crate::voxel::VoxelType;
use super::{ChunkManager, ChunkModified};
#[derive(Resource, Debug, Clone)]
pub struct PlacementConfig {
pub cooldown: f32,
}
impl Default for PlacementConfig {
fn default() -> Self {
Self { cooldown: 0.25 }
}
}
#[derive(Resource, Default, Debug)]
pub struct PlacementState {
pub cooldown_elapsed: f32,
}
impl PlacementState {
pub fn can_place(&self, config: &PlacementConfig) -> bool {
self.cooldown_elapsed >= config.cooldown
}
}
#[derive(Message, Debug, Clone)]
pub struct VoxelPlaced {
pub chunk_coord: IVec3,
pub local: (usize, usize, usize),
pub world_pos: Vec3,
pub face_normal: IVec3,
}
fn notify_border_neighbors(
chunk_coord: IVec3,
local: (usize, usize, usize),
modified: &mut MessageWriter<ChunkModified>,
) {
use crate::chunk::CHUNK_SIZE;
let (x, y, z) = local;
let offsets: [(usize, IVec3); 6] = [
(x, IVec3::NEG_X),
(CHUNK_SIZE - 1 - x, IVec3::X),
(y, IVec3::NEG_Y),
(CHUNK_SIZE - 1 - y, IVec3::Y),
(z, IVec3::NEG_Z),
(CHUNK_SIZE - 1 - z, IVec3::Z),
];
for (dist, dir) in offsets {
if dist == 0 {
modified.write(ChunkModified(chunk_coord + dir));
}
}
}
fn voxel_world_pos(chunk_coord: IVec3, local: (usize, usize, usize)) -> Vec3 {
let chunk_origin = chunk_coord.as_vec3() * crate::chunk::CHUNK_SIZE as f32;
chunk_origin
+ Vec3::new(
local.0 as f32 + 0.5,
local.1 as f32 + 0.5,
local.2 as f32 + 0.5,
)
}
#[allow(clippy::too_many_arguments)]
pub fn try_place_voxel<V: VoxelType>(
target_chunk: IVec3,
target_local: (usize, usize, usize),
voxel: V,
face_normal: IVec3,
state: &mut PlacementState,
config: &PlacementConfig,
manager: &ChunkManager,
chunks: &mut Query<&mut Chunk<V>>,
placed: &mut MessageWriter<VoxelPlaced>,
modified: &mut MessageWriter<ChunkModified>,
) -> bool {
if !state.can_place(config) {
return false;
}
let Some(entity) = manager.get_entity(target_chunk) else {
return false;
};
let Ok(mut chunk) = chunks.get_mut(entity) else {
return false;
};
let (x, y, z) = target_local;
if chunk.get(x, y, z).is_solid() {
return false;
}
chunk.set(x, y, z, voxel);
chunk.set_state(x, y, z, crate::chunk::face_to_state(face_normal));
state.cooldown_elapsed = 0.0;
let world_pos = voxel_world_pos(target_chunk, target_local);
placed.write(VoxelPlaced {
chunk_coord: target_chunk,
local: target_local,
world_pos,
face_normal,
});
modified.write(ChunkModified(target_chunk));
notify_border_neighbors(target_chunk, target_local, modified);
true
}
pub fn tick_placement(delta_secs: f32, state: &mut PlacementState, config: &PlacementConfig) {
state.cooldown_elapsed = (state.cooldown_elapsed + delta_secs).min(config.cooldown);
}
pub struct PlacementPlugin;
impl Plugin for PlacementPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<PlacementConfig>();
app.init_resource::<PlacementState>();
app.add_message::<VoxelPlaced>();
}
}
#[cfg(feature = "items")]
pub struct PlacementInputPlugin<V: VoxelType> {
_m: std::marker::PhantomData<V>,
}
#[cfg(feature = "items")]
impl<V: VoxelType> PlacementInputPlugin<V> {
pub fn new() -> Self {
Self {
_m: std::marker::PhantomData,
}
}
}
#[cfg(feature = "items")]
impl<V: VoxelType> Default for PlacementInputPlugin<V> {
fn default() -> Self {
Self::new()
}
}
#[cfg(feature = "items")]
impl<V: VoxelType> Plugin for PlacementInputPlugin<V> {
fn build(&self, app: &mut App) {
app.add_systems(Update, placement_input_system::<V>);
}
}
#[cfg(feature = "items")]
pub fn placement_input_system<V: VoxelType>(
buttons: Res<ButtonInput<MouseButton>>,
camera_q: Query<&GlobalTransform, With<Camera3d>>,
manager: Res<ChunkManager>,
mut chunks: Query<&mut crate::chunk::Chunk<V>>,
mut state: ResMut<PlacementState>,
config: Res<PlacementConfig>,
hotbar: Res<crate::items::hotbar::HotbarState>,
mut placed: MessageWriter<VoxelPlaced>,
mut modified: MessageWriter<ChunkModified>,
time: Res<Time>,
) {
tick_placement(time.delta_secs(), &mut state, &config);
if !buttons.just_pressed(MouseButton::Right) {
return;
}
let Ok(cam_tf) = camera_q.single() else {
return;
};
let origin = cam_tf.translation();
let direction = cam_tf.forward().as_vec3();
let mut lens = chunks.transmute_lens::<&crate::chunk::Chunk<V>>();
let Some(hit) = super::raycast::raycast(origin, direction, 6.0, &manager, &lens.query()) else {
return;
};
let place_world = hit.position + hit.face_normal;
let place_chunk = crate::chunk::world_to_chunk_coord(place_world);
let place_local = crate::chunk::world_to_local_coord(place_world);
let voxel = V::from_byte(hotbar.selected as u8 + 1);
let face_normal = hit.face_normal.as_ivec3();
try_place_voxel(
place_chunk,
place_local,
voxel,
face_normal,
&mut state,
&config,
&manager,
&mut chunks,
&mut placed,
&mut modified,
);
}
#[cfg(test)]
mod tests {
use super::*;
fn default_config() -> PlacementConfig {
PlacementConfig { cooldown: 0.25 }
}
#[test]
fn test_can_place_when_cooldown_expired() {
let config = default_config();
let state = PlacementState {
cooldown_elapsed: 0.25,
};
assert!(state.can_place(&config));
}
#[test]
fn test_cannot_place_when_on_cooldown() {
let config = default_config();
let state = PlacementState {
cooldown_elapsed: 0.10,
};
assert!(!state.can_place(&config));
}
#[test]
fn test_tick_advances_cooldown() {
let config = default_config();
let mut state = PlacementState {
cooldown_elapsed: 0.0,
};
tick_placement(0.10, &mut state, &config);
assert!((state.cooldown_elapsed - 0.10).abs() < f32::EPSILON);
}
#[test]
fn test_tick_clamps_to_cooldown_max() {
let config = default_config();
let mut state = PlacementState {
cooldown_elapsed: 0.20,
};
tick_placement(0.20, &mut state, &config);
assert_eq!(state.cooldown_elapsed, config.cooldown);
}
}