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