1use crate::{
5 camera::Camera3D,
6 collision::{Aabb3, Body3D},
7 input::{Action, Input, InputView},
8};
9use glam::{Vec2, Vec3};
10use std::fmt;
11
12#[derive(Clone, Copy, Debug)]
14pub struct FirstPersonActions {
15 pub left: Action,
17 pub right: Action,
19 pub forward: Action,
21 pub back: Action,
23 pub jump: Action,
25 pub sprint: Option<Action>,
27 pub turn_left: Option<Action>,
29 pub turn_right: Option<Action>,
31}
32
33#[derive(Clone, Copy, Debug, Default)]
36pub struct FirstPersonInput {
37 pub movement: Vec2,
39 pub look_delta: Vec2,
41 pub turn_axis: f32,
43 pub sprint: bool,
45 pub jump_pressed: bool,
47}
48impl FirstPersonInput {
49 pub fn from_actions(input: &Input, actions: FirstPersonActions) -> Self {
51 Self::from_view(input.routed(&[], false), actions)
52 }
53 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#[derive(Clone, Copy, Debug)]
71pub struct FirstPersonConfig {
72 pub walk_speed: f32,
74 pub sprint_speed: f32,
76 pub response: f32,
78 pub jump_speed: f32,
80 pub gravity: f32,
82 pub max_fall_speed: f32,
84 pub mouse_sensitivity: f32,
86 pub keyboard_turn_speed: f32,
88 pub min_pitch: f32,
90 pub max_pitch: f32,
92 pub eye_offset: Vec3,
94 pub vertical_fov: f32,
96 pub coyote_time: f32,
98 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#[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 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#[derive(Clone, Copy, Debug)]
184pub struct FirstPersonController {
185 pub body: Body3D,
187 pub previous: Vec3,
189 config: FirstPersonConfig,
190 yaw: f32,
191 pitch: f32,
192 coyote: f32,
193 jump_buffer: f32,
194}
195impl FirstPersonController {
196 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 pub fn config(&self) -> &FirstPersonConfig {
227 &self.config
228 }
229 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 pub fn yaw(&self) -> f32 {
240 self.yaw
241 }
242 pub fn pitch(&self) -> f32 {
244 self.pitch
245 }
246 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 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 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 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 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 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;