Skip to main content

voxel_framework/player/
mod.rs

1//! Six-degrees-of-freedom (6DOF) player controller for zero-gravity environments.
2//!
3//! This module implements a first-person camera-player that moves freely in all
4//! six directions with no gravity, no floor constraint, and no pitch clamp — the
5//! equivalent of an astronaut or jetpack pilot. The camera entity IS the player:
6//! there is no separate hierarchy between the logical player and the rendered
7//! view.
8//!
9//! Collisions are resolved against loaded voxel chunks using a capsule-vs-AABB
10//! algorithm that correctly handles any 6DOF orientation, including full roll and
11//! inverted pitch.
12//!
13//! # Physics model
14//!
15//! Velocity is smoothed each frame using exponential lerp:
16//!
17//! - **Accelerating** (key held): `velocity = lerp(velocity, target, acceleration * dt)`
18//! - **Decelerating** (no input): `velocity = lerp(velocity, Vec3::ZERO, deceleration * dt)`
19//!
20//! The two rates come from [`PlayerMovementConfig`] (defaults 12 and 7).
21//!
22//! This gives snappy starts and a natural coast-to-stop feel without requiring a
23//! fixed physics timestep.
24//!
25//! # Quick start — [`PlayerPlugin`]
26//!
27//! The simplest integration: add [`PlayerPlugin`] and everything is wired
28//! automatically. Systems run every frame, or only while unpaused when
29//! [`PauseMenuPlugin`](crate::ui::PauseMenuPlugin) is installed.
30//!
31//! ```rust,no_run
32//! use bevy::prelude::*;
33//! use voxel_framework::prelude::*;
34//! use voxel_framework::player::PlayerPlugin;
35//!
36//! App::new()
37//!     .add_plugins(DefaultPlugins)
38//!     .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
39//!     .add_plugins(GeneratorPlugin::<DefaultVoxel>::new())
40//!     .add_plugins(PlayerPlugin::<DefaultVoxel>::new())
41//!     .run();
42//! ```
43//!
44//! # AppState integration
45//!
46//! When your game has an `AppState` enum, keep [`PlayerPlugin`] and gate (or
47//! order) all of its `Update` systems through the [`PlayerSystems`] set:
48//!
49//! ```rust,no_run
50//! # use bevy::prelude::*;
51//! # use voxel_framework::player::{PlayerPlugin, PlayerSystems};
52//! # use voxel_framework::voxel::DefaultVoxel;
53//! # #[derive(States, Default, Clone, PartialEq, Eq, Hash, Debug)]
54//! # enum AppState { #[default] Playing }
55//! App::new()
56//!     .add_plugins(PlayerPlugin::<DefaultVoxel>::new())
57//!     .configure_sets(Update, PlayerSystems.run_if(in_state(AppState::Playing)));
58//! ```
59//!
60//! Alternatively, skip [`PlayerPlugin`] and register the systems manually
61//! (this drops the plugin's spawn-position persistence):
62//!
63//! ```rust,no_run
64//! # use bevy::prelude::*;
65//! # use voxel_framework::player::{spawn_player, player_look, player_move, player_cursor_system};
66//! # use voxel_framework::player::player_resolve_collision;
67//! # use voxel_framework::voxel::DefaultVoxel;
68//! # #[derive(States, Default, Clone, PartialEq, Eq, Hash, Debug)]
69//! # enum AppState { #[default] Playing }
70//! App::new()
71//!     .add_systems(Startup, spawn_player)
72//!     .add_systems(Update,
73//!         (player_look, player_move::<DefaultVoxel>, player_resolve_collision::<DefaultVoxel>)
74//!             .chain()
75//!             .run_if(in_state(AppState::Playing)),
76//!     )
77//!     .add_systems(Update, player_cursor_system);
78//! ```
79//!
80//! # Cursor management contract
81//!
82//! [`spawn_player`] leaves the cursor free. [`player_cursor_system`] manages
83//! the primary window's lock state without requesting OS keyboard focus:
84//!
85//! - **Left click** in the focused window while cursor is free → locks and hides it.
86//! - **Focus loss** → releases the cursor; returning requires another click.
87//! - **First Escape** while cursor is locked → releases cursor (makes it visible).
88//! - **Escape** while cursor is already free → closes the focused window.
89//!
90//! Look and movement require a focused primary window with a captured cursor.
91//! Headless calls without a primary window retain synthetic-input support.
92//!
93//! With [`PauseMenuPlugin`](crate::ui::PauseMenuPlugin) installed the pause
94//! menu owns Escape: [`player_cursor_system`] ignores the key (Escape opens
95//! the menu and never closes the window) and keeps handling click-to-capture
96//! and focus-loss release while the game is unpaused. The menu releases the
97//! cursor when it opens and captures it again on resume.
98//!
99//! # Controls
100//!
101//! | Input        | Action                              |
102//! |--------------|-------------------------------------|
103//! | Mouse        | Yaw + pitch (6DOF, no clamp)        |
104//! | Q / E        | Roll left / right                   |
105//! | W / S        | Forward / backward                  |
106//! | A / D        | Strafe left / right                 |
107//! | Space        | Move along local up                 |
108//! | Shift        | Move along local down               |
109//! | Left click   | Lock cursor                         |
110//! | Escape       | Release cursor (if already free: close focused window); opens the pause menu instead when `PauseMenuPlugin` is installed |
111
112use bevy::ecs::message::MessageWriter;
113use bevy::input::mouse::MouseMotion;
114use bevy::prelude::*;
115use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
116
117use crate::audio::{SfxEvent, SfxRequest};
118use crate::chunk::{CHUNK_SIZE, Chunk, VOXEL_SIZE};
119use crate::voxel::VoxelType;
120use crate::world::{ChunkManager, ViewerPosition, WorldDataDir, get_voxel_at};
121
122pub mod effects;
123pub mod persistence;
124
125// ─── Health & damage messages ─────────────────────────────────────────────────
126
127/// Emitted when the player takes damage from any source.
128#[derive(Message, Debug, Clone)]
129pub struct PlayerDamaged {
130    /// Amount of health points lost.
131    pub amount: f32,
132}
133
134/// Emitted when the player's health reaches zero and they respawn.
135#[derive(Message, Debug, Clone)]
136pub struct PlayerDied;
137
138/// Player health and respawn state.
139///
140/// Inserted as a resource by [`PlayerPlugin`]. Games can read and modify
141/// `health` directly (e.g. from environmental hazards); fall damage is applied
142/// automatically when landing with high vertical velocity.
143///
144/// When `health` drops to zero the player is teleported to `spawn_position`
145/// and health is restored to `max_health`. A [`PlayerDied`] message is sent.
146#[derive(Resource, Debug, Clone)]
147pub struct PlayerHealth {
148    /// Current health points. Clamped to `[0, max_health]` after damage.
149    pub health: f32,
150    /// Maximum health points. **Default: `20.0`.**
151    pub max_health: f32,
152    /// World position used for respawn on death.
153    ///
154    /// Defaults to the player's spawn position from [`PlayerConfig`]. Games
155    /// can update this at runtime (e.g. when placing a bed or checkpoint).
156    pub spawn_position: Vec3,
157    /// Vertical fall speed (m/s) below which no fall damage is taken.
158    ///
159    /// Impact speeds below this threshold deal zero damage. **Default: `10.0`.**
160    pub fall_safe_speed: f32,
161}
162
163impl Default for PlayerHealth {
164    fn default() -> Self {
165        Self {
166            health: 20.0,
167            max_health: 20.0,
168            spawn_position: Vec3::new(0.0, 30.0, 0.0),
169            fall_safe_speed: 10.0,
170        }
171    }
172}
173
174// ─── PlayerCrouching resource ─────────────────────────────────────────────────
175
176/// Tracks whether the player is currently crouching.
177///
178/// Updated every frame by [`player_move`] in [`PlayerMode::Grounded`] mode
179/// based on `ControlLeft` key state. Readable by external systems (e.g. UI,
180/// animation) without querying the [`Player`] component directly.
181///
182/// The resource mirrors [`Player::crouching`] and is kept in sync by
183/// [`player_move`] each frame. Modifying it directly has no effect — it is
184/// overwritten by the movement system.
185#[derive(Resource, Default, Debug, Clone, Copy, PartialEq, Eq)]
186pub struct PlayerCrouching(pub bool);
187
188// ─── PlayerMode ──────────────────────────────────────────────────────────────
189
190/// Selects the movement model used by [`PlayerPlugin`] and the player systems.
191///
192/// Set this inside [`PlayerConfig::mode`] before adding [`PlayerPlugin`] (or
193/// before the `Startup` schedule runs).  Changing the mode at runtime is
194/// **not** supported — the value is copied into the [`Player`] component once
195/// on spawn and used from there.
196///
197/// # Variants
198///
199/// - [`PlayerMode::FreeFlightSixDof`] — classic 6DOF, no gravity.  Default.
200/// - [`PlayerMode::FreeFlightAnchored`] — free flight with a world-axis-anchored horizon.
201/// - [`PlayerMode::Grounded`] — gravity + jump, WASD on the XZ plane, pitch
202///   clamped to ±89°.  Suitable for Minetest / Minecraft–style games.
203#[derive(Debug, Clone)]
204pub enum PlayerMode {
205    /// Six-degrees-of-freedom flight. No gravity, no pitch clamp, Q/E roll.
206    ///
207    /// This is the default mode and matches the original behaviour of the
208    /// player controller.  All six movement axes (forward, back, left, right,
209    /// up, down) are relative to the camera's current orientation.
210    FreeFlightSixDof {
211        /// How Q/E roll input is applied.
212        roll_mode: RollMode,
213    },
214    /// Six-degrees-of-freedom flight with an FPS-style, world-axis-anchored
215    /// horizon. Q/E switch the anchor axis instead of rolling.
216    FreeFlightAnchored,
217    /// Gravity-based grounded movement.
218    ///
219    /// - WASD moves on the **world XZ plane** relative to the camera's current
220    ///   yaw, ignoring pitch tilt.
221    /// - `Space` jumps when [`Player::on_ground`] is `true`.
222    /// - Gravity accumulates in [`Player::vertical_velocity`] each frame.
223    /// - Mouse yaw rotates the entity around the **world Y axis** (player stays
224    ///   upright); pitch rotates the view up/down and is clamped to ±89°.
225    /// - Q/E roll is disabled.
226    Grounded {
227        /// Downward acceleration in world units per second squared.
228        ///
229        /// Applied every frame as `vertical_velocity -= gravity * dt`.
230        /// Typical value: `20.0`.
231        gravity: f32,
232        /// Upward velocity impulse applied when the player jumps.
233        ///
234        /// Assigned to [`Player::vertical_velocity`] on the frame `Space` is
235        /// pressed while [`Player::on_ground`] is `true`.  Typical value: `8.0`.
236        jump_speed: f32,
237    },
238}
239
240impl Default for PlayerMode {
241    fn default() -> Self {
242        PlayerMode::FreeFlightSixDof {
243            roll_mode: RollMode::Continuous,
244        }
245    }
246}
247
248// ─── Physics constants ────────────────────────────────────────────────────────
249
250/// Radius of the player's collision capsule in world units (≈ 0.6 voxels).
251///
252/// Each hemispherical end cap of the capsule has this radius. The value keeps
253/// the player from clipping single-voxel corners while still fitting through
254/// one-voxel-wide gaps when combined with [`PLAYER_HALF_HEIGHT`].
255pub const PLAYER_RADIUS: f32 = 0.6;
256
257/// Half-height of the capsule's cylindrical spine in world units (≈ 1.8 voxels).
258///
259/// The spine runs along the player's local Y axis between offsets
260/// `−PLAYER_HALF_HEIGHT` and `+PLAYER_HALF_HEIGHT` from the entity origin.
261/// The total capsule height is `2 × (PLAYER_HALF_HEIGHT + PLAYER_RADIUS)` ≈ 4.8
262/// world units. In 6DOF mode this axis rolls with the player's orientation.
263pub const PLAYER_HALF_HEIGHT: f32 = 1.8;
264
265/// Half-height of the capsule when crouching (≈ 60% of normal).
266///
267/// Reduces the total capsule height enough to let the player pass through
268/// gaps that are one voxel tall. Used by [`player_resolve_collision`] when
269/// [`Player::crouching`] is `true` in [`PlayerMode::Grounded`] mode.
270pub const CROUCH_HALF_HEIGHT: f32 = PLAYER_HALF_HEIGHT * 0.6;
271
272/// Speed multiplier applied to horizontal movement while sprinting.
273///
274/// Active in [`PlayerMode::Grounded`] when `Shift` is held and the player is
275/// on solid ground. Crouch takes priority — if both are held this multiplier
276/// is not applied. See [`player_move`] and [`PlayerCrouching`].
277pub const SPRINT_MULTIPLIER: f32 = 1.6;
278
279/// Lerp factor applied when the player is accelerating.
280const ACCEL: f32 = 12.0;
281
282/// Lerp factor applied when the player is decelerating (no input).
283const DECEL: f32 = 7.0;
284
285/// How quickly the player reaches and loses speed, and when a collision counts
286/// as an impact.
287///
288/// [`PlayerPlugin`] initializes this resource with the defaults. Insert your
289/// own value to tune the feel of movement:
290///
291/// ```rust,no_run
292/// use bevy::prelude::*;
293/// use voxel_framework::prelude::*;
294///
295/// App::new()
296///     .add_plugins(PlayerPlugin::<DefaultVoxel>::new())
297///     .insert_resource(PlayerMovementConfig {
298///         acceleration: 4.0, // slower to reach speed
299///         deceleration: 2.0, // longer coast
300///         ..default()
301///     });
302/// ```
303///
304/// Each frame the velocity moves toward its target by
305/// `min(rate * dt, 1.0)` of the remaining difference, so a higher rate means a
306/// snappier response. The values are read every frame.
307///
308/// [`player_move`] and [`player_resolve_collision`] also run without this
309/// resource (a game registering them by hand) and then use the defaults.
310#[derive(Resource, Debug, Clone, Copy, PartialEq)]
311pub struct PlayerMovementConfig {
312    /// Rate at which velocity approaches the target while a movement key is
313    /// held. Default [`PlayerMovementConfig::DEFAULT_ACCELERATION`]. A
314    /// negative or non-finite value falls back to the default.
315    pub acceleration: f32,
316    /// Rate at which velocity approaches zero with no movement input. In
317    /// grounded mode it is further scaled by the surface friction. Default
318    /// [`PlayerMovementConfig::DEFAULT_DECELERATION`]. A negative or
319    /// non-finite value falls back to the default.
320    pub deceleration: f32,
321    /// Speed into a surface, in world units per second, above which a
322    /// collision emits [`PlayerImpact`]. `f32::INFINITY` disables the message.
323    /// Default [`PlayerMovementConfig::DEFAULT_IMPACT_SPEED_THRESHOLD`].
324    pub impact_speed_threshold: f32,
325}
326
327impl PlayerMovementConfig {
328    /// Default [`acceleration`](Self::acceleration).
329    pub const DEFAULT_ACCELERATION: f32 = ACCEL;
330    /// Default [`deceleration`](Self::deceleration).
331    pub const DEFAULT_DECELERATION: f32 = DECEL;
332    /// Default [`impact_speed_threshold`](Self::impact_speed_threshold).
333    pub const DEFAULT_IMPACT_SPEED_THRESHOLD: f32 = 1.0;
334
335    fn acceleration_rate(config: Option<&Self>) -> f32 {
336        config
337            .map(|c| c.acceleration)
338            .filter(|rate| rate.is_finite() && *rate >= 0.0)
339            .unwrap_or(Self::DEFAULT_ACCELERATION)
340    }
341
342    fn deceleration_rate(config: Option<&Self>) -> f32 {
343        config
344            .map(|c| c.deceleration)
345            .filter(|rate| rate.is_finite() && *rate >= 0.0)
346            .unwrap_or(Self::DEFAULT_DECELERATION)
347    }
348
349    fn impact_threshold(config: Option<&Self>) -> f32 {
350        config
351            .map(|c| c.impact_speed_threshold)
352            .unwrap_or(Self::DEFAULT_IMPACT_SPEED_THRESHOLD)
353    }
354}
355
356impl Default for PlayerMovementConfig {
357    fn default() -> Self {
358        Self {
359            acceleration: Self::DEFAULT_ACCELERATION,
360            deceleration: Self::DEFAULT_DECELERATION,
361            impact_speed_threshold: Self::DEFAULT_IMPACT_SPEED_THRESHOLD,
362        }
363    }
364}
365
366/// Emitted by [`player_resolve_collision`] when the player runs into terrain.
367///
368/// One message is written when the speed into the surface rises above
369/// [`PlayerMovementConfig::impact_speed_threshold`]. Staying pressed against
370/// the same surface does not repeat it; the speed has to drop below the
371/// threshold (or contact has to end) before another impact is reported.
372///
373/// [`PlayerPlugin`] registers the message. Typical use is feedback scaled by
374/// `speed`, such as a sound.
375#[derive(Message, Debug, Clone, Copy, PartialEq)]
376pub struct PlayerImpact {
377    /// Player position after the collision was resolved.
378    pub position: Vec3,
379    /// Unit vector pointing away from the surface that was hit.
380    pub normal: Vec3,
381    /// Speed into the surface at the moment of contact, in world units per
382    /// second. Always above the configured threshold.
383    pub speed: f32,
384}
385
386/// Internal mouse scale factor applied before the user-facing
387/// [`Player::sensitivity`] multiplier.
388///
389/// Mouse deltas arrive in pixels (often `10+` per frame) so a raw multiplier of
390/// `1.0` would spin the camera wildly. This constant converts pixels to a base
391/// rad/px rate comparable to Minecraft, so that `sensitivity = 1.0` feels
392/// "normal". Users scale around this via the Settings slider (10% → very slow,
393/// 100% → default, above 100% would be faster but the slider caps there).
394const MOUSE_SCALE: f32 = 0.003;
395
396// ─── Snap roll types ─────────────────────────────────────────────────────────
397
398/// Selects how Q/E roll input is applied in [`PlayerMode::FreeFlightSixDof`].
399///
400/// - [`RollMode::Continuous`] — roll while the key is held (original behavior).
401/// - [`RollMode::Snap`] — each key press animates a snap rotation to the
402///   next world-aligned up candidate (a signed world axis projected onto the
403///   roll plane).
404///
405/// Configured by `PlayerMode::FreeFlightSixDof { roll_mode }`; defaults to
406/// [`RollMode::Continuous`].
407///
408/// Ignored by [`PlayerMode::FreeFlightAnchored`]: in anchored flight Q/E switch
409/// the anchor axis instead of rolling.
410#[derive(Default, Copy, Clone, Debug, PartialEq, Eq)]
411pub enum RollMode {
412    /// Roll continuously while Q/E is held (default, original behavior).
413    #[default]
414    Continuous,
415    /// Snap-rotate to the next world-aligned up candidate per key press with
416    /// easing animation (90° steps when forward is on a world axis).
417    Snap,
418}
419
420/// Easing curve used by [`RollMode::Snap`] animations.
421///
422/// Each variant maps to a simple `f(t) -> f32` curve where `t ∈ [0, 1]`.
423/// The default ([`EaseOutCubic`](SnapRollEasing::EaseOutCubic)) gives a snappy
424/// start that decelerates smoothly.
425#[derive(Default, Copy, Clone, Debug, PartialEq, Eq)]
426pub enum SnapRollEasing {
427    /// `1 − (1 − t)³` — fast start, smooth deceleration (default).
428    #[default]
429    EaseOutCubic,
430    /// `1 − (1 − t)⁴` — slightly slower deceleration than cubic.
431    EaseOutQuart,
432    /// `t² (3 − 2t)` — symmetric S-curve.
433    Smoothstep,
434    /// `t` — constant angular velocity.
435    Linear,
436}
437
438/// Runtime state for an in-progress snap-roll animation.
439///
440/// Stored in [`Player::snap_anim`]. Created by [`start_or_retarget_snap`],
441/// advanced each frame by [`advance_snap`], and cleared when `finished`.
442///
443/// Angles are *relative* to the orientation captured at press time: the
444/// world-aligned candidate is resolved once by [`start_or_retarget_snap`]
445/// (via [`world_lattice_angles`] / [`next_lattice_step`]) and baked into
446/// `target_angle`; the animation then only applies angle differences through
447/// `rotate_local_z`.
448#[derive(Copy, Clone, Debug)]
449pub(crate) struct SnapRollAnim {
450    pub(crate) start_angle: f32,
451    pub(crate) target_angle: f32,
452    pub(crate) elapsed: f32,
453    pub(crate) duration: f32,
454    pub(crate) easing: SnapRollEasing,
455    pub(crate) current_applied: f32,
456}
457
458/// Minimum squared projection length a world axis needs on the roll plane to
459/// count as a lattice candidate in [`world_lattice_angles`]. Keeps an axis
460/// only when it lies ~45° or more away from local Z, so the axis pair the
461/// player is (roughly) looking along never yields near-degenerate up stops —
462/// a mostly-axis-aligned view gives 4 candidates, while a diagonal view (all
463/// axes at ~54.7°) keeps all 6. The constant is `0.49` rather than the exact
464/// `sin²(45°) = 0.5`: on a perfect 45° edge-on view both axis families sit at
465/// projection² ≈ 0.5 and float rounding could otherwise exclude BOTH,
466/// breaking the ≥4-candidate invariant.
467pub(crate) const SNAP_MIN_PROJ_SQ: f32 = 0.49;
468
469/// Angular tolerance in radians within which the reference up already lies ON
470/// a candidate; [`next_lattice_step`] skips that candidate so a press always
471/// produces visible motion (EPS_ON rule).
472pub(crate) const SNAP_EPS_ON: f32 = 1e-3;
473
474// ─── Component ───────────────────────────────────────────────────────────────
475
476/// State component that marks the player camera entity.
477///
478/// Attach this alongside [`Camera3d`] on a single entity. The camera entity
479/// IS the player — there is no separate logical-player / camera hierarchy.
480/// All player systems query for this component to locate the controlled entity.
481///
482/// Prefer constructing through [`PlayerConfig`] via [`spawn_player`] rather
483/// than inserting [`Player`] directly, which also sets the initial transform and
484/// projection from the resource.
485///
486/// # Default values
487///
488/// | Field         | Default  |
489/// |---------------|----------|
490/// | `speed`       | `4.0`    |
491/// | `sensitivity` | `1.0`    |
492/// | `roll_speed`  | `1.5`    |
493/// | `velocity`    | `ZERO`   |
494#[derive(Component, Debug, Clone)]
495pub struct Player {
496    /// Maximum flight speed in world units per second. Clamped implicitly by
497    /// the lerp target: actual speed never exceeds this value regardless of
498    /// frame rate.
499    pub speed: f32,
500    /// Mouse sensitivity multiplier (dimensionless). `1.0` matches the default
501    /// "Minecraft-like" feel via the internal `MOUSE_SCALE` constant; lower
502    /// values are slower, higher values are faster. The Settings slider exposes
503    /// the range `0.10`–`1.00` (10%–100%) to the user.
504    pub sensitivity: f32,
505    /// Roll angular speed in radians per second applied while Q (roll left) or
506    /// E (roll right) is held.
507    pub roll_speed: f32,
508    /// Current world-space velocity in world units per second. Smoothed each
509    /// frame by [`player_move`] using an exponential lerp; do not set this
510    /// directly unless you want to override the current momentum.
511    pub velocity: Vec3,
512    /// Movement mode, copied from [`PlayerConfig::mode`] on spawn.
513    ///
514    /// Determines which branch of [`player_look`], [`player_move`], and
515    /// [`player_resolve_collision`] is executed each frame.
516    pub mode: PlayerMode,
517    /// Vertical velocity used in [`PlayerMode::Grounded`] mode.
518    ///
519    /// Gravity accumulates here each frame; a jump impulse sets it to
520    /// [`PlayerMode::Grounded::jump_speed`]. Reset to `0.0` when the player
521    /// lands (collision pushes upward).  Unused in [`PlayerMode::FreeFlightSixDof`].
522    pub vertical_velocity: f32,
523    /// Whether the player was on solid ground at the end of the last frame.
524    ///
525    /// Set to `true` by [`player_resolve_collision`] when a voxel collision
526    /// produces an upward push; cleared to `false` at the start of each
527    /// collision pass.  Gating jumps on this flag prevents infinite jumping.
528    /// Unused in [`PlayerMode::FreeFlightSixDof`].
529    pub on_ground: bool,
530    /// Absolute landing speed (m/s) recorded when the player just touched ground.
531    ///
532    /// Set by [`player_resolve_collision`] on the first landing frame;
533    /// zero at all other times. Read by [`player_fall_damage`] to compute
534    /// and apply damage. Only meaningful in [`PlayerMode::Grounded`].
535    pub(crate) impact_speed: f32,
536    /// Accumulated seconds since the last footstep sound was emitted.
537    ///
538    /// Managed by [`player_footstep_system`]. Reset to `0.0` after each
539    /// footstep; only meaningful in [`PlayerMode::Grounded`].
540    pub(crate) footstep_timer: f32,
541    /// Whether the initial chunk load has completed.
542    ///
543    /// Set to `false` on spawn; flipped to `true` in `player_resolve_collision`
544    /// once the chunk at the player's feet is registered in [`ChunkManager`].
545    /// While `false`, gravity is suppressed so the player does not fall through
546    /// un-loaded terrain during world generation.
547    pub(crate) world_loaded: bool,
548    /// `true` until the player's first landing after spawn (or respawn).
549    ///
550    /// Skips fall-damage on that landing so a spawn point slightly above the
551    /// terrain surface does not instantly kill the player.  Cleared on first
552    /// contact with solid ground.
553    pub(crate) spawn_immune: bool,
554    /// Whether the player is currently sprinting.
555    ///
556    /// `true` when `Shift` is held in [`PlayerMode::Grounded`] with
557    /// [`Player::on_ground`] `true`, and [`Player::crouching`] is `false`.
558    /// Crouch takes priority: if both are held this is `false`.
559    /// Always `false` in [`PlayerMode::FreeFlightSixDof`].
560    pub sprinting: bool,
561    /// Whether the player is currently crouching.
562    ///
563    /// `true` when `Ctrl` is held in [`PlayerMode::Grounded`] mode.
564    /// Reduces the effective capsule half-height to [`CROUCH_HALF_HEIGHT`]
565    /// and movement speed to 40% of base speed.
566    /// Always `false` in [`PlayerMode::FreeFlightSixDof`].
567    pub crouching: bool,
568    /// Duration in seconds for a single snap-roll step animation (one hop to
569    /// the next world-aligned up candidate).
570    /// Only used when `roll_mode == RollMode::Snap`. **Default: `0.5`.**
571    pub snap_roll_duration: f32,
572    /// Easing curve for snap-roll animations.
573    /// Only used when `roll_mode == RollMode::Snap`.
574    pub snap_roll_easing: SnapRollEasing,
575    /// Active snap-roll animation state (runtime-only, not persisted).
576    pub(crate) snap_anim: Option<SnapRollAnim>,
577    /// Current anchor axis for [`PlayerMode::FreeFlightAnchored`] look: always one of the
578    /// 6 signed world axes. Yaw orbits this axis; pitch is clamped to ±89°
579    /// from the plane perpendicular to it. Initialized on spawn to the signed
580    /// world axis nearest the spawn orientation's up. Unused in
581    /// [`PlayerMode::FreeFlightSixDof`].
582    pub anchor_up: Vec3,
583    /// Source signed world axis of an in-flight anchor switch, committed to
584    /// [`Player::anchor_up`] when the animation finishes (runtime-only).
585    pub(crate) pending_anchor: Option<Vec3>,
586}
587
588impl Default for Player {
589    fn default() -> Self {
590        Self {
591            speed: 4.0,
592            sensitivity: 1.0,
593            roll_speed: 1.5,
594            velocity: Vec3::ZERO,
595            mode: PlayerMode::default(),
596            vertical_velocity: 0.0,
597            on_ground: false,
598            impact_speed: 0.0,
599            footstep_timer: 0.0,
600            world_loaded: false,
601            spawn_immune: true,
602            sprinting: false,
603            crouching: false,
604            snap_roll_duration: 0.5,
605            snap_roll_easing: SnapRollEasing::EaseOutCubic,
606            snap_anim: None,
607            anchor_up: Vec3::Y,
608            pending_anchor: None,
609        }
610    }
611}
612
613// ─── Configuration resource ───────────────────────────────────────────────────
614
615/// Startup configuration for [`spawn_player`].
616///
617/// Insert this resource before [`PlayerPlugin`] (or before the `Startup`
618/// schedule runs) to override any default. Fields are consumed once by
619/// [`spawn_player`]; changing the resource after spawn has no effect.
620///
621/// # Example
622///
623/// ```rust,no_run
624/// use bevy::prelude::*;
625/// use voxel_framework::player::PlayerConfig;
626///
627/// App::new()
628///     .insert_resource(PlayerConfig {
629///         spawn_position: Vec3::new(0.0, 50.0, 150.0),
630///         speed: 8.0,
631///         fov_degrees: 80.0,
632///         ..Default::default()
633///     });
634/// ```
635///
636/// # Default values
637///
638/// | Field           | Default                   |
639/// |-----------------|---------------------------|
640/// | `spawn_position`| `(0.0, 0.0, 30.0)`        |
641/// | `speed`         | `4.0` wu/s                |
642/// | `sensitivity`   | `1.0` (unitless multiplier) |
643/// | `roll_speed`    | `1.5` rad/s               |
644/// | `look_at`       | `Vec3::ZERO`              |
645/// | `fov_degrees`   | `90.0`                    |
646#[derive(Resource, Debug, Clone)]
647pub struct PlayerConfig {
648    /// World-space position at which the player entity is spawned.
649    pub spawn_position: Vec3,
650    /// Maximum flight speed in world units per second. Copied into
651    /// [`Player::speed`] on spawn.
652    pub speed: f32,
653    /// Mouse sensitivity multiplier (dimensionless). Copied into
654    /// [`Player::sensitivity`] on spawn. `1.0` = default "Minecraft-like" feel;
655    /// see `MOUSE_SCALE` for the underlying rad/px rate.
656    pub sensitivity: f32,
657    /// Roll angular speed in radians per second. Copied into
658    /// [`Player::roll_speed`] on spawn.
659    pub roll_speed: f32,
660    /// World-space point the camera looks toward immediately after spawning.
661    /// Only affects the initial orientation; the player can look anywhere
662    /// afterwards via mouse input.
663    pub look_at: Vec3,
664    /// Vertical field-of-view in degrees. Valid range: `50.0`–`120.0`.
665    /// Converted to radians and stored in the [`PerspectiveProjection`] on
666    /// spawn; runtime changes must be made directly on the [`Projection`]
667    /// component (e.g., via the Settings menu).
668    pub fov_degrees: f32,
669    /// Movement model used by the player systems.
670    ///
671    /// Defaults to [`PlayerMode::FreeFlightSixDof`] for backwards compatibility.
672    /// Set to [`PlayerMode::Grounded`] for gravity-based gameplay.
673    pub mode: PlayerMode,
674    /// Duration in seconds for a single snap-roll step animation (one hop to
675    /// the next world-aligned up candidate).
676    /// Copied into [`Player::snap_roll_duration`] on spawn. **Default: `0.5`.**
677    pub snap_roll_duration_secs: f32,
678    /// Easing curve for snap-roll animations.
679    /// Copied into [`Player::snap_roll_easing`] on spawn.
680    pub snap_roll_easing: SnapRollEasing,
681}
682
683impl Default for PlayerConfig {
684    fn default() -> Self {
685        Self {
686            spawn_position: Vec3::new(0.0, 0.0, 30.0),
687            speed: 4.0,
688            sensitivity: 1.0,
689            roll_speed: 1.5,
690            look_at: Vec3::ZERO,
691            fov_degrees: 90.0,
692            mode: PlayerMode::default(),
693            snap_roll_duration_secs: 0.5,
694            snap_roll_easing: SnapRollEasing::EaseOutCubic,
695        }
696    }
697}
698
699// ─── Systems ──────────────────────────────────────────────────────────────────
700
701/// Spawns the player camera entity configured by [`PlayerConfig`].
702///
703/// This system is **idempotent**: if a [`Player`] entity already exists in the
704/// world it returns immediately without spawning a second one. This makes it
705/// safe to register on `Startup` even when transitioning through `AppState`
706/// variants that re-enter the startup flow.
707///
708/// Leaves the cursor free. A focused left click through [`player_cursor_system`]
709/// activates native player input; pointer capture never grants keyboard focus.
710pub fn spawn_player(
711    mut commands: Commands,
712    config: Res<PlayerConfig>,
713    existing: Query<(), With<Player>>,
714    mut health: ResMut<PlayerHealth>,
715) {
716    if !existing.is_empty() {
717        return;
718    }
719
720    // Sync spawn_position with the configured spawn so respawn lands in the right place.
721    health.spawn_position = config.spawn_position;
722
723    let spawn = config.spawn_position;
724    let look_at = config.look_at;
725    let fov = config.fov_degrees.to_radians();
726    let mode = config.mode.clone();
727
728    // Build the transform first so the anchor axis can be derived from the
729    // actual spawn orientation.
730    let transform = Transform::from_translation(spawn).looking_at(look_at, Vec3::Y);
731
732    commands.spawn((
733        Player {
734            speed: config.speed,
735            sensitivity: config.sensitivity,
736            roll_speed: config.roll_speed,
737            velocity: Vec3::ZERO,
738            mode,
739            vertical_velocity: 0.0,
740            on_ground: false,
741            impact_speed: 0.0,
742            footstep_timer: 0.0,
743            world_loaded: false,
744            spawn_immune: true,
745            sprinting: false,
746            crouching: false,
747            snap_roll_duration: config.snap_roll_duration_secs,
748            snap_roll_easing: config.snap_roll_easing,
749            snap_anim: None,
750            anchor_up: nearest_world_axis(*transform.up()),
751            pending_anchor: None,
752        },
753        Camera3d::default(),
754        Projection::Perspective(PerspectiveProjection { fov, ..default() }),
755        transform,
756    ));
757}
758
759// ─── Snap roll helpers ──────────────────────────────────────────────────────
760
761pub(crate) fn apply_easing(t: f32, easing: SnapRollEasing) -> f32 {
762    match easing {
763        SnapRollEasing::EaseOutCubic => 1.0 - (1.0 - t).powi(3),
764        SnapRollEasing::EaseOutQuart => 1.0 - (1.0 - t).powi(4),
765        SnapRollEasing::Smoothstep => t * t * (3.0 - 2.0 * t),
766        SnapRollEasing::Linear => t,
767    }
768}
769
770/// The 6 signed world axes in canonical order.
771///
772/// The order is load-bearing: it is the candidate iteration order of
773/// [`world_lattice_candidates`] and the deterministic tie-break sequence of
774/// [`nearest_world_axis`] (first-in-order wins).
775pub(crate) const AXES: [Vec3; 6] = [
776    Vec3::X,
777    Vec3::NEG_X,
778    Vec3::Y,
779    Vec3::NEG_Y,
780    Vec3::Z,
781    Vec3::NEG_Z,
782];
783
784/// Like [`world_lattice_angles`] but returns `(angle δ, SOURCE signed world
785/// axis)` per surviving candidate.
786///
787/// The candidate set is the 6 signed world axes ([`AXES`]) projected onto
788/// the plane perpendicular to `local_z` and normalized. Axes whose projection
789/// has length² < [`SNAP_MIN_PROJ_SQ`] are excluded — an axis within 45° of
790/// the roll axis is "the one you are looking along" and would yield a
791/// perceptually arbitrary up stop (at least 4 candidates always survive).
792/// Each angle is `δ = atan2(cross(up, c) · local_z, up · c)` — the
793/// [`Transform::rotate_local_z`] convention, so δ feeds it unmodified.
794pub(crate) fn world_lattice_candidates(local_z: Vec3, up: Vec3) -> Vec<(f32, Vec3)> {
795    let mut candidates = Vec::with_capacity(6);
796    for axis in AXES {
797        let proj = axis - axis.dot(local_z) * local_z;
798        if proj.length_squared() < SNAP_MIN_PROJ_SQ {
799            continue;
800        }
801        let c = proj.normalize();
802        candidates.push((up.cross(c).dot(local_z).atan2(up.dot(c)), axis));
803    }
804    candidates
805}
806
807/// Signed roll angles δ ∈ (−π, π] from `up` to each surviving world-axis
808/// candidate around the roll axis `local_z` (Bevy's BACK vector).
809///
810/// Thin wrapper over [`world_lattice_candidates`] that drops each candidate's
811/// source axis — see that function for the lattice rule.
812pub(crate) fn world_lattice_angles(local_z: Vec3, up: Vec3) -> Vec<f32> {
813    world_lattice_candidates(local_z, up)
814        .into_iter()
815        .map(|(a, _)| a)
816        .collect()
817}
818
819/// Next lattice step in press direction `dir` (+1 = Q / CCW, −1 = E / CW).
820///
821/// dir > 0 → min over `{δ > SNAP_EPS_ON ? δ : δ + TAU}`;
822/// dir < 0 → max over `{δ < −SNAP_EPS_ON ? δ : δ − TAU}`.
823/// Candidates within [`SNAP_EPS_ON`] of the reference up wrap a full turn
824/// (EPS_ON rule), so the result is always a nonzero signed angle.
825pub(crate) fn next_lattice_step(angles: &[f32], dir: i32) -> f32 {
826    use std::f32::consts::TAU;
827    if dir > 0 {
828        angles
829            .iter()
830            .map(|&d| if d > SNAP_EPS_ON { d } else { d + TAU })
831            .fold(f32::INFINITY, f32::min)
832    } else {
833        angles
834            .iter()
835            .map(|&d| if d < -SNAP_EPS_ON { d } else { d - TAU })
836            .fold(f32::NEG_INFINITY, f32::max)
837    }
838}
839
840/// Mirror of [`next_lattice_step`] carrying each candidate's source axis:
841/// same [`SNAP_EPS_ON`] wrap, min (dir > 0) / max (dir < 0) by wrapped angle.
842/// Returns the wrapped angle together with the winning candidate's SOURCE
843/// signed world axis.
844///
845/// The caller guarantees a non-empty slice (the [`SNAP_MIN_PROJ_SQ`]
846/// ≥4-candidate invariant); panics otherwise rather than returning garbage.
847pub(crate) fn next_lattice_candidate(cands: &[(f32, Vec3)], dir: i32) -> (f32, Vec3) {
848    use std::f32::consts::TAU;
849    assert!(
850        !cands.is_empty(),
851        "next_lattice_candidate: empty candidate slice — SNAP_MIN_PROJ_SQ \
852         guarantees at least 4 lattice candidates"
853    );
854    if dir > 0 {
855        cands
856            .iter()
857            .map(|&(d, axis)| (if d > SNAP_EPS_ON { d } else { d + TAU }, axis))
858            .min_by(|a, b| a.0.total_cmp(&b.0))
859            .unwrap()
860    } else {
861        cands
862            .iter()
863            .map(|&(d, axis)| (if d < -SNAP_EPS_ON { d } else { d - TAU }, axis))
864            .max_by(|a, b| a.0.total_cmp(&b.0))
865            .unwrap()
866    }
867}
868
869/// Builds (or retargets) a snap-roll animation toward the next world-aligned
870/// up candidate in press direction `dir`.
871///
872/// `local_z` / `up` are `*transform.local_z()` / `*transform.up()` at press
873/// time. Every press resolves through one primitive — "next candidate in
874/// direction `dir` from a reference up" ([`world_lattice_angles`] +
875/// [`next_lattice_step`]):
876///
877/// - **Fresh press** — reference = `up`; the animation starts at `0.0`
878///   toward the first step.
879/// - **Same direction mid-animation** — reference = the in-flight target up
880///   (`up` advanced by the not-yet-applied residual; exact because
881///   `up ⊥ local_z`); retargets one candidate further, resuming from the
882///   currently applied angle.
883/// - **Opposite direction mid-animation** — reference = `up`; reverses to
884///   the nearest candidate behind, resuming from the currently applied angle.
885///
886/// The target is fixed here at press time and never re-resolved mid-flight.
887/// Angles stay relative: [`advance_snap`] applies only differences via
888/// `rotate_local_z`, so the animation lands exactly on the world candidate
889/// computed from `local_z` / `up`.
890pub(crate) fn start_or_retarget_snap(
891    existing: Option<SnapRollAnim>,
892    local_z: Vec3,
893    up: Vec3,
894    dir: i32,
895    duration: f32,
896    easing: SnapRollEasing,
897) -> SnapRollAnim {
898    match existing {
899        None => {
900            let step = next_lattice_step(&world_lattice_angles(local_z, up), dir);
901            SnapRollAnim {
902                start_angle: 0.0,
903                target_angle: step,
904                elapsed: 0.0,
905                duration,
906                easing,
907                current_applied: 0.0,
908            }
909        }
910        Some(anim) => {
911            let same_dir = (dir > 0 && anim.target_angle > anim.start_angle)
912                || (dir < 0 && anim.target_angle < anim.start_angle);
913
914            if same_dir {
915                // Reference = in-flight target up: advance `up` by the
916                // not-yet-applied residual, then extend one candidate further.
917                let residual = anim.target_angle - anim.current_applied;
918                let ref_up = Quat::from_axis_angle(local_z, residual) * up;
919                let step = next_lattice_step(&world_lattice_angles(local_z, ref_up), dir);
920                SnapRollAnim {
921                    start_angle: anim.current_applied,
922                    target_angle: anim.target_angle + step,
923                    elapsed: 0.0,
924                    duration,
925                    easing,
926                    current_applied: anim.current_applied,
927                }
928            } else {
929                // Opposite direction: nearest candidate behind current up.
930                let step = next_lattice_step(&world_lattice_angles(local_z, up), dir);
931                SnapRollAnim {
932                    start_angle: anim.current_applied,
933                    target_angle: anim.current_applied + step,
934                    elapsed: 0.0,
935                    duration,
936                    easing,
937                    current_applied: anim.current_applied,
938                }
939            }
940        }
941    }
942}
943
944/// The reference up [`start_or_retarget_snap`] resolves candidates from,
945/// replicated as a pure helper so the Anchored arm can compute the SOURCE
946/// axis of the exact candidate the animation will land on:
947///
948/// - Same direction mid-animation → `up` advanced by the not-yet-applied
949///   residual (`Quat::from_axis_angle(local_z, target − applied) * up`).
950/// - Fresh press or opposite direction → `up` unchanged.
951pub(crate) fn snap_reference_up(
952    existing: Option<SnapRollAnim>,
953    local_z: Vec3,
954    up: Vec3,
955    dir: i32,
956) -> Vec3 {
957    match existing {
958        Some(anim) => {
959            let same_dir = (dir > 0 && anim.target_angle > anim.start_angle)
960                || (dir < 0 && anim.target_angle < anim.start_angle);
961            if same_dir {
962                let residual = anim.target_angle - anim.current_applied;
963                Quat::from_axis_angle(local_z, residual) * up
964            } else {
965                up
966            }
967        }
968        None => up,
969    }
970}
971
972/// Clamps a pitch delta so `asin(forward · anchor_up)` stays within ±89°.
973///
974/// `pitch = asin(clamp(forward · anchor_up, −1, 1))`; returns
975/// `clamp(pitch + pitch_d, ±89°) − pitch`. The clamp-then-subtract form gives
976/// exact truncation at the poles for free: at the limit, outward deltas
977/// return 0 while inward deltas pass through. Pure and NaN-free (the dot is
978/// clamped to asin's domain).
979pub(crate) fn clamp_pitch_delta(forward: Vec3, anchor_up: Vec3, pitch_d: f32) -> f32 {
980    let limit = 89_f32.to_radians();
981    let pitch = forward.dot(anchor_up).clamp(-1.0, 1.0).asin();
982    (pitch + pitch_d).clamp(-limit, limit) - pitch
983}
984
985/// Signed world axis with the maximum dot product against `v`.
986///
987/// Iterates [`AXES`] in canonical order keeping the max with strict `>`, so
988/// ties break deterministically toward the first axis in the order
989/// `[X, NEG_X, Y, NEG_Y, Z, NEG_Z]`. Used to initialize
990/// [`Player::anchor_up`] at spawn.
991pub(crate) fn nearest_world_axis(v: Vec3) -> Vec3 {
992    let mut best = AXES[0];
993    let mut best_dot = v.dot(AXES[0]);
994    for axis in AXES.into_iter().skip(1) {
995        let d = v.dot(axis);
996        if d > best_dot {
997            best = axis;
998            best_dot = d;
999        }
1000    }
1001    best
1002}
1003
1004pub(crate) fn advance_snap(anim: &mut SnapRollAnim, dt: f32) -> (f32, bool) {
1005    anim.elapsed += dt;
1006    let t = (anim.elapsed / anim.duration).clamp(0.0, 1.0);
1007    let eased = apply_easing(t, anim.easing);
1008    let total = anim.start_angle + (anim.target_angle - anim.start_angle) * eased;
1009    let delta = total - anim.current_applied;
1010    anim.current_applied = total;
1011    let finished = anim.elapsed >= anim.duration;
1012    if finished {
1013        // Snap exactly to target to avoid FP residue
1014        let correction = anim.target_angle - anim.current_applied;
1015        anim.current_applied = anim.target_angle;
1016        return (delta + correction, true);
1017    }
1018    (delta, false)
1019}
1020
1021/// Updates the player orientation from mouse movement and Q/E roll keys.
1022///
1023/// Implements **true 6DOF rotation** with no pitch clamp. Each axis rotates
1024/// around the entity's *local* frame:
1025///
1026/// - Mouse X → `rotate_local_y` (yaw relative to current up)
1027/// - Mouse Y → `rotate_local_x` (pitch relative to current right)
1028/// - Q / E   → `rotate_local_z` (roll at [`Player::roll_speed`] rad/s)
1029///
1030/// Rotating in local space means all three axes compose correctly regardless
1031/// of the accumulated orientation — the player can pitch past vertical, roll
1032/// upside-down, and continue steering intuitively without gimbal lock.
1033///
1034/// All [`MouseMotion`] events for the frame are accumulated into a single
1035/// delta before applying rotation, preventing inter-frame jitter at high
1036/// polling rates.
1037pub fn player_look(
1038    mut query: Query<(&mut Player, &mut Transform)>,
1039    mut mouse_motion: MessageReader<MouseMotion>,
1040    keys: Res<ButtonInput<KeyCode>>,
1041    time: Res<Time>,
1042    windows: Query<(&Window, &CursorOptions), With<PrimaryWindow>>,
1043) {
1044    if !player_input_active(windows) {
1045        mouse_motion.clear();
1046        return;
1047    }
1048    let Ok((mut player, mut transform)) = query.single_mut() else {
1049        return;
1050    };
1051
1052    // Accumulate mouse delta for this frame.
1053    let mut delta = Vec2::ZERO;
1054    for event in mouse_motion.read() {
1055        delta += event.delta;
1056    }
1057
1058    match &player.mode {
1059        PlayerMode::FreeFlightSixDof { roll_mode } => {
1060            if delta != Vec2::ZERO {
1061                let yaw_d = -delta.x * MOUSE_SCALE * player.sensitivity;
1062                let pitch_d = -delta.y * MOUSE_SCALE * player.sensitivity;
1063                // Rotate around LOCAL axes — preserves 6DOF orientation.
1064                transform.rotate_local_y(yaw_d);
1065                transform.rotate_local_x(pitch_d);
1066            }
1067
1068            // Q / E roll.
1069            match roll_mode {
1070                RollMode::Continuous => {
1071                    let mut roll = 0.0_f32;
1072                    if keys.pressed(KeyCode::KeyQ) {
1073                        roll += 1.0;
1074                    }
1075                    if keys.pressed(KeyCode::KeyE) {
1076                        roll -= 1.0;
1077                    }
1078                    if roll != 0.0 {
1079                        transform.rotate_local_z(roll * player.roll_speed * time.delta_secs());
1080                    }
1081                }
1082                RollMode::Snap => {
1083                    if keys.just_pressed(KeyCode::KeyQ) {
1084                        player.snap_anim = Some(start_or_retarget_snap(
1085                            player.snap_anim,
1086                            *transform.local_z(),
1087                            *transform.up(),
1088                            1,
1089                            player.snap_roll_duration,
1090                            player.snap_roll_easing,
1091                        ));
1092                    }
1093                    if keys.just_pressed(KeyCode::KeyE) {
1094                        player.snap_anim = Some(start_or_retarget_snap(
1095                            player.snap_anim,
1096                            *transform.local_z(),
1097                            *transform.up(),
1098                            -1,
1099                            player.snap_roll_duration,
1100                            player.snap_roll_easing,
1101                        ));
1102                    }
1103                    if let Some(ref mut anim) = player.snap_anim {
1104                        let (delta, finished) = advance_snap(anim, time.delta_secs());
1105                        transform.rotate_local_z(delta);
1106                        if finished {
1107                            player.snap_anim = None;
1108                        }
1109                    }
1110                }
1111            }
1112        }
1113        PlayerMode::FreeFlightAnchored => {
1114            if delta != Vec2::ZERO {
1115                let yaw_d = -delta.x * MOUSE_SCALE * player.sensitivity;
1116                let pitch_d = -delta.y * MOUSE_SCALE * player.sensitivity;
1117                // Yaw: WORLD-space rotation around the anchor axis. While a
1118                // switch animation runs this is still the OLD anchor —
1119                // pending_anchor is only committed on finish.
1120                transform.rotate(Quat::from_axis_angle(player.anchor_up, yaw_d));
1121                // Pitch: local-X rotation, clamped so the elevation against
1122                // the anchor stays within ±89°.
1123                let clamped = clamp_pitch_delta(*transform.forward(), player.anchor_up, pitch_d);
1124                transform.rotate_local_x(clamped);
1125            }
1126
1127            // Q / E: switch the anchor to the next lattice candidate
1128            // (RollMode is ignored in Anchored look).
1129            if keys.just_pressed(KeyCode::KeyQ) {
1130                let local_z = *transform.local_z();
1131                let up = *transform.up();
1132                let ref_up = snap_reference_up(player.snap_anim, local_z, up, 1);
1133                let (_, axis) =
1134                    next_lattice_candidate(&world_lattice_candidates(local_z, ref_up), 1);
1135                player.pending_anchor = Some(axis);
1136                player.snap_anim = Some(start_or_retarget_snap(
1137                    player.snap_anim,
1138                    local_z,
1139                    up,
1140                    1,
1141                    player.snap_roll_duration,
1142                    player.snap_roll_easing,
1143                ));
1144            }
1145            if keys.just_pressed(KeyCode::KeyE) {
1146                let local_z = *transform.local_z();
1147                let up = *transform.up();
1148                let ref_up = snap_reference_up(player.snap_anim, local_z, up, -1);
1149                let (_, axis) =
1150                    next_lattice_candidate(&world_lattice_candidates(local_z, ref_up), -1);
1151                player.pending_anchor = Some(axis);
1152                player.snap_anim = Some(start_or_retarget_snap(
1153                    player.snap_anim,
1154                    local_z,
1155                    up,
1156                    -1,
1157                    player.snap_roll_duration,
1158                    player.snap_roll_easing,
1159                ));
1160            }
1161            if let Some(ref mut anim) = player.snap_anim {
1162                let (delta, finished) = advance_snap(anim, time.delta_secs());
1163                transform.rotate_local_z(delta);
1164                if finished {
1165                    // Commit the pure signed world axis, then renormalize
1166                    // the frame: look_to preserves forward and snaps
1167                    // screen-up onto the new anchor's projection, absorbing
1168                    // any roll accumulated vs. the new axis mid-animation.
1169                    if let Some(anchor) = player.pending_anchor.take() {
1170                        player.anchor_up = anchor;
1171                    }
1172                    let fwd = *transform.forward();
1173                    transform.look_to(fwd, player.anchor_up);
1174                    player.snap_anim = None;
1175                }
1176            }
1177        }
1178        PlayerMode::Grounded { .. } => {
1179            if delta != Vec2::ZERO {
1180                let yaw_d = -delta.x * MOUSE_SCALE * player.sensitivity;
1181                let pitch_d = -delta.y * MOUSE_SCALE * player.sensitivity;
1182
1183                // Yaw: rotate around WORLD Y so the player stays upright.
1184                transform.rotate_y(yaw_d);
1185
1186                // Pitch: decompose current rotation, apply clamped pitch.
1187                let (yaw, pitch, _roll) = transform.rotation.to_euler(EulerRot::YXZ);
1188                let new_pitch = (pitch + pitch_d).clamp(-89_f32.to_radians(), 89_f32.to_radians());
1189                transform.rotation = Quat::from_euler(EulerRot::YXZ, yaw, new_pitch, 0.0);
1190            }
1191            // No roll in grounded mode.
1192        }
1193    }
1194}
1195
1196/// Translates the player based on keyboard input and updates [`ViewerPosition`].
1197///
1198/// Movement axes are derived from the current entity rotation, so all six
1199/// directions (forward, back, left, right, up, down) are always relative to
1200/// wherever the player is currently looking — including after roll and pitch.
1201///
1202/// **Velocity smoothing** uses exponential lerp clamped to `[0, 1]`:
1203///
1204/// ```text
1205/// factor = if moving { acceleration } else { deceleration }  // PlayerMovementConfig
1206/// velocity = lerp(velocity, target, (factor * dt).min(1.0))
1207/// ```
1208///
1209/// This is frame-rate-independent for reasonable frame times and produces a
1210/// snappy start with a natural coast-to-stop deceleration.
1211///
1212/// After translating the entity, the system writes the new world position to
1213/// [`ViewerPosition`] so the chunk streaming system can load/unload chunks
1214/// around the player without querying the player transform directly.
1215pub fn player_move<V: VoxelType>(
1216    mut query: Query<(&mut Player, &mut Transform)>,
1217    keys: Res<ButtonInput<KeyCode>>,
1218    time: Res<Time>,
1219    mut viewer: ResMut<ViewerPosition>,
1220    manager: Res<ChunkManager>,
1221    chunks: Query<&Chunk<V>>,
1222    mut crouch_res: ResMut<PlayerCrouching>,
1223    applied: Option<Res<effects::AppliedEffectModifiers>>,
1224    windows: Query<(&Window, &CursorOptions), With<PrimaryWindow>>,
1225    movement: Option<Res<PlayerMovementConfig>>,
1226) {
1227    let Ok((mut player, mut transform)) = query.single_mut() else {
1228        return;
1229    };
1230
1231    if !player_input_active(windows) {
1232        player.velocity = Vec3::ZERO;
1233        return;
1234    }
1235    let dt = time.delta_secs();
1236    let accel = PlayerMovementConfig::acceleration_rate(movement.as_deref());
1237    let decel = PlayerMovementConfig::deceleration_rate(movement.as_deref());
1238
1239    match player.mode.clone() {
1240        PlayerMode::FreeFlightSixDof { .. } | PlayerMode::FreeFlightAnchored => {
1241            // Sprint/crouch are not applicable in FreeFlight.
1242            player.sprinting = false;
1243            player.crouching = false;
1244            crouch_res.0 = false;
1245
1246            // Local-space axes — full 6DOF.
1247            let forward = transform.rotation * Vec3::NEG_Z;
1248            let right = transform.rotation * Vec3::X;
1249            let up = transform.rotation * Vec3::Y;
1250
1251            let mut direction = Vec3::ZERO;
1252            if keys.pressed(KeyCode::KeyW) {
1253                direction += forward;
1254            }
1255            if keys.pressed(KeyCode::KeyS) {
1256                direction -= forward;
1257            }
1258            if keys.pressed(KeyCode::KeyA) {
1259                direction -= right;
1260            }
1261            if keys.pressed(KeyCode::KeyD) {
1262                direction += right;
1263            }
1264            if keys.pressed(KeyCode::Space) {
1265                direction += up;
1266            }
1267            if keys.pressed(KeyCode::ShiftLeft) || keys.pressed(KeyCode::ShiftRight) {
1268                direction -= up;
1269            }
1270
1271            let target = if direction != Vec3::ZERO {
1272                direction.normalize() * player.speed
1273            } else {
1274                Vec3::ZERO
1275            };
1276
1277            let factor = if direction != Vec3::ZERO {
1278                accel
1279            } else {
1280                decel
1281            };
1282            player.velocity = player.velocity.lerp(target, (factor * dt).min(1.0));
1283            transform.translation += player.velocity * dt;
1284        }
1285        PlayerMode::Grounded {
1286            gravity,
1287            jump_speed,
1288        } => {
1289            // Horizontal movement on XZ using yaw-only orientation.
1290            let yaw = transform.rotation.to_euler(EulerRot::YXZ).0;
1291            let forward = Vec3::new(-yaw.sin(), 0.0, -yaw.cos());
1292            let right = Vec3::new(yaw.cos(), 0.0, -yaw.sin());
1293
1294            let mut h_dir = Vec3::ZERO;
1295            if keys.pressed(KeyCode::KeyW) {
1296                h_dir += forward;
1297            }
1298            if keys.pressed(KeyCode::KeyS) {
1299                h_dir -= forward;
1300            }
1301            if keys.pressed(KeyCode::KeyA) {
1302                h_dir -= right;
1303            }
1304            if keys.pressed(KeyCode::KeyD) {
1305                h_dir += right;
1306            }
1307
1308            // Sprint (Shift) and crouch (Ctrl) speed multipliers.
1309            // Crouch takes priority over sprint if both are held.
1310            // Sprint only activates when on solid ground (no air-sprinting).
1311            let crouching =
1312                keys.pressed(KeyCode::ControlLeft) || keys.pressed(KeyCode::ControlRight);
1313            let sprinting = !crouching
1314                && player.on_ground
1315                && (keys.pressed(KeyCode::ShiftLeft) || keys.pressed(KeyCode::ShiftRight));
1316            player.crouching = crouching;
1317            player.sprinting = sprinting;
1318            crouch_res.0 = crouching;
1319            let speed_mult = if crouching {
1320                0.5
1321            } else if sprinting {
1322                SPRINT_MULTIPLIER
1323            } else {
1324                1.0
1325            };
1326
1327            // Sample the block under the player's feet to get movement modifiers.
1328            let foot_pos = transform.translation - Vec3::Y * (PLAYER_HALF_HEIGHT + 0.3);
1329            let modifier = get_voxel_at::<V>(foot_pos, &manager, &chunks)
1330                .map(|v| v.movement_modifier())
1331                .unwrap_or_default();
1332
1333            let effect_speed = applied.as_deref().map(|a| a.0.speed_mult).unwrap_or(1.0);
1334            let h_target = if h_dir != Vec3::ZERO {
1335                h_dir.normalize() * player.speed * speed_mult * modifier.speed_mult * effect_speed
1336            } else {
1337                Vec3::ZERO
1338            };
1339
1340            let effective_decel = decel * modifier.friction_mult;
1341            let factor = if h_dir != Vec3::ZERO {
1342                accel
1343            } else {
1344                effective_decel
1345            };
1346            player.velocity = player.velocity.lerp(h_target, (factor * dt).min(1.0));
1347
1348            // Freeze gravity until the initial chunk load completes so the
1349            // player does not fall through un-loaded terrain on startup.
1350            if !player.world_loaded {
1351                player.vertical_velocity = 0.0;
1352                transform.translation += player.velocity * dt;
1353                viewer.position = transform.translation;
1354                return;
1355            }
1356
1357            // Jump impulse (only when on the ground; disabled while crouching).
1358            if keys.just_pressed(KeyCode::Space) && player.on_ground && !crouching {
1359                let effect_jump = applied.as_deref().map(|a| a.0.jump_mult).unwrap_or(1.0);
1360                player.vertical_velocity = jump_speed * modifier.jump_mult * effect_jump;
1361            }
1362
1363            // Apply gravity.
1364            player.vertical_velocity -= gravity * modifier.gravity_mult * dt;
1365
1366            // Water buoyancy: if the player's center voxel is transparent (e.g.
1367            // water), apply a gentle upward push each frame to make them float
1368            // toward the surface. The movement_modifier already reduces gravity
1369            // via gravity_mult; buoyancy adds a positive upward impulse.
1370            let center_voxel = get_voxel_at::<V>(transform.translation, &manager, &chunks);
1371            if center_voxel.map(|v| v.alpha() < 1.0).unwrap_or(false) {
1372                player.vertical_velocity += jump_speed * 0.3 * dt;
1373            }
1374
1375            // Translate: horizontal from smoothed velocity + vertical from gravity.
1376            transform.translation += player.velocity * dt;
1377            transform.translation.y += player.vertical_velocity * dt;
1378        }
1379    }
1380
1381    // Keep the streaming origin at the player position.
1382    viewer.position = transform.translation;
1383}
1384
1385/// Resolves capsule-vs-voxel AABB collisions and repositions the player.
1386///
1387/// The collision shape is a capsule whose spine runs along the player's **local
1388/// Y axis** between `±PLAYER_HALF_HEIGHT`. Because the spine follows the
1389/// entity rotation, roll and pitch do not break collision detection — the
1390/// capsule tilts with the player.
1391///
1392/// **Algorithm (per chunk, per solid voxel in the AABB):**
1393///
1394/// 1. Compute the axis-aligned bounding box of the capsule in chunk-local space.
1395/// 2. Clamp the AABB to the chunk bounds to skip out-of-range voxels.
1396/// 3. For each solid voxel in the range, call `push_capsule_out` which:
1397///    a. Finds the closest point on the capsule spine to the voxel AABB center.
1398///    b. Treats that point as a sphere center of radius [`PLAYER_RADIUS`].
1399///    c. Computes the minimum separation vector from the sphere to the voxel AABB.
1400///    d. Accumulates the push into the running position.
1401///
1402/// The final corrected position is written back to the player transform. This
1403/// system should always run **after** [`player_move`] in the same frame.
1404///
1405/// When the player arrives at a surface faster than
1406/// [`PlayerMovementConfig::impact_speed_threshold`], one [`PlayerImpact`] is
1407/// written (if the message is registered). The player's velocity is not
1408/// changed by the collision.
1409pub fn player_resolve_collision<V: VoxelType>(
1410    mut player_q: Query<(&mut Player, &mut Transform)>,
1411    chunk_q: Query<(&Chunk<V>, &Transform), Without<Player>>,
1412    manager: Res<ChunkManager>,
1413    movement: Option<Res<PlayerMovementConfig>>,
1414    impacts: Option<ResMut<Messages<PlayerImpact>>>,
1415    mut was_impacting: Local<bool>,
1416) {
1417    let Ok((mut player, mut player_tf)) = player_q.single_mut() else {
1418        return;
1419    };
1420
1421    // Grounded mode tracks whether the player is standing on solid ground.
1422    let is_grounded = matches!(player.mode, PlayerMode::Grounded { .. });
1423    // Velocity the player arrives with, before landing zeroes the vertical part.
1424    let incoming_velocity = if is_grounded {
1425        player.velocity + Vec3::Y * player.vertical_velocity
1426    } else {
1427        player.velocity
1428    };
1429    let start_pos = player_tf.translation;
1430    if is_grounded {
1431        player.on_ground = false;
1432        player.impact_speed = 0.0; // reset each frame; set below on landing
1433    }
1434
1435    // Use reduced capsule height when crouching so the player fits through
1436    // 1-block-tall gaps. In FreeFlight mode crouching is always false.
1437    let half_height = if player.crouching {
1438        CROUCH_HALF_HEIGHT
1439    } else {
1440        PLAYER_HALF_HEIGHT
1441    };
1442
1443    // Enable gravity only once the chunk containing the player's feet is
1444    // registered in ChunkManager — meaning the generator has actually produced
1445    // terrain data for that chunk.  Checking a distant chunk being present
1446    // (chunk_q.is_empty) is not sufficient: it fires too early.
1447    if !player.world_loaded {
1448        let feet = player_tf.translation - Vec3::Y * half_height;
1449        let coord = crate::chunk::world_to_chunk_coord(feet);
1450        if manager.is_loaded(coord) {
1451            player.world_loaded = true;
1452        }
1453    }
1454
1455    let mut pos = player_tf.translation;
1456    // FreeFlight: capsule spine follows entity rotation (true 6DOF).
1457    // Grounded: spine is always world-vertical (Vec3::Y) so the capsule stands upright.
1458    let up = if is_grounded {
1459        Vec3::Y
1460    } else {
1461        player_tf.rotation * Vec3::Y
1462    };
1463
1464    let extent = half_height + PLAYER_RADIUS;
1465    let voxel_size = VOXEL_SIZE;
1466
1467    for (chunk, chunk_tf) in &chunk_q {
1468        let chunk_pos = chunk_tf.translation;
1469        let local = pos - chunk_pos;
1470
1471        // AABB of voxels that could possibly overlap the capsule.
1472        let min_vox = IVec3::new(
1473            ((local.x - extent) / voxel_size).floor() as i32,
1474            ((local.y - extent) / voxel_size).floor() as i32,
1475            ((local.z - extent) / voxel_size).floor() as i32,
1476        );
1477        let max_vox = IVec3::new(
1478            ((local.x + extent) / voxel_size).ceil() as i32,
1479            ((local.y + extent) / voxel_size).ceil() as i32,
1480            ((local.z + extent) / voxel_size).ceil() as i32,
1481        );
1482
1483        // Clamp to chunk bounds for the loop — is_solid_at returns false for
1484        // out-of-range coords, but skipping them avoids pointless iterations.
1485        let lo = min_vox.max(IVec3::ZERO);
1486        let hi = max_vox.min(IVec3::splat(CHUNK_SIZE as i32 - 1));
1487
1488        for vx in lo.x..=hi.x {
1489            for vy in lo.y..=hi.y {
1490                for vz in lo.z..=hi.z {
1491                    if !chunk.is_solid_at(vx as usize, vy as usize, vz as usize) {
1492                        continue;
1493                    }
1494                    let new_pos = push_capsule_out(pos, up, half_height, chunk_pos, vx, vy, vz);
1495
1496                    // In grounded mode detect landing: a positive Y correction
1497                    // means the player was pushed upward off a solid surface.
1498                    if is_grounded && new_pos.y > pos.y + 0.001 {
1499                        if !player.on_ground {
1500                            // First contact this frame — record impact speed for fall damage.
1501                            player.impact_speed = player.vertical_velocity.abs();
1502                        }
1503                        player.on_ground = true;
1504                        player.vertical_velocity = 0.0;
1505                    }
1506
1507                    pos = new_pos;
1508                }
1509            }
1510        }
1511    }
1512
1513    player_tf.translation = pos;
1514
1515    // Report an impact when the speed into the surface rises above the
1516    // threshold. The total push-out gives the surface normal.
1517    let push = pos - start_pos;
1518    let speed_into_surface = push
1519        .try_normalize()
1520        .map(|normal| (normal, (-incoming_velocity.dot(normal)).max(0.0)));
1521    let threshold = PlayerMovementConfig::impact_threshold(movement.as_deref());
1522    let is_impacting = speed_into_surface.is_some_and(|(_, speed)| speed > threshold);
1523    if is_impacting
1524        && !*was_impacting
1525        && let Some((normal, speed)) = speed_into_surface
1526        && let Some(mut impacts) = impacts
1527    {
1528        impacts.write(PlayerImpact {
1529            position: pos,
1530            normal,
1531            speed,
1532        });
1533    }
1534    *was_impacting = is_impacting;
1535}
1536
1537// ─── Cursor grab ──────────────────────────────────────────────────────────────
1538
1539/// Manages the primary window's cursor capture.
1540///
1541/// | Trigger | Cursor state before | Effect |
1542/// |---------|---------------------|--------|
1543/// | Window loses focus | Locked | Releases cursor, shows it |
1544/// | Left click in the focused window | Free (`None`) | Locks cursor, hides it |
1545/// | Escape | Locked | Releases cursor, shows it |
1546/// | Escape | Free | Despawns the window entity (closes the app) |
1547///
1548/// ## With the pause menu
1549///
1550/// When [`PauseMenuPlugin`](crate::ui::PauseMenuPlugin) is installed (its
1551/// [`PauseMenuState`](crate::ui::PauseMenuState) exists) the pause menu owns
1552/// Escape: this system ignores the key, so Escape opens the menu instead of
1553/// releasing the cursor or closing the window. Click-to-capture and
1554/// focus-loss release keep working while the state is `Playing`, and clicks
1555/// are ignored while a menu is open, so menu buttons never capture the cursor.
1556/// The two can be used together; [`PlayerPlugin`] does exactly that.
1557pub fn player_cursor_system(
1558    mut commands: Commands,
1559    mouse: Res<ButtonInput<MouseButton>>,
1560    keys: Res<ButtonInput<KeyCode>>,
1561    mut windows: Query<(Entity, &Window, &mut CursorOptions), With<PrimaryWindow>>,
1562    pause: Option<Res<State<crate::ui::PauseMenuState>>>,
1563) {
1564    use crate::ui::PauseMenuState;
1565
1566    let pause_menu_installed = pause.is_some();
1567    let menu_open = pause.is_some_and(|state| !matches!(state.get(), PauseMenuState::Playing));
1568
1569    for (entity, window, mut cursor) in windows.iter_mut() {
1570        if !window.focused {
1571            if cursor.grab_mode != CursorGrabMode::None || !cursor.visible {
1572                cursor.grab_mode = CursorGrabMode::None;
1573                cursor.visible = true;
1574            }
1575            continue;
1576        }
1577        if menu_open {
1578            // The pause menu shows a free cursor; its clicks are for buttons.
1579            continue;
1580        }
1581        if mouse.just_pressed(MouseButton::Left)
1582            && cursor.grab_mode == bevy::window::CursorGrabMode::None
1583        {
1584            cursor.grab_mode = bevy::window::CursorGrabMode::Locked;
1585            cursor.visible = false;
1586        }
1587
1588        // With the pause menu installed, Escape opens the menu instead.
1589        if !pause_menu_installed && keys.just_pressed(KeyCode::Escape) {
1590            if cursor.grab_mode != bevy::window::CursorGrabMode::None {
1591                cursor.grab_mode = bevy::window::CursorGrabMode::None;
1592                cursor.visible = true;
1593            } else {
1594                commands.entity(entity).despawn();
1595            }
1596        }
1597    }
1598}
1599
1600/// Whether the primary window owns player input (focused and cursor captured).
1601/// No primary window preserves synthetic input for headless simulations.
1602///
1603/// Useful as a run condition for other gameplay input systems. Keep
1604/// [`player_look`] scheduled: it discards inactive mouse deltas itself.
1605/// This checks Bevy's current window state, not OS activation or grab success.
1606pub fn player_input_active(windows: Query<(&Window, &CursorOptions), With<PrimaryWindow>>) -> bool {
1607    match windows.single() {
1608        Ok((window, cursor)) => window.focused && cursor.grab_mode != CursorGrabMode::None,
1609        Err(_) => windows.is_empty(),
1610    }
1611}
1612
1613/// Applies fall damage when the player lands after a significant drop.
1614///
1615/// Reads `Player::impact_speed` set by [`player_resolve_collision`] and
1616/// computes damage as `(impact_speed - fall_safe_speed).max(0) * 2.0`. When
1617/// health reaches zero the player is teleported to [`PlayerHealth::spawn_position`]
1618/// and a [`PlayerDied`] message is sent.
1619///
1620/// Run this system **after** [`player_resolve_collision`].
1621pub fn player_fall_damage(
1622    mut player_q: Query<(&mut Player, &mut Transform)>,
1623    mut health: ResMut<PlayerHealth>,
1624    mut damaged_writer: MessageWriter<PlayerDamaged>,
1625    mut died_writer: MessageWriter<PlayerDied>,
1626) {
1627    let Ok((mut player, mut transform)) = player_q.single_mut() else {
1628        return;
1629    };
1630
1631    if player.impact_speed <= 0.0 {
1632        return;
1633    }
1634
1635    // First landing after spawn or respawn is immune to fall damage so the
1636    // player doesn't die just because the spawn point is a few blocks above
1637    // the terrain surface.
1638    if player.spawn_immune {
1639        player.spawn_immune = false;
1640        player.impact_speed = 0.0;
1641        return;
1642    }
1643
1644    let damage = (player.impact_speed - health.fall_safe_speed).max(0.0) * 2.0;
1645    player.impact_speed = 0.0;
1646
1647    if damage <= 0.0 {
1648        return;
1649    }
1650
1651    health.health = (health.health - damage).max(0.0);
1652    damaged_writer.write(PlayerDamaged { amount: damage });
1653
1654    if health.health <= 0.0 {
1655        health.health = health.max_health;
1656        transform.translation = health.spawn_position;
1657        // Reset velocity so the player doesn't inherit falling momentum after respawn.
1658        player.vertical_velocity = 0.0;
1659        player.velocity = Vec3::ZERO;
1660        player.world_loaded = false; // re-freeze gravity until feet chunk reloads
1661        player.spawn_immune = true; // grant immunity on the next landing too
1662        died_writer.write(PlayerDied);
1663    }
1664}
1665
1666/// Processes incoming damage messages and runs the death / respawn check.
1667///
1668/// Regen and poison are handled exclusively by
1669/// [`apply_health_effects`](crate::player::effects::apply_health_effects)
1670/// inside [`StatusEffectsPlugin`](crate::player::effects::StatusEffectsPlugin).
1671/// This system only reads [`AppliedEffectModifiers`](crate::player::effects::AppliedEffectModifiers) to apply damage resistance
1672/// to incoming [`PlayerDamaged`] events. `AppliedEffectModifiers` is optional —
1673/// the system degrades gracefully when no `StatusEffectsPlugin` is registered.
1674///
1675/// Run this system **every frame**, regardless of pause state.
1676pub fn health_system(
1677    applied: Option<Res<effects::AppliedEffectModifiers>>,
1678    mut health: ResMut<PlayerHealth>,
1679    mut damaged_reader: bevy::ecs::message::MessageReader<PlayerDamaged>,
1680    mut died_writer: MessageWriter<PlayerDied>,
1681) {
1682    // Process every pending damage event, reduced by damage resistance.
1683    for event in damaged_reader.read() {
1684        let resistance = applied
1685            .as_ref()
1686            .map(|a| a.0.damage_resistance)
1687            .unwrap_or(0.0);
1688        let actual = event.amount * (1.0 - resistance.clamp(0.0, 1.0));
1689        health.health = (health.health - actual).max(0.0);
1690    }
1691
1692    // Death check — instant respawn (position is handled by respawn_system).
1693    if health.health <= 0.0 {
1694        health.health = health.max_health;
1695        died_writer.write(PlayerDied);
1696    }
1697}
1698
1699/// Teleports the streaming origin to the spawn position on player death.
1700///
1701/// Listens for [`PlayerDied`] messages and updates [`ViewerPosition`] so the
1702/// chunk streaming system starts loading terrain around the respawn location
1703/// immediately. Physical entity teleportation is handled by
1704/// [`player_fall_damage`].
1705///
1706/// If no [`PlayerConfig`] resource is present, the player is teleported to
1707/// [`Vec3::ZERO`].
1708pub fn respawn_system(
1709    mut died_reader: bevy::ecs::message::MessageReader<PlayerDied>,
1710    mut viewer: ResMut<ViewerPosition>,
1711    config: Option<Res<PlayerConfig>>,
1712) {
1713    for _ in died_reader.read() {
1714        let spawn = config
1715            .as_ref()
1716            .map(|c| c.spawn_position)
1717            .unwrap_or(Vec3::ZERO);
1718        viewer.position = spawn;
1719    }
1720}
1721
1722// ─── Push helper ─────────────────────────────────────────────────────────────
1723
1724/// Returns the corrected capsule-center position after pushing out of a solid voxel.
1725///
1726/// The algorithm treats the capsule as a swept sphere along the spine segment
1727/// `[pos − up*half_height, pos + up*half_height]`:
1728///
1729/// 1. Find the point on the spine segment closest to the voxel AABB center
1730///    (clamped parametric projection, `t ∈ [0, 1]`).
1731/// 2. Treat that spine point as a sphere center `sphere_c` with radius
1732///    [`PLAYER_RADIUS`].
1733/// 3. Find the point on the voxel AABB closest to `sphere_c`.
1734/// 4. If the sphere overlaps the AABB (distance² < `PLAYER_RADIUS²`), compute
1735///    the minimum translation vector and apply it to `pos`.
1736///
1737/// A degenerate case (sphere center exactly inside the voxel) is handled by
1738/// pushing along the dominant axis of the relative offset to avoid a zero-
1739/// length normal.
1740fn push_capsule_out(
1741    pos: Vec3,
1742    up: Vec3,
1743    half_height: f32,
1744    chunk_pos: Vec3,
1745    vx: i32,
1746    vy: i32,
1747    vz: i32,
1748) -> Vec3 {
1749    let vmin = chunk_pos + Vec3::new(vx as f32, vy as f32, vz as f32) * VOXEL_SIZE;
1750    let vmax = vmin + Vec3::splat(VOXEL_SIZE);
1751
1752    // Capsule spine endpoints.
1753    let p0 = pos - up * half_height;
1754    let p1 = pos + up * half_height;
1755    let spine = p1 - p0;
1756
1757    // Closest point on spine to the voxel center.
1758    let vox_center = (vmin + vmax) * 0.5;
1759    let len_sq = spine.length_squared();
1760    let sphere_c = if len_sq > f32::EPSILON {
1761        let t = ((vox_center - p0).dot(spine) / len_sq).clamp(0.0, 1.0);
1762        p0 + spine * t
1763    } else {
1764        pos
1765    };
1766
1767    // Sphere-AABB collision.
1768    let closest = sphere_c.clamp(vmin, vmax);
1769    let diff = sphere_c - closest;
1770    let dist_sq = diff.length_squared();
1771
1772    if dist_sq >= PLAYER_RADIUS * PLAYER_RADIUS {
1773        return pos;
1774    }
1775
1776    let delta = if dist_sq > f32::EPSILON {
1777        let dist = dist_sq.sqrt();
1778        (diff / dist) * (PLAYER_RADIUS - dist)
1779    } else {
1780        // Degenerate: center exactly inside voxel — push along dominant axis.
1781        let rel = sphere_c - vox_center;
1782        let abs_rel = rel.abs();
1783        let half = VOXEL_SIZE * 0.5 + PLAYER_RADIUS;
1784        if abs_rel.x >= abs_rel.y && abs_rel.x >= abs_rel.z {
1785            Vec3::new(half * rel.x.signum() - rel.x, 0.0, 0.0)
1786        } else if abs_rel.y >= abs_rel.z {
1787            Vec3::new(0.0, half * rel.y.signum() - rel.y, 0.0)
1788        } else {
1789            Vec3::new(0.0, 0.0, half * rel.z.signum() - rel.z)
1790        }
1791    };
1792
1793    pos + delta
1794}
1795
1796/// Emits [`SfxRequest`] footstep sounds when the player walks on solid ground.
1797///
1798/// Samples the voxel directly below the player's feet and passes its byte
1799/// representation as [`SfxEvent::Footstep`] so games can map surface types to
1800/// different audio assets. The step interval scales with horizontal speed.
1801pub fn player_footstep_system<V: VoxelType>(
1802    mut query: Query<(&mut Player, &Transform)>,
1803    time: Res<Time>,
1804    manager: Res<ChunkManager>,
1805    chunks: Query<&Chunk<V>>,
1806    mut sfx: MessageWriter<SfxRequest>,
1807) {
1808    let Ok((mut player, transform)) = query.single_mut() else {
1809        return;
1810    };
1811
1812    if !matches!(player.mode, PlayerMode::Grounded { .. }) || !player.on_ground {
1813        return;
1814    }
1815
1816    let h_speed = Vec3::new(player.velocity.x, 0.0, player.velocity.z).length();
1817    if h_speed < 0.5 {
1818        player.footstep_timer = 0.0;
1819        return;
1820    }
1821
1822    // Step interval: shorter at higher speeds (clamped between 0.2–0.5s).
1823    let step_interval = (0.5 / h_speed).clamp(0.2, 0.5);
1824    player.footstep_timer += time.delta_secs();
1825
1826    if player.footstep_timer < step_interval {
1827        return;
1828    }
1829    player.footstep_timer = 0.0;
1830
1831    // Sample voxel just below the player's feet.
1832    let foot_pos = transform.translation - Vec3::Y * (PLAYER_HALF_HEIGHT + 0.3);
1833    let voxel_byte = get_voxel_at::<V>(foot_pos, &manager, &chunks)
1834        .map(|v| v.to_byte())
1835        .unwrap_or(0);
1836
1837    sfx.write(SfxRequest {
1838        event: SfxEvent::Footstep(voxel_byte),
1839        position: None,
1840    });
1841}
1842
1843// ─── Spawn persistence ────────────────────────────────────────────────────────
1844
1845/// Startup system that applies a persisted spawn position to [`PlayerConfig`]
1846/// and [`PlayerHealth`] before the player entity is spawned.
1847///
1848/// Reads the world data directory from [`WorldDataDir`] (set by
1849/// [`PlayerPlugin::with_world`]).  Silent no-op if `player_data.json` does not
1850/// exist.
1851fn load_spawn_on_startup(
1852    mut config: ResMut<PlayerConfig>,
1853    mut health: ResMut<PlayerHealth>,
1854    world_data_dir: Res<WorldDataDir>,
1855) {
1856    let data_dir = world_data_dir.as_str();
1857    if let Some(pos) = persistence::load_spawn_position(data_dir) {
1858        config.spawn_position = pos;
1859        health.spawn_position = pos;
1860    } else {
1861        // First run: persist the configured default so subsequent runs reload it.
1862        persistence::save_spawn_position(config.spawn_position, data_dir);
1863    }
1864}
1865
1866/// System that saves [`PlayerHealth::spawn_position`] to disk on [`AppExit`].
1867///
1868/// This preserves a custom spawn set at runtime (e.g. sleeping in a bed)
1869/// across sessions.  The [`PlayerConfig::spawn_position`] default is used as
1870/// fallback when no file exists.
1871fn save_spawn_on_exit(
1872    health: Res<PlayerHealth>,
1873    world_data_dir: Res<WorldDataDir>,
1874    mut exit_reader: bevy::ecs::message::MessageReader<AppExit>,
1875) {
1876    for _ in exit_reader.read() {
1877        persistence::save_spawn_position(health.spawn_position, world_data_dir.as_str());
1878    }
1879}
1880
1881// ─── Run condition ────────────────────────────────────────────────────────────
1882
1883/// Returns `true` when gameplay should be active.
1884///
1885/// If [`crate::ui::PauseMenuState`] is registered, returns `true`
1886/// only while in the `Playing` variant. If the state is not present (i.e.
1887/// [`crate::ui::PauseMenuPlugin`] was not added), always returns `true` so the
1888/// player systems run unconditionally.
1889fn gameplay_active(state: Option<Res<bevy::prelude::State<crate::ui::PauseMenuState>>>) -> bool {
1890    use crate::ui::PauseMenuState;
1891    state.map_or(true, |s| matches!(s.get(), PauseMenuState::Playing))
1892}
1893
1894// ─── System set ───────────────────────────────────────────────────────────────
1895
1896/// System set containing every `Update` system that [`PlayerPlugin`] adds.
1897///
1898/// Use it to order the player against your own systems or to add a run
1899/// condition without registering the player systems by hand:
1900///
1901/// ```rust,no_run
1902/// use bevy::prelude::*;
1903/// use voxel_framework::prelude::*;
1904///
1905/// #[derive(States, Default, Clone, PartialEq, Eq, Hash, Debug)]
1906/// enum AppState { #[default] Menu, InGame }
1907///
1908/// App::new()
1909///     .add_plugins(PlayerPlugin::<DefaultVoxel>::new())
1910///     .configure_sets(Update, PlayerSystems.run_if(in_state(AppState::InGame)));
1911/// ```
1912///
1913/// Conditions added here combine with the plugin's own pause gating.
1914#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
1915pub struct PlayerSystems;
1916
1917// ─── Plugin ───────────────────────────────────────────────────────────────────
1918
1919/// Plugin that wires up the complete 6DOF player controller.
1920///
1921/// Registers [`PlayerConfig`] as an init resource, spawns the player camera
1922/// on `Startup`, and chains the three frame-update systems in the correct
1923/// dependency order every `Update`:
1924///
1925/// ```text
1926/// player_look → player_move → player_resolve_collision<V>
1927/// ```
1928///
1929/// [`player_cursor_system`] is added as a separate, un-chained `Update` system
1930/// so cursor events are processed independently of the movement pipeline.
1931///
1932/// ## Pause menu
1933///
1934/// The plugin works together with [`PauseMenuPlugin`](crate::ui::PauseMenuPlugin):
1935/// when that plugin is installed, look, movement and collision run only in
1936/// `PauseMenuState::Playing`, and Escape opens the menu. The cursor system,
1937/// health and respawn keep running while paused; the cursor system then only
1938/// releases the cursor on focus loss. Without the pause menu
1939/// everything runs every frame.
1940///
1941/// ## Extra conditions and ordering
1942///
1943/// All `Update` systems of the plugin are in [`PlayerSystems`]. Configure that
1944/// set to gate the player on your own state or to order it against your
1945/// systems. Registering the systems manually is still possible:
1946///
1947/// ```rust,no_run
1948/// # use bevy::prelude::*;
1949/// # use voxel_framework::player::{spawn_player, player_look, player_move,
1950/// #     player_resolve_collision};
1951/// # use voxel_framework::voxel::DefaultVoxel;
1952/// # #[derive(States, Default, Clone, PartialEq, Eq, Hash, Debug)]
1953/// # enum AppState { #[default] Playing }
1954/// App::new()
1955///     .add_systems(Startup, spawn_player)
1956///     .add_systems(Update,
1957///         (player_look, player_move::<DefaultVoxel>, player_resolve_collision::<DefaultVoxel>)
1958///             .chain()
1959///             .run_if(in_state(AppState::Playing)),
1960///     );
1961/// ```
1962///
1963/// The generic parameter `V` must match the [`VoxelType`] used by the loaded
1964/// [`Chunk`] entities so the collision system can read
1965/// solid-voxel data.
1966pub struct PlayerPlugin<V: VoxelType> {
1967    _marker: std::marker::PhantomData<V>,
1968    world_name: String,
1969}
1970
1971impl<V: VoxelType> PlayerPlugin<V> {
1972    /// Creates a `PlayerPlugin` using the default world name (`"world"`).
1973    pub fn new() -> Self {
1974        Self {
1975            _marker: std::marker::PhantomData,
1976            world_name: String::new(),
1977        }
1978    }
1979
1980    /// Creates a `PlayerPlugin` that stores player data under
1981    /// `./worlds/{world_name}/player_data.json`.
1982    pub fn with_world(world_name: impl Into<String>) -> Self {
1983        Self {
1984            _marker: std::marker::PhantomData,
1985            world_name: world_name.into(),
1986        }
1987    }
1988}
1989
1990impl<V: VoxelType> Default for PlayerPlugin<V> {
1991    fn default() -> Self {
1992        Self::new()
1993    }
1994}
1995
1996impl<V: VoxelType> Plugin for PlayerPlugin<V> {
1997    fn build(&self, app: &mut App) {
1998        let name = if self.world_name.is_empty() {
1999            "world"
2000        } else {
2001            &self.world_name
2002        };
2003        app.insert_resource(WorldDataDir::for_world(name));
2004        app.init_resource::<PlayerConfig>();
2005        app.init_resource::<PlayerHealth>();
2006        app.init_resource::<PlayerCrouching>();
2007        app.add_message::<PlayerDamaged>();
2008        app.add_message::<PlayerDied>();
2009        app.init_resource::<PlayerMovementConfig>();
2010        app.add_message::<PlayerImpact>();
2011        app.add_systems(Startup, (load_spawn_on_startup, spawn_player).chain());
2012        app.add_systems(
2013            Update,
2014            (
2015                player_look,
2016                player_move::<V>,
2017                player_resolve_collision::<V>,
2018                player_fall_damage,
2019                player_footstep_system::<V>,
2020            )
2021                .chain()
2022                .run_if(gameplay_active)
2023                .in_set(PlayerSystems),
2024        );
2025        // health_system and respawn_system are not gated by pause.
2026        app.add_systems(
2027            Update,
2028            (health_system, respawn_system).in_set(PlayerSystems),
2029        );
2030        app.add_systems(
2031            Update,
2032            // Not gated by pause: the system ignores clicks and Escape itself
2033            // while a menu is open, and must still release on focus loss.
2034            player_cursor_system
2035                .before(player_look)
2036                .in_set(PlayerSystems),
2037        );
2038        app.add_systems(PostUpdate, save_spawn_on_exit);
2039    }
2040}
2041
2042// ─── Tests ────────────────────────────────────────────────────────────────────
2043
2044#[cfg(test)]
2045mod tests {
2046    use super::*;
2047
2048    #[test]
2049    fn player_default_values() {
2050        let p = Player::default();
2051        assert_eq!(p.speed, 4.0);
2052        assert_eq!(p.sensitivity, 1.0);
2053        assert_eq!(p.roll_speed, 1.5);
2054        assert_eq!(p.velocity, Vec3::ZERO);
2055    }
2056
2057    #[test]
2058    fn player_config_default_values() {
2059        let c = PlayerConfig::default();
2060        assert_eq!(c.speed, 4.0);
2061        assert_eq!(c.fov_degrees, 90.0);
2062        assert!(matches!(
2063            c.mode,
2064            PlayerMode::FreeFlightSixDof {
2065                roll_mode: RollMode::Continuous
2066            }
2067        ));
2068        assert!((c.snap_roll_duration_secs - 0.5).abs() < f32::EPSILON);
2069        assert_eq!(c.snap_roll_easing, SnapRollEasing::EaseOutCubic);
2070    }
2071
2072    #[test]
2073    fn snap_roll_completes_to_90deg() {
2074        let mut anim = start_or_retarget_snap(
2075            None,
2076            Vec3::Z,
2077            Vec3::Y,
2078            1,
2079            0.18,
2080            SnapRollEasing::EaseOutCubic,
2081        );
2082        let (delta, finished) = advance_snap(&mut anim, 0.18);
2083        assert!(finished);
2084        assert!(
2085            (delta - std::f32::consts::FRAC_PI_2).abs() < 1e-4,
2086            "Expected ~PI/2, got {delta}"
2087        );
2088    }
2089
2090    #[test]
2091    fn snap_roll_easing_monotonic() {
2092        let mut anim = start_or_retarget_snap(
2093            None,
2094            Vec3::Z,
2095            Vec3::Y,
2096            1,
2097            0.18,
2098            SnapRollEasing::EaseOutCubic,
2099        );
2100        let step = 0.045;
2101        let mut deltas = Vec::new();
2102        for _ in 0..4 {
2103            let (d, _) = advance_snap(&mut anim, step);
2104            assert!(d > 0.0, "Delta should be positive, got {d}");
2105            deltas.push(d);
2106        }
2107        let total: f32 = deltas.iter().sum();
2108        assert!(
2109            (total - std::f32::consts::FRAC_PI_2).abs() < 1e-3,
2110            "Sum should be ~PI/2, got {total}"
2111        );
2112        // Ease-out: deltas should be non-increasing (each <= previous)
2113        for i in 1..deltas.len() {
2114            assert!(
2115                deltas[i] <= deltas[i - 1] + 1e-6,
2116                "Easing not monotonically decreasing: {:?}",
2117                deltas
2118            );
2119        }
2120    }
2121
2122    #[test]
2123    fn snap_roll_same_direction_extends_target() {
2124        let mut anim = start_or_retarget_snap(
2125            None,
2126            Vec3::Z,
2127            Vec3::Y,
2128            1,
2129            0.18,
2130            SnapRollEasing::EaseOutCubic,
2131        );
2132        // Advance ~30%
2133        advance_snap(&mut anim, 0.054);
2134        let prev_applied = anim.current_applied;
2135        // The transform has rotated with the animation: up at press time
2136        // reflects the applied angle (world-aligned start).
2137        let up = Quat::from_axis_angle(Vec3::Z, anim.current_applied) * Vec3::Y;
2138        let new_anim = start_or_retarget_snap(
2139            Some(anim),
2140            Vec3::Z,
2141            up,
2142            1,
2143            0.18,
2144            SnapRollEasing::EaseOutCubic,
2145        );
2146        assert!((new_anim.start_angle - prev_applied).abs() < 1e-6);
2147        assert!(
2148            (new_anim.target_angle - std::f32::consts::PI).abs() < 1e-4,
2149            "Expected target ~PI (2x90°), got {}",
2150            new_anim.target_angle
2151        );
2152    }
2153
2154    #[test]
2155    fn snap_roll_opposite_direction_reverses_to_lattice() {
2156        let mut anim = start_or_retarget_snap(
2157            None,
2158            Vec3::Z,
2159            Vec3::Y,
2160            1,
2161            0.18,
2162            SnapRollEasing::EaseOutCubic,
2163        );
2164        // Advance ~30% (heading to PI/2 ≈ 1.571)
2165        advance_snap(&mut anim, 0.054);
2166        let current = anim.current_applied;
2167        assert!(current > 0.0 && current < std::f32::consts::FRAC_PI_2);
2168        // The transform has rotated with the animation: up at press time
2169        // reflects the applied angle (world-aligned start).
2170        let up = Quat::from_axis_angle(Vec3::Z, current) * Vec3::Y;
2171        let new_anim = start_or_retarget_snap(
2172            Some(anim),
2173            Vec3::Z,
2174            up,
2175            -1,
2176            0.18,
2177            SnapRollEasing::EaseOutCubic,
2178        );
2179        // Should target 0.0 (nearest lattice below current in negative direction)
2180        assert!(
2181            new_anim.target_angle.abs() < 1e-6,
2182            "Expected target ~0, got {}",
2183            new_anim.target_angle
2184        );
2185    }
2186
2187    #[test]
2188    fn continuous_mode_unchanged() {
2189        let player = Player::default();
2190        assert!(matches!(
2191            player.mode,
2192            PlayerMode::FreeFlightSixDof {
2193                roll_mode: RollMode::Continuous
2194            }
2195        ));
2196        assert!(player.snap_anim.is_none());
2197    }
2198
2199    #[test]
2200    fn snap_roll_config_copies_to_player() {
2201        let config = PlayerConfig {
2202            mode: PlayerMode::FreeFlightSixDof {
2203                roll_mode: RollMode::Snap,
2204            },
2205            snap_roll_duration_secs: 0.3,
2206            snap_roll_easing: SnapRollEasing::Smoothstep,
2207            ..default()
2208        };
2209        let player = Player {
2210            mode: config.mode.clone(),
2211            snap_roll_duration: config.snap_roll_duration_secs,
2212            snap_roll_easing: config.snap_roll_easing,
2213            ..default()
2214        };
2215        assert!(matches!(
2216            player.mode,
2217            PlayerMode::FreeFlightSixDof {
2218                roll_mode: RollMode::Snap
2219            }
2220        ));
2221        assert!((player.snap_roll_duration - 0.3).abs() < f32::EPSILON);
2222        assert_eq!(player.snap_roll_easing, SnapRollEasing::Smoothstep);
2223    }
2224
2225    #[test]
2226    fn snap_roll_start_from_none_is_independent() {
2227        let anim1 = start_or_retarget_snap(
2228            None,
2229            Vec3::Z,
2230            Vec3::Y,
2231            1,
2232            0.18,
2233            SnapRollEasing::EaseOutCubic,
2234        );
2235        let anim2 = start_or_retarget_snap(
2236            None,
2237            Vec3::Z,
2238            Vec3::Y,
2239            1,
2240            0.18,
2241            SnapRollEasing::EaseOutCubic,
2242        );
2243        assert!((anim1.target_angle - anim2.target_angle).abs() < f32::EPSILON);
2244        assert!((anim1.start_angle - anim2.start_angle).abs() < f32::EPSILON);
2245    }
2246
2247    #[test]
2248    fn lattice_axis_forward_yields_four_candidates_at_90deg() {
2249        // Looking straight down: local Z (back) parallel to world Y.
2250        let mut angles = world_lattice_angles(Vec3::Y, Vec3::Z);
2251        assert_eq!(angles.len(), 4, "Y axis pair must be excluded: {angles:?}");
2252        angles.sort_by(f32::total_cmp);
2253        for pair in angles.windows(2) {
2254            assert!(
2255                (pair[1] - pair[0] - std::f32::consts::FRAC_PI_2).abs() < 1e-5,
2256                "Candidates must be exactly 90° apart: {angles:?}"
2257            );
2258        }
2259    }
2260
2261    #[test]
2262    fn lattice_near_axis_forward_still_yields_four_candidates() {
2263        // Playtest regression: view drifted a few degrees off a world axis
2264        // must NOT resurrect the near-forward axis pair as junk candidates
2265        // (6 stops with two perceptually arbitrary ones). 45° dominance rule.
2266        let local_z = Quat::from_axis_angle(Vec3::X, 8_f32.to_radians()) * Vec3::Z;
2267        let up = Quat::from_axis_angle(local_z, 5_f32.to_radians())
2268            * (Vec3::Y - Vec3::Y.dot(local_z) * local_z).normalize();
2269
2270        let angles = world_lattice_angles(local_z, up);
2271        assert_eq!(
2272            angles.len(),
2273            4,
2274            "Near-axis view must exclude the ±Z pair, got {angles:?}"
2275        );
2276
2277        // Exact 45° edge-on view: both axis families sit at proj² ≈ 0.5.
2278        // Float rounding must never exclude both (≥4 invariant) — the 0.49
2279        // threshold keeps the tie inclusive, so all 6 survive.
2280        let boundary_z = Vec3::new(0.0, 1.0, 1.0).normalize();
2281        let boundary_up = (Vec3::Y - Vec3::Y.dot(boundary_z) * boundary_z).normalize();
2282        assert_eq!(
2283            world_lattice_angles(boundary_z, boundary_up).len(),
2284            6,
2285            "At exactly 45° both axis families are equally valid"
2286        );
2287    }
2288
2289    #[test]
2290    fn lattice_diagonal_forward_yields_six_candidates_cycling_2pi() {
2291        use std::f32::consts::{FRAC_PI_2, FRAC_PI_3, TAU};
2292        // Forward = (1,1,1)/√3, so local Z (back) is the opposite diagonal.
2293        let local_z = -Vec3::ONE.normalize();
2294        // Start exactly on a candidate: world X projected onto the roll plane.
2295        let start = (Vec3::X - Vec3::X.dot(local_z) * local_z).normalize();
2296
2297        let angles = world_lattice_angles(local_z, start);
2298        assert_eq!(
2299            angles.len(),
2300            6,
2301            "All 6 axes survive on a diagonal: {angles:?}"
2302        );
2303
2304        // Six Q presses walk the hexagon: each step ~60° (never 90°),
2305        // the total is a full turn, and we return to the start candidate.
2306        let mut up = start;
2307        let mut total = 0.0_f32;
2308        for _ in 0..6 {
2309            let step = next_lattice_step(&world_lattice_angles(local_z, up), 1);
2310            assert!(
2311                (step - FRAC_PI_3).abs() < 1e-3,
2312                "Expected ~60° step, got {step}"
2313            );
2314            assert!(
2315                (step - FRAC_PI_2).abs() > 0.1,
2316                "Step must not be 90°, got {step}"
2317            );
2318            total += step;
2319            up = Quat::from_axis_angle(local_z, step) * up;
2320        }
2321        assert!(
2322            (total - TAU).abs() < 1e-3,
2323            "Six presses must sum to 2π, got {total}"
2324        );
2325        assert!(
2326            up.dot(start) > 0.9999,
2327            "Cycle must return to start, got {up:?}"
2328        );
2329    }
2330
2331    #[test]
2332    fn lattice_drifted_up_travels_residual() {
2333        // Up rolled 10° off the Y candidate (CCW, rotate_local_z convention).
2334        let up = Quat::from_axis_angle(Vec3::Z, 10_f32.to_radians()) * Vec3::Y;
2335        let angles = world_lattice_angles(Vec3::Z, up);
2336
2337        let q = next_lattice_step(&angles, 1);
2338        let e = next_lattice_step(&angles, -1);
2339        assert!(
2340            (q - 80_f32.to_radians()).abs() < 1e-4,
2341            "Q must travel ≈+80°, got {q}"
2342        );
2343        assert!(
2344            (e + 10_f32.to_radians()).abs() < 1e-4,
2345            "E must travel ≈−10°, got {e}"
2346        );
2347
2348        // Both presses land within ε of a world candidate.
2349        let up_q = Quat::from_axis_angle(Vec3::Z, q) * up;
2350        let up_e = Quat::from_axis_angle(Vec3::Z, e) * up;
2351        assert!(
2352            up_q.dot(Vec3::NEG_X) > 0.9999,
2353            "Q must land on −X, got {up_q:?}"
2354        );
2355        assert!(
2356            up_e.dot(Vec3::Y) > 0.9999,
2357            "E must land on +Y, got {up_e:?}"
2358        );
2359    }
2360
2361    #[test]
2362    fn lattice_eps_on_skips_exact_candidate() {
2363        // Up exactly on a candidate: the press must travel a full step, not ~0.
2364        let angles = world_lattice_angles(Vec3::Z, Vec3::Y);
2365        let q = next_lattice_step(&angles, 1);
2366        let e = next_lattice_step(&angles, -1);
2367        assert!(
2368            (q - std::f32::consts::FRAC_PI_2).abs() < 1e-5,
2369            "Q from an exact candidate must be +90°, got {q}"
2370        );
2371        assert!(
2372            (e + std::f32::consts::FRAC_PI_2).abs() < 1e-5,
2373            "E from an exact candidate must be −90°, got {e}"
2374        );
2375    }
2376
2377    #[test]
2378    fn snap_retarget_drifted_frame_lands_on_candidates() {
2379        let local_z = Vec3::Z;
2380        // Start 10° off the Y candidate: fresh Q targets the −X candidate (+80°).
2381        let up0 = Quat::from_axis_angle(local_z, 10_f32.to_radians()) * Vec3::Y;
2382
2383        // Same-direction press mid-flight extends to the NEXT candidate (−Y).
2384        let mut anim =
2385            start_or_retarget_snap(None, local_z, up0, 1, 0.18, SnapRollEasing::EaseOutCubic);
2386        advance_snap(&mut anim, 0.054);
2387        let up_mid = Quat::from_axis_angle(local_z, anim.current_applied) * up0;
2388        let extended = start_or_retarget_snap(
2389            Some(anim),
2390            local_z,
2391            up_mid,
2392            1,
2393            0.18,
2394            SnapRollEasing::EaseOutCubic,
2395        );
2396        let up_ext = Quat::from_axis_angle(local_z, extended.target_angle) * up0;
2397        assert!(
2398            up_ext.dot(Vec3::NEG_Y) > 0.9999,
2399            "Extend must land on −Y, got {up_ext:?}"
2400        );
2401
2402        // Opposite press mid-flight reverses to the candidate behind (+Y).
2403        let mut anim =
2404            start_or_retarget_snap(None, local_z, up0, 1, 0.18, SnapRollEasing::EaseOutCubic);
2405        advance_snap(&mut anim, 0.054);
2406        let up_mid = Quat::from_axis_angle(local_z, anim.current_applied) * up0;
2407        let reversed = start_or_retarget_snap(
2408            Some(anim),
2409            local_z,
2410            up_mid,
2411            -1,
2412            0.18,
2413            SnapRollEasing::EaseOutCubic,
2414        );
2415        let up_rev = Quat::from_axis_angle(local_z, reversed.target_angle) * up0;
2416        assert!(
2417            up_rev.dot(Vec3::Y) > 0.9999,
2418            "Reverse must land on +Y, got {up_rev:?}"
2419        );
2420    }
2421
2422    #[test]
2423    fn push_capsule_no_collision() {
2424        // Voxel at origin, player far away — should not move.
2425        let pos = Vec3::new(10.0, 10.0, 10.0);
2426        let result = push_capsule_out(pos, Vec3::Y, PLAYER_HALF_HEIGHT, Vec3::ZERO, 0, 0, 0);
2427        assert_eq!(result, pos);
2428    }
2429
2430    #[test]
2431    fn push_capsule_resolves_overlap() {
2432        // Player center directly on top of a voxel — must be pushed out.
2433        let pos = Vec3::new(0.5, 0.5, 0.5); // inside voxel [0,0,0]
2434        let result = push_capsule_out(pos, Vec3::Y, PLAYER_HALF_HEIGHT, Vec3::ZERO, 0, 0, 0);
2435        // After push, capsule sphere should clear the voxel.
2436        let vox_center = Vec3::splat(0.5);
2437        let closest = result.clamp(Vec3::ZERO, Vec3::ONE);
2438        let dist = (result - closest).length();
2439        assert!(
2440            dist >= PLAYER_RADIUS - 0.001,
2441            "dist={dist} must be >= PLAYER_RADIUS={PLAYER_RADIUS}"
2442        );
2443        let _ = vox_center; // silence unused warning
2444    }
2445
2446    // ─── Anchored look: pitch clamp ──────────────────────────────────────────
2447
2448    #[test]
2449    fn clamp_pitch_under_limit_passes_through() {
2450        // Level forward (pitch 0 vs +Y anchor): moderate deltas are untouched.
2451        let d = clamp_pitch_delta(Vec3::NEG_Z, Vec3::Y, 30_f32.to_radians());
2452        assert!((d - 30_f32.to_radians()).abs() < 1e-5, "got {d}");
2453        let d = clamp_pitch_delta(Vec3::NEG_Z, Vec3::Y, -30_f32.to_radians());
2454        assert!((d + 30_f32.to_radians()).abs() < 1e-5, "got {d}");
2455    }
2456
2457    #[test]
2458    fn clamp_pitch_crossing_limit_truncates() {
2459        // From +80° elevation a +20° request truncates to +9° (lands at +89°).
2460        let f_hi = Vec3::new(0.0, 80_f32.to_radians().sin(), -(80_f32.to_radians().cos()));
2461        let d = clamp_pitch_delta(f_hi, Vec3::Y, 20_f32.to_radians());
2462        assert!(
2463            (d - 9_f32.to_radians()).abs() < 1e-4,
2464            "expected ~+9°, got {d}"
2465        );
2466
2467        // Mirror: from −80° a −20° request truncates to −9° (lands at −89°).
2468        let f_lo = Vec3::new(
2469            0.0,
2470            -(80_f32.to_radians().sin()),
2471            -(80_f32.to_radians().cos()),
2472        );
2473        let d = clamp_pitch_delta(f_lo, Vec3::Y, -20_f32.to_radians());
2474        assert!(
2475            (d + 9_f32.to_radians()).abs() < 1e-4,
2476            "expected ~−9°, got {d}"
2477        );
2478    }
2479
2480    #[test]
2481    fn clamp_pitch_at_limit_blocks_outward_allows_inward() {
2482        // Exactly at the +89° pole: outward is blocked, inward passes through.
2483        let f = Vec3::new(0.0, 89_f32.to_radians().sin(), -(89_f32.to_radians().cos()));
2484        let outward = clamp_pitch_delta(f, Vec3::Y, 5_f32.to_radians());
2485        assert!(
2486            outward.abs() < 1e-4,
2487            "outward delta at the pole must be ~0, got {outward}"
2488        );
2489        let inward = clamp_pitch_delta(f, Vec3::Y, -5_f32.to_radians());
2490        assert!(
2491            (inward + 5_f32.to_radians()).abs() < 1e-4,
2492            "inward delta must pass through, got {inward}"
2493        );
2494    }
2495
2496    // ─── Anchored look: lattice candidates ───────────────────────────────────
2497
2498    #[test]
2499    fn candidates_axis_forward_have_source_axes() {
2500        use std::f32::consts::FRAC_PI_2;
2501        // Axial view (local Z = world Z, up = Y): the ±Z pair is filtered, the
2502        // four survivors carry their source axes with the expected angles.
2503        let cands = world_lattice_candidates(Vec3::Z, Vec3::Y);
2504        assert_eq!(cands.len(), 4, "±Z must be excluded: {cands:?}");
2505        let angle_of = |axis: Vec3| {
2506            cands
2507                .iter()
2508                .find(|(_, a)| *a == axis)
2509                .unwrap_or_else(|| panic!("axis {axis:?} missing from {cands:?}"))
2510                .0
2511        };
2512        assert!(
2513            (angle_of(Vec3::X) + FRAC_PI_2).abs() < 1e-5,
2514            "X must sit at −π/2"
2515        );
2516        assert!(
2517            (angle_of(Vec3::NEG_X) - FRAC_PI_2).abs() < 1e-5,
2518            "−X must sit at +π/2"
2519        );
2520        assert!(angle_of(Vec3::Y).abs() < 1e-5, "Y must sit at 0");
2521        assert!(
2522            (angle_of(Vec3::NEG_Y).abs() - std::f32::consts::PI).abs() < 1e-5,
2523            "−Y must sit at ±π"
2524        );
2525    }
2526
2527    #[test]
2528    fn candidates_diagonal_forward_yield_six_axes() {
2529        // Diagonal view: every signed world axis survives, each exactly once.
2530        let local_z = -Vec3::ONE.normalize();
2531        let up = (Vec3::X - Vec3::X.dot(local_z) * local_z).normalize();
2532        let cands = world_lattice_candidates(local_z, up);
2533        assert_eq!(
2534            cands.len(),
2535            6,
2536            "all 6 axes survive on a diagonal: {cands:?}"
2537        );
2538        for axis in AXES {
2539            assert_eq!(
2540                cands.iter().filter(|(_, a)| *a == axis).count(),
2541                1,
2542                "axis {axis:?} must appear exactly once: {cands:?}"
2543            );
2544        }
2545    }
2546
2547    #[test]
2548    fn lattice_angles_equal_candidate_angles() {
2549        // The wrapper must be observably identical to the candidate angles.
2550        let diag_z = -Vec3::ONE.normalize();
2551        let diag_up = (Vec3::X - Vec3::X.dot(diag_z) * diag_z).normalize();
2552        for (local_z, up) in [(Vec3::Z, Vec3::Y), (diag_z, diag_up)] {
2553            let angles = world_lattice_angles(local_z, up);
2554            let cands = world_lattice_candidates(local_z, up);
2555            assert_eq!(angles.len(), cands.len());
2556            for (a, (c, _)) in angles.iter().zip(cands.iter()) {
2557                assert_eq!(a, c, "wrapper angle {a} != candidate angle {c}");
2558            }
2559        }
2560    }
2561
2562    // ─── Anchored look: candidate stepping ───────────────────────────────────
2563
2564    #[test]
2565    fn next_lattice_candidate_matches_next_lattice_step() {
2566        // Drifted up (10° off Y): the axis-carrying mirror must agree with the
2567        // locked next_lattice_step in both directions.
2568        let up = Quat::from_axis_angle(Vec3::Z, 10_f32.to_radians()) * Vec3::Y;
2569        let cands = world_lattice_candidates(Vec3::Z, up);
2570        let angles = world_lattice_angles(Vec3::Z, up);
2571        for dir in [1, -1] {
2572            let (cand_angle, _) = next_lattice_candidate(&cands, dir);
2573            let step = next_lattice_step(&angles, dir);
2574            assert_eq!(cand_angle, step, "dir {dir}: {cand_angle} != {step}");
2575        }
2576    }
2577
2578    #[test]
2579    fn next_candidate_q_yields_neg_x_e_yields_x() {
2580        use std::f32::consts::FRAC_PI_2;
2581        // From (local_z = Z, up = Y): Q travels +90° to the −X candidate,
2582        // E travels −90° to the +X candidate.
2583        let cands = world_lattice_candidates(Vec3::Z, Vec3::Y);
2584        let (q_angle, q_axis) = next_lattice_candidate(&cands, 1);
2585        assert!(
2586            (q_angle - FRAC_PI_2).abs() < 1e-5,
2587            "Q must travel +π/2, got {q_angle}"
2588        );
2589        assert_eq!(q_axis, Vec3::NEG_X);
2590        let (e_angle, e_axis) = next_lattice_candidate(&cands, -1);
2591        assert!(
2592            (e_angle + FRAC_PI_2).abs() < 1e-5,
2593            "E must travel −π/2, got {e_angle}"
2594        );
2595        assert_eq!(e_axis, Vec3::X);
2596    }
2597
2598    // ─── Anchored look: reference up and anchor commit ───────────────────────
2599
2600    #[test]
2601    fn snap_reference_up_fresh_and_opposite_use_up() {
2602        let up = Quat::from_axis_angle(Vec3::Z, 10_f32.to_radians()) * Vec3::Y;
2603        // Fresh press: no animation → reference is the current up.
2604        assert_eq!(snap_reference_up(None, Vec3::Z, up, 1), up);
2605        // Opposite-direction press mid-animation → reference is still up.
2606        let mut anim =
2607            start_or_retarget_snap(None, Vec3::Z, up, 1, 0.18, SnapRollEasing::EaseOutCubic);
2608        advance_snap(&mut anim, 0.054);
2609        assert_eq!(snap_reference_up(Some(anim), Vec3::Z, up, -1), up);
2610    }
2611
2612    #[test]
2613    fn snap_reference_up_same_dir_advances_residual() {
2614        let up0 = Vec3::Y;
2615        let mut anim =
2616            start_or_retarget_snap(None, Vec3::Z, up0, 1, 0.18, SnapRollEasing::EaseOutCubic);
2617        advance_snap(&mut anim, 0.054);
2618        // The transform rotated with the animation: up now reflects the
2619        // applied angle. Same-dir reference = up advanced by the residual,
2620        // i.e. the in-flight target up.
2621        let up_mid = Quat::from_axis_angle(Vec3::Z, anim.current_applied) * up0;
2622        let ref_up = snap_reference_up(Some(anim), Vec3::Z, up_mid, 1);
2623        let expected =
2624            Quat::from_axis_angle(Vec3::Z, anim.target_angle - anim.current_applied) * up_mid;
2625        assert!(
2626            ref_up.dot(expected) > 0.9999,
2627            "ref {ref_up:?} != target up {expected:?}"
2628        );
2629        // For this fresh anim the in-flight target is the −X candidate.
2630        assert!(
2631            ref_up.dot(Vec3::NEG_X) > 0.9999,
2632            "expected ~−X, got {ref_up:?}"
2633        );
2634    }
2635
2636    #[test]
2637    fn anchor_commit_matches_pending_projection() {
2638        let local_z = Vec3::Z;
2639        let dur = 0.18;
2640        let ease = SnapRollEasing::EaseOutCubic;
2641        let up0 = Quat::from_axis_angle(local_z, 10_f32.to_radians()) * Vec3::Y;
2642        let proj = |axis: Vec3| (axis - axis.dot(local_z) * local_z).normalize();
2643
2644        // Fresh Q: pending axis −X; the animation must land on its projection.
2645        let ref_up = snap_reference_up(None, local_z, up0, 1);
2646        let (_, axis) = next_lattice_candidate(&world_lattice_candidates(local_z, ref_up), 1);
2647        assert_eq!(axis, Vec3::NEG_X);
2648        let anim = start_or_retarget_snap(None, local_z, up0, 1, dur, ease);
2649        let landed = Quat::from_axis_angle(local_z, anim.target_angle) * up0;
2650        assert!(
2651            landed.dot(proj(axis)) > 0.9999,
2652            "fresh: {landed:?} != proj({axis:?})"
2653        );
2654
2655        // Extend (same dir mid-anim): pending axis −Y, one candidate further.
2656        let mut anim = start_or_retarget_snap(None, local_z, up0, 1, dur, ease);
2657        advance_snap(&mut anim, 0.054);
2658        let up_mid = Quat::from_axis_angle(local_z, anim.current_applied) * up0;
2659        let ref_up = snap_reference_up(Some(anim), local_z, up_mid, 1);
2660        let (_, axis) = next_lattice_candidate(&world_lattice_candidates(local_z, ref_up), 1);
2661        assert_eq!(axis, Vec3::NEG_Y);
2662        let extended = start_or_retarget_snap(Some(anim), local_z, up_mid, 1, dur, ease);
2663        let landed = Quat::from_axis_angle(local_z, extended.target_angle) * up0;
2664        assert!(
2665            landed.dot(proj(axis)) > 0.9999,
2666            "extend: {landed:?} != proj({axis:?})"
2667        );
2668
2669        // Reverse (opposite dir mid-anim): pending axis +Y, behind current up.
2670        let mut anim = start_or_retarget_snap(None, local_z, up0, 1, dur, ease);
2671        advance_snap(&mut anim, 0.054);
2672        let up_mid = Quat::from_axis_angle(local_z, anim.current_applied) * up0;
2673        let ref_up = snap_reference_up(Some(anim), local_z, up_mid, -1);
2674        let (_, axis) = next_lattice_candidate(&world_lattice_candidates(local_z, ref_up), -1);
2675        assert_eq!(axis, Vec3::Y);
2676        let reversed = start_or_retarget_snap(Some(anim), local_z, up_mid, -1, dur, ease);
2677        let landed = Quat::from_axis_angle(local_z, reversed.target_angle) * up0;
2678        assert!(
2679            landed.dot(proj(axis)) > 0.9999,
2680            "reverse: {landed:?} != proj({axis:?})"
2681        );
2682    }
2683
2684    // ─── Anchored look: spawn anchor and defaults ────────────────────────────
2685
2686    #[test]
2687    fn nearest_world_axis_snaps_biased_vectors() {
2688        assert_eq!(nearest_world_axis(Vec3::new(0.9, 0.1, 0.2)), Vec3::X);
2689        assert_eq!(nearest_world_axis(Vec3::new(-2.0, 0.5, 0.5)), Vec3::NEG_X);
2690        assert_eq!(nearest_world_axis(Vec3::new(0.1, -1.5, 0.3)), Vec3::NEG_Y);
2691        assert_eq!(nearest_world_axis(Vec3::new(-0.1, 0.2, 0.95)), Vec3::Z);
2692        assert_eq!(nearest_world_axis(Vec3::new(0.2, 0.3, -0.9)), Vec3::NEG_Z);
2693    }
2694
2695    #[test]
2696    fn nearest_world_axis_tie_uses_axes_order() {
2697        // Strict `>` keeps the first max in AXES order [X, −X, Y, −Y, Z, −Z].
2698        assert_eq!(nearest_world_axis(Vec3::new(1.0, 1.0, 0.0)), Vec3::X);
2699        assert_eq!(nearest_world_axis(Vec3::new(0.0, 1.0, 1.0)), Vec3::Y);
2700        assert_eq!(nearest_world_axis(Vec3::new(-1.0, -1.0, -1.0)), Vec3::NEG_X);
2701    }
2702
2703    #[test]
2704    fn player_mode_defaults_to_sixdof() {
2705        let p = Player::default();
2706        assert!(matches!(
2707            p.mode,
2708            PlayerMode::FreeFlightSixDof {
2709                roll_mode: RollMode::Continuous
2710            }
2711        ));
2712        assert_eq!(p.anchor_up, Vec3::Y);
2713        assert!(p.pending_anchor.is_none());
2714        assert!(matches!(
2715            PlayerConfig::default().mode,
2716            PlayerMode::FreeFlightSixDof {
2717                roll_mode: RollMode::Continuous
2718            }
2719        ));
2720    }
2721
2722    #[test]
2723    fn anchored_mode_config_copies_to_player() {
2724        // Non-default value must propagate config → component.
2725        let config = PlayerConfig {
2726            mode: PlayerMode::FreeFlightAnchored,
2727            ..default()
2728        };
2729        let player = Player {
2730            mode: config.mode.clone(),
2731            ..default()
2732        };
2733        assert!(matches!(player.mode, PlayerMode::FreeFlightAnchored));
2734    }
2735
2736    // ---- Frame-loop integration tests -------------------------------------
2737    //
2738    // Three Anchored behaviors are frame-loop properties, not pure functions:
2739    // a level horizon under diagonal input, mouse-look staying on the OLD
2740    // anchor while a switch animates, and `RollMode::Continuous` being inert.
2741    // These drive `player_look` through a headless `App`.
2742
2743    /// Builds a headless app that runs `player_look` over one Anchored player
2744    /// starting from the identity transform (forward −Z, up +Y, right +X).
2745    fn anchored_app() -> (App, Entity) {
2746        let mut app = App::new();
2747        app.add_message::<MouseMotion>();
2748        app.insert_resource(ButtonInput::<KeyCode>::default());
2749        app.insert_resource(Time::<()>::default());
2750        app.add_systems(Update, player_look);
2751        let entity = app
2752            .world_mut()
2753            .spawn((
2754                Player {
2755                    mode: PlayerMode::FreeFlightAnchored,
2756                    ..default()
2757                },
2758                Transform::default(),
2759            ))
2760            .id();
2761        (app, entity)
2762    }
2763
2764    /// App running only [`player_cursor_system`], with a focused primary
2765    /// window and, optionally, a pause-menu state resource.
2766    fn cursor_app(
2767        pause: Option<crate::ui::PauseMenuState>,
2768        locked: bool,
2769    ) -> (App, bevy::ecs::entity::Entity) {
2770        use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
2771        let mut app = App::new();
2772        app.init_resource::<ButtonInput<KeyCode>>()
2773            .init_resource::<ButtonInput<MouseButton>>()
2774            .add_systems(Update, player_cursor_system);
2775        if let Some(state) = pause {
2776            app.insert_resource(State::new(state));
2777        }
2778        let window = app
2779            .world_mut()
2780            .spawn((
2781                Window {
2782                    focused: true,
2783                    ..default()
2784                },
2785                PrimaryWindow,
2786                CursorOptions {
2787                    grab_mode: if locked {
2788                        CursorGrabMode::Locked
2789                    } else {
2790                        CursorGrabMode::None
2791                    },
2792                    visible: !locked,
2793                    ..default()
2794                },
2795            ))
2796            .id();
2797        (app, window)
2798    }
2799
2800    fn grab_mode(app: &App, window: bevy::ecs::entity::Entity) -> bevy::window::CursorGrabMode {
2801        app.world()
2802            .get::<bevy::window::CursorOptions>(window)
2803            .expect("window should still exist")
2804            .grab_mode
2805    }
2806
2807    #[test]
2808    fn pause_menu_owns_escape_so_a_free_cursor_does_not_close_the_window() {
2809        use crate::ui::PauseMenuState;
2810        let (mut app, window) = cursor_app(Some(PauseMenuState::Playing), false);
2811        app.world_mut()
2812            .resource_mut::<ButtonInput<KeyCode>>()
2813            .press(KeyCode::Escape);
2814
2815        app.update();
2816
2817        assert!(
2818            app.world().get_entity(window).is_ok(),
2819            "Escape belongs to the pause menu when it is installed"
2820        );
2821    }
2822
2823    #[test]
2824    fn pause_menu_owns_escape_so_a_captured_cursor_is_not_released_here() {
2825        use crate::ui::PauseMenuState;
2826        use bevy::window::CursorGrabMode;
2827        let (mut app, window) = cursor_app(Some(PauseMenuState::Playing), true);
2828        app.world_mut()
2829            .resource_mut::<ButtonInput<KeyCode>>()
2830            .press(KeyCode::Escape);
2831
2832        app.update();
2833
2834        // The pause menu releases it when it enters `Paused`.
2835        assert_eq!(grab_mode(&app, window), CursorGrabMode::Locked);
2836    }
2837
2838    #[test]
2839    fn with_pause_menu_a_focused_click_captures_and_focus_loss_releases() {
2840        use crate::ui::PauseMenuState;
2841        use bevy::window::CursorGrabMode;
2842        let (mut app, window) = cursor_app(Some(PauseMenuState::Playing), false);
2843        app.world_mut()
2844            .resource_mut::<ButtonInput<MouseButton>>()
2845            .press(MouseButton::Left);
2846        app.update();
2847        assert_eq!(grab_mode(&app, window), CursorGrabMode::Locked);
2848
2849        app.world_mut()
2850            .resource_mut::<ButtonInput<MouseButton>>()
2851            .reset_all();
2852        app.world_mut().get_mut::<Window>(window).unwrap().focused = false;
2853        app.update();
2854        assert_eq!(grab_mode(&app, window), CursorGrabMode::None);
2855    }
2856
2857    #[test]
2858    fn menu_clicks_do_not_capture_the_cursor_while_paused_or_in_settings() {
2859        use crate::ui::PauseMenuState;
2860        use bevy::window::CursorGrabMode;
2861        for state in [PauseMenuState::Paused, PauseMenuState::Settings] {
2862            // The system is added without a run condition, as a game composing
2863            // the player systems by hand would.
2864            let (mut app, window) = cursor_app(Some(state), false);
2865            app.world_mut()
2866                .resource_mut::<ButtonInput<MouseButton>>()
2867                .press(MouseButton::Left);
2868
2869            app.update();
2870
2871            assert_eq!(grab_mode(&app, window), CursorGrabMode::None);
2872        }
2873    }
2874
2875    #[test]
2876    fn player_systems_set_gates_the_plugin_systems() {
2877        use bevy::window::{CursorGrabMode, PrimaryWindow};
2878        let mut app = App::new();
2879        app.add_plugins(PlayerPlugin::<crate::voxel::DefaultVoxel>::new());
2880        app.init_resource::<ButtonInput<KeyCode>>()
2881            .init_resource::<ButtonInput<MouseButton>>();
2882        // A game-owned condition on the whole plugin, without re-registering
2883        // its systems by hand.
2884        app.configure_sets(Update, PlayerSystems.run_if(|| false));
2885        let window = app
2886            .world_mut()
2887            .spawn((
2888                Window {
2889                    focused: true,
2890                    ..default()
2891                },
2892                PrimaryWindow,
2893            ))
2894            .id();
2895        app.world_mut()
2896            .resource_mut::<ButtonInput<MouseButton>>()
2897            .press(MouseButton::Left);
2898
2899        // Only `Update`: the plugin's `Startup` systems touch the disk.
2900        app.world_mut().run_schedule(Update);
2901
2902        assert_eq!(
2903            grab_mode(&app, window),
2904            CursorGrabMode::None,
2905            "a disabled PlayerSystems set must stop the cursor system"
2906        );
2907    }
2908
2909    #[test]
2910    fn focus_loss_releases_the_cursor_even_while_a_menu_is_open() {
2911        use crate::ui::PauseMenuState;
2912        use bevy::window::CursorGrabMode;
2913        let (mut app, window) = cursor_app(Some(PauseMenuState::Paused), true);
2914        app.world_mut().get_mut::<Window>(window).unwrap().focused = false;
2915
2916        app.update();
2917
2918        assert_eq!(grab_mode(&app, window), CursorGrabMode::None);
2919    }
2920
2921    #[test]
2922    fn without_pause_menu_escape_keeps_its_two_stage_behavior() {
2923        use bevy::window::CursorGrabMode;
2924        let (mut app, window) = cursor_app(None, true);
2925        app.world_mut()
2926            .resource_mut::<ButtonInput<KeyCode>>()
2927            .press(KeyCode::Escape);
2928        app.update();
2929        assert_eq!(grab_mode(&app, window), CursorGrabMode::None);
2930
2931        // Still held as "just pressed": the second stage closes the window.
2932        app.update();
2933        assert!(app.world().get_entity(window).is_err());
2934    }
2935
2936    #[test]
2937    fn focus_loss_releases_capture_and_ignores_unfocused_click_and_escape() {
2938        use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
2939        let mut app = App::new();
2940        app.init_resource::<ButtonInput<KeyCode>>()
2941            .init_resource::<ButtonInput<MouseButton>>()
2942            .add_systems(Update, player_cursor_system);
2943        let window = app
2944            .world_mut()
2945            .spawn((
2946                Window {
2947                    focused: false,
2948                    ..default()
2949                },
2950                PrimaryWindow,
2951                CursorOptions {
2952                    grab_mode: CursorGrabMode::Locked,
2953                    visible: false,
2954                    ..default()
2955                },
2956            ))
2957            .id();
2958        app.world_mut()
2959            .resource_mut::<ButtonInput<KeyCode>>()
2960            .press(KeyCode::Escape);
2961        app.world_mut()
2962            .resource_mut::<ButtonInput<MouseButton>>()
2963            .press(MouseButton::Left);
2964        app.update();
2965        let cursor = app
2966            .world()
2967            .get::<CursorOptions>(window)
2968            .expect("unfocused Escape must not close the window");
2969        assert_eq!(cursor.grab_mode, CursorGrabMode::None);
2970        assert!(cursor.visible);
2971        app.world_mut()
2972            .resource_mut::<ButtonInput<KeyCode>>()
2973            .reset_all();
2974        app.world_mut()
2975            .resource_mut::<ButtonInput<MouseButton>>()
2976            .reset_all();
2977        app.world_mut().get_mut::<Window>(window).unwrap().focused = true;
2978        app.update();
2979        assert_eq!(
2980            app.world().get::<CursorOptions>(window).unwrap().grab_mode,
2981            CursorGrabMode::None
2982        );
2983        app.world_mut()
2984            .resource_mut::<ButtonInput<MouseButton>>()
2985            .press(MouseButton::Left);
2986        app.update();
2987        assert_eq!(
2988            app.world().get::<CursorOptions>(window).unwrap().grab_mode,
2989            CursorGrabMode::Locked
2990        );
2991    }
2992
2993    #[test]
2994    fn inactive_primary_window_discards_look_without_replaying_it() {
2995        use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
2996        let (mut app, player) = anchored_app();
2997        let window = app
2998            .world_mut()
2999            .spawn((
3000                Window {
3001                    focused: false,
3002                    ..default()
3003                },
3004                PrimaryWindow,
3005            ))
3006            .id();
3007        step(&mut app, Vec2::new(100.0, 20.0), &[KeyCode::KeyQ], 0.1);
3008        assert_eq!(
3009            app.world().get::<Transform>(player).unwrap().rotation,
3010            Quat::IDENTITY
3011        );
3012        assert!(
3013            app.world()
3014                .get::<Player>(player)
3015                .unwrap()
3016                .snap_anim
3017                .is_none()
3018        );
3019        app.world_mut().get_mut::<Window>(window).unwrap().focused = true;
3020        app.world_mut()
3021            .get_mut::<CursorOptions>(window)
3022            .unwrap()
3023            .grab_mode = CursorGrabMode::Locked;
3024        step(&mut app, Vec2::ZERO, &[], 0.1);
3025        assert_eq!(
3026            app.world().get::<Transform>(player).unwrap().rotation,
3027            Quat::IDENTITY
3028        );
3029        step(&mut app, Vec2::new(10.0, 0.0), &[], 0.1);
3030        assert_ne!(
3031            app.world().get::<Transform>(player).unwrap().rotation,
3032            Quat::IDENTITY
3033        );
3034    }
3035
3036    #[test]
3037    fn spawning_player_leaves_cursor_free_until_focused_click() {
3038        use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
3039        let mut app = App::new();
3040        app.init_resource::<PlayerConfig>()
3041            .init_resource::<PlayerHealth>()
3042            .add_systems(Startup, spawn_player);
3043        let window = app
3044            .world_mut()
3045            .spawn((Window::default(), PrimaryWindow))
3046            .id();
3047        app.update();
3048        let cursor = app.world().get::<CursorOptions>(window).unwrap();
3049        assert_eq!(cursor.grab_mode, CursorGrabMode::None);
3050        assert!(cursor.visible);
3051    }
3052
3053    /// App running only [`player_move`] with one free-flight player and no
3054    /// window, so synthetic input is active.
3055    fn movement_app(config: Option<PlayerMovementConfig>, velocity: Vec3) -> (App, Entity) {
3056        let mut app = App::new();
3057        app.init_resource::<ButtonInput<KeyCode>>()
3058            .init_resource::<Time>()
3059            .init_resource::<ViewerPosition>()
3060            .init_resource::<ChunkManager>()
3061            .init_resource::<PlayerCrouching>()
3062            .add_systems(Update, player_move::<crate::voxel::DefaultVoxel>);
3063        if let Some(config) = config {
3064            app.insert_resource(config);
3065        }
3066        let player = app
3067            .world_mut()
3068            .spawn((
3069                Player {
3070                    velocity,
3071                    ..default()
3072                },
3073                Transform::default(),
3074            ))
3075            .id();
3076        (app, player)
3077    }
3078
3079    /// Advances 0.1 s with `keys` held and returns the player's speed.
3080    fn speed_after_step(app: &mut App, player: Entity, keys: &[KeyCode]) -> f32 {
3081        app.world_mut()
3082            .resource_mut::<Time>()
3083            .advance_by(std::time::Duration::from_millis(100));
3084        for key in keys {
3085            app.world_mut()
3086                .resource_mut::<ButtonInput<KeyCode>>()
3087                .press(*key);
3088        }
3089        app.update();
3090        app.world().get::<Player>(player).unwrap().velocity.length()
3091    }
3092
3093    #[test]
3094    fn movement_config_defaults_match_the_built_in_feel() {
3095        let config = PlayerMovementConfig::default();
3096        assert_eq!(config.acceleration, 12.0);
3097        assert_eq!(config.deceleration, 7.0);
3098        assert_eq!(config.impact_speed_threshold, 1.0);
3099
3100        // Without the resource the systems behave exactly like the default.
3101        let (mut bare, bare_player) = movement_app(None, Vec3::ZERO);
3102        let (mut with, with_player) = movement_app(Some(config), Vec3::ZERO);
3103        assert_eq!(
3104            speed_after_step(&mut bare, bare_player, &[KeyCode::KeyW]),
3105            speed_after_step(&mut with, with_player, &[KeyCode::KeyW]),
3106        );
3107    }
3108
3109    #[test]
3110    fn acceleration_controls_how_fast_speed_builds() {
3111        let slow = PlayerMovementConfig {
3112            acceleration: 1.0,
3113            ..default()
3114        };
3115        let (mut app, player) = movement_app(Some(slow), Vec3::ZERO);
3116
3117        let speed = speed_after_step(&mut app, player, &[KeyCode::KeyW]);
3118
3119        // One 0.1 s step at rate 1.0 covers a tenth of the way to full speed.
3120        let full = Player::default().speed;
3121        assert!((speed - 0.1 * full).abs() < 1e-4, "speed was {speed}");
3122    }
3123
3124    #[test]
3125    fn deceleration_controls_how_fast_the_player_stops() {
3126        let coast = PlayerMovementConfig {
3127            deceleration: 1.0,
3128            ..default()
3129        };
3130        let (mut app, player) = movement_app(Some(coast), Vec3::Z);
3131
3132        let speed = speed_after_step(&mut app, player, &[]);
3133
3134        assert!((speed - 0.9).abs() < 1e-4, "speed was {speed}");
3135    }
3136
3137    #[test]
3138    fn unusable_movement_rates_fall_back_to_the_defaults() {
3139        let broken = PlayerMovementConfig {
3140            acceleration: f32::NAN,
3141            deceleration: -3.0,
3142            ..default()
3143        };
3144        let (mut app, player) = movement_app(Some(broken), Vec3::ZERO);
3145        let (mut reference, reference_player) = movement_app(None, Vec3::ZERO);
3146
3147        assert_eq!(
3148            speed_after_step(&mut app, player, &[KeyCode::KeyW]),
3149            speed_after_step(&mut reference, reference_player, &[KeyCode::KeyW]),
3150        );
3151        let (mut app, player) = movement_app(Some(broken), Vec3::Z);
3152        let (mut reference, reference_player) = movement_app(None, Vec3::Z);
3153        assert_eq!(
3154            speed_after_step(&mut app, player, &[]),
3155            speed_after_step(&mut reference, reference_player, &[]),
3156        );
3157    }
3158
3159    /// App running only [`player_resolve_collision`] over one solid chunk at
3160    /// the origin, with a free-flight player sunk slightly into its top face.
3161    fn impact_app(register_message: bool) -> (App, Entity) {
3162        use crate::voxel::DefaultVoxel;
3163        let mut app = App::new();
3164        app.init_resource::<ChunkManager>();
3165        if register_message {
3166            app.add_message::<PlayerImpact>();
3167        }
3168        app.add_systems(Update, player_resolve_collision::<DefaultVoxel>);
3169        app.world_mut().spawn((
3170            crate::test_support::filled_chunk(DefaultVoxel::Rock),
3171            Transform::default(),
3172        ));
3173        let player = app
3174            .world_mut()
3175            .spawn((Player::default(), Transform::default()))
3176            .id();
3177        (app, player)
3178    }
3179
3180    /// Puts the player 0.05 units into the top face, moving at `velocity`.
3181    fn sink_into_top(app: &mut App, player: Entity, velocity: Vec3) {
3182        let top = CHUNK_SIZE as f32 * VOXEL_SIZE;
3183        let resting_y = top + PLAYER_HALF_HEIGHT + PLAYER_RADIUS;
3184        app.world_mut()
3185            .get_mut::<Transform>(player)
3186            .unwrap()
3187            .translation = Vec3::new(8.5, resting_y - 0.05, 8.5);
3188        app.world_mut().get_mut::<Player>(player).unwrap().velocity = velocity;
3189    }
3190
3191    fn drain_impacts(app: &mut App) -> Vec<PlayerImpact> {
3192        app.world_mut()
3193            .resource_mut::<Messages<PlayerImpact>>()
3194            .drain()
3195            .collect()
3196    }
3197
3198    #[test]
3199    fn flying_into_terrain_reports_one_impact_with_normal_and_speed() {
3200        let (mut app, player) = impact_app(true);
3201        sink_into_top(&mut app, player, Vec3::new(0.0, -5.0, 0.0));
3202
3203        app.update();
3204
3205        let impacts = drain_impacts(&mut app);
3206        assert_eq!(impacts.len(), 1);
3207        let impact = impacts[0];
3208        assert!(
3209            impact.normal.distance(Vec3::Y) < 1e-3,
3210            "{:?}",
3211            impact.normal
3212        );
3213        assert!((impact.speed - 5.0).abs() < 1e-3, "{}", impact.speed);
3214        assert_eq!(
3215            impact.position,
3216            app.world().get::<Transform>(player).unwrap().translation
3217        );
3218
3219        // Still pressed against the surface: no second report.
3220        sink_into_top(&mut app, player, Vec3::new(0.0, -5.0, 0.0));
3221        app.update();
3222        assert!(drain_impacts(&mut app).is_empty());
3223
3224        // Contact ends, then a new hit is reported again.
3225        app.world_mut()
3226            .get_mut::<Transform>(player)
3227            .unwrap()
3228            .translation
3229            .y += 10.0;
3230        app.update();
3231        sink_into_top(&mut app, player, Vec3::new(0.0, -3.0, 0.0));
3232        app.update();
3233        let impacts = drain_impacts(&mut app);
3234        assert_eq!(impacts.len(), 1);
3235        assert!((impacts[0].speed - 3.0).abs() < 1e-3);
3236    }
3237
3238    #[test]
3239    fn only_the_speed_into_the_surface_counts() {
3240        let (mut app, player) = impact_app(true);
3241        // Fast along the surface, slow into it.
3242        sink_into_top(&mut app, player, Vec3::new(9.0, -0.5, 0.0));
3243
3244        app.update();
3245
3246        assert!(drain_impacts(&mut app).is_empty());
3247    }
3248
3249    #[test]
3250    fn impact_threshold_is_configurable() {
3251        let (mut app, player) = impact_app(true);
3252        app.insert_resource(PlayerMovementConfig {
3253            impact_speed_threshold: 8.0,
3254            ..default()
3255        });
3256        sink_into_top(&mut app, player, Vec3::new(0.0, -5.0, 0.0));
3257        app.update();
3258        assert!(drain_impacts(&mut app).is_empty());
3259
3260        app.insert_resource(PlayerMovementConfig {
3261            impact_speed_threshold: f32::INFINITY,
3262            ..default()
3263        });
3264        sink_into_top(&mut app, player, Vec3::new(0.0, -500.0, 0.0));
3265        app.update();
3266        assert!(drain_impacts(&mut app).is_empty());
3267    }
3268
3269    #[test]
3270    fn collision_still_resolves_without_the_impact_message() {
3271        let (mut app, player) = impact_app(false);
3272        sink_into_top(&mut app, player, Vec3::new(0.0, -5.0, 0.0));
3273        let before = app.world().get::<Transform>(player).unwrap().translation.y;
3274
3275        app.update();
3276
3277        let after = app.world().get::<Transform>(player).unwrap().translation.y;
3278        assert!(after > before, "the player is pushed out of the terrain");
3279    }
3280
3281    #[test]
3282    fn inactive_movement_clears_velocity_and_preserves_position() {
3283        use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
3284        let mut app = App::new();
3285        app.init_resource::<ButtonInput<KeyCode>>()
3286            .init_resource::<Time>()
3287            .init_resource::<ViewerPosition>()
3288            .init_resource::<ChunkManager>()
3289            .init_resource::<PlayerCrouching>()
3290            .add_systems(Update, player_move::<crate::voxel::DefaultVoxel>);
3291        let window = app
3292            .world_mut()
3293            .spawn((
3294                Window {
3295                    focused: false,
3296                    ..default()
3297                },
3298                PrimaryWindow,
3299                CursorOptions {
3300                    grab_mode: CursorGrabMode::Locked,
3301                    ..default()
3302                },
3303            ))
3304            .id();
3305        let player = app
3306            .world_mut()
3307            .spawn((
3308                Player {
3309                    velocity: Vec3::Z,
3310                    ..default()
3311                },
3312                Transform::default(),
3313            ))
3314            .id();
3315        app.world_mut()
3316            .resource_mut::<Time>()
3317            .advance_by(std::time::Duration::from_millis(100));
3318        app.world_mut()
3319            .resource_mut::<ButtonInput<KeyCode>>()
3320            .press(KeyCode::KeyW);
3321        app.update();
3322        assert_eq!(
3323            app.world().get::<Transform>(player).unwrap().translation,
3324            Vec3::ZERO
3325        );
3326        assert_eq!(
3327            app.world().get::<Player>(player).unwrap().velocity,
3328            Vec3::ZERO
3329        );
3330        app.world_mut().get_mut::<Window>(window).unwrap().focused = true;
3331        app.world_mut()
3332            .get_mut::<CursorOptions>(window)
3333            .unwrap()
3334            .grab_mode = CursorGrabMode::None;
3335        app.update();
3336        assert_eq!(
3337            app.world().get::<Transform>(player).unwrap().translation,
3338            Vec3::ZERO
3339        );
3340        app.world_mut()
3341            .get_mut::<CursorOptions>(window)
3342            .unwrap()
3343            .grab_mode = CursorGrabMode::Locked;
3344        app.update();
3345        assert!(app.world().get::<Transform>(player).unwrap().translation.z < 0.0);
3346    }
3347
3348    /// Advances one frame: sets `dt`, applies the exact held-key set (freshly
3349    /// added keys register as `just_pressed`, persisting keys do not), injects
3350    /// mouse motion, then runs the schedule.
3351    fn step(app: &mut App, mouse: Vec2, held: &[KeyCode], dt: f32) {
3352        app.world_mut()
3353            .resource_mut::<Time>()
3354            .advance_by(std::time::Duration::from_secs_f32(dt));
3355        {
3356            let mut input = app.world_mut().resource_mut::<ButtonInput<KeyCode>>();
3357            input.clear(); // drop last frame's just_pressed / just_released
3358            let stale: Vec<KeyCode> = input
3359                .get_pressed()
3360                .copied()
3361                .filter(|k| !held.contains(k))
3362                .collect();
3363            for k in stale {
3364                input.release(k);
3365            }
3366            for k in held {
3367                input.press(*k);
3368            } // re-press keeps held keys out of just_pressed
3369        }
3370        if mouse != Vec2::ZERO {
3371            app.world_mut().write_message(MouseMotion { delta: mouse });
3372        }
3373        app.update();
3374    }
3375
3376    fn forward_of(app: &App, entity: Entity) -> Vec3 {
3377        *app.world()
3378            .entity(entity)
3379            .get::<Transform>()
3380            .unwrap()
3381            .forward()
3382    }
3383
3384    #[test]
3385    fn anchored_diagonal_input_keeps_horizon_level() {
3386        let (mut app, e) = anchored_app();
3387        // Strong diagonal input for enough frames to push pitch into the clamp.
3388        for _ in 0..15 {
3389            step(&mut app, Vec2::new(60.0, -80.0), &[], 0.016);
3390            let right = *app.world().entity(e).get::<Transform>().unwrap().right();
3391            // World-yaw around Y ∘ local-X pitch never rolls the frame: the
3392            // camera's right vector stays in the horizontal plane.
3393            assert!(
3394                right.dot(Vec3::Y).abs() < 1e-4,
3395                "horizon rolled: right·Y = {}",
3396                right.dot(Vec3::Y)
3397            );
3398        }
3399        // The ±89° clamp both engaged (we pushed past 88°) and held (never over).
3400        let elevation = forward_of(&app, e).dot(Vec3::Y).abs();
3401        assert!(
3402            elevation >= 88_f32.to_radians().sin(),
3403            "clamp never engaged: |forward·Y| = {elevation}"
3404        );
3405        assert!(
3406            elevation <= 89_f32.to_radians().sin() + 1e-4,
3407            "pitch exceeded ±89°: |forward·Y| = {elevation}"
3408        );
3409    }
3410
3411    #[test]
3412    fn anchored_switch_yaw_uses_old_anchor() {
3413        let (mut app, e) = anchored_app();
3414        // Frame 1: tap Q to begin a switch. The default 0.5s duration keeps it
3415        // running across the next frame (2 × 0.1s = 0.2s < 0.5s).
3416        step(&mut app, Vec2::ZERO, &[KeyCode::KeyQ], 0.1);
3417        {
3418            let p = app.world().entity(e).get::<Player>().unwrap();
3419            assert!(p.snap_anim.is_some(), "Q should start a switch animation");
3420            assert!(p.pending_anchor.is_some(), "pending anchor should be set");
3421            assert_eq!(p.anchor_up, Vec3::Y, "anchor must not commit mid-animation");
3422        }
3423        let before = forward_of(&app, e);
3424        // Frame 2: release Q, yaw with the mouse while the switch still runs.
3425        step(&mut app, Vec2::new(50.0, 0.0), &[], 0.1);
3426        let p = app.world().entity(e).get::<Player>().unwrap();
3427        assert!(p.snap_anim.is_some(), "animation should still be running");
3428        assert_eq!(
3429            p.anchor_up,
3430            Vec3::Y,
3431            "yaw must not commit the pending anchor"
3432        );
3433        let after = forward_of(&app, e);
3434        // Yaw ran around the OLD anchor (world Y): a rotation about Y preserves
3435        // forward·Y, and the pending axis is non-Y, so a wrong anchor would
3436        // tilt forward out of the horizontal plane.
3437        assert!(
3438            after.dot(Vec3::Y).abs() < 1e-5,
3439            "yaw left the Y-plane → wrong anchor"
3440        );
3441        assert!(
3442            (after - before).length() > 1e-3,
3443            "yaw had no visible effect"
3444        );
3445    }
3446
3447    #[test]
3448    fn anchored_q_switches_anchor() {
3449        let (mut app, e) = anchored_app();
3450        // In SixDof this would roll the frame every tick; in Anchored, Q must
3451        // instead begin an animated anchor switch — RollMode is inert.
3452        step(&mut app, Vec2::ZERO, &[KeyCode::KeyQ], 0.1);
3453        let p = app.world().entity(e).get::<Player>().unwrap();
3454        assert!(
3455            p.snap_anim.is_some() && p.pending_anchor.is_some(),
3456            "Continuous roll_mode must be inert in Anchored — Q takes the switch path"
3457        );
3458    }
3459}