Skip to main content

rayengine_core/
first_person.rs

1//! Optional first-person movement over Body3D. Games own worlds, spawning,
2//! checkpoints, menus, interaction and input-edge consumption.
3
4use crate::{
5    camera::Camera3D,
6    collision::{Aabb3, Body3D},
7    input::{Action, Input, InputView},
8};
9use glam::{Vec2, Vec3};
10use std::fmt;
11
12/// Game-chosen action IDs, independent of physical keyboard/mouse bindings.
13#[derive(Clone, Copy, Debug)]
14pub struct FirstPersonActions {
15    /// Strafe left.
16    pub left: Action,
17    /// Strafe right.
18    pub right: Action,
19    /// Walk forward.
20    pub forward: Action,
21    /// Walk backward.
22    pub back: Action,
23    /// Jump on a press edge.
24    pub jump: Action,
25    /// Optional held sprint action.
26    pub sprint: Option<Action>,
27    /// Optional keyboard look left.
28    pub turn_left: Option<Action>,
29    /// Optional keyboard look right.
30    pub turn_right: Option<Action>,
31}
32
33/// One fixed tick's input. Movement/turn axes must be finite and in [-1, 1].
34/// Mouse motion is accumulated displacement, not velocity; never multiply by dt.
35#[derive(Clone, Copy, Debug, Default)]
36pub struct FirstPersonInput {
37    /// Right/back positive; forward is negative Y. Diagonals are normalized.
38    pub movement: Vec2,
39    /// Relative logical-window pointer displacement, positive Y looks down.
40    pub look_delta: Vec2,
41    /// Keyboard yaw axis, positive turns right. This is multiplied by dt.
42    pub turn_axis: f32,
43    /// Held sprint state.
44    pub sprint: bool,
45    /// Jump press edge, supplied once per fixed update sequence.
46    pub jump_pressed: bool,
47}
48impl FirstPersonInput {
49    /// Samples the game's bindings. The caller consumes Input edges after a tick.
50    pub fn from_actions(input: &Input, actions: FirstPersonActions) -> Self {
51        Self::from_view(input.routed(&[], false), actions)
52    }
53    /// Samples a routed view so UI can mask gameplay actions and mouse look.
54    pub fn from_view(input: InputView<'_>, actions: FirstPersonActions) -> Self {
55        Self {
56            movement: Vec2::new(
57                input.axis(actions.left, actions.right),
58                input.axis(actions.forward, actions.back),
59            ),
60            look_delta: input.pointer_delta(),
61            turn_axis: f32::from(actions.turn_right.is_some_and(|a| input.down(a)))
62                - f32::from(actions.turn_left.is_some_and(|a| input.down(a))),
63            sprint: actions.sprint.is_some_and(|a| input.down(a)),
64            jump_pressed: input.pressed(actions.jump),
65        }
66    }
67}
68
69/// Validated once when creating/reconfiguring a controller. Positive Y is up.
70#[derive(Clone, Copy, Debug)]
71pub struct FirstPersonConfig {
72    /// Walking speed, world units/second.
73    pub walk_speed: f32,
74    /// Sprinting speed, world units/second.
75    pub sprint_speed: f32,
76    /// Exponential horizontal response rate, per second. Zero selects immediate motion.
77    pub response: f32,
78    /// Initial jump velocity, world units/second.
79    pub jump_speed: f32,
80    /// Positive downward acceleration, world units/second squared.
81    pub gravity: f32,
82    /// Positive maximum falling speed, world units/second.
83    pub max_fall_speed: f32,
84    /// Radians per logical-window pointer unit, independent of viewport/DPI scaling.
85    pub mouse_sensitivity: f32,
86    /// Keyboard yaw speed, radians/second.
87    pub keyboard_turn_speed: f32,
88    /// Minimum pitch in radians, strictly above -PI/2.
89    pub min_pitch: f32,
90    /// Maximum pitch in radians, strictly below PI/2.
91    pub max_pitch: f32,
92    /// World-space eye offset relative to body center.
93    pub eye_offset: Vec3,
94    /// Vertical field of view in degrees, strictly between 0 and 180.
95    pub vertical_fov: f32,
96    /// Seconds after leaving ground in which jumping remains possible; zero disables grace.
97    pub coyote_time: f32,
98    /// Seconds to retain a jump edge before landing; zero requires an immediate jump.
99    pub jump_buffer_time: f32,
100}
101impl Default for FirstPersonConfig {
102    fn default() -> Self {
103        Self {
104            walk_speed: 6.0,
105            sprint_speed: 10.0,
106            response: 18.0,
107            jump_speed: 11.0,
108            gravity: 26.0,
109            max_fall_speed: 40.0,
110            mouse_sensitivity: 0.0025,
111            keyboard_turn_speed: 1.8,
112            min_pitch: -std::f32::consts::FRAC_PI_2 + 0.05,
113            max_pitch: std::f32::consts::FRAC_PI_2 - 0.05,
114            eye_offset: Vec3::new(0.0, 0.7, 0.0),
115            vertical_fov: 75.0,
116            coyote_time: 0.1,
117            jump_buffer_time: 0.12,
118        }
119    }
120}
121
122/// Invalid controller configuration or explicit position/look change.
123#[derive(Clone, Copy, Debug, PartialEq, Eq)]
124pub struct FirstPersonError(pub &'static str);
125impl fmt::Display for FirstPersonError {
126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127        f.write_str(self.0)
128    }
129}
130impl std::error::Error for FirstPersonError {}
131impl FirstPersonConfig {
132    /// Rejects nonfinite values, negative rates and camera limits crossing the poles.
133    pub fn validate(&self) -> Result<(), FirstPersonError> {
134        let nonnegative = [
135            self.walk_speed,
136            self.sprint_speed,
137            self.response,
138            self.jump_speed,
139            self.mouse_sensitivity,
140            self.keyboard_turn_speed,
141            self.coyote_time,
142            self.jump_buffer_time,
143        ];
144        if nonnegative.into_iter().any(|v| !v.is_finite() || v < 0.0) {
145            return Err(FirstPersonError(
146                "speeds, response, sensitivity and grace times must be finite and nonnegative",
147            ));
148        }
149        if !self.gravity.is_finite()
150            || self.gravity <= 0.0
151            || !self.max_fall_speed.is_finite()
152            || self.max_fall_speed <= 0.0
153        {
154            return Err(FirstPersonError(
155                "gravity and maximum falling speed must be finite and positive",
156            ));
157        }
158        if !self.min_pitch.is_finite()
159            || !self.max_pitch.is_finite()
160            || self.min_pitch <= -std::f32::consts::FRAC_PI_2
161            || self.max_pitch >= std::f32::consts::FRAC_PI_2
162            || self.min_pitch > self.max_pitch
163        {
164            return Err(FirstPersonError(
165                "pitch limits must be ordered and strictly inside (-PI/2, PI/2)",
166            ));
167        }
168        if !self.eye_offset.is_finite()
169            || !self.vertical_fov.is_finite()
170            || !(0.0..180.0).contains(&self.vertical_fov)
171            || self.vertical_fov == 0.0
172        {
173            return Err(FirstPersonError(
174                "eye offset must be finite and vertical FOV must be in (0, 180)",
175            ));
176        }
177        Ok(())
178    }
179}
180
181/// Allocation-free optional helper. Spawn outside static solids; initial overlaps
182/// are not depenetrated. Body movement resolves X, Z then Y, using Body3D sweeps.
183#[derive(Clone, Copy, Debug)]
184pub struct FirstPersonController {
185    /// Game-accessible swept body. External edits must retain Body3D invariants.
186    pub body: Body3D,
187    /// Previous center for interpolation. Use teleport for discontinuous movement.
188    pub previous: Vec3,
189    config: FirstPersonConfig,
190    yaw: f32,
191    pitch: f32,
192    coyote: f32,
193    jump_buffer: f32,
194}
195impl FirstPersonController {
196    /// Creates a controller from center/full body dimensions. Rejects invalid
197    /// config and nonfinite/nonpositive body dimensions before constructing it.
198    pub fn new(
199        position: Vec3,
200        size: Vec3,
201        config: FirstPersonConfig,
202    ) -> Result<Self, FirstPersonError> {
203        config.validate()?;
204        if !position.is_finite() || !size.is_finite() || size.min_element() <= 0.0 {
205            return Err(FirstPersonError(
206                "body position must be finite and dimensions finite and positive",
207            ));
208        }
209        let body = Body3D::new(position, size);
210        if !valid_bounds(body.position, body.half_size) {
211            return Err(FirstPersonError(
212                "body bounds must retain finite positive extent at the chosen coordinates",
213            ));
214        }
215        Ok(Self {
216            body,
217            previous: position,
218            config,
219            yaw: 0.0,
220            pitch: 0.0_f32.clamp(config.min_pitch, config.max_pitch),
221            coyote: 0.0,
222            jump_buffer: 0.0,
223        })
224    }
225    /// Current validated configuration.
226    pub fn config(&self) -> &FirstPersonConfig {
227        &self.config
228    }
229    /// Reconfigures atomically, clamping pitch and clearing pending jump/grace state.
230    pub fn set_config(&mut self, config: FirstPersonConfig) -> Result<(), FirstPersonError> {
231        config.validate()?;
232        self.config = config;
233        self.pitch = self.pitch.clamp(config.min_pitch, config.max_pitch);
234        self.coyote = 0.0;
235        self.jump_buffer = 0.0;
236        Ok(())
237    }
238    /// Horizontal yaw in radians, positive turns toward +X from the -Z heading.
239    pub fn yaw(&self) -> f32 {
240        self.yaw
241    }
242    /// Vertical pitch in radians, positive looks up.
243    pub fn pitch(&self) -> f32 {
244        self.pitch
245    }
246    /// Sets finite angles, wrapping yaw and clamping pitch. Failure changes nothing.
247    pub fn set_look(&mut self, yaw: f32, pitch: f32) -> Result<(), FirstPersonError> {
248        if !yaw.is_finite() || !pitch.is_finite() {
249            return Err(FirstPersonError("look angles must be finite"));
250        }
251        self.yaw = wrap_yaw(f64::from(yaw));
252        self.pitch = pitch.clamp(self.config.min_pitch, self.config.max_pitch);
253        Ok(())
254    }
255    /// Resets movement, contact, interpolation and pending jumps at a game-chosen
256    /// position. Keeps look angles; checkpoint/spawn validity remains game policy.
257    pub fn teleport(&mut self, position: Vec3) -> Result<(), FirstPersonError> {
258        if !valid_bounds(position, self.body.half_size) {
259            return Err(FirstPersonError(
260                "teleport bounds must retain finite positive extent",
261            ));
262        }
263        self.body.position = position;
264        self.previous = position;
265        self.body.velocity = Vec3::ZERO;
266        self.body.grounded = false;
267        self.coyote = 0.0;
268        self.jump_buffer = 0.0;
269        Ok(())
270    }
271    /// Applies one fixed tick. Panics for invalid input or nonfinite/negative dt.
272    /// A zero dt applies look only, retaining movement/contact/interpolation state.
273    /// Consume press edges and relative motion once afterward, including catch-up.
274    pub fn step(&mut self, input: FirstPersonInput, dt: f32, solids: &[Aabb3]) {
275        assert!(dt.is_finite() && dt >= 0.0);
276        assert!(
277            input.movement.is_finite()
278                && input.movement.abs().max_element() <= 1.0
279                && input.look_delta.is_finite()
280                && input.turn_axis.is_finite()
281                && input.turn_axis.abs() <= 1.0
282        );
283        // f64 avoids overflow from large finite mouse displacements/sensitivities.
284        let turn = f64::from(input.look_delta.x) * f64::from(self.config.mouse_sensitivity)
285            + f64::from(input.turn_axis)
286                * f64::from(dt)
287                * f64::from(self.config.keyboard_turn_speed);
288        if turn != 0.0 {
289            self.yaw = wrap_yaw(f64::from(self.yaw) + turn);
290        }
291        self.pitch = (f64::from(self.pitch)
292            - f64::from(input.look_delta.y) * f64::from(self.config.mouse_sensitivity))
293        .clamp(
294            f64::from(self.config.min_pitch),
295            f64::from(self.config.max_pitch),
296        ) as f32;
297        if dt == 0.0 {
298            return;
299        }
300        self.previous = self.body.position;
301        let axis = input.movement.clamp_length_max(1.0);
302        let (sin, cos) = self.yaw.sin_cos();
303        let movement = Vec3::new(
304            axis.x * cos - axis.y * sin,
305            0.0,
306            axis.x * sin + axis.y * cos,
307        );
308        let speed = if input.sprint {
309            self.config.sprint_speed
310        } else {
311            self.config.walk_speed
312        };
313        let blend = if self.config.response == 0.0 {
314            1.0
315        } else {
316            -(-self.config.response * dt).exp_m1()
317        };
318        self.body.velocity.x += (movement.x * speed - self.body.velocity.x) * blend;
319        self.body.velocity.z += (movement.z * speed - self.body.velocity.z) * blend;
320        self.coyote = if self.body.grounded {
321            self.config.coyote_time
322        } else {
323            (self.coyote - dt).max(0.0)
324        };
325        self.jump_buffer = if input.jump_pressed {
326            self.config.jump_buffer_time
327        } else {
328            (self.jump_buffer - dt).max(0.0)
329        };
330        if (self.body.grounded || self.coyote > 0.0)
331            && (input.jump_pressed || self.jump_buffer > 0.0)
332        {
333            self.body.velocity.y = self.config.jump_speed;
334            self.body.grounded = false;
335            self.coyote = 0.0;
336            self.jump_buffer = 0.0;
337        }
338        self.body.velocity.y =
339            (self.body.velocity.y - self.config.gravity * dt).max(-self.config.max_fall_speed);
340        self.body.move_and_slide(dt, solids);
341    }
342    /// Eye camera with interpolated position and latest (uninterpolated) angles.
343    /// Alpha must be finite in [0, 1]. Teleport removes interpolation across resets.
344    pub fn camera(&self, alpha: f32) -> Camera3D {
345        assert!(alpha.is_finite() && (0.0..=1.0).contains(&alpha));
346        let position = self.previous.lerp(self.body.position, alpha) + self.config.eye_offset;
347        let (sin_yaw, cos_yaw) = self.yaw.sin_cos();
348        let (sin_pitch, cos_pitch) = self.pitch.sin_cos();
349        Camera3D {
350            position,
351            target: position + Vec3::new(sin_yaw * cos_pitch, sin_pitch, -cos_yaw * cos_pitch),
352            // The pitched up vector preserves yaw even when adding a near-pole
353            // direction to the eye rounds away its horizontal components.
354            up: Vec3::new(-sin_yaw * sin_pitch, cos_pitch, cos_yaw * sin_pitch),
355            vertical_fov: self.config.vertical_fov,
356        }
357    }
358}
359fn wrap_yaw(yaw: f64) -> f32 {
360    ((yaw + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI) as f32
361}
362
363fn valid_bounds(position: Vec3, half_size: Vec3) -> bool {
364    let (min, max) = (position - half_size, position + half_size);
365    min.is_finite() && max.is_finite() && min.cmplt(max).all()
366}
367
368#[cfg(test)]
369mod tests;