1use bevy::ecs::message::MessageWriter;
122use bevy::input::mouse::MouseMotion;
123use bevy::prelude::*;
124use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
125
126use crate::audio::{SfxEvent, SfxRequest};
127use crate::chunk::{CHUNK_SIZE, Chunk, VOXEL_SIZE, world_to_chunk_coord};
128use crate::voxel::VoxelType;
129use crate::world::{ChunkManager, ViewerPosition, WorldDataDir, get_voxel_at};
130
131pub mod camera_response;
132pub mod effects;
133pub mod persistence;
134
135pub use camera_response::{
136 CameraResponse, CameraResponseConfig, camera_response_apply, camera_response_restore,
137};
138
139#[derive(Message, Debug, Clone)]
143pub struct PlayerDamaged {
144 pub amount: f32,
146}
147
148#[derive(Message, Debug, Clone)]
150pub struct PlayerDied;
151
152#[derive(Resource, Debug, Clone)]
161pub struct PlayerHealth {
162 pub health: f32,
164 pub max_health: f32,
166 pub spawn_position: Vec3,
171 pub fall_safe_speed: f32,
175}
176
177impl Default for PlayerHealth {
178 fn default() -> Self {
179 Self {
180 health: 20.0,
181 max_health: 20.0,
182 spawn_position: Vec3::new(0.0, 30.0, 0.0),
183 fall_safe_speed: 10.0,
184 }
185 }
186}
187
188#[derive(Resource, Default, Debug, Clone, Copy, PartialEq, Eq)]
200pub struct PlayerCrouching(pub bool);
201
202#[derive(Debug, Clone)]
218pub enum PlayerMode {
219 FreeFlightSixDof {
225 roll_mode: RollMode,
227 },
228 FreeFlightAnchored,
231 Grounded {
241 gravity: f32,
246 jump_speed: f32,
251 },
252}
253
254impl Default for PlayerMode {
255 fn default() -> Self {
256 PlayerMode::FreeFlightSixDof {
257 roll_mode: RollMode::Continuous,
258 }
259 }
260}
261
262pub const PLAYER_RADIUS: f32 = 0.6;
270
271pub const PLAYER_HALF_HEIGHT: f32 = 1.8;
278
279pub const CROUCH_HALF_HEIGHT: f32 = PLAYER_HALF_HEIGHT * 0.6;
285
286pub const SPRINT_MULTIPLIER: f32 = 1.6;
292
293const ACCEL: f32 = 12.0;
295
296const DECEL: f32 = 7.0;
298
299#[derive(Resource, Debug, Clone, Copy, PartialEq)]
325pub struct PlayerMovementConfig {
326 pub acceleration: f32,
330 pub deceleration: f32,
335 pub impact_speed_threshold: f32,
339 pub wait_for_chunks: bool,
349}
350
351impl PlayerMovementConfig {
352 pub const DEFAULT_ACCELERATION: f32 = ACCEL;
354 pub const DEFAULT_DECELERATION: f32 = DECEL;
356 pub const DEFAULT_IMPACT_SPEED_THRESHOLD: f32 = 1.0;
358
359 fn acceleration_rate(config: Option<&Self>) -> f32 {
360 config
361 .map(|c| c.acceleration)
362 .filter(|rate| rate.is_finite() && *rate >= 0.0)
363 .unwrap_or(Self::DEFAULT_ACCELERATION)
364 }
365
366 fn deceleration_rate(config: Option<&Self>) -> f32 {
367 config
368 .map(|c| c.deceleration)
369 .filter(|rate| rate.is_finite() && *rate >= 0.0)
370 .unwrap_or(Self::DEFAULT_DECELERATION)
371 }
372
373 fn impact_threshold(config: Option<&Self>) -> f32 {
374 config
375 .map(|c| c.impact_speed_threshold)
376 .unwrap_or(Self::DEFAULT_IMPACT_SPEED_THRESHOLD)
377 }
378}
379
380impl Default for PlayerMovementConfig {
381 fn default() -> Self {
382 Self {
383 acceleration: Self::DEFAULT_ACCELERATION,
384 deceleration: Self::DEFAULT_DECELERATION,
385 impact_speed_threshold: Self::DEFAULT_IMPACT_SPEED_THRESHOLD,
386 wait_for_chunks: false,
387 }
388 }
389}
390
391#[derive(Message, Debug, Clone, Copy, PartialEq)]
401pub struct PlayerImpact {
402 pub position: Vec3,
404 pub normal: Vec3,
406 pub speed: f32,
409}
410
411const MOUSE_SCALE: f32 = 0.003;
420
421#[derive(Default, Copy, Clone, Debug, PartialEq, Eq)]
436pub enum RollMode {
437 #[default]
439 Continuous,
440 Snap,
443}
444
445#[derive(Default, Copy, Clone, Debug, PartialEq, Eq)]
451pub enum SnapRollEasing {
452 #[default]
454 EaseOutCubic,
455 EaseOutQuart,
457 Smoothstep,
459 Linear,
461}
462
463#[derive(Copy, Clone, Debug)]
474pub(crate) struct SnapRollAnim {
475 pub(crate) start_angle: f32,
476 pub(crate) target_angle: f32,
477 pub(crate) elapsed: f32,
478 pub(crate) duration: f32,
479 pub(crate) easing: SnapRollEasing,
480 pub(crate) current_applied: f32,
481}
482
483pub(crate) const SNAP_MIN_PROJ_SQ: f32 = 0.49;
493
494pub(crate) const SNAP_EPS_ON: f32 = 1e-3;
498
499#[derive(Component, Debug, Clone)]
520pub struct Player {
521 pub speed: f32,
525 pub sensitivity: f32,
530 pub roll_speed: f32,
533 pub velocity: Vec3,
537 pub mode: PlayerMode,
542 pub vertical_velocity: f32,
548 pub on_ground: bool,
555 pub(crate) impact_speed: f32,
561 pub(crate) footstep_timer: f32,
566 pub(crate) world_loaded: bool,
573 pub(crate) spawn_immune: bool,
579 pub sprinting: bool,
586 pub crouching: bool,
593 pub snap_roll_duration: f32,
597 pub snap_roll_easing: SnapRollEasing,
600 pub(crate) snap_anim: Option<SnapRollAnim>,
602 pub anchor_up: Vec3,
608 pub(crate) pending_anchor: Option<Vec3>,
611}
612
613impl Default for Player {
614 fn default() -> Self {
615 Self {
616 speed: 4.0,
617 sensitivity: 1.0,
618 roll_speed: 1.5,
619 velocity: Vec3::ZERO,
620 mode: PlayerMode::default(),
621 vertical_velocity: 0.0,
622 on_ground: false,
623 impact_speed: 0.0,
624 footstep_timer: 0.0,
625 world_loaded: false,
626 spawn_immune: true,
627 sprinting: false,
628 crouching: false,
629 snap_roll_duration: 0.5,
630 snap_roll_easing: SnapRollEasing::EaseOutCubic,
631 snap_anim: None,
632 anchor_up: Vec3::Y,
633 pending_anchor: None,
634 }
635 }
636}
637
638#[derive(Resource, Debug, Clone)]
672pub struct PlayerConfig {
673 pub spawn_position: Vec3,
675 pub speed: f32,
678 pub sensitivity: f32,
682 pub roll_speed: f32,
685 pub look_at: Vec3,
689 pub fov_degrees: f32,
694 pub mode: PlayerMode,
699 pub snap_roll_duration_secs: f32,
703 pub snap_roll_easing: SnapRollEasing,
706}
707
708impl Default for PlayerConfig {
709 fn default() -> Self {
710 Self {
711 spawn_position: Vec3::new(0.0, 0.0, 30.0),
712 speed: 4.0,
713 sensitivity: 1.0,
714 roll_speed: 1.5,
715 look_at: Vec3::ZERO,
716 fov_degrees: 90.0,
717 mode: PlayerMode::default(),
718 snap_roll_duration_secs: 0.5,
719 snap_roll_easing: SnapRollEasing::EaseOutCubic,
720 }
721 }
722}
723
724pub fn spawn_player(
739 mut commands: Commands,
740 config: Res<PlayerConfig>,
741 existing: Query<(), With<Player>>,
742 mut health: ResMut<PlayerHealth>,
743 viewer: Option<ResMut<ViewerPosition>>,
744) {
745 if !existing.is_empty() {
746 return;
747 }
748
749 if let Some(mut viewer) = viewer {
752 viewer.position = config.spawn_position;
753 }
754
755 health.spawn_position = config.spawn_position;
757
758 let spawn = config.spawn_position;
759 let look_at = config.look_at;
760 let fov = config.fov_degrees.to_radians();
761 let mode = config.mode.clone();
762
763 let transform = Transform::from_translation(spawn).looking_at(look_at, Vec3::Y);
766
767 commands.spawn((
768 Player {
769 speed: config.speed,
770 sensitivity: config.sensitivity,
771 roll_speed: config.roll_speed,
772 velocity: Vec3::ZERO,
773 mode,
774 vertical_velocity: 0.0,
775 on_ground: false,
776 impact_speed: 0.0,
777 footstep_timer: 0.0,
778 world_loaded: false,
779 spawn_immune: true,
780 sprinting: false,
781 crouching: false,
782 snap_roll_duration: config.snap_roll_duration_secs,
783 snap_roll_easing: config.snap_roll_easing,
784 snap_anim: None,
785 anchor_up: nearest_world_axis(*transform.up()),
786 pending_anchor: None,
787 },
788 Camera3d::default(),
789 Projection::Perspective(PerspectiveProjection { fov, ..default() }),
790 transform,
791 ));
792}
793
794pub(crate) fn apply_easing(t: f32, easing: SnapRollEasing) -> f32 {
797 match easing {
798 SnapRollEasing::EaseOutCubic => 1.0 - (1.0 - t).powi(3),
799 SnapRollEasing::EaseOutQuart => 1.0 - (1.0 - t).powi(4),
800 SnapRollEasing::Smoothstep => t * t * (3.0 - 2.0 * t),
801 SnapRollEasing::Linear => t,
802 }
803}
804
805pub(crate) const AXES: [Vec3; 6] = [
811 Vec3::X,
812 Vec3::NEG_X,
813 Vec3::Y,
814 Vec3::NEG_Y,
815 Vec3::Z,
816 Vec3::NEG_Z,
817];
818
819pub(crate) fn world_lattice_candidates(local_z: Vec3, up: Vec3) -> Vec<(f32, Vec3)> {
830 let mut candidates = Vec::with_capacity(6);
831 for axis in AXES {
832 let proj = axis - axis.dot(local_z) * local_z;
833 if proj.length_squared() < SNAP_MIN_PROJ_SQ {
834 continue;
835 }
836 let c = proj.normalize();
837 candidates.push((up.cross(c).dot(local_z).atan2(up.dot(c)), axis));
838 }
839 candidates
840}
841
842pub(crate) fn world_lattice_angles(local_z: Vec3, up: Vec3) -> Vec<f32> {
848 world_lattice_candidates(local_z, up)
849 .into_iter()
850 .map(|(a, _)| a)
851 .collect()
852}
853
854pub(crate) fn next_lattice_step(angles: &[f32], dir: i32) -> f32 {
861 use std::f32::consts::TAU;
862 if dir > 0 {
863 angles
864 .iter()
865 .map(|&d| if d > SNAP_EPS_ON { d } else { d + TAU })
866 .fold(f32::INFINITY, f32::min)
867 } else {
868 angles
869 .iter()
870 .map(|&d| if d < -SNAP_EPS_ON { d } else { d - TAU })
871 .fold(f32::NEG_INFINITY, f32::max)
872 }
873}
874
875pub(crate) fn next_lattice_candidate(cands: &[(f32, Vec3)], dir: i32) -> (f32, Vec3) {
883 use std::f32::consts::TAU;
884 assert!(
885 !cands.is_empty(),
886 "next_lattice_candidate: empty candidate slice — SNAP_MIN_PROJ_SQ \
887 guarantees at least 4 lattice candidates"
888 );
889 if dir > 0 {
890 cands
891 .iter()
892 .map(|&(d, axis)| (if d > SNAP_EPS_ON { d } else { d + TAU }, axis))
893 .min_by(|a, b| a.0.total_cmp(&b.0))
894 .unwrap()
895 } else {
896 cands
897 .iter()
898 .map(|&(d, axis)| (if d < -SNAP_EPS_ON { d } else { d - TAU }, axis))
899 .max_by(|a, b| a.0.total_cmp(&b.0))
900 .unwrap()
901 }
902}
903
904pub(crate) fn start_or_retarget_snap(
926 existing: Option<SnapRollAnim>,
927 local_z: Vec3,
928 up: Vec3,
929 dir: i32,
930 duration: f32,
931 easing: SnapRollEasing,
932) -> SnapRollAnim {
933 match existing {
934 None => {
935 let step = next_lattice_step(&world_lattice_angles(local_z, up), dir);
936 SnapRollAnim {
937 start_angle: 0.0,
938 target_angle: step,
939 elapsed: 0.0,
940 duration,
941 easing,
942 current_applied: 0.0,
943 }
944 }
945 Some(anim) => {
946 let same_dir = (dir > 0 && anim.target_angle > anim.start_angle)
947 || (dir < 0 && anim.target_angle < anim.start_angle);
948
949 if same_dir {
950 let residual = anim.target_angle - anim.current_applied;
953 let ref_up = Quat::from_axis_angle(local_z, residual) * up;
954 let step = next_lattice_step(&world_lattice_angles(local_z, ref_up), dir);
955 SnapRollAnim {
956 start_angle: anim.current_applied,
957 target_angle: anim.target_angle + step,
958 elapsed: 0.0,
959 duration,
960 easing,
961 current_applied: anim.current_applied,
962 }
963 } else {
964 let step = next_lattice_step(&world_lattice_angles(local_z, up), dir);
966 SnapRollAnim {
967 start_angle: anim.current_applied,
968 target_angle: anim.current_applied + step,
969 elapsed: 0.0,
970 duration,
971 easing,
972 current_applied: anim.current_applied,
973 }
974 }
975 }
976 }
977}
978
979pub(crate) fn snap_reference_up(
987 existing: Option<SnapRollAnim>,
988 local_z: Vec3,
989 up: Vec3,
990 dir: i32,
991) -> Vec3 {
992 match existing {
993 Some(anim) => {
994 let same_dir = (dir > 0 && anim.target_angle > anim.start_angle)
995 || (dir < 0 && anim.target_angle < anim.start_angle);
996 if same_dir {
997 let residual = anim.target_angle - anim.current_applied;
998 Quat::from_axis_angle(local_z, residual) * up
999 } else {
1000 up
1001 }
1002 }
1003 None => up,
1004 }
1005}
1006
1007pub(crate) fn clamp_pitch_delta(forward: Vec3, anchor_up: Vec3, pitch_d: f32) -> f32 {
1015 let limit = 89_f32.to_radians();
1016 let pitch = forward.dot(anchor_up).clamp(-1.0, 1.0).asin();
1017 (pitch + pitch_d).clamp(-limit, limit) - pitch
1018}
1019
1020pub(crate) fn nearest_world_axis(v: Vec3) -> Vec3 {
1027 let mut best = AXES[0];
1028 let mut best_dot = v.dot(AXES[0]);
1029 for axis in AXES.into_iter().skip(1) {
1030 let d = v.dot(axis);
1031 if d > best_dot {
1032 best = axis;
1033 best_dot = d;
1034 }
1035 }
1036 best
1037}
1038
1039pub(crate) fn advance_snap(anim: &mut SnapRollAnim, dt: f32) -> (f32, bool) {
1040 anim.elapsed += dt;
1041 let t = (anim.elapsed / anim.duration).clamp(0.0, 1.0);
1042 let eased = apply_easing(t, anim.easing);
1043 let total = anim.start_angle + (anim.target_angle - anim.start_angle) * eased;
1044 let delta = total - anim.current_applied;
1045 anim.current_applied = total;
1046 let finished = anim.elapsed >= anim.duration;
1047 if finished {
1048 let correction = anim.target_angle - anim.current_applied;
1050 anim.current_applied = anim.target_angle;
1051 return (delta + correction, true);
1052 }
1053 (delta, false)
1054}
1055
1056pub fn player_look(
1073 mut query: Query<(&mut Player, &mut Transform)>,
1074 mut mouse_motion: MessageReader<MouseMotion>,
1075 keys: Res<ButtonInput<KeyCode>>,
1076 time: Res<Time>,
1077 windows: Query<(&Window, &CursorOptions), With<PrimaryWindow>>,
1078) {
1079 if !player_input_active(windows) {
1080 mouse_motion.clear();
1081 return;
1082 }
1083 let Ok((mut player, mut transform)) = query.single_mut() else {
1084 return;
1085 };
1086
1087 let mut delta = Vec2::ZERO;
1089 for event in mouse_motion.read() {
1090 delta += event.delta;
1091 }
1092
1093 match &player.mode {
1094 PlayerMode::FreeFlightSixDof { roll_mode } => {
1095 if delta != Vec2::ZERO {
1096 let yaw_d = -delta.x * MOUSE_SCALE * player.sensitivity;
1097 let pitch_d = -delta.y * MOUSE_SCALE * player.sensitivity;
1098 transform.rotate_local_y(yaw_d);
1100 transform.rotate_local_x(pitch_d);
1101 }
1102
1103 match roll_mode {
1105 RollMode::Continuous => {
1106 let mut roll = 0.0_f32;
1107 if keys.pressed(KeyCode::KeyQ) {
1108 roll += 1.0;
1109 }
1110 if keys.pressed(KeyCode::KeyE) {
1111 roll -= 1.0;
1112 }
1113 if roll != 0.0 {
1114 transform.rotate_local_z(roll * player.roll_speed * time.delta_secs());
1115 }
1116 }
1117 RollMode::Snap => {
1118 if keys.just_pressed(KeyCode::KeyQ) {
1119 player.snap_anim = Some(start_or_retarget_snap(
1120 player.snap_anim,
1121 *transform.local_z(),
1122 *transform.up(),
1123 1,
1124 player.snap_roll_duration,
1125 player.snap_roll_easing,
1126 ));
1127 }
1128 if keys.just_pressed(KeyCode::KeyE) {
1129 player.snap_anim = Some(start_or_retarget_snap(
1130 player.snap_anim,
1131 *transform.local_z(),
1132 *transform.up(),
1133 -1,
1134 player.snap_roll_duration,
1135 player.snap_roll_easing,
1136 ));
1137 }
1138 if let Some(ref mut anim) = player.snap_anim {
1139 let (delta, finished) = advance_snap(anim, time.delta_secs());
1140 transform.rotate_local_z(delta);
1141 if finished {
1142 player.snap_anim = None;
1143 }
1144 }
1145 }
1146 }
1147 }
1148 PlayerMode::FreeFlightAnchored => {
1149 if delta != Vec2::ZERO {
1150 let yaw_d = -delta.x * MOUSE_SCALE * player.sensitivity;
1151 let pitch_d = -delta.y * MOUSE_SCALE * player.sensitivity;
1152 transform.rotate(Quat::from_axis_angle(player.anchor_up, yaw_d));
1156 let clamped = clamp_pitch_delta(*transform.forward(), player.anchor_up, pitch_d);
1159 transform.rotate_local_x(clamped);
1160 }
1161
1162 if keys.just_pressed(KeyCode::KeyQ) {
1165 let local_z = *transform.local_z();
1166 let up = *transform.up();
1167 let ref_up = snap_reference_up(player.snap_anim, local_z, up, 1);
1168 let (_, axis) =
1169 next_lattice_candidate(&world_lattice_candidates(local_z, ref_up), 1);
1170 player.pending_anchor = Some(axis);
1171 player.snap_anim = Some(start_or_retarget_snap(
1172 player.snap_anim,
1173 local_z,
1174 up,
1175 1,
1176 player.snap_roll_duration,
1177 player.snap_roll_easing,
1178 ));
1179 }
1180 if keys.just_pressed(KeyCode::KeyE) {
1181 let local_z = *transform.local_z();
1182 let up = *transform.up();
1183 let ref_up = snap_reference_up(player.snap_anim, local_z, up, -1);
1184 let (_, axis) =
1185 next_lattice_candidate(&world_lattice_candidates(local_z, ref_up), -1);
1186 player.pending_anchor = Some(axis);
1187 player.snap_anim = Some(start_or_retarget_snap(
1188 player.snap_anim,
1189 local_z,
1190 up,
1191 -1,
1192 player.snap_roll_duration,
1193 player.snap_roll_easing,
1194 ));
1195 }
1196 if let Some(ref mut anim) = player.snap_anim {
1197 let (delta, finished) = advance_snap(anim, time.delta_secs());
1198 transform.rotate_local_z(delta);
1199 if finished {
1200 if let Some(anchor) = player.pending_anchor.take() {
1205 player.anchor_up = anchor;
1206 }
1207 let fwd = *transform.forward();
1208 transform.look_to(fwd, player.anchor_up);
1209 player.snap_anim = None;
1210 }
1211 }
1212 }
1213 PlayerMode::Grounded { .. } => {
1214 if delta != Vec2::ZERO {
1215 let yaw_d = -delta.x * MOUSE_SCALE * player.sensitivity;
1216 let pitch_d = -delta.y * MOUSE_SCALE * player.sensitivity;
1217
1218 transform.rotate_y(yaw_d);
1220
1221 let (yaw, pitch, _roll) = transform.rotation.to_euler(EulerRot::YXZ);
1223 let new_pitch = (pitch + pitch_d).clamp(-89_f32.to_radians(), 89_f32.to_radians());
1224 transform.rotation = Quat::from_euler(EulerRot::YXZ, yaw, new_pitch, 0.0);
1225 }
1226 }
1228 }
1229}
1230
1231pub fn player_move<V: VoxelType>(
1254 mut query: Query<(&mut Player, &mut Transform)>,
1255 keys: Res<ButtonInput<KeyCode>>,
1256 time: Res<Time>,
1257 mut viewer: ResMut<ViewerPosition>,
1258 manager: Res<ChunkManager>,
1259 chunks: Query<&Chunk<V>>,
1260 mut crouch_res: ResMut<PlayerCrouching>,
1261 applied: Option<Res<effects::AppliedEffectModifiers>>,
1262 windows: Query<(&Window, &CursorOptions), With<PrimaryWindow>>,
1263 movement: Option<Res<PlayerMovementConfig>>,
1264) {
1265 let Ok((mut player, mut transform)) = query.single_mut() else {
1266 return;
1267 };
1268
1269 if !player_input_active(windows) {
1270 player.velocity = Vec3::ZERO;
1271 return;
1272 }
1273 let dt = time.delta_secs();
1274 let accel = PlayerMovementConfig::acceleration_rate(movement.as_deref());
1275 let decel = PlayerMovementConfig::deceleration_rate(movement.as_deref());
1276 let wait_for_chunks = movement.as_deref().is_some_and(|m| m.wait_for_chunks);
1277 let start = transform.translation;
1278
1279 match player.mode.clone() {
1280 PlayerMode::FreeFlightSixDof { .. } | PlayerMode::FreeFlightAnchored => {
1281 player.sprinting = false;
1283 player.crouching = false;
1284 crouch_res.0 = false;
1285
1286 let forward = transform.rotation * Vec3::NEG_Z;
1288 let right = transform.rotation * Vec3::X;
1289 let up = transform.rotation * Vec3::Y;
1290
1291 let mut direction = Vec3::ZERO;
1292 if keys.pressed(KeyCode::KeyW) {
1293 direction += forward;
1294 }
1295 if keys.pressed(KeyCode::KeyS) {
1296 direction -= forward;
1297 }
1298 if keys.pressed(KeyCode::KeyA) {
1299 direction -= right;
1300 }
1301 if keys.pressed(KeyCode::KeyD) {
1302 direction += right;
1303 }
1304 if keys.pressed(KeyCode::Space) {
1305 direction += up;
1306 }
1307 if keys.pressed(KeyCode::ShiftLeft) || keys.pressed(KeyCode::ShiftRight) {
1308 direction -= up;
1309 }
1310
1311 let target = if direction != Vec3::ZERO {
1312 direction.normalize() * player.speed
1313 } else {
1314 Vec3::ZERO
1315 };
1316
1317 let factor = if direction != Vec3::ZERO {
1318 accel
1319 } else {
1320 decel
1321 };
1322 player.velocity = player.velocity.lerp(target, (factor * dt).min(1.0));
1323 transform.translation += player.velocity * dt;
1324 }
1325 PlayerMode::Grounded {
1326 gravity,
1327 jump_speed,
1328 } => {
1329 let yaw = transform.rotation.to_euler(EulerRot::YXZ).0;
1331 let forward = Vec3::new(-yaw.sin(), 0.0, -yaw.cos());
1332 let right = Vec3::new(yaw.cos(), 0.0, -yaw.sin());
1333
1334 let mut h_dir = Vec3::ZERO;
1335 if keys.pressed(KeyCode::KeyW) {
1336 h_dir += forward;
1337 }
1338 if keys.pressed(KeyCode::KeyS) {
1339 h_dir -= forward;
1340 }
1341 if keys.pressed(KeyCode::KeyA) {
1342 h_dir -= right;
1343 }
1344 if keys.pressed(KeyCode::KeyD) {
1345 h_dir += right;
1346 }
1347
1348 let crouching =
1352 keys.pressed(KeyCode::ControlLeft) || keys.pressed(KeyCode::ControlRight);
1353 let sprinting = !crouching
1354 && player.on_ground
1355 && (keys.pressed(KeyCode::ShiftLeft) || keys.pressed(KeyCode::ShiftRight));
1356 player.crouching = crouching;
1357 player.sprinting = sprinting;
1358 crouch_res.0 = crouching;
1359 let speed_mult = if crouching {
1360 0.5
1361 } else if sprinting {
1362 SPRINT_MULTIPLIER
1363 } else {
1364 1.0
1365 };
1366
1367 let foot_pos = transform.translation - Vec3::Y * (PLAYER_HALF_HEIGHT + 0.3);
1369 let modifier = get_voxel_at::<V>(foot_pos, &manager, &chunks)
1370 .map(|v| v.movement_modifier())
1371 .unwrap_or_default();
1372
1373 let effect_speed = applied.as_deref().map(|a| a.0.speed_mult).unwrap_or(1.0);
1374 let h_target = if h_dir != Vec3::ZERO {
1375 h_dir.normalize() * player.speed * speed_mult * modifier.speed_mult * effect_speed
1376 } else {
1377 Vec3::ZERO
1378 };
1379
1380 let effective_decel = decel * modifier.friction_mult;
1381 let factor = if h_dir != Vec3::ZERO {
1382 accel
1383 } else {
1384 effective_decel
1385 };
1386 player.velocity = player.velocity.lerp(h_target, (factor * dt).min(1.0));
1387
1388 if !player.world_loaded {
1391 player.vertical_velocity = 0.0;
1392 transform.translation += player.velocity * dt;
1393 if wait_for_chunks && !player_chunks_loaded(transform.translation, &manager) {
1394 transform.translation = start;
1395 }
1396 viewer.position = transform.translation;
1397 return;
1398 }
1399
1400 if keys.just_pressed(KeyCode::Space) && player.on_ground && !crouching {
1402 let effect_jump = applied.as_deref().map(|a| a.0.jump_mult).unwrap_or(1.0);
1403 player.vertical_velocity = jump_speed * modifier.jump_mult * effect_jump;
1404 }
1405
1406 player.vertical_velocity -= gravity * modifier.gravity_mult * dt;
1408
1409 let center_voxel = get_voxel_at::<V>(transform.translation, &manager, &chunks);
1414 if center_voxel.map(|v| v.alpha() < 1.0).unwrap_or(false) {
1415 player.vertical_velocity += jump_speed * 0.3 * dt;
1416 }
1417
1418 transform.translation += player.velocity * dt;
1420 transform.translation.y += player.vertical_velocity * dt;
1421 }
1422 }
1423
1424 if wait_for_chunks && !player_chunks_loaded(transform.translation, &manager) {
1427 transform.translation = start;
1428 player.vertical_velocity = 0.0;
1430 }
1431
1432 viewer.position = transform.translation;
1434}
1435
1436pub fn player_resolve_collision<V: VoxelType>(
1461 mut player_q: Query<(&mut Player, &mut Transform)>,
1462 chunk_q: Query<(&Chunk<V>, &Transform), Without<Player>>,
1463 manager: Res<ChunkManager>,
1464 movement: Option<Res<PlayerMovementConfig>>,
1465 impacts: Option<ResMut<Messages<PlayerImpact>>>,
1466 mut was_impacting: Local<bool>,
1467) {
1468 let Ok((mut player, mut player_tf)) = player_q.single_mut() else {
1469 return;
1470 };
1471
1472 let is_grounded = matches!(player.mode, PlayerMode::Grounded { .. });
1474 let incoming_velocity = if is_grounded {
1476 player.velocity + Vec3::Y * player.vertical_velocity
1477 } else {
1478 player.velocity
1479 };
1480 let start_pos = player_tf.translation;
1481 if is_grounded {
1482 player.on_ground = false;
1483 player.impact_speed = 0.0; }
1485
1486 let half_height = if player.crouching {
1489 CROUCH_HALF_HEIGHT
1490 } else {
1491 PLAYER_HALF_HEIGHT
1492 };
1493
1494 if !player.world_loaded {
1499 let feet = player_tf.translation - Vec3::Y * half_height;
1500 let coord = crate::chunk::world_to_chunk_coord(feet);
1501 if manager.is_loaded(coord) {
1502 player.world_loaded = true;
1503 }
1504 }
1505
1506 let mut pos = player_tf.translation;
1507 let up = if is_grounded {
1510 Vec3::Y
1511 } else {
1512 player_tf.rotation * Vec3::Y
1513 };
1514
1515 let extent = half_height + PLAYER_RADIUS;
1516 let voxel_size = VOXEL_SIZE;
1517
1518 for (chunk, chunk_tf) in &chunk_q {
1519 let chunk_pos = chunk_tf.translation;
1520 let local = pos - chunk_pos;
1521
1522 let min_vox = IVec3::new(
1524 ((local.x - extent) / voxel_size).floor() as i32,
1525 ((local.y - extent) / voxel_size).floor() as i32,
1526 ((local.z - extent) / voxel_size).floor() as i32,
1527 );
1528 let max_vox = IVec3::new(
1529 ((local.x + extent) / voxel_size).ceil() as i32,
1530 ((local.y + extent) / voxel_size).ceil() as i32,
1531 ((local.z + extent) / voxel_size).ceil() as i32,
1532 );
1533
1534 let lo = min_vox.max(IVec3::ZERO);
1537 let hi = max_vox.min(IVec3::splat(CHUNK_SIZE as i32 - 1));
1538
1539 for vx in lo.x..=hi.x {
1540 for vy in lo.y..=hi.y {
1541 for vz in lo.z..=hi.z {
1542 if !chunk.is_solid_at(vx as usize, vy as usize, vz as usize) {
1543 continue;
1544 }
1545 let new_pos = push_capsule_out(pos, up, half_height, chunk_pos, vx, vy, vz);
1546
1547 if is_grounded && new_pos.y > pos.y + 0.001 {
1550 if !player.on_ground {
1551 player.impact_speed = player.vertical_velocity.abs();
1553 }
1554 player.on_ground = true;
1555 player.vertical_velocity = 0.0;
1556 }
1557
1558 pos = new_pos;
1559 }
1560 }
1561 }
1562 }
1563
1564 player_tf.translation = pos;
1565
1566 let push = pos - start_pos;
1569 let speed_into_surface = push
1570 .try_normalize()
1571 .map(|normal| (normal, (-incoming_velocity.dot(normal)).max(0.0)));
1572 let threshold = PlayerMovementConfig::impact_threshold(movement.as_deref());
1573 let is_impacting = speed_into_surface.is_some_and(|(_, speed)| speed > threshold);
1574 if is_impacting
1575 && !*was_impacting
1576 && let Some((normal, speed)) = speed_into_surface
1577 && let Some(mut impacts) = impacts
1578 {
1579 impacts.write(PlayerImpact {
1580 position: pos,
1581 normal,
1582 speed,
1583 });
1584 }
1585 *was_impacting = is_impacting;
1586}
1587
1588pub fn player_cursor_system(
1609 mut commands: Commands,
1610 mouse: Res<ButtonInput<MouseButton>>,
1611 keys: Res<ButtonInput<KeyCode>>,
1612 mut windows: Query<(Entity, &Window, &mut CursorOptions), With<PrimaryWindow>>,
1613 pause: Option<Res<State<crate::ui::PauseMenuState>>>,
1614) {
1615 use crate::ui::PauseMenuState;
1616
1617 let pause_menu_installed = pause.is_some();
1618 let menu_open = pause.is_some_and(|state| !matches!(state.get(), PauseMenuState::Playing));
1619
1620 for (entity, window, mut cursor) in windows.iter_mut() {
1621 if !window.focused {
1622 if cursor.grab_mode != CursorGrabMode::None || !cursor.visible {
1623 cursor.grab_mode = CursorGrabMode::None;
1624 cursor.visible = true;
1625 }
1626 continue;
1627 }
1628 if menu_open {
1629 continue;
1631 }
1632 if mouse.just_pressed(MouseButton::Left)
1633 && cursor.grab_mode == bevy::window::CursorGrabMode::None
1634 {
1635 cursor.grab_mode = bevy::window::CursorGrabMode::Locked;
1636 cursor.visible = false;
1637 }
1638
1639 if !pause_menu_installed && keys.just_pressed(KeyCode::Escape) {
1641 if cursor.grab_mode != bevy::window::CursorGrabMode::None {
1642 cursor.grab_mode = bevy::window::CursorGrabMode::None;
1643 cursor.visible = true;
1644 } else {
1645 commands.entity(entity).despawn();
1646 }
1647 }
1648 }
1649}
1650
1651pub fn player_input_active(windows: Query<(&Window, &CursorOptions), With<PrimaryWindow>>) -> bool {
1658 match windows.single() {
1659 Ok((window, cursor)) => window.focused && cursor.grab_mode != CursorGrabMode::None,
1660 Err(_) => windows.is_empty(),
1661 }
1662}
1663
1664pub fn player_fall_damage(
1673 mut player_q: Query<(&mut Player, &mut Transform)>,
1674 mut health: ResMut<PlayerHealth>,
1675 mut damaged_writer: MessageWriter<PlayerDamaged>,
1676 mut died_writer: MessageWriter<PlayerDied>,
1677) {
1678 let Ok((mut player, mut transform)) = player_q.single_mut() else {
1679 return;
1680 };
1681
1682 if player.impact_speed <= 0.0 {
1683 return;
1684 }
1685
1686 if player.spawn_immune {
1690 player.spawn_immune = false;
1691 player.impact_speed = 0.0;
1692 return;
1693 }
1694
1695 let damage = (player.impact_speed - health.fall_safe_speed).max(0.0) * 2.0;
1696 player.impact_speed = 0.0;
1697
1698 if damage <= 0.0 {
1699 return;
1700 }
1701
1702 health.health = (health.health - damage).max(0.0);
1703 damaged_writer.write(PlayerDamaged { amount: damage });
1704
1705 if health.health <= 0.0 {
1706 health.health = health.max_health;
1707 transform.translation = health.spawn_position;
1708 player.vertical_velocity = 0.0;
1710 player.velocity = Vec3::ZERO;
1711 player.world_loaded = false; player.spawn_immune = true; died_writer.write(PlayerDied);
1714 }
1715}
1716
1717pub fn health_system(
1728 applied: Option<Res<effects::AppliedEffectModifiers>>,
1729 mut health: ResMut<PlayerHealth>,
1730 mut damaged_reader: bevy::ecs::message::MessageReader<PlayerDamaged>,
1731 mut died_writer: MessageWriter<PlayerDied>,
1732) {
1733 for event in damaged_reader.read() {
1735 let resistance = applied
1736 .as_ref()
1737 .map(|a| a.0.damage_resistance)
1738 .unwrap_or(0.0);
1739 let actual = event.amount * (1.0 - resistance.clamp(0.0, 1.0));
1740 health.health = (health.health - actual).max(0.0);
1741 }
1742
1743 if health.health <= 0.0 {
1745 health.health = health.max_health;
1746 died_writer.write(PlayerDied);
1747 }
1748}
1749
1750pub fn respawn_system(
1760 mut died_reader: bevy::ecs::message::MessageReader<PlayerDied>,
1761 mut viewer: ResMut<ViewerPosition>,
1762 config: Option<Res<PlayerConfig>>,
1763) {
1764 for _ in died_reader.read() {
1765 let spawn = config
1766 .as_ref()
1767 .map(|c| c.spawn_position)
1768 .unwrap_or(Vec3::ZERO);
1769 viewer.position = spawn;
1770 }
1771}
1772
1773fn push_capsule_out(
1792 pos: Vec3,
1793 up: Vec3,
1794 half_height: f32,
1795 chunk_pos: Vec3,
1796 vx: i32,
1797 vy: i32,
1798 vz: i32,
1799) -> Vec3 {
1800 let vmin = chunk_pos + Vec3::new(vx as f32, vy as f32, vz as f32) * VOXEL_SIZE;
1801 let vmax = vmin + Vec3::splat(VOXEL_SIZE);
1802
1803 let p0 = pos - up * half_height;
1805 let p1 = pos + up * half_height;
1806 let spine = p1 - p0;
1807
1808 let vox_center = (vmin + vmax) * 0.5;
1810 let len_sq = spine.length_squared();
1811 let sphere_c = if len_sq > f32::EPSILON {
1812 let t = ((vox_center - p0).dot(spine) / len_sq).clamp(0.0, 1.0);
1813 p0 + spine * t
1814 } else {
1815 pos
1816 };
1817
1818 let closest = sphere_c.clamp(vmin, vmax);
1820 let diff = sphere_c - closest;
1821 let dist_sq = diff.length_squared();
1822
1823 if dist_sq >= PLAYER_RADIUS * PLAYER_RADIUS {
1824 return pos;
1825 }
1826
1827 let delta = if dist_sq > f32::EPSILON {
1828 let dist = dist_sq.sqrt();
1829 (diff / dist) * (PLAYER_RADIUS - dist)
1830 } else {
1831 let rel = sphere_c - vox_center;
1833 let abs_rel = rel.abs();
1834 let half = VOXEL_SIZE * 0.5 + PLAYER_RADIUS;
1835 if abs_rel.x >= abs_rel.y && abs_rel.x >= abs_rel.z {
1836 Vec3::new(half * rel.x.signum() - rel.x, 0.0, 0.0)
1837 } else if abs_rel.y >= abs_rel.z {
1838 Vec3::new(0.0, half * rel.y.signum() - rel.y, 0.0)
1839 } else {
1840 Vec3::new(0.0, 0.0, half * rel.z.signum() - rel.z)
1841 }
1842 };
1843
1844 pos + delta
1845}
1846
1847pub fn player_footstep_system<V: VoxelType>(
1853 mut query: Query<(&mut Player, &Transform)>,
1854 time: Res<Time>,
1855 manager: Res<ChunkManager>,
1856 chunks: Query<&Chunk<V>>,
1857 mut sfx: MessageWriter<SfxRequest>,
1858) {
1859 let Ok((mut player, transform)) = query.single_mut() else {
1860 return;
1861 };
1862
1863 if !matches!(player.mode, PlayerMode::Grounded { .. }) || !player.on_ground {
1864 return;
1865 }
1866
1867 let h_speed = Vec3::new(player.velocity.x, 0.0, player.velocity.z).length();
1868 if h_speed < 0.5 {
1869 player.footstep_timer = 0.0;
1870 return;
1871 }
1872
1873 let step_interval = (0.5 / h_speed).clamp(0.2, 0.5);
1875 player.footstep_timer += time.delta_secs();
1876
1877 if player.footstep_timer < step_interval {
1878 return;
1879 }
1880 player.footstep_timer = 0.0;
1881
1882 let foot_pos = transform.translation - Vec3::Y * (PLAYER_HALF_HEIGHT + 0.3);
1884 let voxel_byte = get_voxel_at::<V>(foot_pos, &manager, &chunks)
1885 .map(|v| v.to_byte())
1886 .unwrap_or(0);
1887
1888 sfx.write(SfxRequest {
1889 event: SfxEvent::Footstep(voxel_byte),
1890 position: None,
1891 });
1892}
1893
1894fn load_spawn_on_startup(
1903 mut config: ResMut<PlayerConfig>,
1904 mut health: ResMut<PlayerHealth>,
1905 world_data_dir: Res<WorldDataDir>,
1906) {
1907 let data_dir = world_data_dir.as_str();
1908 if let Some(pos) = persistence::load_spawn_position(data_dir) {
1909 config.spawn_position = pos;
1910 health.spawn_position = pos;
1911 } else {
1912 persistence::save_spawn_position(config.spawn_position, data_dir);
1914 }
1915}
1916
1917fn save_spawn_on_exit(
1923 health: Res<PlayerHealth>,
1924 world_data_dir: Res<WorldDataDir>,
1925 mut exit_reader: bevy::ecs::message::MessageReader<AppExit>,
1926) {
1927 for _ in exit_reader.read() {
1928 persistence::save_spawn_position(health.spawn_position, world_data_dir.as_str());
1929 }
1930}
1931
1932pub fn player_chunks_loaded(position: Vec3, manager: &ChunkManager) -> bool {
1945 let extent = Vec3::splat(PLAYER_HALF_HEIGHT + PLAYER_RADIUS);
1946 let min = world_to_chunk_coord(position - extent);
1947 let max = world_to_chunk_coord(position + extent);
1948 (min.x..=max.x).all(|x| {
1949 (min.y..=max.y).all(|y| (min.z..=max.z).all(|z| manager.is_loaded(IVec3::new(x, y, z))))
1950 })
1951}
1952
1953pub fn player_sync_viewer(
1966 player: Query<&Transform, With<Player>>,
1967 viewer: Option<ResMut<ViewerPosition>>,
1968) {
1969 let (Ok(transform), Some(mut viewer)) = (player.single(), viewer) else {
1970 return;
1971 };
1972 if viewer.position != transform.translation {
1974 viewer.position = transform.translation;
1975 }
1976}
1977
1978fn gameplay_active(state: Option<Res<bevy::prelude::State<crate::ui::PauseMenuState>>>) -> bool {
1985 use crate::ui::PauseMenuState;
1986 state.map_or(true, |s| matches!(s.get(), PauseMenuState::Playing))
1987}
1988
1989#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
2010pub struct PlayerSystems;
2011
2012pub struct PlayerPlugin<V: VoxelType> {
2066 _marker: std::marker::PhantomData<V>,
2067 world_name: String,
2068}
2069
2070impl<V: VoxelType> PlayerPlugin<V> {
2071 pub fn new() -> Self {
2073 Self {
2074 _marker: std::marker::PhantomData,
2075 world_name: String::new(),
2076 }
2077 }
2078
2079 pub fn with_world(world_name: impl Into<String>) -> Self {
2082 Self {
2083 _marker: std::marker::PhantomData,
2084 world_name: world_name.into(),
2085 }
2086 }
2087}
2088
2089impl<V: VoxelType> Default for PlayerPlugin<V> {
2090 fn default() -> Self {
2091 Self::new()
2092 }
2093}
2094
2095impl<V: VoxelType> Plugin for PlayerPlugin<V> {
2096 fn build(&self, app: &mut App) {
2097 let name = if self.world_name.is_empty() {
2098 "world"
2099 } else {
2100 &self.world_name
2101 };
2102 app.insert_resource(WorldDataDir::for_world(name));
2103 app.init_resource::<PlayerConfig>();
2104 app.init_resource::<PlayerHealth>();
2105 app.init_resource::<PlayerCrouching>();
2106 app.add_message::<PlayerDamaged>();
2107 app.add_message::<PlayerDied>();
2108 app.init_resource::<PlayerMovementConfig>();
2109 app.add_message::<PlayerImpact>();
2110 app.add_message::<SfxRequest>();
2113 app.init_resource::<CameraResponseConfig>();
2114 app.add_systems(Startup, (load_spawn_on_startup, spawn_player).chain());
2115 app.add_systems(
2116 Update,
2117 (
2118 camera_response_restore,
2119 player_look,
2120 player_move::<V>,
2121 player_resolve_collision::<V>,
2122 player_fall_damage,
2123 player_footstep_system::<V>,
2124 )
2125 .chain()
2126 .run_if(gameplay_active)
2127 .in_set(PlayerSystems),
2128 );
2129 app.add_systems(
2131 Update,
2132 (health_system, respawn_system).in_set(PlayerSystems),
2133 );
2134 app.add_systems(
2135 Update,
2136 player_cursor_system
2139 .before(player_look)
2140 .in_set(PlayerSystems),
2141 );
2142 app.add_systems(
2143 Update,
2144 camera_response_apply
2148 .after(player_footstep_system::<V>)
2149 .in_set(PlayerSystems),
2150 );
2151 app.add_systems(
2152 Update,
2153 player_sync_viewer
2156 .after(player_resolve_collision::<V>)
2157 .before(crate::world::systems::streaming_system)
2158 .in_set(PlayerSystems),
2159 );
2160 app.add_systems(PostUpdate, save_spawn_on_exit);
2161 }
2162}
2163
2164#[cfg(test)]
2167mod tests {
2168 use super::*;
2169
2170 #[test]
2171 fn player_default_values() {
2172 let p = Player::default();
2173 assert_eq!(p.speed, 4.0);
2174 assert_eq!(p.sensitivity, 1.0);
2175 assert_eq!(p.roll_speed, 1.5);
2176 assert_eq!(p.velocity, Vec3::ZERO);
2177 }
2178
2179 #[test]
2180 fn player_config_default_values() {
2181 let c = PlayerConfig::default();
2182 assert_eq!(c.speed, 4.0);
2183 assert_eq!(c.fov_degrees, 90.0);
2184 assert!(matches!(
2185 c.mode,
2186 PlayerMode::FreeFlightSixDof {
2187 roll_mode: RollMode::Continuous
2188 }
2189 ));
2190 assert!((c.snap_roll_duration_secs - 0.5).abs() < f32::EPSILON);
2191 assert_eq!(c.snap_roll_easing, SnapRollEasing::EaseOutCubic);
2192 }
2193
2194 #[test]
2195 fn snap_roll_completes_to_90deg() {
2196 let mut anim = start_or_retarget_snap(
2197 None,
2198 Vec3::Z,
2199 Vec3::Y,
2200 1,
2201 0.18,
2202 SnapRollEasing::EaseOutCubic,
2203 );
2204 let (delta, finished) = advance_snap(&mut anim, 0.18);
2205 assert!(finished);
2206 assert!(
2207 (delta - std::f32::consts::FRAC_PI_2).abs() < 1e-4,
2208 "Expected ~PI/2, got {delta}"
2209 );
2210 }
2211
2212 #[test]
2213 fn snap_roll_easing_monotonic() {
2214 let mut anim = start_or_retarget_snap(
2215 None,
2216 Vec3::Z,
2217 Vec3::Y,
2218 1,
2219 0.18,
2220 SnapRollEasing::EaseOutCubic,
2221 );
2222 let step = 0.045;
2223 let mut deltas = Vec::new();
2224 for _ in 0..4 {
2225 let (d, _) = advance_snap(&mut anim, step);
2226 assert!(d > 0.0, "Delta should be positive, got {d}");
2227 deltas.push(d);
2228 }
2229 let total: f32 = deltas.iter().sum();
2230 assert!(
2231 (total - std::f32::consts::FRAC_PI_2).abs() < 1e-3,
2232 "Sum should be ~PI/2, got {total}"
2233 );
2234 for i in 1..deltas.len() {
2236 assert!(
2237 deltas[i] <= deltas[i - 1] + 1e-6,
2238 "Easing not monotonically decreasing: {:?}",
2239 deltas
2240 );
2241 }
2242 }
2243
2244 #[test]
2245 fn snap_roll_same_direction_extends_target() {
2246 let mut anim = start_or_retarget_snap(
2247 None,
2248 Vec3::Z,
2249 Vec3::Y,
2250 1,
2251 0.18,
2252 SnapRollEasing::EaseOutCubic,
2253 );
2254 advance_snap(&mut anim, 0.054);
2256 let prev_applied = anim.current_applied;
2257 let up = Quat::from_axis_angle(Vec3::Z, anim.current_applied) * Vec3::Y;
2260 let new_anim = start_or_retarget_snap(
2261 Some(anim),
2262 Vec3::Z,
2263 up,
2264 1,
2265 0.18,
2266 SnapRollEasing::EaseOutCubic,
2267 );
2268 assert!((new_anim.start_angle - prev_applied).abs() < 1e-6);
2269 assert!(
2270 (new_anim.target_angle - std::f32::consts::PI).abs() < 1e-4,
2271 "Expected target ~PI (2x90°), got {}",
2272 new_anim.target_angle
2273 );
2274 }
2275
2276 #[test]
2277 fn snap_roll_opposite_direction_reverses_to_lattice() {
2278 let mut anim = start_or_retarget_snap(
2279 None,
2280 Vec3::Z,
2281 Vec3::Y,
2282 1,
2283 0.18,
2284 SnapRollEasing::EaseOutCubic,
2285 );
2286 advance_snap(&mut anim, 0.054);
2288 let current = anim.current_applied;
2289 assert!(current > 0.0 && current < std::f32::consts::FRAC_PI_2);
2290 let up = Quat::from_axis_angle(Vec3::Z, current) * Vec3::Y;
2293 let new_anim = start_or_retarget_snap(
2294 Some(anim),
2295 Vec3::Z,
2296 up,
2297 -1,
2298 0.18,
2299 SnapRollEasing::EaseOutCubic,
2300 );
2301 assert!(
2303 new_anim.target_angle.abs() < 1e-6,
2304 "Expected target ~0, got {}",
2305 new_anim.target_angle
2306 );
2307 }
2308
2309 #[test]
2310 fn continuous_mode_unchanged() {
2311 let player = Player::default();
2312 assert!(matches!(
2313 player.mode,
2314 PlayerMode::FreeFlightSixDof {
2315 roll_mode: RollMode::Continuous
2316 }
2317 ));
2318 assert!(player.snap_anim.is_none());
2319 }
2320
2321 #[test]
2322 fn snap_roll_config_copies_to_player() {
2323 let config = PlayerConfig {
2324 mode: PlayerMode::FreeFlightSixDof {
2325 roll_mode: RollMode::Snap,
2326 },
2327 snap_roll_duration_secs: 0.3,
2328 snap_roll_easing: SnapRollEasing::Smoothstep,
2329 ..default()
2330 };
2331 let player = Player {
2332 mode: config.mode.clone(),
2333 snap_roll_duration: config.snap_roll_duration_secs,
2334 snap_roll_easing: config.snap_roll_easing,
2335 ..default()
2336 };
2337 assert!(matches!(
2338 player.mode,
2339 PlayerMode::FreeFlightSixDof {
2340 roll_mode: RollMode::Snap
2341 }
2342 ));
2343 assert!((player.snap_roll_duration - 0.3).abs() < f32::EPSILON);
2344 assert_eq!(player.snap_roll_easing, SnapRollEasing::Smoothstep);
2345 }
2346
2347 #[test]
2348 fn snap_roll_start_from_none_is_independent() {
2349 let anim1 = start_or_retarget_snap(
2350 None,
2351 Vec3::Z,
2352 Vec3::Y,
2353 1,
2354 0.18,
2355 SnapRollEasing::EaseOutCubic,
2356 );
2357 let anim2 = start_or_retarget_snap(
2358 None,
2359 Vec3::Z,
2360 Vec3::Y,
2361 1,
2362 0.18,
2363 SnapRollEasing::EaseOutCubic,
2364 );
2365 assert!((anim1.target_angle - anim2.target_angle).abs() < f32::EPSILON);
2366 assert!((anim1.start_angle - anim2.start_angle).abs() < f32::EPSILON);
2367 }
2368
2369 #[test]
2370 fn lattice_axis_forward_yields_four_candidates_at_90deg() {
2371 let mut angles = world_lattice_angles(Vec3::Y, Vec3::Z);
2373 assert_eq!(angles.len(), 4, "Y axis pair must be excluded: {angles:?}");
2374 angles.sort_by(f32::total_cmp);
2375 for pair in angles.windows(2) {
2376 assert!(
2377 (pair[1] - pair[0] - std::f32::consts::FRAC_PI_2).abs() < 1e-5,
2378 "Candidates must be exactly 90° apart: {angles:?}"
2379 );
2380 }
2381 }
2382
2383 #[test]
2384 fn lattice_near_axis_forward_still_yields_four_candidates() {
2385 let local_z = Quat::from_axis_angle(Vec3::X, 8_f32.to_radians()) * Vec3::Z;
2389 let up = Quat::from_axis_angle(local_z, 5_f32.to_radians())
2390 * (Vec3::Y - Vec3::Y.dot(local_z) * local_z).normalize();
2391
2392 let angles = world_lattice_angles(local_z, up);
2393 assert_eq!(
2394 angles.len(),
2395 4,
2396 "Near-axis view must exclude the ±Z pair, got {angles:?}"
2397 );
2398
2399 let boundary_z = Vec3::new(0.0, 1.0, 1.0).normalize();
2403 let boundary_up = (Vec3::Y - Vec3::Y.dot(boundary_z) * boundary_z).normalize();
2404 assert_eq!(
2405 world_lattice_angles(boundary_z, boundary_up).len(),
2406 6,
2407 "At exactly 45° both axis families are equally valid"
2408 );
2409 }
2410
2411 #[test]
2412 fn lattice_diagonal_forward_yields_six_candidates_cycling_2pi() {
2413 use std::f32::consts::{FRAC_PI_2, FRAC_PI_3, TAU};
2414 let local_z = -Vec3::ONE.normalize();
2416 let start = (Vec3::X - Vec3::X.dot(local_z) * local_z).normalize();
2418
2419 let angles = world_lattice_angles(local_z, start);
2420 assert_eq!(
2421 angles.len(),
2422 6,
2423 "All 6 axes survive on a diagonal: {angles:?}"
2424 );
2425
2426 let mut up = start;
2429 let mut total = 0.0_f32;
2430 for _ in 0..6 {
2431 let step = next_lattice_step(&world_lattice_angles(local_z, up), 1);
2432 assert!(
2433 (step - FRAC_PI_3).abs() < 1e-3,
2434 "Expected ~60° step, got {step}"
2435 );
2436 assert!(
2437 (step - FRAC_PI_2).abs() > 0.1,
2438 "Step must not be 90°, got {step}"
2439 );
2440 total += step;
2441 up = Quat::from_axis_angle(local_z, step) * up;
2442 }
2443 assert!(
2444 (total - TAU).abs() < 1e-3,
2445 "Six presses must sum to 2π, got {total}"
2446 );
2447 assert!(
2448 up.dot(start) > 0.9999,
2449 "Cycle must return to start, got {up:?}"
2450 );
2451 }
2452
2453 #[test]
2454 fn lattice_drifted_up_travels_residual() {
2455 let up = Quat::from_axis_angle(Vec3::Z, 10_f32.to_radians()) * Vec3::Y;
2457 let angles = world_lattice_angles(Vec3::Z, up);
2458
2459 let q = next_lattice_step(&angles, 1);
2460 let e = next_lattice_step(&angles, -1);
2461 assert!(
2462 (q - 80_f32.to_radians()).abs() < 1e-4,
2463 "Q must travel ≈+80°, got {q}"
2464 );
2465 assert!(
2466 (e + 10_f32.to_radians()).abs() < 1e-4,
2467 "E must travel ≈−10°, got {e}"
2468 );
2469
2470 let up_q = Quat::from_axis_angle(Vec3::Z, q) * up;
2472 let up_e = Quat::from_axis_angle(Vec3::Z, e) * up;
2473 assert!(
2474 up_q.dot(Vec3::NEG_X) > 0.9999,
2475 "Q must land on −X, got {up_q:?}"
2476 );
2477 assert!(
2478 up_e.dot(Vec3::Y) > 0.9999,
2479 "E must land on +Y, got {up_e:?}"
2480 );
2481 }
2482
2483 #[test]
2484 fn lattice_eps_on_skips_exact_candidate() {
2485 let angles = world_lattice_angles(Vec3::Z, Vec3::Y);
2487 let q = next_lattice_step(&angles, 1);
2488 let e = next_lattice_step(&angles, -1);
2489 assert!(
2490 (q - std::f32::consts::FRAC_PI_2).abs() < 1e-5,
2491 "Q from an exact candidate must be +90°, got {q}"
2492 );
2493 assert!(
2494 (e + std::f32::consts::FRAC_PI_2).abs() < 1e-5,
2495 "E from an exact candidate must be −90°, got {e}"
2496 );
2497 }
2498
2499 #[test]
2500 fn snap_retarget_drifted_frame_lands_on_candidates() {
2501 let local_z = Vec3::Z;
2502 let up0 = Quat::from_axis_angle(local_z, 10_f32.to_radians()) * Vec3::Y;
2504
2505 let mut anim =
2507 start_or_retarget_snap(None, local_z, up0, 1, 0.18, SnapRollEasing::EaseOutCubic);
2508 advance_snap(&mut anim, 0.054);
2509 let up_mid = Quat::from_axis_angle(local_z, anim.current_applied) * up0;
2510 let extended = start_or_retarget_snap(
2511 Some(anim),
2512 local_z,
2513 up_mid,
2514 1,
2515 0.18,
2516 SnapRollEasing::EaseOutCubic,
2517 );
2518 let up_ext = Quat::from_axis_angle(local_z, extended.target_angle) * up0;
2519 assert!(
2520 up_ext.dot(Vec3::NEG_Y) > 0.9999,
2521 "Extend must land on −Y, got {up_ext:?}"
2522 );
2523
2524 let mut anim =
2526 start_or_retarget_snap(None, local_z, up0, 1, 0.18, SnapRollEasing::EaseOutCubic);
2527 advance_snap(&mut anim, 0.054);
2528 let up_mid = Quat::from_axis_angle(local_z, anim.current_applied) * up0;
2529 let reversed = start_or_retarget_snap(
2530 Some(anim),
2531 local_z,
2532 up_mid,
2533 -1,
2534 0.18,
2535 SnapRollEasing::EaseOutCubic,
2536 );
2537 let up_rev = Quat::from_axis_angle(local_z, reversed.target_angle) * up0;
2538 assert!(
2539 up_rev.dot(Vec3::Y) > 0.9999,
2540 "Reverse must land on +Y, got {up_rev:?}"
2541 );
2542 }
2543
2544 #[test]
2545 fn push_capsule_no_collision() {
2546 let pos = Vec3::new(10.0, 10.0, 10.0);
2548 let result = push_capsule_out(pos, Vec3::Y, PLAYER_HALF_HEIGHT, Vec3::ZERO, 0, 0, 0);
2549 assert_eq!(result, pos);
2550 }
2551
2552 #[test]
2553 fn push_capsule_resolves_overlap() {
2554 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);
2557 let vox_center = Vec3::splat(0.5);
2559 let closest = result.clamp(Vec3::ZERO, Vec3::ONE);
2560 let dist = (result - closest).length();
2561 assert!(
2562 dist >= PLAYER_RADIUS - 0.001,
2563 "dist={dist} must be >= PLAYER_RADIUS={PLAYER_RADIUS}"
2564 );
2565 let _ = vox_center; }
2567
2568 #[test]
2571 fn clamp_pitch_under_limit_passes_through() {
2572 let d = clamp_pitch_delta(Vec3::NEG_Z, Vec3::Y, 30_f32.to_radians());
2574 assert!((d - 30_f32.to_radians()).abs() < 1e-5, "got {d}");
2575 let d = clamp_pitch_delta(Vec3::NEG_Z, Vec3::Y, -30_f32.to_radians());
2576 assert!((d + 30_f32.to_radians()).abs() < 1e-5, "got {d}");
2577 }
2578
2579 #[test]
2580 fn clamp_pitch_crossing_limit_truncates() {
2581 let f_hi = Vec3::new(0.0, 80_f32.to_radians().sin(), -(80_f32.to_radians().cos()));
2583 let d = clamp_pitch_delta(f_hi, Vec3::Y, 20_f32.to_radians());
2584 assert!(
2585 (d - 9_f32.to_radians()).abs() < 1e-4,
2586 "expected ~+9°, got {d}"
2587 );
2588
2589 let f_lo = Vec3::new(
2591 0.0,
2592 -(80_f32.to_radians().sin()),
2593 -(80_f32.to_radians().cos()),
2594 );
2595 let d = clamp_pitch_delta(f_lo, Vec3::Y, -20_f32.to_radians());
2596 assert!(
2597 (d + 9_f32.to_radians()).abs() < 1e-4,
2598 "expected ~−9°, got {d}"
2599 );
2600 }
2601
2602 #[test]
2603 fn clamp_pitch_at_limit_blocks_outward_allows_inward() {
2604 let f = Vec3::new(0.0, 89_f32.to_radians().sin(), -(89_f32.to_radians().cos()));
2606 let outward = clamp_pitch_delta(f, Vec3::Y, 5_f32.to_radians());
2607 assert!(
2608 outward.abs() < 1e-4,
2609 "outward delta at the pole must be ~0, got {outward}"
2610 );
2611 let inward = clamp_pitch_delta(f, Vec3::Y, -5_f32.to_radians());
2612 assert!(
2613 (inward + 5_f32.to_radians()).abs() < 1e-4,
2614 "inward delta must pass through, got {inward}"
2615 );
2616 }
2617
2618 #[test]
2621 fn candidates_axis_forward_have_source_axes() {
2622 use std::f32::consts::FRAC_PI_2;
2623 let cands = world_lattice_candidates(Vec3::Z, Vec3::Y);
2626 assert_eq!(cands.len(), 4, "±Z must be excluded: {cands:?}");
2627 let angle_of = |axis: Vec3| {
2628 cands
2629 .iter()
2630 .find(|(_, a)| *a == axis)
2631 .unwrap_or_else(|| panic!("axis {axis:?} missing from {cands:?}"))
2632 .0
2633 };
2634 assert!(
2635 (angle_of(Vec3::X) + FRAC_PI_2).abs() < 1e-5,
2636 "X must sit at −π/2"
2637 );
2638 assert!(
2639 (angle_of(Vec3::NEG_X) - FRAC_PI_2).abs() < 1e-5,
2640 "−X must sit at +π/2"
2641 );
2642 assert!(angle_of(Vec3::Y).abs() < 1e-5, "Y must sit at 0");
2643 assert!(
2644 (angle_of(Vec3::NEG_Y).abs() - std::f32::consts::PI).abs() < 1e-5,
2645 "−Y must sit at ±π"
2646 );
2647 }
2648
2649 #[test]
2650 fn candidates_diagonal_forward_yield_six_axes() {
2651 let local_z = -Vec3::ONE.normalize();
2653 let up = (Vec3::X - Vec3::X.dot(local_z) * local_z).normalize();
2654 let cands = world_lattice_candidates(local_z, up);
2655 assert_eq!(
2656 cands.len(),
2657 6,
2658 "all 6 axes survive on a diagonal: {cands:?}"
2659 );
2660 for axis in AXES {
2661 assert_eq!(
2662 cands.iter().filter(|(_, a)| *a == axis).count(),
2663 1,
2664 "axis {axis:?} must appear exactly once: {cands:?}"
2665 );
2666 }
2667 }
2668
2669 #[test]
2670 fn lattice_angles_equal_candidate_angles() {
2671 let diag_z = -Vec3::ONE.normalize();
2673 let diag_up = (Vec3::X - Vec3::X.dot(diag_z) * diag_z).normalize();
2674 for (local_z, up) in [(Vec3::Z, Vec3::Y), (diag_z, diag_up)] {
2675 let angles = world_lattice_angles(local_z, up);
2676 let cands = world_lattice_candidates(local_z, up);
2677 assert_eq!(angles.len(), cands.len());
2678 for (a, (c, _)) in angles.iter().zip(cands.iter()) {
2679 assert_eq!(a, c, "wrapper angle {a} != candidate angle {c}");
2680 }
2681 }
2682 }
2683
2684 #[test]
2687 fn next_lattice_candidate_matches_next_lattice_step() {
2688 let up = Quat::from_axis_angle(Vec3::Z, 10_f32.to_radians()) * Vec3::Y;
2691 let cands = world_lattice_candidates(Vec3::Z, up);
2692 let angles = world_lattice_angles(Vec3::Z, up);
2693 for dir in [1, -1] {
2694 let (cand_angle, _) = next_lattice_candidate(&cands, dir);
2695 let step = next_lattice_step(&angles, dir);
2696 assert_eq!(cand_angle, step, "dir {dir}: {cand_angle} != {step}");
2697 }
2698 }
2699
2700 #[test]
2701 fn next_candidate_q_yields_neg_x_e_yields_x() {
2702 use std::f32::consts::FRAC_PI_2;
2703 let cands = world_lattice_candidates(Vec3::Z, Vec3::Y);
2706 let (q_angle, q_axis) = next_lattice_candidate(&cands, 1);
2707 assert!(
2708 (q_angle - FRAC_PI_2).abs() < 1e-5,
2709 "Q must travel +π/2, got {q_angle}"
2710 );
2711 assert_eq!(q_axis, Vec3::NEG_X);
2712 let (e_angle, e_axis) = next_lattice_candidate(&cands, -1);
2713 assert!(
2714 (e_angle + FRAC_PI_2).abs() < 1e-5,
2715 "E must travel −π/2, got {e_angle}"
2716 );
2717 assert_eq!(e_axis, Vec3::X);
2718 }
2719
2720 #[test]
2723 fn snap_reference_up_fresh_and_opposite_use_up() {
2724 let up = Quat::from_axis_angle(Vec3::Z, 10_f32.to_radians()) * Vec3::Y;
2725 assert_eq!(snap_reference_up(None, Vec3::Z, up, 1), up);
2727 let mut anim =
2729 start_or_retarget_snap(None, Vec3::Z, up, 1, 0.18, SnapRollEasing::EaseOutCubic);
2730 advance_snap(&mut anim, 0.054);
2731 assert_eq!(snap_reference_up(Some(anim), Vec3::Z, up, -1), up);
2732 }
2733
2734 #[test]
2735 fn snap_reference_up_same_dir_advances_residual() {
2736 let up0 = Vec3::Y;
2737 let mut anim =
2738 start_or_retarget_snap(None, Vec3::Z, up0, 1, 0.18, SnapRollEasing::EaseOutCubic);
2739 advance_snap(&mut anim, 0.054);
2740 let up_mid = Quat::from_axis_angle(Vec3::Z, anim.current_applied) * up0;
2744 let ref_up = snap_reference_up(Some(anim), Vec3::Z, up_mid, 1);
2745 let expected =
2746 Quat::from_axis_angle(Vec3::Z, anim.target_angle - anim.current_applied) * up_mid;
2747 assert!(
2748 ref_up.dot(expected) > 0.9999,
2749 "ref {ref_up:?} != target up {expected:?}"
2750 );
2751 assert!(
2753 ref_up.dot(Vec3::NEG_X) > 0.9999,
2754 "expected ~−X, got {ref_up:?}"
2755 );
2756 }
2757
2758 #[test]
2759 fn anchor_commit_matches_pending_projection() {
2760 let local_z = Vec3::Z;
2761 let dur = 0.18;
2762 let ease = SnapRollEasing::EaseOutCubic;
2763 let up0 = Quat::from_axis_angle(local_z, 10_f32.to_radians()) * Vec3::Y;
2764 let proj = |axis: Vec3| (axis - axis.dot(local_z) * local_z).normalize();
2765
2766 let ref_up = snap_reference_up(None, local_z, up0, 1);
2768 let (_, axis) = next_lattice_candidate(&world_lattice_candidates(local_z, ref_up), 1);
2769 assert_eq!(axis, Vec3::NEG_X);
2770 let anim = start_or_retarget_snap(None, local_z, up0, 1, dur, ease);
2771 let landed = Quat::from_axis_angle(local_z, anim.target_angle) * up0;
2772 assert!(
2773 landed.dot(proj(axis)) > 0.9999,
2774 "fresh: {landed:?} != proj({axis:?})"
2775 );
2776
2777 let mut anim = start_or_retarget_snap(None, local_z, up0, 1, dur, ease);
2779 advance_snap(&mut anim, 0.054);
2780 let up_mid = Quat::from_axis_angle(local_z, anim.current_applied) * up0;
2781 let ref_up = snap_reference_up(Some(anim), local_z, up_mid, 1);
2782 let (_, axis) = next_lattice_candidate(&world_lattice_candidates(local_z, ref_up), 1);
2783 assert_eq!(axis, Vec3::NEG_Y);
2784 let extended = start_or_retarget_snap(Some(anim), local_z, up_mid, 1, dur, ease);
2785 let landed = Quat::from_axis_angle(local_z, extended.target_angle) * up0;
2786 assert!(
2787 landed.dot(proj(axis)) > 0.9999,
2788 "extend: {landed:?} != proj({axis:?})"
2789 );
2790
2791 let mut anim = start_or_retarget_snap(None, local_z, up0, 1, dur, ease);
2793 advance_snap(&mut anim, 0.054);
2794 let up_mid = Quat::from_axis_angle(local_z, anim.current_applied) * up0;
2795 let ref_up = snap_reference_up(Some(anim), local_z, up_mid, -1);
2796 let (_, axis) = next_lattice_candidate(&world_lattice_candidates(local_z, ref_up), -1);
2797 assert_eq!(axis, Vec3::Y);
2798 let reversed = start_or_retarget_snap(Some(anim), local_z, up_mid, -1, dur, ease);
2799 let landed = Quat::from_axis_angle(local_z, reversed.target_angle) * up0;
2800 assert!(
2801 landed.dot(proj(axis)) > 0.9999,
2802 "reverse: {landed:?} != proj({axis:?})"
2803 );
2804 }
2805
2806 #[test]
2809 fn nearest_world_axis_snaps_biased_vectors() {
2810 assert_eq!(nearest_world_axis(Vec3::new(0.9, 0.1, 0.2)), Vec3::X);
2811 assert_eq!(nearest_world_axis(Vec3::new(-2.0, 0.5, 0.5)), Vec3::NEG_X);
2812 assert_eq!(nearest_world_axis(Vec3::new(0.1, -1.5, 0.3)), Vec3::NEG_Y);
2813 assert_eq!(nearest_world_axis(Vec3::new(-0.1, 0.2, 0.95)), Vec3::Z);
2814 assert_eq!(nearest_world_axis(Vec3::new(0.2, 0.3, -0.9)), Vec3::NEG_Z);
2815 }
2816
2817 #[test]
2818 fn nearest_world_axis_tie_uses_axes_order() {
2819 assert_eq!(nearest_world_axis(Vec3::new(1.0, 1.0, 0.0)), Vec3::X);
2821 assert_eq!(nearest_world_axis(Vec3::new(0.0, 1.0, 1.0)), Vec3::Y);
2822 assert_eq!(nearest_world_axis(Vec3::new(-1.0, -1.0, -1.0)), Vec3::NEG_X);
2823 }
2824
2825 #[test]
2826 fn player_mode_defaults_to_sixdof() {
2827 let p = Player::default();
2828 assert!(matches!(
2829 p.mode,
2830 PlayerMode::FreeFlightSixDof {
2831 roll_mode: RollMode::Continuous
2832 }
2833 ));
2834 assert_eq!(p.anchor_up, Vec3::Y);
2835 assert!(p.pending_anchor.is_none());
2836 assert!(matches!(
2837 PlayerConfig::default().mode,
2838 PlayerMode::FreeFlightSixDof {
2839 roll_mode: RollMode::Continuous
2840 }
2841 ));
2842 }
2843
2844 #[test]
2845 fn anchored_mode_config_copies_to_player() {
2846 let config = PlayerConfig {
2848 mode: PlayerMode::FreeFlightAnchored,
2849 ..default()
2850 };
2851 let player = Player {
2852 mode: config.mode.clone(),
2853 ..default()
2854 };
2855 assert!(matches!(player.mode, PlayerMode::FreeFlightAnchored));
2856 }
2857
2858 fn anchored_app() -> (App, Entity) {
2868 let mut app = App::new();
2869 app.add_message::<MouseMotion>();
2870 app.insert_resource(ButtonInput::<KeyCode>::default());
2871 app.insert_resource(Time::<()>::default());
2872 app.add_systems(Update, player_look);
2873 let entity = app
2874 .world_mut()
2875 .spawn((
2876 Player {
2877 mode: PlayerMode::FreeFlightAnchored,
2878 ..default()
2879 },
2880 Transform::default(),
2881 ))
2882 .id();
2883 (app, entity)
2884 }
2885
2886 fn cursor_app(
2889 pause: Option<crate::ui::PauseMenuState>,
2890 locked: bool,
2891 ) -> (App, bevy::ecs::entity::Entity) {
2892 use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
2893 let mut app = App::new();
2894 app.init_resource::<ButtonInput<KeyCode>>()
2895 .init_resource::<ButtonInput<MouseButton>>()
2896 .add_systems(Update, player_cursor_system);
2897 if let Some(state) = pause {
2898 app.insert_resource(State::new(state));
2899 }
2900 let window = app
2901 .world_mut()
2902 .spawn((
2903 Window {
2904 focused: true,
2905 ..default()
2906 },
2907 PrimaryWindow,
2908 CursorOptions {
2909 grab_mode: if locked {
2910 CursorGrabMode::Locked
2911 } else {
2912 CursorGrabMode::None
2913 },
2914 visible: !locked,
2915 ..default()
2916 },
2917 ))
2918 .id();
2919 (app, window)
2920 }
2921
2922 fn grab_mode(app: &App, window: bevy::ecs::entity::Entity) -> bevy::window::CursorGrabMode {
2923 app.world()
2924 .get::<bevy::window::CursorOptions>(window)
2925 .expect("window should still exist")
2926 .grab_mode
2927 }
2928
2929 #[test]
2930 fn pause_menu_owns_escape_so_a_free_cursor_does_not_close_the_window() {
2931 use crate::ui::PauseMenuState;
2932 let (mut app, window) = cursor_app(Some(PauseMenuState::Playing), false);
2933 app.world_mut()
2934 .resource_mut::<ButtonInput<KeyCode>>()
2935 .press(KeyCode::Escape);
2936
2937 app.update();
2938
2939 assert!(
2940 app.world().get_entity(window).is_ok(),
2941 "Escape belongs to the pause menu when it is installed"
2942 );
2943 }
2944
2945 #[test]
2946 fn pause_menu_owns_escape_so_a_captured_cursor_is_not_released_here() {
2947 use crate::ui::PauseMenuState;
2948 use bevy::window::CursorGrabMode;
2949 let (mut app, window) = cursor_app(Some(PauseMenuState::Playing), true);
2950 app.world_mut()
2951 .resource_mut::<ButtonInput<KeyCode>>()
2952 .press(KeyCode::Escape);
2953
2954 app.update();
2955
2956 assert_eq!(grab_mode(&app, window), CursorGrabMode::Locked);
2958 }
2959
2960 #[test]
2961 fn with_pause_menu_a_focused_click_captures_and_focus_loss_releases() {
2962 use crate::ui::PauseMenuState;
2963 use bevy::window::CursorGrabMode;
2964 let (mut app, window) = cursor_app(Some(PauseMenuState::Playing), false);
2965 app.world_mut()
2966 .resource_mut::<ButtonInput<MouseButton>>()
2967 .press(MouseButton::Left);
2968 app.update();
2969 assert_eq!(grab_mode(&app, window), CursorGrabMode::Locked);
2970
2971 app.world_mut()
2972 .resource_mut::<ButtonInput<MouseButton>>()
2973 .reset_all();
2974 app.world_mut().get_mut::<Window>(window).unwrap().focused = false;
2975 app.update();
2976 assert_eq!(grab_mode(&app, window), CursorGrabMode::None);
2977 }
2978
2979 #[test]
2980 fn menu_clicks_do_not_capture_the_cursor_while_paused_or_in_settings() {
2981 use crate::ui::PauseMenuState;
2982 use bevy::window::CursorGrabMode;
2983 for state in [PauseMenuState::Paused, PauseMenuState::Settings] {
2984 let (mut app, window) = cursor_app(Some(state), false);
2987 app.world_mut()
2988 .resource_mut::<ButtonInput<MouseButton>>()
2989 .press(MouseButton::Left);
2990
2991 app.update();
2992
2993 assert_eq!(grab_mode(&app, window), CursorGrabMode::None);
2994 }
2995 }
2996
2997 #[test]
2998 fn player_systems_set_gates_the_plugin_systems() {
2999 use bevy::window::{CursorGrabMode, PrimaryWindow};
3000 let mut app = App::new();
3001 app.add_plugins(PlayerPlugin::<crate::voxel::DefaultVoxel>::new());
3002 app.init_resource::<ButtonInput<KeyCode>>()
3003 .init_resource::<ButtonInput<MouseButton>>();
3004 app.configure_sets(Update, PlayerSystems.run_if(|| false));
3007 let window = app
3008 .world_mut()
3009 .spawn((
3010 Window {
3011 focused: true,
3012 ..default()
3013 },
3014 PrimaryWindow,
3015 ))
3016 .id();
3017 app.world_mut()
3018 .resource_mut::<ButtonInput<MouseButton>>()
3019 .press(MouseButton::Left);
3020
3021 app.world_mut().run_schedule(Update);
3023
3024 assert_eq!(
3025 grab_mode(&app, window),
3026 CursorGrabMode::None,
3027 "a disabled PlayerSystems set must stop the cursor system"
3028 );
3029 }
3030
3031 #[test]
3032 fn player_plugin_runs_without_the_audio_and_ui_plugins() {
3033 let mut app = App::new();
3034 app.add_plugins(MinimalPlugins)
3035 .add_plugins(bevy::input::InputPlugin)
3036 .add_plugins(crate::world::WorldPlugin)
3037 .add_plugins(PlayerPlugin::<crate::voxel::DefaultVoxel>::new());
3038
3039 app.world_mut().run_schedule(Update);
3043 }
3044
3045 #[test]
3046 fn focus_loss_releases_the_cursor_even_while_a_menu_is_open() {
3047 use crate::ui::PauseMenuState;
3048 use bevy::window::CursorGrabMode;
3049 let (mut app, window) = cursor_app(Some(PauseMenuState::Paused), true);
3050 app.world_mut().get_mut::<Window>(window).unwrap().focused = false;
3051
3052 app.update();
3053
3054 assert_eq!(grab_mode(&app, window), CursorGrabMode::None);
3055 }
3056
3057 #[test]
3058 fn without_pause_menu_escape_keeps_its_two_stage_behavior() {
3059 use bevy::window::CursorGrabMode;
3060 let (mut app, window) = cursor_app(None, true);
3061 app.world_mut()
3062 .resource_mut::<ButtonInput<KeyCode>>()
3063 .press(KeyCode::Escape);
3064 app.update();
3065 assert_eq!(grab_mode(&app, window), CursorGrabMode::None);
3066
3067 app.update();
3069 assert!(app.world().get_entity(window).is_err());
3070 }
3071
3072 #[test]
3073 fn focus_loss_releases_capture_and_ignores_unfocused_click_and_escape() {
3074 use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
3075 let mut app = App::new();
3076 app.init_resource::<ButtonInput<KeyCode>>()
3077 .init_resource::<ButtonInput<MouseButton>>()
3078 .add_systems(Update, player_cursor_system);
3079 let window = app
3080 .world_mut()
3081 .spawn((
3082 Window {
3083 focused: false,
3084 ..default()
3085 },
3086 PrimaryWindow,
3087 CursorOptions {
3088 grab_mode: CursorGrabMode::Locked,
3089 visible: false,
3090 ..default()
3091 },
3092 ))
3093 .id();
3094 app.world_mut()
3095 .resource_mut::<ButtonInput<KeyCode>>()
3096 .press(KeyCode::Escape);
3097 app.world_mut()
3098 .resource_mut::<ButtonInput<MouseButton>>()
3099 .press(MouseButton::Left);
3100 app.update();
3101 let cursor = app
3102 .world()
3103 .get::<CursorOptions>(window)
3104 .expect("unfocused Escape must not close the window");
3105 assert_eq!(cursor.grab_mode, CursorGrabMode::None);
3106 assert!(cursor.visible);
3107 app.world_mut()
3108 .resource_mut::<ButtonInput<KeyCode>>()
3109 .reset_all();
3110 app.world_mut()
3111 .resource_mut::<ButtonInput<MouseButton>>()
3112 .reset_all();
3113 app.world_mut().get_mut::<Window>(window).unwrap().focused = true;
3114 app.update();
3115 assert_eq!(
3116 app.world().get::<CursorOptions>(window).unwrap().grab_mode,
3117 CursorGrabMode::None
3118 );
3119 app.world_mut()
3120 .resource_mut::<ButtonInput<MouseButton>>()
3121 .press(MouseButton::Left);
3122 app.update();
3123 assert_eq!(
3124 app.world().get::<CursorOptions>(window).unwrap().grab_mode,
3125 CursorGrabMode::Locked
3126 );
3127 }
3128
3129 #[test]
3130 fn inactive_primary_window_discards_look_without_replaying_it() {
3131 use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
3132 let (mut app, player) = anchored_app();
3133 let window = app
3134 .world_mut()
3135 .spawn((
3136 Window {
3137 focused: false,
3138 ..default()
3139 },
3140 PrimaryWindow,
3141 ))
3142 .id();
3143 step(&mut app, Vec2::new(100.0, 20.0), &[KeyCode::KeyQ], 0.1);
3144 assert_eq!(
3145 app.world().get::<Transform>(player).unwrap().rotation,
3146 Quat::IDENTITY
3147 );
3148 assert!(
3149 app.world()
3150 .get::<Player>(player)
3151 .unwrap()
3152 .snap_anim
3153 .is_none()
3154 );
3155 app.world_mut().get_mut::<Window>(window).unwrap().focused = true;
3156 app.world_mut()
3157 .get_mut::<CursorOptions>(window)
3158 .unwrap()
3159 .grab_mode = CursorGrabMode::Locked;
3160 step(&mut app, Vec2::ZERO, &[], 0.1);
3161 assert_eq!(
3162 app.world().get::<Transform>(player).unwrap().rotation,
3163 Quat::IDENTITY
3164 );
3165 step(&mut app, Vec2::new(10.0, 0.0), &[], 0.1);
3166 assert_ne!(
3167 app.world().get::<Transform>(player).unwrap().rotation,
3168 Quat::IDENTITY
3169 );
3170 }
3171
3172 #[test]
3173 fn spawning_player_leaves_cursor_free_until_focused_click() {
3174 use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
3175 let mut app = App::new();
3176 app.init_resource::<PlayerConfig>()
3177 .init_resource::<PlayerHealth>()
3178 .add_systems(Startup, spawn_player);
3179 let window = app
3180 .world_mut()
3181 .spawn((Window::default(), PrimaryWindow))
3182 .id();
3183 app.update();
3184 let cursor = app.world().get::<CursorOptions>(window).unwrap();
3185 assert_eq!(cursor.grab_mode, CursorGrabMode::None);
3186 assert!(cursor.visible);
3187 }
3188
3189 #[test]
3190 fn spawn_player_puts_the_viewer_at_the_spawn_position() {
3191 let spawn = Vec3::new(500.0, 20.0, -300.0);
3192 let mut app = App::new();
3193 app.insert_resource(PlayerConfig {
3194 spawn_position: spawn,
3195 ..default()
3196 })
3197 .init_resource::<PlayerHealth>()
3198 .init_resource::<ViewerPosition>()
3199 .add_systems(Startup, spawn_player);
3200
3201 app.update();
3202
3203 assert_eq!(app.world().resource::<ViewerPosition>().position, spawn);
3204 }
3205
3206 #[test]
3207 fn spawn_player_works_without_a_viewer_position() {
3208 let mut app = App::new();
3209 app.init_resource::<PlayerConfig>()
3210 .init_resource::<PlayerHealth>()
3211 .add_systems(Startup, spawn_player);
3212
3213 app.update();
3214
3215 let mut players = app.world_mut().query::<&Player>();
3216 assert_eq!(players.iter(app.world()).count(), 1);
3217 }
3218
3219 fn plugin_app_with_player(position: Vec3) -> (App, Entity) {
3222 let mut app = App::new();
3223 app.add_plugins(MinimalPlugins)
3224 .add_plugins(bevy::input::InputPlugin)
3225 .add_plugins(crate::world::WorldPlugin)
3226 .add_plugins(PlayerPlugin::<crate::voxel::DefaultVoxel>::new());
3227 let player = app
3228 .world_mut()
3229 .spawn((Player::default(), Transform::from_translation(position)))
3230 .id();
3231 (app, player)
3232 }
3233
3234 #[test]
3235 fn the_viewer_follows_a_player_whose_input_is_not_active() {
3236 use bevy::window::PrimaryWindow;
3237 let position = Vec3::new(500.0, 20.0, -300.0);
3238 let (mut app, _) = plugin_app_with_player(position);
3239 app.world_mut().spawn((Window::default(), PrimaryWindow));
3242
3243 app.world_mut().run_schedule(Update);
3244
3245 assert_eq!(app.world().resource::<ViewerPosition>().position, position);
3246 }
3247
3248 #[test]
3249 fn the_viewer_follows_the_player_while_gameplay_is_paused() {
3250 let position = Vec3::new(-64.0, 8.0, 128.0);
3251 let (mut app, player) = plugin_app_with_player(Vec3::ZERO);
3252 app.insert_resource(State::new(crate::ui::PauseMenuState::Paused));
3254 app.world_mut()
3255 .get_mut::<Transform>(player)
3256 .unwrap()
3257 .translation = position;
3258
3259 app.world_mut().run_schedule(Update);
3260
3261 assert_eq!(app.world().resource::<ViewerPosition>().position, position);
3262 }
3263
3264 fn movement_app(config: Option<PlayerMovementConfig>, velocity: Vec3) -> (App, Entity) {
3267 let mut app = App::new();
3268 app.init_resource::<ButtonInput<KeyCode>>()
3269 .init_resource::<Time>()
3270 .init_resource::<ViewerPosition>()
3271 .init_resource::<ChunkManager>()
3272 .init_resource::<PlayerCrouching>()
3273 .add_systems(Update, player_move::<crate::voxel::DefaultVoxel>);
3274 if let Some(config) = config {
3275 app.insert_resource(config);
3276 }
3277 let player = app
3278 .world_mut()
3279 .spawn((
3280 Player {
3281 velocity,
3282 ..default()
3283 },
3284 Transform::default(),
3285 ))
3286 .id();
3287 (app, player)
3288 }
3289
3290 fn speed_after_step(app: &mut App, player: Entity, keys: &[KeyCode]) -> f32 {
3292 app.world_mut()
3293 .resource_mut::<Time>()
3294 .advance_by(std::time::Duration::from_millis(100));
3295 for key in keys {
3296 app.world_mut()
3297 .resource_mut::<ButtonInput<KeyCode>>()
3298 .press(*key);
3299 }
3300 app.update();
3301 app.world().get::<Player>(player).unwrap().velocity.length()
3302 }
3303
3304 fn distance_after_step(app: &mut App, player: Entity) -> f32 {
3306 let before = app.world().get::<Transform>(player).unwrap().translation;
3307 app.world_mut()
3308 .resource_mut::<Time>()
3309 .advance_by(std::time::Duration::from_millis(100));
3310 app.update();
3311 let after = app.world().get::<Transform>(player).unwrap().translation;
3312 after.distance(before)
3313 }
3314
3315 fn waiting_for_chunks() -> Option<PlayerMovementConfig> {
3316 Some(PlayerMovementConfig {
3317 wait_for_chunks: true,
3318 ..default()
3319 })
3320 }
3321
3322 fn load_chunks_around_origin(app: &mut App) {
3324 for x in -1..=1 {
3325 for y in -1..=1 {
3326 for z in -1..=1 {
3327 let entity = app.world_mut().spawn_empty().id();
3328 app.world_mut()
3329 .resource_mut::<ChunkManager>()
3330 .register(IVec3::new(x, y, z), entity);
3331 }
3332 }
3333 }
3334 }
3335
3336 #[test]
3337 fn by_default_the_player_moves_into_chunks_that_are_not_loaded() {
3338 let (mut app, player) = movement_app(None, Vec3::X * 10.0);
3339 assert!(!PlayerMovementConfig::default().wait_for_chunks);
3340
3341 assert!(distance_after_step(&mut app, player) > 0.0);
3342 }
3343
3344 #[test]
3345 fn a_waiting_player_does_not_move_into_chunks_that_are_not_loaded() {
3346 let (mut app, player) = movement_app(waiting_for_chunks(), Vec3::X * 10.0);
3347
3348 assert_eq!(distance_after_step(&mut app, player), 0.0);
3349 assert_eq!(
3351 app.world().resource::<ViewerPosition>().position,
3352 app.world().get::<Transform>(player).unwrap().translation
3353 );
3354 }
3355
3356 #[test]
3357 fn a_waiting_player_moves_once_the_chunks_around_it_are_loaded() {
3358 let (mut app, player) = movement_app(waiting_for_chunks(), Vec3::X * 10.0);
3359 assert_eq!(distance_after_step(&mut app, player), 0.0);
3360
3361 load_chunks_around_origin(&mut app);
3362
3363 assert!(distance_after_step(&mut app, player) > 0.0);
3364 }
3365
3366 #[test]
3367 fn a_waiting_player_needs_every_chunk_its_capsule_touches() {
3368 let (mut app, player) = movement_app(waiting_for_chunks(), Vec3::X * 10.0);
3369 load_chunks_around_origin(&mut app);
3370 let near_edge = Vec3::new(31.9, 8.0, 8.0);
3372 app.world_mut()
3373 .get_mut::<Transform>(player)
3374 .unwrap()
3375 .translation = near_edge;
3376
3377 assert_eq!(distance_after_step(&mut app, player), 0.0);
3379 }
3380
3381 #[test]
3382 fn a_waiting_grounded_player_does_not_build_up_fall_speed() {
3383 let (mut app, player) = movement_app(waiting_for_chunks(), Vec3::ZERO);
3384 {
3385 let mut p = app.world_mut().get_mut::<Player>(player).unwrap();
3386 p.mode = PlayerMode::Grounded {
3387 gravity: 20.0,
3388 jump_speed: 8.0,
3389 };
3390 p.world_loaded = true;
3391 }
3392
3393 for _ in 0..5 {
3394 assert_eq!(distance_after_step(&mut app, player), 0.0);
3395 }
3396
3397 let p = app.world().get::<Player>(player).unwrap();
3398 assert_eq!(p.vertical_velocity, 0.0);
3399 }
3400
3401 #[test]
3402 fn player_chunks_loaded_checks_the_volume_of_the_capsule() {
3403 let mut manager = ChunkManager::default();
3404 let middle = Vec3::splat(8.0);
3405 assert!(!player_chunks_loaded(middle, &manager));
3406
3407 manager.register(IVec3::ZERO, Entity::PLACEHOLDER);
3408 assert!(player_chunks_loaded(middle, &manager));
3409 assert!(!player_chunks_loaded(Vec3::new(15.5, 8.0, 8.0), &manager));
3411 }
3412
3413 #[test]
3414 fn movement_config_defaults_match_the_built_in_feel() {
3415 let config = PlayerMovementConfig::default();
3416 assert_eq!(config.acceleration, 12.0);
3417 assert_eq!(config.deceleration, 7.0);
3418 assert_eq!(config.impact_speed_threshold, 1.0);
3419
3420 let (mut bare, bare_player) = movement_app(None, Vec3::ZERO);
3422 let (mut with, with_player) = movement_app(Some(config), Vec3::ZERO);
3423 assert_eq!(
3424 speed_after_step(&mut bare, bare_player, &[KeyCode::KeyW]),
3425 speed_after_step(&mut with, with_player, &[KeyCode::KeyW]),
3426 );
3427 }
3428
3429 #[test]
3430 fn acceleration_controls_how_fast_speed_builds() {
3431 let slow = PlayerMovementConfig {
3432 acceleration: 1.0,
3433 ..default()
3434 };
3435 let (mut app, player) = movement_app(Some(slow), Vec3::ZERO);
3436
3437 let speed = speed_after_step(&mut app, player, &[KeyCode::KeyW]);
3438
3439 let full = Player::default().speed;
3441 assert!((speed - 0.1 * full).abs() < 1e-4, "speed was {speed}");
3442 }
3443
3444 #[test]
3445 fn deceleration_controls_how_fast_the_player_stops() {
3446 let coast = PlayerMovementConfig {
3447 deceleration: 1.0,
3448 ..default()
3449 };
3450 let (mut app, player) = movement_app(Some(coast), Vec3::Z);
3451
3452 let speed = speed_after_step(&mut app, player, &[]);
3453
3454 assert!((speed - 0.9).abs() < 1e-4, "speed was {speed}");
3455 }
3456
3457 #[test]
3458 fn unusable_movement_rates_fall_back_to_the_defaults() {
3459 let broken = PlayerMovementConfig {
3460 acceleration: f32::NAN,
3461 deceleration: -3.0,
3462 ..default()
3463 };
3464 let (mut app, player) = movement_app(Some(broken), Vec3::ZERO);
3465 let (mut reference, reference_player) = movement_app(None, Vec3::ZERO);
3466
3467 assert_eq!(
3468 speed_after_step(&mut app, player, &[KeyCode::KeyW]),
3469 speed_after_step(&mut reference, reference_player, &[KeyCode::KeyW]),
3470 );
3471 let (mut app, player) = movement_app(Some(broken), Vec3::Z);
3472 let (mut reference, reference_player) = movement_app(None, Vec3::Z);
3473 assert_eq!(
3474 speed_after_step(&mut app, player, &[]),
3475 speed_after_step(&mut reference, reference_player, &[]),
3476 );
3477 }
3478
3479 fn impact_app(register_message: bool) -> (App, Entity) {
3482 use crate::voxel::DefaultVoxel;
3483 let mut app = App::new();
3484 app.init_resource::<ChunkManager>();
3485 if register_message {
3486 app.add_message::<PlayerImpact>();
3487 }
3488 app.add_systems(Update, player_resolve_collision::<DefaultVoxel>);
3489 app.world_mut().spawn((
3490 crate::test_support::filled_chunk(DefaultVoxel::Rock),
3491 Transform::default(),
3492 ));
3493 let player = app
3494 .world_mut()
3495 .spawn((Player::default(), Transform::default()))
3496 .id();
3497 (app, player)
3498 }
3499
3500 fn sink_into_top(app: &mut App, player: Entity, velocity: Vec3) {
3502 let top = CHUNK_SIZE as f32 * VOXEL_SIZE;
3503 let resting_y = top + PLAYER_HALF_HEIGHT + PLAYER_RADIUS;
3504 app.world_mut()
3505 .get_mut::<Transform>(player)
3506 .unwrap()
3507 .translation = Vec3::new(8.5, resting_y - 0.05, 8.5);
3508 app.world_mut().get_mut::<Player>(player).unwrap().velocity = velocity;
3509 }
3510
3511 fn drain_impacts(app: &mut App) -> Vec<PlayerImpact> {
3512 app.world_mut()
3513 .resource_mut::<Messages<PlayerImpact>>()
3514 .drain()
3515 .collect()
3516 }
3517
3518 #[test]
3519 fn flying_into_terrain_reports_one_impact_with_normal_and_speed() {
3520 let (mut app, player) = impact_app(true);
3521 sink_into_top(&mut app, player, Vec3::new(0.0, -5.0, 0.0));
3522
3523 app.update();
3524
3525 let impacts = drain_impacts(&mut app);
3526 assert_eq!(impacts.len(), 1);
3527 let impact = impacts[0];
3528 assert!(
3529 impact.normal.distance(Vec3::Y) < 1e-3,
3530 "{:?}",
3531 impact.normal
3532 );
3533 assert!((impact.speed - 5.0).abs() < 1e-3, "{}", impact.speed);
3534 assert_eq!(
3535 impact.position,
3536 app.world().get::<Transform>(player).unwrap().translation
3537 );
3538
3539 sink_into_top(&mut app, player, Vec3::new(0.0, -5.0, 0.0));
3541 app.update();
3542 assert!(drain_impacts(&mut app).is_empty());
3543
3544 app.world_mut()
3546 .get_mut::<Transform>(player)
3547 .unwrap()
3548 .translation
3549 .y += 10.0;
3550 app.update();
3551 sink_into_top(&mut app, player, Vec3::new(0.0, -3.0, 0.0));
3552 app.update();
3553 let impacts = drain_impacts(&mut app);
3554 assert_eq!(impacts.len(), 1);
3555 assert!((impacts[0].speed - 3.0).abs() < 1e-3);
3556 }
3557
3558 #[test]
3559 fn only_the_speed_into_the_surface_counts() {
3560 let (mut app, player) = impact_app(true);
3561 sink_into_top(&mut app, player, Vec3::new(9.0, -0.5, 0.0));
3563
3564 app.update();
3565
3566 assert!(drain_impacts(&mut app).is_empty());
3567 }
3568
3569 #[test]
3570 fn impact_threshold_is_configurable() {
3571 let (mut app, player) = impact_app(true);
3572 app.insert_resource(PlayerMovementConfig {
3573 impact_speed_threshold: 8.0,
3574 ..default()
3575 });
3576 sink_into_top(&mut app, player, Vec3::new(0.0, -5.0, 0.0));
3577 app.update();
3578 assert!(drain_impacts(&mut app).is_empty());
3579
3580 app.insert_resource(PlayerMovementConfig {
3581 impact_speed_threshold: f32::INFINITY,
3582 ..default()
3583 });
3584 sink_into_top(&mut app, player, Vec3::new(0.0, -500.0, 0.0));
3585 app.update();
3586 assert!(drain_impacts(&mut app).is_empty());
3587 }
3588
3589 #[test]
3590 fn collision_still_resolves_without_the_impact_message() {
3591 let (mut app, player) = impact_app(false);
3592 sink_into_top(&mut app, player, Vec3::new(0.0, -5.0, 0.0));
3593 let before = app.world().get::<Transform>(player).unwrap().translation.y;
3594
3595 app.update();
3596
3597 let after = app.world().get::<Transform>(player).unwrap().translation.y;
3598 assert!(after > before, "the player is pushed out of the terrain");
3599 }
3600
3601 #[test]
3602 fn inactive_movement_clears_velocity_and_preserves_position() {
3603 use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
3604 let mut app = App::new();
3605 app.init_resource::<ButtonInput<KeyCode>>()
3606 .init_resource::<Time>()
3607 .init_resource::<ViewerPosition>()
3608 .init_resource::<ChunkManager>()
3609 .init_resource::<PlayerCrouching>()
3610 .add_systems(Update, player_move::<crate::voxel::DefaultVoxel>);
3611 let window = app
3612 .world_mut()
3613 .spawn((
3614 Window {
3615 focused: false,
3616 ..default()
3617 },
3618 PrimaryWindow,
3619 CursorOptions {
3620 grab_mode: CursorGrabMode::Locked,
3621 ..default()
3622 },
3623 ))
3624 .id();
3625 let player = app
3626 .world_mut()
3627 .spawn((
3628 Player {
3629 velocity: Vec3::Z,
3630 ..default()
3631 },
3632 Transform::default(),
3633 ))
3634 .id();
3635 app.world_mut()
3636 .resource_mut::<Time>()
3637 .advance_by(std::time::Duration::from_millis(100));
3638 app.world_mut()
3639 .resource_mut::<ButtonInput<KeyCode>>()
3640 .press(KeyCode::KeyW);
3641 app.update();
3642 assert_eq!(
3643 app.world().get::<Transform>(player).unwrap().translation,
3644 Vec3::ZERO
3645 );
3646 assert_eq!(
3647 app.world().get::<Player>(player).unwrap().velocity,
3648 Vec3::ZERO
3649 );
3650 app.world_mut().get_mut::<Window>(window).unwrap().focused = true;
3651 app.world_mut()
3652 .get_mut::<CursorOptions>(window)
3653 .unwrap()
3654 .grab_mode = CursorGrabMode::None;
3655 app.update();
3656 assert_eq!(
3657 app.world().get::<Transform>(player).unwrap().translation,
3658 Vec3::ZERO
3659 );
3660 app.world_mut()
3661 .get_mut::<CursorOptions>(window)
3662 .unwrap()
3663 .grab_mode = CursorGrabMode::Locked;
3664 app.update();
3665 assert!(app.world().get::<Transform>(player).unwrap().translation.z < 0.0);
3666 }
3667
3668 fn step(app: &mut App, mouse: Vec2, held: &[KeyCode], dt: f32) {
3672 app.world_mut()
3673 .resource_mut::<Time>()
3674 .advance_by(std::time::Duration::from_secs_f32(dt));
3675 {
3676 let mut input = app.world_mut().resource_mut::<ButtonInput<KeyCode>>();
3677 input.clear(); let stale: Vec<KeyCode> = input
3679 .get_pressed()
3680 .copied()
3681 .filter(|k| !held.contains(k))
3682 .collect();
3683 for k in stale {
3684 input.release(k);
3685 }
3686 for k in held {
3687 input.press(*k);
3688 } }
3690 if mouse != Vec2::ZERO {
3691 app.world_mut().write_message(MouseMotion { delta: mouse });
3692 }
3693 app.update();
3694 }
3695
3696 fn forward_of(app: &App, entity: Entity) -> Vec3 {
3697 *app.world()
3698 .entity(entity)
3699 .get::<Transform>()
3700 .unwrap()
3701 .forward()
3702 }
3703
3704 #[test]
3705 fn anchored_diagonal_input_keeps_horizon_level() {
3706 let (mut app, e) = anchored_app();
3707 for _ in 0..15 {
3709 step(&mut app, Vec2::new(60.0, -80.0), &[], 0.016);
3710 let right = *app.world().entity(e).get::<Transform>().unwrap().right();
3711 assert!(
3714 right.dot(Vec3::Y).abs() < 1e-4,
3715 "horizon rolled: right·Y = {}",
3716 right.dot(Vec3::Y)
3717 );
3718 }
3719 let elevation = forward_of(&app, e).dot(Vec3::Y).abs();
3721 assert!(
3722 elevation >= 88_f32.to_radians().sin(),
3723 "clamp never engaged: |forward·Y| = {elevation}"
3724 );
3725 assert!(
3726 elevation <= 89_f32.to_radians().sin() + 1e-4,
3727 "pitch exceeded ±89°: |forward·Y| = {elevation}"
3728 );
3729 }
3730
3731 #[test]
3732 fn anchored_switch_yaw_uses_old_anchor() {
3733 let (mut app, e) = anchored_app();
3734 step(&mut app, Vec2::ZERO, &[KeyCode::KeyQ], 0.1);
3737 {
3738 let p = app.world().entity(e).get::<Player>().unwrap();
3739 assert!(p.snap_anim.is_some(), "Q should start a switch animation");
3740 assert!(p.pending_anchor.is_some(), "pending anchor should be set");
3741 assert_eq!(p.anchor_up, Vec3::Y, "anchor must not commit mid-animation");
3742 }
3743 let before = forward_of(&app, e);
3744 step(&mut app, Vec2::new(50.0, 0.0), &[], 0.1);
3746 let p = app.world().entity(e).get::<Player>().unwrap();
3747 assert!(p.snap_anim.is_some(), "animation should still be running");
3748 assert_eq!(
3749 p.anchor_up,
3750 Vec3::Y,
3751 "yaw must not commit the pending anchor"
3752 );
3753 let after = forward_of(&app, e);
3754 assert!(
3758 after.dot(Vec3::Y).abs() < 1e-5,
3759 "yaw left the Y-plane → wrong anchor"
3760 );
3761 assert!(
3762 (after - before).length() > 1e-3,
3763 "yaw had no visible effect"
3764 );
3765 }
3766
3767 #[test]
3768 fn anchored_q_switches_anchor() {
3769 let (mut app, e) = anchored_app();
3770 step(&mut app, Vec2::ZERO, &[KeyCode::KeyQ], 0.1);
3773 let p = app.world().entity(e).get::<Player>().unwrap();
3774 assert!(
3775 p.snap_anim.is_some() && p.pending_anchor.is_some(),
3776 "Continuous roll_mode must be inert in Anchored — Q takes the switch path"
3777 );
3778 }
3779}