use bevy::ecs::message::MessageWriter;
use bevy::input::mouse::MouseMotion;
use bevy::prelude::*;
use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
use crate::audio::{SfxEvent, SfxRequest};
use crate::chunk::{CHUNK_SIZE, Chunk, VOXEL_SIZE};
use crate::voxel::VoxelType;
use crate::world::{ChunkManager, ViewerPosition, WorldDataDir, get_voxel_at};
pub mod effects;
pub mod persistence;
#[derive(Message, Debug, Clone)]
pub struct PlayerDamaged {
pub amount: f32,
}
#[derive(Message, Debug, Clone)]
pub struct PlayerDied;
#[derive(Resource, Debug, Clone)]
pub struct PlayerHealth {
pub health: f32,
pub max_health: f32,
pub spawn_position: Vec3,
pub fall_safe_speed: f32,
}
impl Default for PlayerHealth {
fn default() -> Self {
Self {
health: 20.0,
max_health: 20.0,
spawn_position: Vec3::new(0.0, 30.0, 0.0),
fall_safe_speed: 10.0,
}
}
}
#[derive(Resource, Default, Debug, Clone, Copy, PartialEq, Eq)]
pub struct PlayerCrouching(pub bool);
#[derive(Debug, Clone)]
pub enum PlayerMode {
FreeFlightSixDof {
roll_mode: RollMode,
},
FreeFlightAnchored,
Grounded {
gravity: f32,
jump_speed: f32,
},
}
impl Default for PlayerMode {
fn default() -> Self {
PlayerMode::FreeFlightSixDof {
roll_mode: RollMode::Continuous,
}
}
}
pub const PLAYER_RADIUS: f32 = 0.6;
pub const PLAYER_HALF_HEIGHT: f32 = 1.8;
pub const CROUCH_HALF_HEIGHT: f32 = PLAYER_HALF_HEIGHT * 0.6;
pub const SPRINT_MULTIPLIER: f32 = 1.6;
const ACCEL: f32 = 12.0;
const DECEL: f32 = 7.0;
const MOUSE_SCALE: f32 = 0.003;
#[derive(Default, Copy, Clone, Debug, PartialEq, Eq)]
pub enum RollMode {
#[default]
Continuous,
Snap,
}
#[derive(Default, Copy, Clone, Debug, PartialEq, Eq)]
pub enum SnapRollEasing {
#[default]
EaseOutCubic,
EaseOutQuart,
Smoothstep,
Linear,
}
#[derive(Copy, Clone, Debug)]
pub(crate) struct SnapRollAnim {
pub(crate) start_angle: f32,
pub(crate) target_angle: f32,
pub(crate) elapsed: f32,
pub(crate) duration: f32,
pub(crate) easing: SnapRollEasing,
pub(crate) current_applied: f32,
}
pub(crate) const SNAP_MIN_PROJ_SQ: f32 = 0.49;
pub(crate) const SNAP_EPS_ON: f32 = 1e-3;
#[derive(Component, Debug, Clone)]
pub struct Player {
pub speed: f32,
pub sensitivity: f32,
pub roll_speed: f32,
pub velocity: Vec3,
pub mode: PlayerMode,
pub vertical_velocity: f32,
pub on_ground: bool,
pub(crate) impact_speed: f32,
pub(crate) footstep_timer: f32,
pub(crate) world_loaded: bool,
pub(crate) spawn_immune: bool,
pub sprinting: bool,
pub crouching: bool,
pub snap_roll_duration: f32,
pub snap_roll_easing: SnapRollEasing,
pub(crate) snap_anim: Option<SnapRollAnim>,
pub anchor_up: Vec3,
pub(crate) pending_anchor: Option<Vec3>,
}
impl Default for Player {
fn default() -> Self {
Self {
speed: 4.0,
sensitivity: 1.0,
roll_speed: 1.5,
velocity: Vec3::ZERO,
mode: PlayerMode::default(),
vertical_velocity: 0.0,
on_ground: false,
impact_speed: 0.0,
footstep_timer: 0.0,
world_loaded: false,
spawn_immune: true,
sprinting: false,
crouching: false,
snap_roll_duration: 0.5,
snap_roll_easing: SnapRollEasing::EaseOutCubic,
snap_anim: None,
anchor_up: Vec3::Y,
pending_anchor: None,
}
}
}
#[derive(Resource, Debug, Clone)]
pub struct PlayerConfig {
pub spawn_position: Vec3,
pub speed: f32,
pub sensitivity: f32,
pub roll_speed: f32,
pub look_at: Vec3,
pub fov_degrees: f32,
pub mode: PlayerMode,
pub snap_roll_duration_secs: f32,
pub snap_roll_easing: SnapRollEasing,
}
impl Default for PlayerConfig {
fn default() -> Self {
Self {
spawn_position: Vec3::new(0.0, 0.0, 30.0),
speed: 4.0,
sensitivity: 1.0,
roll_speed: 1.5,
look_at: Vec3::ZERO,
fov_degrees: 90.0,
mode: PlayerMode::default(),
snap_roll_duration_secs: 0.5,
snap_roll_easing: SnapRollEasing::EaseOutCubic,
}
}
}
pub fn spawn_player(
mut commands: Commands,
config: Res<PlayerConfig>,
existing: Query<(), With<Player>>,
mut health: ResMut<PlayerHealth>,
) {
if !existing.is_empty() {
return;
}
health.spawn_position = config.spawn_position;
let spawn = config.spawn_position;
let look_at = config.look_at;
let fov = config.fov_degrees.to_radians();
let mode = config.mode.clone();
let transform = Transform::from_translation(spawn).looking_at(look_at, Vec3::Y);
commands.spawn((
Player {
speed: config.speed,
sensitivity: config.sensitivity,
roll_speed: config.roll_speed,
velocity: Vec3::ZERO,
mode,
vertical_velocity: 0.0,
on_ground: false,
impact_speed: 0.0,
footstep_timer: 0.0,
world_loaded: false,
spawn_immune: true,
sprinting: false,
crouching: false,
snap_roll_duration: config.snap_roll_duration_secs,
snap_roll_easing: config.snap_roll_easing,
snap_anim: None,
anchor_up: nearest_world_axis(*transform.up()),
pending_anchor: None,
},
Camera3d::default(),
Projection::Perspective(PerspectiveProjection { fov, ..default() }),
transform,
));
}
pub(crate) fn apply_easing(t: f32, easing: SnapRollEasing) -> f32 {
match easing {
SnapRollEasing::EaseOutCubic => 1.0 - (1.0 - t).powi(3),
SnapRollEasing::EaseOutQuart => 1.0 - (1.0 - t).powi(4),
SnapRollEasing::Smoothstep => t * t * (3.0 - 2.0 * t),
SnapRollEasing::Linear => t,
}
}
pub(crate) const AXES: [Vec3; 6] = [
Vec3::X,
Vec3::NEG_X,
Vec3::Y,
Vec3::NEG_Y,
Vec3::Z,
Vec3::NEG_Z,
];
pub(crate) fn world_lattice_candidates(local_z: Vec3, up: Vec3) -> Vec<(f32, Vec3)> {
let mut candidates = Vec::with_capacity(6);
for axis in AXES {
let proj = axis - axis.dot(local_z) * local_z;
if proj.length_squared() < SNAP_MIN_PROJ_SQ {
continue;
}
let c = proj.normalize();
candidates.push((up.cross(c).dot(local_z).atan2(up.dot(c)), axis));
}
candidates
}
pub(crate) fn world_lattice_angles(local_z: Vec3, up: Vec3) -> Vec<f32> {
world_lattice_candidates(local_z, up)
.into_iter()
.map(|(a, _)| a)
.collect()
}
pub(crate) fn next_lattice_step(angles: &[f32], dir: i32) -> f32 {
use std::f32::consts::TAU;
if dir > 0 {
angles
.iter()
.map(|&d| if d > SNAP_EPS_ON { d } else { d + TAU })
.fold(f32::INFINITY, f32::min)
} else {
angles
.iter()
.map(|&d| if d < -SNAP_EPS_ON { d } else { d - TAU })
.fold(f32::NEG_INFINITY, f32::max)
}
}
pub(crate) fn next_lattice_candidate(cands: &[(f32, Vec3)], dir: i32) -> (f32, Vec3) {
use std::f32::consts::TAU;
assert!(
!cands.is_empty(),
"next_lattice_candidate: empty candidate slice — SNAP_MIN_PROJ_SQ \
guarantees at least 4 lattice candidates"
);
if dir > 0 {
cands
.iter()
.map(|&(d, axis)| (if d > SNAP_EPS_ON { d } else { d + TAU }, axis))
.min_by(|a, b| a.0.total_cmp(&b.0))
.unwrap()
} else {
cands
.iter()
.map(|&(d, axis)| (if d < -SNAP_EPS_ON { d } else { d - TAU }, axis))
.max_by(|a, b| a.0.total_cmp(&b.0))
.unwrap()
}
}
pub(crate) fn start_or_retarget_snap(
existing: Option<SnapRollAnim>,
local_z: Vec3,
up: Vec3,
dir: i32,
duration: f32,
easing: SnapRollEasing,
) -> SnapRollAnim {
match existing {
None => {
let step = next_lattice_step(&world_lattice_angles(local_z, up), dir);
SnapRollAnim {
start_angle: 0.0,
target_angle: step,
elapsed: 0.0,
duration,
easing,
current_applied: 0.0,
}
}
Some(anim) => {
let same_dir = (dir > 0 && anim.target_angle > anim.start_angle)
|| (dir < 0 && anim.target_angle < anim.start_angle);
if same_dir {
let residual = anim.target_angle - anim.current_applied;
let ref_up = Quat::from_axis_angle(local_z, residual) * up;
let step = next_lattice_step(&world_lattice_angles(local_z, ref_up), dir);
SnapRollAnim {
start_angle: anim.current_applied,
target_angle: anim.target_angle + step,
elapsed: 0.0,
duration,
easing,
current_applied: anim.current_applied,
}
} else {
let step = next_lattice_step(&world_lattice_angles(local_z, up), dir);
SnapRollAnim {
start_angle: anim.current_applied,
target_angle: anim.current_applied + step,
elapsed: 0.0,
duration,
easing,
current_applied: anim.current_applied,
}
}
}
}
}
pub(crate) fn snap_reference_up(
existing: Option<SnapRollAnim>,
local_z: Vec3,
up: Vec3,
dir: i32,
) -> Vec3 {
match existing {
Some(anim) => {
let same_dir = (dir > 0 && anim.target_angle > anim.start_angle)
|| (dir < 0 && anim.target_angle < anim.start_angle);
if same_dir {
let residual = anim.target_angle - anim.current_applied;
Quat::from_axis_angle(local_z, residual) * up
} else {
up
}
}
None => up,
}
}
pub(crate) fn clamp_pitch_delta(forward: Vec3, anchor_up: Vec3, pitch_d: f32) -> f32 {
let limit = 89_f32.to_radians();
let pitch = forward.dot(anchor_up).clamp(-1.0, 1.0).asin();
(pitch + pitch_d).clamp(-limit, limit) - pitch
}
pub(crate) fn nearest_world_axis(v: Vec3) -> Vec3 {
let mut best = AXES[0];
let mut best_dot = v.dot(AXES[0]);
for axis in AXES.into_iter().skip(1) {
let d = v.dot(axis);
if d > best_dot {
best = axis;
best_dot = d;
}
}
best
}
pub(crate) fn advance_snap(anim: &mut SnapRollAnim, dt: f32) -> (f32, bool) {
anim.elapsed += dt;
let t = (anim.elapsed / anim.duration).clamp(0.0, 1.0);
let eased = apply_easing(t, anim.easing);
let total = anim.start_angle + (anim.target_angle - anim.start_angle) * eased;
let delta = total - anim.current_applied;
anim.current_applied = total;
let finished = anim.elapsed >= anim.duration;
if finished {
let correction = anim.target_angle - anim.current_applied;
anim.current_applied = anim.target_angle;
return (delta + correction, true);
}
(delta, false)
}
pub fn player_look(
mut query: Query<(&mut Player, &mut Transform)>,
mut mouse_motion: MessageReader<MouseMotion>,
keys: Res<ButtonInput<KeyCode>>,
time: Res<Time>,
windows: Query<(&Window, &CursorOptions), With<PrimaryWindow>>,
) {
if !player_input_active(windows) {
mouse_motion.clear();
return;
}
let Ok((mut player, mut transform)) = query.single_mut() else {
return;
};
let mut delta = Vec2::ZERO;
for event in mouse_motion.read() {
delta += event.delta;
}
match &player.mode {
PlayerMode::FreeFlightSixDof { roll_mode } => {
if delta != Vec2::ZERO {
let yaw_d = -delta.x * MOUSE_SCALE * player.sensitivity;
let pitch_d = -delta.y * MOUSE_SCALE * player.sensitivity;
transform.rotate_local_y(yaw_d);
transform.rotate_local_x(pitch_d);
}
match roll_mode {
RollMode::Continuous => {
let mut roll = 0.0_f32;
if keys.pressed(KeyCode::KeyQ) {
roll += 1.0;
}
if keys.pressed(KeyCode::KeyE) {
roll -= 1.0;
}
if roll != 0.0 {
transform.rotate_local_z(roll * player.roll_speed * time.delta_secs());
}
}
RollMode::Snap => {
if keys.just_pressed(KeyCode::KeyQ) {
player.snap_anim = Some(start_or_retarget_snap(
player.snap_anim,
*transform.local_z(),
*transform.up(),
1,
player.snap_roll_duration,
player.snap_roll_easing,
));
}
if keys.just_pressed(KeyCode::KeyE) {
player.snap_anim = Some(start_or_retarget_snap(
player.snap_anim,
*transform.local_z(),
*transform.up(),
-1,
player.snap_roll_duration,
player.snap_roll_easing,
));
}
if let Some(ref mut anim) = player.snap_anim {
let (delta, finished) = advance_snap(anim, time.delta_secs());
transform.rotate_local_z(delta);
if finished {
player.snap_anim = None;
}
}
}
}
}
PlayerMode::FreeFlightAnchored => {
if delta != Vec2::ZERO {
let yaw_d = -delta.x * MOUSE_SCALE * player.sensitivity;
let pitch_d = -delta.y * MOUSE_SCALE * player.sensitivity;
transform.rotate(Quat::from_axis_angle(player.anchor_up, yaw_d));
let clamped = clamp_pitch_delta(*transform.forward(), player.anchor_up, pitch_d);
transform.rotate_local_x(clamped);
}
if keys.just_pressed(KeyCode::KeyQ) {
let local_z = *transform.local_z();
let up = *transform.up();
let ref_up = snap_reference_up(player.snap_anim, local_z, up, 1);
let (_, axis) =
next_lattice_candidate(&world_lattice_candidates(local_z, ref_up), 1);
player.pending_anchor = Some(axis);
player.snap_anim = Some(start_or_retarget_snap(
player.snap_anim,
local_z,
up,
1,
player.snap_roll_duration,
player.snap_roll_easing,
));
}
if keys.just_pressed(KeyCode::KeyE) {
let local_z = *transform.local_z();
let up = *transform.up();
let ref_up = snap_reference_up(player.snap_anim, local_z, up, -1);
let (_, axis) =
next_lattice_candidate(&world_lattice_candidates(local_z, ref_up), -1);
player.pending_anchor = Some(axis);
player.snap_anim = Some(start_or_retarget_snap(
player.snap_anim,
local_z,
up,
-1,
player.snap_roll_duration,
player.snap_roll_easing,
));
}
if let Some(ref mut anim) = player.snap_anim {
let (delta, finished) = advance_snap(anim, time.delta_secs());
transform.rotate_local_z(delta);
if finished {
if let Some(anchor) = player.pending_anchor.take() {
player.anchor_up = anchor;
}
let fwd = *transform.forward();
transform.look_to(fwd, player.anchor_up);
player.snap_anim = None;
}
}
}
PlayerMode::Grounded { .. } => {
if delta != Vec2::ZERO {
let yaw_d = -delta.x * MOUSE_SCALE * player.sensitivity;
let pitch_d = -delta.y * MOUSE_SCALE * player.sensitivity;
transform.rotate_y(yaw_d);
let (yaw, pitch, _roll) = transform.rotation.to_euler(EulerRot::YXZ);
let new_pitch = (pitch + pitch_d).clamp(-89_f32.to_radians(), 89_f32.to_radians());
transform.rotation = Quat::from_euler(EulerRot::YXZ, yaw, new_pitch, 0.0);
}
}
}
}
pub fn player_move<V: VoxelType>(
mut query: Query<(&mut Player, &mut Transform)>,
keys: Res<ButtonInput<KeyCode>>,
time: Res<Time>,
mut viewer: ResMut<ViewerPosition>,
manager: Res<ChunkManager>,
chunks: Query<&Chunk<V>>,
mut crouch_res: ResMut<PlayerCrouching>,
applied: Option<Res<effects::AppliedEffectModifiers>>,
windows: Query<(&Window, &CursorOptions), With<PrimaryWindow>>,
) {
let Ok((mut player, mut transform)) = query.single_mut() else {
return;
};
if !player_input_active(windows) {
player.velocity = Vec3::ZERO;
return;
}
let dt = time.delta_secs();
match player.mode.clone() {
PlayerMode::FreeFlightSixDof { .. } | PlayerMode::FreeFlightAnchored => {
player.sprinting = false;
player.crouching = false;
crouch_res.0 = false;
let forward = transform.rotation * Vec3::NEG_Z;
let right = transform.rotation * Vec3::X;
let up = transform.rotation * Vec3::Y;
let mut direction = Vec3::ZERO;
if keys.pressed(KeyCode::KeyW) {
direction += forward;
}
if keys.pressed(KeyCode::KeyS) {
direction -= forward;
}
if keys.pressed(KeyCode::KeyA) {
direction -= right;
}
if keys.pressed(KeyCode::KeyD) {
direction += right;
}
if keys.pressed(KeyCode::Space) {
direction += up;
}
if keys.pressed(KeyCode::ShiftLeft) || keys.pressed(KeyCode::ShiftRight) {
direction -= up;
}
let target = if direction != Vec3::ZERO {
direction.normalize() * player.speed
} else {
Vec3::ZERO
};
let factor = if direction != Vec3::ZERO {
ACCEL
} else {
DECEL
};
player.velocity = player.velocity.lerp(target, (factor * dt).min(1.0));
transform.translation += player.velocity * dt;
}
PlayerMode::Grounded {
gravity,
jump_speed,
} => {
let yaw = transform.rotation.to_euler(EulerRot::YXZ).0;
let forward = Vec3::new(-yaw.sin(), 0.0, -yaw.cos());
let right = Vec3::new(yaw.cos(), 0.0, -yaw.sin());
let mut h_dir = Vec3::ZERO;
if keys.pressed(KeyCode::KeyW) {
h_dir += forward;
}
if keys.pressed(KeyCode::KeyS) {
h_dir -= forward;
}
if keys.pressed(KeyCode::KeyA) {
h_dir -= right;
}
if keys.pressed(KeyCode::KeyD) {
h_dir += right;
}
let crouching =
keys.pressed(KeyCode::ControlLeft) || keys.pressed(KeyCode::ControlRight);
let sprinting = !crouching
&& player.on_ground
&& (keys.pressed(KeyCode::ShiftLeft) || keys.pressed(KeyCode::ShiftRight));
player.crouching = crouching;
player.sprinting = sprinting;
crouch_res.0 = crouching;
let speed_mult = if crouching {
0.5
} else if sprinting {
SPRINT_MULTIPLIER
} else {
1.0
};
let foot_pos = transform.translation - Vec3::Y * (PLAYER_HALF_HEIGHT + 0.3);
let modifier = get_voxel_at::<V>(foot_pos, &manager, &chunks)
.map(|v| v.movement_modifier())
.unwrap_or_default();
let effect_speed = applied.as_deref().map(|a| a.0.speed_mult).unwrap_or(1.0);
let h_target = if h_dir != Vec3::ZERO {
h_dir.normalize() * player.speed * speed_mult * modifier.speed_mult * effect_speed
} else {
Vec3::ZERO
};
let effective_decel = DECEL * modifier.friction_mult;
let factor = if h_dir != Vec3::ZERO {
ACCEL
} else {
effective_decel
};
player.velocity = player.velocity.lerp(h_target, (factor * dt).min(1.0));
if !player.world_loaded {
player.vertical_velocity = 0.0;
transform.translation += player.velocity * dt;
viewer.position = transform.translation;
return;
}
if keys.just_pressed(KeyCode::Space) && player.on_ground && !crouching {
let effect_jump = applied.as_deref().map(|a| a.0.jump_mult).unwrap_or(1.0);
player.vertical_velocity = jump_speed * modifier.jump_mult * effect_jump;
}
player.vertical_velocity -= gravity * modifier.gravity_mult * dt;
let center_voxel = get_voxel_at::<V>(transform.translation, &manager, &chunks);
if center_voxel.map(|v| v.alpha() < 1.0).unwrap_or(false) {
player.vertical_velocity += jump_speed * 0.3 * dt;
}
transform.translation += player.velocity * dt;
transform.translation.y += player.vertical_velocity * dt;
}
}
viewer.position = transform.translation;
}
pub fn player_resolve_collision<V: VoxelType>(
mut player_q: Query<(&mut Player, &mut Transform)>,
chunk_q: Query<(&Chunk<V>, &Transform), Without<Player>>,
manager: Res<ChunkManager>,
) {
let Ok((mut player, mut player_tf)) = player_q.single_mut() else {
return;
};
let is_grounded = matches!(player.mode, PlayerMode::Grounded { .. });
if is_grounded {
player.on_ground = false;
player.impact_speed = 0.0; }
let half_height = if player.crouching {
CROUCH_HALF_HEIGHT
} else {
PLAYER_HALF_HEIGHT
};
if !player.world_loaded {
let feet = player_tf.translation - Vec3::Y * half_height;
let coord = crate::chunk::world_to_chunk_coord(feet);
if manager.is_loaded(coord) {
player.world_loaded = true;
}
}
let mut pos = player_tf.translation;
let up = if is_grounded {
Vec3::Y
} else {
player_tf.rotation * Vec3::Y
};
let extent = half_height + PLAYER_RADIUS;
let voxel_size = VOXEL_SIZE;
for (chunk, chunk_tf) in &chunk_q {
let chunk_pos = chunk_tf.translation;
let local = pos - chunk_pos;
let min_vox = IVec3::new(
((local.x - extent) / voxel_size).floor() as i32,
((local.y - extent) / voxel_size).floor() as i32,
((local.z - extent) / voxel_size).floor() as i32,
);
let max_vox = IVec3::new(
((local.x + extent) / voxel_size).ceil() as i32,
((local.y + extent) / voxel_size).ceil() as i32,
((local.z + extent) / voxel_size).ceil() as i32,
);
let lo = min_vox.max(IVec3::ZERO);
let hi = max_vox.min(IVec3::splat(CHUNK_SIZE as i32 - 1));
for vx in lo.x..=hi.x {
for vy in lo.y..=hi.y {
for vz in lo.z..=hi.z {
if !chunk.is_solid_at(vx as usize, vy as usize, vz as usize) {
continue;
}
let new_pos = push_capsule_out(pos, up, half_height, chunk_pos, vx, vy, vz);
if is_grounded && new_pos.y > pos.y + 0.001 {
if !player.on_ground {
player.impact_speed = player.vertical_velocity.abs();
}
player.on_ground = true;
player.vertical_velocity = 0.0;
}
pos = new_pos;
}
}
}
}
player_tf.translation = pos;
}
pub fn player_cursor_system(
mut commands: Commands,
mouse: Res<ButtonInput<MouseButton>>,
keys: Res<ButtonInput<KeyCode>>,
mut windows: Query<(Entity, &Window, &mut CursorOptions), With<PrimaryWindow>>,
) {
for (entity, window, mut cursor) in windows.iter_mut() {
if !window.focused {
if cursor.grab_mode != CursorGrabMode::None || !cursor.visible {
cursor.grab_mode = CursorGrabMode::None;
cursor.visible = true;
}
continue;
}
if mouse.just_pressed(MouseButton::Left)
&& cursor.grab_mode == bevy::window::CursorGrabMode::None
{
cursor.grab_mode = bevy::window::CursorGrabMode::Locked;
cursor.visible = false;
}
if keys.just_pressed(KeyCode::Escape) {
if cursor.grab_mode != bevy::window::CursorGrabMode::None {
cursor.grab_mode = bevy::window::CursorGrabMode::None;
cursor.visible = true;
} else {
commands.entity(entity).despawn();
}
}
}
}
pub fn player_input_active(windows: Query<(&Window, &CursorOptions), With<PrimaryWindow>>) -> bool {
match windows.single() {
Ok((window, cursor)) => window.focused && cursor.grab_mode != CursorGrabMode::None,
Err(_) => windows.is_empty(),
}
}
pub fn player_fall_damage(
mut player_q: Query<(&mut Player, &mut Transform)>,
mut health: ResMut<PlayerHealth>,
mut damaged_writer: MessageWriter<PlayerDamaged>,
mut died_writer: MessageWriter<PlayerDied>,
) {
let Ok((mut player, mut transform)) = player_q.single_mut() else {
return;
};
if player.impact_speed <= 0.0 {
return;
}
if player.spawn_immune {
player.spawn_immune = false;
player.impact_speed = 0.0;
return;
}
let damage = (player.impact_speed - health.fall_safe_speed).max(0.0) * 2.0;
player.impact_speed = 0.0;
if damage <= 0.0 {
return;
}
health.health = (health.health - damage).max(0.0);
damaged_writer.write(PlayerDamaged { amount: damage });
if health.health <= 0.0 {
health.health = health.max_health;
transform.translation = health.spawn_position;
player.vertical_velocity = 0.0;
player.velocity = Vec3::ZERO;
player.world_loaded = false; player.spawn_immune = true; died_writer.write(PlayerDied);
}
}
pub fn health_system(
applied: Option<Res<effects::AppliedEffectModifiers>>,
mut health: ResMut<PlayerHealth>,
mut damaged_reader: bevy::ecs::message::MessageReader<PlayerDamaged>,
mut died_writer: MessageWriter<PlayerDied>,
) {
for event in damaged_reader.read() {
let resistance = applied
.as_ref()
.map(|a| a.0.damage_resistance)
.unwrap_or(0.0);
let actual = event.amount * (1.0 - resistance.clamp(0.0, 1.0));
health.health = (health.health - actual).max(0.0);
}
if health.health <= 0.0 {
health.health = health.max_health;
died_writer.write(PlayerDied);
}
}
pub fn respawn_system(
mut died_reader: bevy::ecs::message::MessageReader<PlayerDied>,
mut viewer: ResMut<ViewerPosition>,
config: Option<Res<PlayerConfig>>,
) {
for _ in died_reader.read() {
let spawn = config
.as_ref()
.map(|c| c.spawn_position)
.unwrap_or(Vec3::ZERO);
viewer.position = spawn;
}
}
fn push_capsule_out(
pos: Vec3,
up: Vec3,
half_height: f32,
chunk_pos: Vec3,
vx: i32,
vy: i32,
vz: i32,
) -> Vec3 {
let vmin = chunk_pos + Vec3::new(vx as f32, vy as f32, vz as f32) * VOXEL_SIZE;
let vmax = vmin + Vec3::splat(VOXEL_SIZE);
let p0 = pos - up * half_height;
let p1 = pos + up * half_height;
let spine = p1 - p0;
let vox_center = (vmin + vmax) * 0.5;
let len_sq = spine.length_squared();
let sphere_c = if len_sq > f32::EPSILON {
let t = ((vox_center - p0).dot(spine) / len_sq).clamp(0.0, 1.0);
p0 + spine * t
} else {
pos
};
let closest = sphere_c.clamp(vmin, vmax);
let diff = sphere_c - closest;
let dist_sq = diff.length_squared();
if dist_sq >= PLAYER_RADIUS * PLAYER_RADIUS {
return pos;
}
let delta = if dist_sq > f32::EPSILON {
let dist = dist_sq.sqrt();
(diff / dist) * (PLAYER_RADIUS - dist)
} else {
let rel = sphere_c - vox_center;
let abs_rel = rel.abs();
let half = VOXEL_SIZE * 0.5 + PLAYER_RADIUS;
if abs_rel.x >= abs_rel.y && abs_rel.x >= abs_rel.z {
Vec3::new(half * rel.x.signum() - rel.x, 0.0, 0.0)
} else if abs_rel.y >= abs_rel.z {
Vec3::new(0.0, half * rel.y.signum() - rel.y, 0.0)
} else {
Vec3::new(0.0, 0.0, half * rel.z.signum() - rel.z)
}
};
pos + delta
}
pub fn player_footstep_system<V: VoxelType>(
mut query: Query<(&mut Player, &Transform)>,
time: Res<Time>,
manager: Res<ChunkManager>,
chunks: Query<&Chunk<V>>,
mut sfx: MessageWriter<SfxRequest>,
) {
let Ok((mut player, transform)) = query.single_mut() else {
return;
};
if !matches!(player.mode, PlayerMode::Grounded { .. }) || !player.on_ground {
return;
}
let h_speed = Vec3::new(player.velocity.x, 0.0, player.velocity.z).length();
if h_speed < 0.5 {
player.footstep_timer = 0.0;
return;
}
let step_interval = (0.5 / h_speed).clamp(0.2, 0.5);
player.footstep_timer += time.delta_secs();
if player.footstep_timer < step_interval {
return;
}
player.footstep_timer = 0.0;
let foot_pos = transform.translation - Vec3::Y * (PLAYER_HALF_HEIGHT + 0.3);
let voxel_byte = get_voxel_at::<V>(foot_pos, &manager, &chunks)
.map(|v| v.to_byte())
.unwrap_or(0);
sfx.write(SfxRequest {
event: SfxEvent::Footstep(voxel_byte),
position: None,
});
}
fn load_spawn_on_startup(
mut config: ResMut<PlayerConfig>,
mut health: ResMut<PlayerHealth>,
world_data_dir: Res<WorldDataDir>,
) {
let data_dir = world_data_dir.as_str();
if let Some(pos) = persistence::load_spawn_position(data_dir) {
config.spawn_position = pos;
health.spawn_position = pos;
} else {
persistence::save_spawn_position(config.spawn_position, data_dir);
}
}
fn save_spawn_on_exit(
health: Res<PlayerHealth>,
world_data_dir: Res<WorldDataDir>,
mut exit_reader: bevy::ecs::message::MessageReader<AppExit>,
) {
for _ in exit_reader.read() {
persistence::save_spawn_position(health.spawn_position, world_data_dir.as_str());
}
}
fn gameplay_active(state: Option<Res<bevy::prelude::State<crate::ui::PauseMenuState>>>) -> bool {
use crate::ui::PauseMenuState;
state.map_or(true, |s| matches!(s.get(), PauseMenuState::Playing))
}
pub struct PlayerPlugin<V: VoxelType> {
_marker: std::marker::PhantomData<V>,
world_name: String,
}
impl<V: VoxelType> PlayerPlugin<V> {
pub fn new() -> Self {
Self {
_marker: std::marker::PhantomData,
world_name: String::new(),
}
}
pub fn with_world(world_name: impl Into<String>) -> Self {
Self {
_marker: std::marker::PhantomData,
world_name: world_name.into(),
}
}
}
impl<V: VoxelType> Default for PlayerPlugin<V> {
fn default() -> Self {
Self::new()
}
}
impl<V: VoxelType> Plugin for PlayerPlugin<V> {
fn build(&self, app: &mut App) {
let name = if self.world_name.is_empty() {
"world"
} else {
&self.world_name
};
app.insert_resource(WorldDataDir::for_world(name));
app.init_resource::<PlayerConfig>();
app.init_resource::<PlayerHealth>();
app.init_resource::<PlayerCrouching>();
app.add_message::<PlayerDamaged>();
app.add_message::<PlayerDied>();
app.add_systems(Startup, (load_spawn_on_startup, spawn_player).chain());
app.add_systems(
Update,
(
player_look,
player_move::<V>,
player_resolve_collision::<V>,
player_fall_damage,
player_footstep_system::<V>,
)
.chain()
.run_if(gameplay_active),
);
app.add_systems(Update, health_system);
app.add_systems(Update, respawn_system);
app.add_systems(
Update,
player_cursor_system
.run_if(gameplay_active)
.before(player_look),
);
app.add_systems(PostUpdate, save_spawn_on_exit);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn player_default_values() {
let p = Player::default();
assert_eq!(p.speed, 4.0);
assert_eq!(p.sensitivity, 1.0);
assert_eq!(p.roll_speed, 1.5);
assert_eq!(p.velocity, Vec3::ZERO);
}
#[test]
fn player_config_default_values() {
let c = PlayerConfig::default();
assert_eq!(c.speed, 4.0);
assert_eq!(c.fov_degrees, 90.0);
assert!(matches!(
c.mode,
PlayerMode::FreeFlightSixDof {
roll_mode: RollMode::Continuous
}
));
assert!((c.snap_roll_duration_secs - 0.5).abs() < f32::EPSILON);
assert_eq!(c.snap_roll_easing, SnapRollEasing::EaseOutCubic);
}
#[test]
fn snap_roll_completes_to_90deg() {
let mut anim = start_or_retarget_snap(
None,
Vec3::Z,
Vec3::Y,
1,
0.18,
SnapRollEasing::EaseOutCubic,
);
let (delta, finished) = advance_snap(&mut anim, 0.18);
assert!(finished);
assert!(
(delta - std::f32::consts::FRAC_PI_2).abs() < 1e-4,
"Expected ~PI/2, got {delta}"
);
}
#[test]
fn snap_roll_easing_monotonic() {
let mut anim = start_or_retarget_snap(
None,
Vec3::Z,
Vec3::Y,
1,
0.18,
SnapRollEasing::EaseOutCubic,
);
let step = 0.045;
let mut deltas = Vec::new();
for _ in 0..4 {
let (d, _) = advance_snap(&mut anim, step);
assert!(d > 0.0, "Delta should be positive, got {d}");
deltas.push(d);
}
let total: f32 = deltas.iter().sum();
assert!(
(total - std::f32::consts::FRAC_PI_2).abs() < 1e-3,
"Sum should be ~PI/2, got {total}"
);
for i in 1..deltas.len() {
assert!(
deltas[i] <= deltas[i - 1] + 1e-6,
"Easing not monotonically decreasing: {:?}",
deltas
);
}
}
#[test]
fn snap_roll_same_direction_extends_target() {
let mut anim = start_or_retarget_snap(
None,
Vec3::Z,
Vec3::Y,
1,
0.18,
SnapRollEasing::EaseOutCubic,
);
advance_snap(&mut anim, 0.054);
let prev_applied = anim.current_applied;
let up = Quat::from_axis_angle(Vec3::Z, anim.current_applied) * Vec3::Y;
let new_anim = start_or_retarget_snap(
Some(anim),
Vec3::Z,
up,
1,
0.18,
SnapRollEasing::EaseOutCubic,
);
assert!((new_anim.start_angle - prev_applied).abs() < 1e-6);
assert!(
(new_anim.target_angle - std::f32::consts::PI).abs() < 1e-4,
"Expected target ~PI (2x90°), got {}",
new_anim.target_angle
);
}
#[test]
fn snap_roll_opposite_direction_reverses_to_lattice() {
let mut anim = start_or_retarget_snap(
None,
Vec3::Z,
Vec3::Y,
1,
0.18,
SnapRollEasing::EaseOutCubic,
);
advance_snap(&mut anim, 0.054);
let current = anim.current_applied;
assert!(current > 0.0 && current < std::f32::consts::FRAC_PI_2);
let up = Quat::from_axis_angle(Vec3::Z, current) * Vec3::Y;
let new_anim = start_or_retarget_snap(
Some(anim),
Vec3::Z,
up,
-1,
0.18,
SnapRollEasing::EaseOutCubic,
);
assert!(
new_anim.target_angle.abs() < 1e-6,
"Expected target ~0, got {}",
new_anim.target_angle
);
}
#[test]
fn continuous_mode_unchanged() {
let player = Player::default();
assert!(matches!(
player.mode,
PlayerMode::FreeFlightSixDof {
roll_mode: RollMode::Continuous
}
));
assert!(player.snap_anim.is_none());
}
#[test]
fn snap_roll_config_copies_to_player() {
let config = PlayerConfig {
mode: PlayerMode::FreeFlightSixDof {
roll_mode: RollMode::Snap,
},
snap_roll_duration_secs: 0.3,
snap_roll_easing: SnapRollEasing::Smoothstep,
..default()
};
let player = Player {
mode: config.mode.clone(),
snap_roll_duration: config.snap_roll_duration_secs,
snap_roll_easing: config.snap_roll_easing,
..default()
};
assert!(matches!(
player.mode,
PlayerMode::FreeFlightSixDof {
roll_mode: RollMode::Snap
}
));
assert!((player.snap_roll_duration - 0.3).abs() < f32::EPSILON);
assert_eq!(player.snap_roll_easing, SnapRollEasing::Smoothstep);
}
#[test]
fn snap_roll_start_from_none_is_independent() {
let anim1 = start_or_retarget_snap(
None,
Vec3::Z,
Vec3::Y,
1,
0.18,
SnapRollEasing::EaseOutCubic,
);
let anim2 = start_or_retarget_snap(
None,
Vec3::Z,
Vec3::Y,
1,
0.18,
SnapRollEasing::EaseOutCubic,
);
assert!((anim1.target_angle - anim2.target_angle).abs() < f32::EPSILON);
assert!((anim1.start_angle - anim2.start_angle).abs() < f32::EPSILON);
}
#[test]
fn lattice_axis_forward_yields_four_candidates_at_90deg() {
let mut angles = world_lattice_angles(Vec3::Y, Vec3::Z);
assert_eq!(angles.len(), 4, "Y axis pair must be excluded: {angles:?}");
angles.sort_by(f32::total_cmp);
for pair in angles.windows(2) {
assert!(
(pair[1] - pair[0] - std::f32::consts::FRAC_PI_2).abs() < 1e-5,
"Candidates must be exactly 90° apart: {angles:?}"
);
}
}
#[test]
fn lattice_near_axis_forward_still_yields_four_candidates() {
let local_z = Quat::from_axis_angle(Vec3::X, 8_f32.to_radians()) * Vec3::Z;
let up = Quat::from_axis_angle(local_z, 5_f32.to_radians())
* (Vec3::Y - Vec3::Y.dot(local_z) * local_z).normalize();
let angles = world_lattice_angles(local_z, up);
assert_eq!(
angles.len(),
4,
"Near-axis view must exclude the ±Z pair, got {angles:?}"
);
let boundary_z = Vec3::new(0.0, 1.0, 1.0).normalize();
let boundary_up = (Vec3::Y - Vec3::Y.dot(boundary_z) * boundary_z).normalize();
assert_eq!(
world_lattice_angles(boundary_z, boundary_up).len(),
6,
"At exactly 45° both axis families are equally valid"
);
}
#[test]
fn lattice_diagonal_forward_yields_six_candidates_cycling_2pi() {
use std::f32::consts::{FRAC_PI_2, FRAC_PI_3, TAU};
let local_z = -Vec3::ONE.normalize();
let start = (Vec3::X - Vec3::X.dot(local_z) * local_z).normalize();
let angles = world_lattice_angles(local_z, start);
assert_eq!(
angles.len(),
6,
"All 6 axes survive on a diagonal: {angles:?}"
);
let mut up = start;
let mut total = 0.0_f32;
for _ in 0..6 {
let step = next_lattice_step(&world_lattice_angles(local_z, up), 1);
assert!(
(step - FRAC_PI_3).abs() < 1e-3,
"Expected ~60° step, got {step}"
);
assert!(
(step - FRAC_PI_2).abs() > 0.1,
"Step must not be 90°, got {step}"
);
total += step;
up = Quat::from_axis_angle(local_z, step) * up;
}
assert!(
(total - TAU).abs() < 1e-3,
"Six presses must sum to 2π, got {total}"
);
assert!(
up.dot(start) > 0.9999,
"Cycle must return to start, got {up:?}"
);
}
#[test]
fn lattice_drifted_up_travels_residual() {
let up = Quat::from_axis_angle(Vec3::Z, 10_f32.to_radians()) * Vec3::Y;
let angles = world_lattice_angles(Vec3::Z, up);
let q = next_lattice_step(&angles, 1);
let e = next_lattice_step(&angles, -1);
assert!(
(q - 80_f32.to_radians()).abs() < 1e-4,
"Q must travel ≈+80°, got {q}"
);
assert!(
(e + 10_f32.to_radians()).abs() < 1e-4,
"E must travel ≈−10°, got {e}"
);
let up_q = Quat::from_axis_angle(Vec3::Z, q) * up;
let up_e = Quat::from_axis_angle(Vec3::Z, e) * up;
assert!(
up_q.dot(Vec3::NEG_X) > 0.9999,
"Q must land on −X, got {up_q:?}"
);
assert!(
up_e.dot(Vec3::Y) > 0.9999,
"E must land on +Y, got {up_e:?}"
);
}
#[test]
fn lattice_eps_on_skips_exact_candidate() {
let angles = world_lattice_angles(Vec3::Z, Vec3::Y);
let q = next_lattice_step(&angles, 1);
let e = next_lattice_step(&angles, -1);
assert!(
(q - std::f32::consts::FRAC_PI_2).abs() < 1e-5,
"Q from an exact candidate must be +90°, got {q}"
);
assert!(
(e + std::f32::consts::FRAC_PI_2).abs() < 1e-5,
"E from an exact candidate must be −90°, got {e}"
);
}
#[test]
fn snap_retarget_drifted_frame_lands_on_candidates() {
let local_z = Vec3::Z;
let up0 = Quat::from_axis_angle(local_z, 10_f32.to_radians()) * Vec3::Y;
let mut anim =
start_or_retarget_snap(None, local_z, up0, 1, 0.18, SnapRollEasing::EaseOutCubic);
advance_snap(&mut anim, 0.054);
let up_mid = Quat::from_axis_angle(local_z, anim.current_applied) * up0;
let extended = start_or_retarget_snap(
Some(anim),
local_z,
up_mid,
1,
0.18,
SnapRollEasing::EaseOutCubic,
);
let up_ext = Quat::from_axis_angle(local_z, extended.target_angle) * up0;
assert!(
up_ext.dot(Vec3::NEG_Y) > 0.9999,
"Extend must land on −Y, got {up_ext:?}"
);
let mut anim =
start_or_retarget_snap(None, local_z, up0, 1, 0.18, SnapRollEasing::EaseOutCubic);
advance_snap(&mut anim, 0.054);
let up_mid = Quat::from_axis_angle(local_z, anim.current_applied) * up0;
let reversed = start_or_retarget_snap(
Some(anim),
local_z,
up_mid,
-1,
0.18,
SnapRollEasing::EaseOutCubic,
);
let up_rev = Quat::from_axis_angle(local_z, reversed.target_angle) * up0;
assert!(
up_rev.dot(Vec3::Y) > 0.9999,
"Reverse must land on +Y, got {up_rev:?}"
);
}
#[test]
fn push_capsule_no_collision() {
let pos = Vec3::new(10.0, 10.0, 10.0);
let result = push_capsule_out(pos, Vec3::Y, PLAYER_HALF_HEIGHT, Vec3::ZERO, 0, 0, 0);
assert_eq!(result, pos);
}
#[test]
fn push_capsule_resolves_overlap() {
let pos = Vec3::new(0.5, 0.5, 0.5); let result = push_capsule_out(pos, Vec3::Y, PLAYER_HALF_HEIGHT, Vec3::ZERO, 0, 0, 0);
let vox_center = Vec3::splat(0.5);
let closest = result.clamp(Vec3::ZERO, Vec3::ONE);
let dist = (result - closest).length();
assert!(
dist >= PLAYER_RADIUS - 0.001,
"dist={dist} must be >= PLAYER_RADIUS={PLAYER_RADIUS}"
);
let _ = vox_center; }
#[test]
fn clamp_pitch_under_limit_passes_through() {
let d = clamp_pitch_delta(Vec3::NEG_Z, Vec3::Y, 30_f32.to_radians());
assert!((d - 30_f32.to_radians()).abs() < 1e-5, "got {d}");
let d = clamp_pitch_delta(Vec3::NEG_Z, Vec3::Y, -30_f32.to_radians());
assert!((d + 30_f32.to_radians()).abs() < 1e-5, "got {d}");
}
#[test]
fn clamp_pitch_crossing_limit_truncates() {
let f_hi = Vec3::new(0.0, 80_f32.to_radians().sin(), -(80_f32.to_radians().cos()));
let d = clamp_pitch_delta(f_hi, Vec3::Y, 20_f32.to_radians());
assert!(
(d - 9_f32.to_radians()).abs() < 1e-4,
"expected ~+9°, got {d}"
);
let f_lo = Vec3::new(
0.0,
-(80_f32.to_radians().sin()),
-(80_f32.to_radians().cos()),
);
let d = clamp_pitch_delta(f_lo, Vec3::Y, -20_f32.to_radians());
assert!(
(d + 9_f32.to_radians()).abs() < 1e-4,
"expected ~−9°, got {d}"
);
}
#[test]
fn clamp_pitch_at_limit_blocks_outward_allows_inward() {
let f = Vec3::new(0.0, 89_f32.to_radians().sin(), -(89_f32.to_radians().cos()));
let outward = clamp_pitch_delta(f, Vec3::Y, 5_f32.to_radians());
assert!(
outward.abs() < 1e-4,
"outward delta at the pole must be ~0, got {outward}"
);
let inward = clamp_pitch_delta(f, Vec3::Y, -5_f32.to_radians());
assert!(
(inward + 5_f32.to_radians()).abs() < 1e-4,
"inward delta must pass through, got {inward}"
);
}
#[test]
fn candidates_axis_forward_have_source_axes() {
use std::f32::consts::FRAC_PI_2;
let cands = world_lattice_candidates(Vec3::Z, Vec3::Y);
assert_eq!(cands.len(), 4, "±Z must be excluded: {cands:?}");
let angle_of = |axis: Vec3| {
cands
.iter()
.find(|(_, a)| *a == axis)
.unwrap_or_else(|| panic!("axis {axis:?} missing from {cands:?}"))
.0
};
assert!(
(angle_of(Vec3::X) + FRAC_PI_2).abs() < 1e-5,
"X must sit at −π/2"
);
assert!(
(angle_of(Vec3::NEG_X) - FRAC_PI_2).abs() < 1e-5,
"−X must sit at +π/2"
);
assert!(angle_of(Vec3::Y).abs() < 1e-5, "Y must sit at 0");
assert!(
(angle_of(Vec3::NEG_Y).abs() - std::f32::consts::PI).abs() < 1e-5,
"−Y must sit at ±π"
);
}
#[test]
fn candidates_diagonal_forward_yield_six_axes() {
let local_z = -Vec3::ONE.normalize();
let up = (Vec3::X - Vec3::X.dot(local_z) * local_z).normalize();
let cands = world_lattice_candidates(local_z, up);
assert_eq!(
cands.len(),
6,
"all 6 axes survive on a diagonal: {cands:?}"
);
for axis in AXES {
assert_eq!(
cands.iter().filter(|(_, a)| *a == axis).count(),
1,
"axis {axis:?} must appear exactly once: {cands:?}"
);
}
}
#[test]
fn lattice_angles_equal_candidate_angles() {
let diag_z = -Vec3::ONE.normalize();
let diag_up = (Vec3::X - Vec3::X.dot(diag_z) * diag_z).normalize();
for (local_z, up) in [(Vec3::Z, Vec3::Y), (diag_z, diag_up)] {
let angles = world_lattice_angles(local_z, up);
let cands = world_lattice_candidates(local_z, up);
assert_eq!(angles.len(), cands.len());
for (a, (c, _)) in angles.iter().zip(cands.iter()) {
assert_eq!(a, c, "wrapper angle {a} != candidate angle {c}");
}
}
}
#[test]
fn next_lattice_candidate_matches_next_lattice_step() {
let up = Quat::from_axis_angle(Vec3::Z, 10_f32.to_radians()) * Vec3::Y;
let cands = world_lattice_candidates(Vec3::Z, up);
let angles = world_lattice_angles(Vec3::Z, up);
for dir in [1, -1] {
let (cand_angle, _) = next_lattice_candidate(&cands, dir);
let step = next_lattice_step(&angles, dir);
assert_eq!(cand_angle, step, "dir {dir}: {cand_angle} != {step}");
}
}
#[test]
fn next_candidate_q_yields_neg_x_e_yields_x() {
use std::f32::consts::FRAC_PI_2;
let cands = world_lattice_candidates(Vec3::Z, Vec3::Y);
let (q_angle, q_axis) = next_lattice_candidate(&cands, 1);
assert!(
(q_angle - FRAC_PI_2).abs() < 1e-5,
"Q must travel +π/2, got {q_angle}"
);
assert_eq!(q_axis, Vec3::NEG_X);
let (e_angle, e_axis) = next_lattice_candidate(&cands, -1);
assert!(
(e_angle + FRAC_PI_2).abs() < 1e-5,
"E must travel −π/2, got {e_angle}"
);
assert_eq!(e_axis, Vec3::X);
}
#[test]
fn snap_reference_up_fresh_and_opposite_use_up() {
let up = Quat::from_axis_angle(Vec3::Z, 10_f32.to_radians()) * Vec3::Y;
assert_eq!(snap_reference_up(None, Vec3::Z, up, 1), up);
let mut anim =
start_or_retarget_snap(None, Vec3::Z, up, 1, 0.18, SnapRollEasing::EaseOutCubic);
advance_snap(&mut anim, 0.054);
assert_eq!(snap_reference_up(Some(anim), Vec3::Z, up, -1), up);
}
#[test]
fn snap_reference_up_same_dir_advances_residual() {
let up0 = Vec3::Y;
let mut anim =
start_or_retarget_snap(None, Vec3::Z, up0, 1, 0.18, SnapRollEasing::EaseOutCubic);
advance_snap(&mut anim, 0.054);
let up_mid = Quat::from_axis_angle(Vec3::Z, anim.current_applied) * up0;
let ref_up = snap_reference_up(Some(anim), Vec3::Z, up_mid, 1);
let expected =
Quat::from_axis_angle(Vec3::Z, anim.target_angle - anim.current_applied) * up_mid;
assert!(
ref_up.dot(expected) > 0.9999,
"ref {ref_up:?} != target up {expected:?}"
);
assert!(
ref_up.dot(Vec3::NEG_X) > 0.9999,
"expected ~−X, got {ref_up:?}"
);
}
#[test]
fn anchor_commit_matches_pending_projection() {
let local_z = Vec3::Z;
let dur = 0.18;
let ease = SnapRollEasing::EaseOutCubic;
let up0 = Quat::from_axis_angle(local_z, 10_f32.to_radians()) * Vec3::Y;
let proj = |axis: Vec3| (axis - axis.dot(local_z) * local_z).normalize();
let ref_up = snap_reference_up(None, local_z, up0, 1);
let (_, axis) = next_lattice_candidate(&world_lattice_candidates(local_z, ref_up), 1);
assert_eq!(axis, Vec3::NEG_X);
let anim = start_or_retarget_snap(None, local_z, up0, 1, dur, ease);
let landed = Quat::from_axis_angle(local_z, anim.target_angle) * up0;
assert!(
landed.dot(proj(axis)) > 0.9999,
"fresh: {landed:?} != proj({axis:?})"
);
let mut anim = start_or_retarget_snap(None, local_z, up0, 1, dur, ease);
advance_snap(&mut anim, 0.054);
let up_mid = Quat::from_axis_angle(local_z, anim.current_applied) * up0;
let ref_up = snap_reference_up(Some(anim), local_z, up_mid, 1);
let (_, axis) = next_lattice_candidate(&world_lattice_candidates(local_z, ref_up), 1);
assert_eq!(axis, Vec3::NEG_Y);
let extended = start_or_retarget_snap(Some(anim), local_z, up_mid, 1, dur, ease);
let landed = Quat::from_axis_angle(local_z, extended.target_angle) * up0;
assert!(
landed.dot(proj(axis)) > 0.9999,
"extend: {landed:?} != proj({axis:?})"
);
let mut anim = start_or_retarget_snap(None, local_z, up0, 1, dur, ease);
advance_snap(&mut anim, 0.054);
let up_mid = Quat::from_axis_angle(local_z, anim.current_applied) * up0;
let ref_up = snap_reference_up(Some(anim), local_z, up_mid, -1);
let (_, axis) = next_lattice_candidate(&world_lattice_candidates(local_z, ref_up), -1);
assert_eq!(axis, Vec3::Y);
let reversed = start_or_retarget_snap(Some(anim), local_z, up_mid, -1, dur, ease);
let landed = Quat::from_axis_angle(local_z, reversed.target_angle) * up0;
assert!(
landed.dot(proj(axis)) > 0.9999,
"reverse: {landed:?} != proj({axis:?})"
);
}
#[test]
fn nearest_world_axis_snaps_biased_vectors() {
assert_eq!(nearest_world_axis(Vec3::new(0.9, 0.1, 0.2)), Vec3::X);
assert_eq!(nearest_world_axis(Vec3::new(-2.0, 0.5, 0.5)), Vec3::NEG_X);
assert_eq!(nearest_world_axis(Vec3::new(0.1, -1.5, 0.3)), Vec3::NEG_Y);
assert_eq!(nearest_world_axis(Vec3::new(-0.1, 0.2, 0.95)), Vec3::Z);
assert_eq!(nearest_world_axis(Vec3::new(0.2, 0.3, -0.9)), Vec3::NEG_Z);
}
#[test]
fn nearest_world_axis_tie_uses_axes_order() {
assert_eq!(nearest_world_axis(Vec3::new(1.0, 1.0, 0.0)), Vec3::X);
assert_eq!(nearest_world_axis(Vec3::new(0.0, 1.0, 1.0)), Vec3::Y);
assert_eq!(nearest_world_axis(Vec3::new(-1.0, -1.0, -1.0)), Vec3::NEG_X);
}
#[test]
fn player_mode_defaults_to_sixdof() {
let p = Player::default();
assert!(matches!(
p.mode,
PlayerMode::FreeFlightSixDof {
roll_mode: RollMode::Continuous
}
));
assert_eq!(p.anchor_up, Vec3::Y);
assert!(p.pending_anchor.is_none());
assert!(matches!(
PlayerConfig::default().mode,
PlayerMode::FreeFlightSixDof {
roll_mode: RollMode::Continuous
}
));
}
#[test]
fn anchored_mode_config_copies_to_player() {
let config = PlayerConfig {
mode: PlayerMode::FreeFlightAnchored,
..default()
};
let player = Player {
mode: config.mode.clone(),
..default()
};
assert!(matches!(player.mode, PlayerMode::FreeFlightAnchored));
}
fn anchored_app() -> (App, Entity) {
let mut app = App::new();
app.add_message::<MouseMotion>();
app.insert_resource(ButtonInput::<KeyCode>::default());
app.insert_resource(Time::<()>::default());
app.add_systems(Update, player_look);
let entity = app
.world_mut()
.spawn((
Player {
mode: PlayerMode::FreeFlightAnchored,
..default()
},
Transform::default(),
))
.id();
(app, entity)
}
#[test]
fn focus_loss_releases_capture_and_ignores_unfocused_click_and_escape() {
use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
let mut app = App::new();
app.init_resource::<ButtonInput<KeyCode>>()
.init_resource::<ButtonInput<MouseButton>>()
.add_systems(Update, player_cursor_system);
let window = app
.world_mut()
.spawn((
Window {
focused: false,
..default()
},
PrimaryWindow,
CursorOptions {
grab_mode: CursorGrabMode::Locked,
visible: false,
..default()
},
))
.id();
app.world_mut()
.resource_mut::<ButtonInput<KeyCode>>()
.press(KeyCode::Escape);
app.world_mut()
.resource_mut::<ButtonInput<MouseButton>>()
.press(MouseButton::Left);
app.update();
let cursor = app
.world()
.get::<CursorOptions>(window)
.expect("unfocused Escape must not close the window");
assert_eq!(cursor.grab_mode, CursorGrabMode::None);
assert!(cursor.visible);
app.world_mut()
.resource_mut::<ButtonInput<KeyCode>>()
.reset_all();
app.world_mut()
.resource_mut::<ButtonInput<MouseButton>>()
.reset_all();
app.world_mut().get_mut::<Window>(window).unwrap().focused = true;
app.update();
assert_eq!(
app.world().get::<CursorOptions>(window).unwrap().grab_mode,
CursorGrabMode::None
);
app.world_mut()
.resource_mut::<ButtonInput<MouseButton>>()
.press(MouseButton::Left);
app.update();
assert_eq!(
app.world().get::<CursorOptions>(window).unwrap().grab_mode,
CursorGrabMode::Locked
);
}
#[test]
fn inactive_primary_window_discards_look_without_replaying_it() {
use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
let (mut app, player) = anchored_app();
let window = app
.world_mut()
.spawn((
Window {
focused: false,
..default()
},
PrimaryWindow,
))
.id();
step(&mut app, Vec2::new(100.0, 20.0), &[KeyCode::KeyQ], 0.1);
assert_eq!(
app.world().get::<Transform>(player).unwrap().rotation,
Quat::IDENTITY
);
assert!(
app.world()
.get::<Player>(player)
.unwrap()
.snap_anim
.is_none()
);
app.world_mut().get_mut::<Window>(window).unwrap().focused = true;
app.world_mut()
.get_mut::<CursorOptions>(window)
.unwrap()
.grab_mode = CursorGrabMode::Locked;
step(&mut app, Vec2::ZERO, &[], 0.1);
assert_eq!(
app.world().get::<Transform>(player).unwrap().rotation,
Quat::IDENTITY
);
step(&mut app, Vec2::new(10.0, 0.0), &[], 0.1);
assert_ne!(
app.world().get::<Transform>(player).unwrap().rotation,
Quat::IDENTITY
);
}
#[test]
fn spawning_player_leaves_cursor_free_until_focused_click() {
use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
let mut app = App::new();
app.init_resource::<PlayerConfig>()
.init_resource::<PlayerHealth>()
.add_systems(Startup, spawn_player);
let window = app
.world_mut()
.spawn((Window::default(), PrimaryWindow))
.id();
app.update();
let cursor = app.world().get::<CursorOptions>(window).unwrap();
assert_eq!(cursor.grab_mode, CursorGrabMode::None);
assert!(cursor.visible);
}
#[test]
fn inactive_movement_clears_velocity_and_preserves_position() {
use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
let mut app = App::new();
app.init_resource::<ButtonInput<KeyCode>>()
.init_resource::<Time>()
.init_resource::<ViewerPosition>()
.init_resource::<ChunkManager>()
.init_resource::<PlayerCrouching>()
.add_systems(Update, player_move::<crate::voxel::DefaultVoxel>);
let window = app
.world_mut()
.spawn((
Window {
focused: false,
..default()
},
PrimaryWindow,
CursorOptions {
grab_mode: CursorGrabMode::Locked,
..default()
},
))
.id();
let player = app
.world_mut()
.spawn((
Player {
velocity: Vec3::Z,
..default()
},
Transform::default(),
))
.id();
app.world_mut()
.resource_mut::<Time>()
.advance_by(std::time::Duration::from_millis(100));
app.world_mut()
.resource_mut::<ButtonInput<KeyCode>>()
.press(KeyCode::KeyW);
app.update();
assert_eq!(
app.world().get::<Transform>(player).unwrap().translation,
Vec3::ZERO
);
assert_eq!(
app.world().get::<Player>(player).unwrap().velocity,
Vec3::ZERO
);
app.world_mut().get_mut::<Window>(window).unwrap().focused = true;
app.world_mut()
.get_mut::<CursorOptions>(window)
.unwrap()
.grab_mode = CursorGrabMode::None;
app.update();
assert_eq!(
app.world().get::<Transform>(player).unwrap().translation,
Vec3::ZERO
);
app.world_mut()
.get_mut::<CursorOptions>(window)
.unwrap()
.grab_mode = CursorGrabMode::Locked;
app.update();
assert!(app.world().get::<Transform>(player).unwrap().translation.z < 0.0);
}
fn step(app: &mut App, mouse: Vec2, held: &[KeyCode], dt: f32) {
app.world_mut()
.resource_mut::<Time>()
.advance_by(std::time::Duration::from_secs_f32(dt));
{
let mut input = app.world_mut().resource_mut::<ButtonInput<KeyCode>>();
input.clear(); let stale: Vec<KeyCode> = input
.get_pressed()
.copied()
.filter(|k| !held.contains(k))
.collect();
for k in stale {
input.release(k);
}
for k in held {
input.press(*k);
} }
if mouse != Vec2::ZERO {
app.world_mut().write_message(MouseMotion { delta: mouse });
}
app.update();
}
fn forward_of(app: &App, entity: Entity) -> Vec3 {
*app.world()
.entity(entity)
.get::<Transform>()
.unwrap()
.forward()
}
#[test]
fn anchored_diagonal_input_keeps_horizon_level() {
let (mut app, e) = anchored_app();
for _ in 0..15 {
step(&mut app, Vec2::new(60.0, -80.0), &[], 0.016);
let right = *app.world().entity(e).get::<Transform>().unwrap().right();
assert!(
right.dot(Vec3::Y).abs() < 1e-4,
"horizon rolled: right·Y = {}",
right.dot(Vec3::Y)
);
}
let elevation = forward_of(&app, e).dot(Vec3::Y).abs();
assert!(
elevation >= 88_f32.to_radians().sin(),
"clamp never engaged: |forward·Y| = {elevation}"
);
assert!(
elevation <= 89_f32.to_radians().sin() + 1e-4,
"pitch exceeded ±89°: |forward·Y| = {elevation}"
);
}
#[test]
fn anchored_switch_yaw_uses_old_anchor() {
let (mut app, e) = anchored_app();
step(&mut app, Vec2::ZERO, &[KeyCode::KeyQ], 0.1);
{
let p = app.world().entity(e).get::<Player>().unwrap();
assert!(p.snap_anim.is_some(), "Q should start a switch animation");
assert!(p.pending_anchor.is_some(), "pending anchor should be set");
assert_eq!(p.anchor_up, Vec3::Y, "anchor must not commit mid-animation");
}
let before = forward_of(&app, e);
step(&mut app, Vec2::new(50.0, 0.0), &[], 0.1);
let p = app.world().entity(e).get::<Player>().unwrap();
assert!(p.snap_anim.is_some(), "animation should still be running");
assert_eq!(
p.anchor_up,
Vec3::Y,
"yaw must not commit the pending anchor"
);
let after = forward_of(&app, e);
assert!(
after.dot(Vec3::Y).abs() < 1e-5,
"yaw left the Y-plane → wrong anchor"
);
assert!(
(after - before).length() > 1e-3,
"yaw had no visible effect"
);
}
#[test]
fn anchored_q_switches_anchor() {
let (mut app, e) = anchored_app();
step(&mut app, Vec2::ZERO, &[KeyCode::KeyQ], 0.1);
let p = app.world().entity(e).get::<Player>().unwrap();
assert!(
p.snap_anim.is_some() && p.pending_anchor.is_some(),
"Continuous roll_mode must be inert in Anchored — Q takes the switch path"
);
}
}