ferravex_physics/character/motion.rs
1use super::{
2 geometry::{Hit, Queries},
3 *,
4};
5#[derive(Clone, Copy, Debug, Default, PartialEq)]
6pub struct JumpState {
7 /// Seconds remaining. Include both timers and held in prediction snapshots/replays.
8 pub coyote: f32,
9 pub buffer: f32,
10 pub held: bool,
11}
12impl JumpState {
13 fn valid(self) -> bool {
14 self.coyote.is_finite()
15 && (0. ..=0.5).contains(&self.coyote)
16 && self.buffer.is_finite()
17 && (0. ..=0.5).contains(&self.buffer)
18 }
19}
20#[derive(Clone, Copy, Debug, PartialEq)]
21pub struct Support {
22 pub id: u64,
23 pub local_anchor: Vec3,
24 pub previous_anchor: Vec3,
25}
26impl Support {
27 fn new(o: Obstacle, feet: Vec3) -> Self {
28 Self {
29 id: o.id,
30 local_anchor: o.rotation.conjugate() * (feet - o.position),
31 previous_anchor: feet,
32 }
33 }
34}
35/// Overlap corrections performed during one successful move, step or teleport.
36/// This excludes requested motion, platform carry and ground snap. Errors still
37/// return no partial motion and leave a [`Character`] unchanged.
38#[derive(Clone, Copy, Debug, Default, PartialEq)]
39pub struct Recovery {
40 /// Sum of all separation corrections, including corrections before platform carry.
41 pub translation: Vec3,
42 /// Sum of correction lengths, bounded by [`CharacterSettings::max_recovery`].
43 pub distance: f32,
44 /// Number of applied separation corrections; clearance checks are not counted.
45 pub iterations: u32,
46 /// Largest penetration depth encountered before a correction (excluding skin).
47 pub max_depth: f32,
48}
49/// Motion requested by the previous supporting obstacle during a fixed tick.
50#[derive(Clone, Copy, Debug, PartialEq)]
51pub struct SupportMotion {
52 pub id: u64,
53 /// World-space displacement of the saved anchor, including platform rotation.
54 pub requested: Vec3,
55 /// Swept displacement actually applied, excluding overlap correction and snap.
56 /// Only this displacement contributes platform velocity when jumping.
57 pub applied: Vec3,
58 /// Whether the platform carry encountered an obstacle.
59 pub blocked: bool,
60}
61#[derive(Clone, Copy, Debug)]
62pub struct Motion {
63 pub position: Vec3,
64 /// Displacement from this sweep's origin. In [`Character::step`] this is the
65 /// final velocity-driven sweep, after carry and preliminary overlap recovery.
66 pub translation: Vec3,
67 pub grounded: bool,
68 pub ground_normal: Vec3,
69 pub support: Option<Support>,
70 pub stepped: bool,
71 pub blocked: bool,
72 pub candidates: usize,
73 /// Corrections across the entire public operation, including platform carry
74 /// and preliminary recovery in [`Character::step`].
75 pub recovery: Recovery,
76 /// Previous support's carry for [`Character::step`], even if the character
77 /// jumped or lost support later this tick. `None` for a sweep/teleport or if
78 /// the old support was absent, removed, a sensor or excluded by the mask.
79 /// [`Self::support`] instead describes walkable support at the final pose.
80 pub support_motion: Option<SupportMotion>,
81 normals: [Vec3; 16],
82 normal_count: usize,
83}
84fn slide(mut value: Vec3, normal: Vec3, min_ground: f32) -> Vec3 {
85 let into = value.dot(normal);
86 if into < 0. {
87 value -= normal * into;
88 }
89 if normal.y > 0. && normal.y < min_ground && value.y > 0. {
90 value.y = 0.;
91 let horizontal = Vec3::new(normal.x, 0., normal.z).normalize_or_zero();
92 let into = value.dot(horizontal);
93 if into < 0. {
94 value -= horizontal * into;
95 }
96 }
97 value
98}
99fn ground<T: Terrain + ?Sized>(
100 queries: &mut Queries<'_, T>,
101 p: Vec3,
102 distance: f32,
103) -> Result<Option<Hit>, CharacterError> {
104 Ok(queries
105 .cast(p, -Vec3::Y * distance)?
106 .filter(|h| h.normal.y >= queries.settings.min_ground_normal))
107}
108fn try_step<T: Terrain + ?Sized>(
109 q: &mut Queries<'_, T>,
110 p: Vec3,
111 remaining: Vec3,
112) -> Result<Option<(Vec3, Hit)>, CharacterError> {
113 let up = Vec3::Y * q.settings.step_height;
114 let across = Vec3::new(remaining.x, 0., remaining.z);
115 if across.length_squared() < 1e-12 || q.cast(p, up)?.is_some() {
116 return Ok(None);
117 }
118 let raised = p + up;
119 if q.cast(raised, across)?.is_some() {
120 return Ok(None);
121 }
122 let destination = raised + across;
123 let distance = q.settings.step_height + q.settings.ground_snap;
124 let Some(mut hit) = q.cast(destination, -Vec3::Y * distance)? else {
125 return Ok(None);
126 };
127 if hit.normal.y < q.settings.min_ground_normal {
128 // A capsule meets a short stair's rounded Minkowski edge before its center
129 // reaches the tread. Classify that authored tread, not the round edge, while
130 // still sweeping the full capsule and advancing only the requested XY/XZ move.
131 let ObstacleShape::Box { half } = hit.obstacle.shape else {
132 return Ok(None);
133 };
134 let top = hit.obstacle.rotation * Vec3::Y;
135 if top.y < q.settings.min_ground_normal || hit.normal.y <= 0. {
136 return Ok(None);
137 }
138 let plane = hit.obstacle.position + top * half.y;
139 let height = (plane.dot(top) - destination.x * top.x - destination.z * top.z) / top.y;
140 if height - p.y > q.settings.step_height + q.settings.skin || height < p.y - q.settings.skin
141 {
142 return Ok(None);
143 }
144 hit.normal = top;
145 }
146 Ok(Some((destination - Vec3::Y * distance * hit.fraction, hit)))
147}
148fn move_inner<T: Terrain + ?Sized>(
149 q: &mut Queries<'_, T>,
150 origin: Vec3,
151 delta: Vec3,
152 was_grounded: bool,
153 snap: bool,
154) -> Result<Motion, CharacterError> {
155 let mut p = q.recover(origin)?;
156 let mut remaining = delta;
157 let mut result = Motion {
158 position: p,
159 translation: Vec3::ZERO,
160 grounded: false,
161 ground_normal: Vec3::Y,
162 support: None,
163 stepped: false,
164 blocked: false,
165 candidates: 0,
166 recovery: Recovery::default(),
167 support_motion: None,
168 normals: [Vec3::ZERO; 16],
169 normal_count: 0,
170 };
171 let mut stair_support = None;
172 for _ in 0..q.settings.max_iterations {
173 if remaining.length_squared() < 1e-12 {
174 break;
175 }
176 let Some(hit) = q.cast(p, remaining)? else {
177 p += remaining;
178 break;
179 };
180 p += remaining * hit.fraction;
181 remaining *= 1. - hit.fraction;
182 result.blocked = true;
183 if was_grounded
184 && delta.y <= 0.
185 && hit.normal.y < q.settings.min_ground_normal
186 && q.settings.step_height > 0.
187 && let Some((stepped, landing)) = try_step(q, p, remaining)?
188 {
189 p = stepped;
190 stair_support = Some(landing);
191 result.stepped = true;
192 break;
193 }
194 if result.normal_count < result.normals.len() {
195 result.normals[result.normal_count] = hit.normal;
196 result.normal_count += 1;
197 }
198 remaining = slide(remaining, hit.normal, q.settings.min_ground_normal);
199 }
200 let support = if snap && delta.y <= 0. {
201 ground(q, p, q.settings.ground_snap + q.settings.skin)?
202 } else {
203 None
204 };
205 if let Some(hit) = support {
206 p -= Vec3::Y * (q.settings.ground_snap + q.settings.skin) * hit.fraction;
207 }
208 if let Some(hit) = support.or(stair_support) {
209 result.grounded = true;
210 result.ground_normal = hit.normal;
211 result.support = Some(Support::new(hit.obstacle, p));
212 }
213 if !bounded(p) {
214 return Err(CharacterError::InvalidInput);
215 }
216 result.position = p;
217 result.translation = p - origin;
218 result.candidates = q.candidates;
219 result.recovery = q.recovery;
220 Ok(result)
221}
222/// Sweep/slide without applying acceleration, gravity or jump state. Displacement
223/// may be long; no destination-only collision tests or discrete movement substeps.
224/// A bounded starting-overlap recovery is attempted; errors leave caller state intact.
225pub fn move_and_slide<T: Terrain + ?Sized>(
226 world: &T,
227 shape: CharacterShape,
228 settings: CharacterSettings,
229 position: Vec3,
230 displacement: Vec3,
231 was_grounded: bool,
232) -> Result<Motion, CharacterError> {
233 if !shape.valid()
234 || !settings.valid()
235 || !bounded(position)
236 || !bounded(displacement)
237 || (shape.planar() && (position.z != 0. || displacement.z != 0.))
238 {
239 return Err(CharacterError::InvalidInput);
240 }
241 let mut queries = Queries {
242 world,
243 shape,
244 settings,
245 candidates: 0,
246 ignored: None,
247 recovery: Recovery::default(),
248 };
249 move_inner(&mut queries, position, displacement, was_grounded, true)
250}
251#[derive(Clone, Copy, Debug, Default)]
252pub struct CharacterInput {
253 /// Desired horizontal direction, clamped to unit length. Y is ignored.
254 pub direction: Vec3,
255 /// Current held state; the motor buffers only a new press, avoiding automatic bunny hops.
256 pub jump: bool,
257}
258#[derive(Clone, Copy, Debug, PartialEq)]
259pub struct Character {
260 pub position: Vec3,
261 /// Velocity relative to a supporting platform; airborne velocity is in world space.
262 pub velocity: Vec3,
263 pub grounded: bool,
264 pub ground_normal: Vec3,
265 pub jump: JumpState,
266 pub support: Option<Support>,
267}
268impl Character {
269 pub fn new(feet: Vec3) -> Self {
270 Self {
271 position: feet,
272 velocity: Vec3::ZERO,
273 grounded: false,
274 ground_normal: Vec3::Y,
275 jump: Default::default(),
276 support: None,
277 }
278 }
279 /// Change the caller-owned shape's full sole-to-top height at the current
280 /// feet position. Capsule radius or Box2 half-width stays exactly unchanged;
281 /// Box2 stores half of `height` in `half.y`. Shape limits still apply.
282 ///
283 /// Queries the target shape even for shrinking or an unchanged height. Only
284 /// a successful complete clearance query commits `shape`; every error leaves
285 /// both shape and motor unchanged. The motor is borrowed immutably: velocity,
286 /// jump timers/held state, grounded state, normal and support anchors all stay
287 /// intact. No input edge, tick, recovery, carry or snap is performed. Terrain
288 /// is tested at its current pose; pending platform carry remains for `step`.
289 ///
290 /// Pass the accepted shape to later steps. Use the movement settings' mask
291 /// and candidate limit for consistent filtering. This operation permits a
292 /// zero candidate limit as documented by [`check_clearance`].
293 ///
294 /// This runnable slice-Terrain recipe keeps support across crouching and a
295 /// rejected stand, then stands in clear space and receives platform carry:
296 /// ```
297 /// use ferravex_math::Vec3;
298 /// use ferravex_physics::character::{Character, CharacterSettings, CharacterShape,
299 /// ClearanceError, Obstacle};
300 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
301 /// let settings = CharacterSettings::default();
302 /// let mut shape = CharacterShape::Capsule { radius: 0.3, height: 1.8 };
303 /// let mut platform = Obstacle::cuboid(7, -Vec3::Y * 0.1, Vec3::new(4., 0.1, 4.));
304 /// let mut motor = Character::new(Vec3::Y * settings.skin);
305 /// motor.teleport(&[platform][..], shape, settings, motor.position)?;
306 /// let saved = motor;
307 /// motor.try_set_height(&[platform][..], &mut shape, 1.,
308 /// settings.membership_mask, settings.max_candidates)?;
309 /// let ceiling = Obstacle::cuboid(9, Vec3::Y * 1.5, Vec3::new(2., 0.1, 2.));
310 /// assert_eq!(motor.try_set_height(&[platform, ceiling][..], &mut shape, 1.8,
311 /// settings.membership_mask, settings.max_candidates),
312 /// Err(ClearanceError::Blocked { obstacle: 9 }));
313 /// assert_eq!(shape, CharacterShape::Capsule { radius: 0.3, height: 1. });
314 /// assert_eq!(motor, saved);
315 /// motor.try_set_height(&[platform][..], &mut shape, 1.8,
316 /// settings.membership_mask, settings.max_candidates)?;
317 /// platform.position.x += 0.1;
318 /// let tick = motor.step(&[platform][..], shape, settings, Default::default(), 1. / 120.)?;
319 /// assert!((tick.carried.x - 0.1).abs() < 1e-5);
320 /// # Ok(())
321 /// # }
322 /// ```
323 pub fn try_set_height<T: Terrain + ?Sized>(
324 &self,
325 world: &T,
326 shape: &mut CharacterShape,
327 height: f32,
328 membership_mask: u32,
329 max_candidates: usize,
330 ) -> Result<Clearance, ClearanceError> {
331 if !shape.valid()
332 || !bounded(self.velocity)
333 || !self.ground_normal.is_finite()
334 || !self.jump.valid()
335 || (shape.planar() && self.velocity.z != 0.)
336 || self
337 .support
338 .is_some_and(|s| !bounded(s.local_anchor) || !bounded(s.previous_anchor))
339 {
340 return Err(ClearanceError::InvalidInput);
341 }
342 let next = match *shape {
343 CharacterShape::Capsule { radius, .. } => CharacterShape::Capsule { radius, height },
344 CharacterShape::Box2 { half } => CharacterShape::Box2 {
345 half: Vec2::new(half.x, height * 0.5),
346 },
347 };
348 let clearance =
349 check_clearance(world, next, self.position, membership_mask, max_candidates)?;
350 *shape = next;
351 Ok(clearance)
352 }
353
354 /// Reset to checked feet coordinates without querying terrain. Clears velocity,
355 /// support, grounded state and all jump state. Invalid coordinates or shape
356 /// leave `self` unchanged. Use [`Self::teleport`] to resolve overlaps immediately.
357 ///
358 /// Hosts must reset both previous/current interpolation poses to `self.position`
359 /// after success, and discard pending gameplay edges on a restart. This method
360 /// does not advance time or consume an input edge.
361 ///
362 /// ```
363 /// use ferravex_math::{Vec2, Vec3};
364 /// use ferravex_physics::character::{Character, CharacterShape, JumpState};
365 /// let shape = CharacterShape::Box2 { half: Vec2::new(0.3, 0.8) };
366 /// let mut motor = Character::new(Vec3::ZERO);
367 /// motor.velocity = Vec3::X * 4.;
368 /// motor.reset(shape, Vec3::Y * 2.)?;
369 /// let (previous, current) = (motor.position, motor.position);
370 /// assert_eq!(previous, current);
371 /// assert_eq!(motor.velocity, Vec3::ZERO);
372 /// assert_eq!(motor.jump, JumpState::default());
373 /// # Ok::<(), ferravex_physics::character::CharacterError>(())
374 /// ```
375 pub fn reset(&mut self, shape: CharacterShape, feet: Vec3) -> Result<(), CharacterError> {
376 if !shape.valid() || !bounded(feet) || (shape.planar() && feet.z != 0.) {
377 return Err(CharacterError::InvalidInput);
378 }
379 *self = Self::new(feet);
380 Ok(())
381 }
382 /// Reset at a destination, recover initial overlaps and probe/snap to walkable
383 /// ground using current terrain poses. This does not sweep from the old pose.
384 /// Velocity and jump state are cleared; support is acquired at the destination
385 /// with fresh anchors. Every error leaves all previous state intact.
386 ///
387 /// The returned translation is relative to `feet`, not the old position. Set
388 /// both host interpolation poses to the **resolved** `self.position` after
389 /// success. Reset camera history and pending gameplay edges as appropriate for
390 /// the host's restart; no fixed tick is consumed here.
391 ///
392 /// ```
393 /// use ferravex_math::Vec3;
394 /// use ferravex_physics::character::{Character, CharacterShape, Obstacle};
395 /// let shape = CharacterShape::Capsule { radius: 0.3, height: 1.8 };
396 /// let floor = Obstacle::cuboid(7, -Vec3::Y * 0.5, Vec3::new(4., 0.5, 4.));
397 /// let mut motor = Character::new(Vec3::Y * 10.);
398 /// let report = motor.teleport(&[floor][..], shape, Default::default(), -Vec3::Y * 0.1)?;
399 /// assert!(report.recovery.distance > 0.1);
400 /// assert!(report.grounded);
401 /// assert_eq!(report.support.unwrap().id, 7);
402 /// let (previous, current) = (motor.position, motor.position);
403 /// assert_eq!(previous, current);
404 /// # Ok::<(), ferravex_physics::character::CharacterError>(())
405 /// ```
406 pub fn teleport<T: Terrain + ?Sized>(
407 &mut self,
408 world: &T,
409 shape: CharacterShape,
410 settings: CharacterSettings,
411 feet: Vec3,
412 ) -> Result<Motion, CharacterError> {
413 let motion = move_and_slide(world, shape, settings, feet, Vec3::ZERO, false)?;
414 *self = Self {
415 grounded: motion.grounded,
416 ground_normal: motion.ground_normal,
417 support: motion.support,
418 ..Self::new(motion.position)
419 };
420 Ok(motion)
421 }
422 /// Advance at a fixed dt in (0, 0.1]. Terrain must already have this tick's pose.
423 /// All state updates commit together; invalid input or exhausted queries leave self unchanged.
424 /// The returned recovery/candidate totals cover the whole tick. Carry is
425 /// reported separately from the final support, so jumping or walking off a
426 /// platform does not hide its contribution earlier in the tick.
427 ///
428 /// ```
429 /// use ferravex_math::Vec3;
430 /// use ferravex_physics::character::{Character, CharacterShape, Obstacle};
431 /// let shape = CharacterShape::Capsule { radius: 0.3, height: 1.8 };
432 /// let mut platform = Obstacle::cuboid(7, -Vec3::Y * 0.1, Vec3::new(4., 0.1, 4.));
433 /// let mut motor = Character::new(Vec3::ZERO);
434 /// motor.teleport(&[platform][..], shape, Default::default(), Vec3::Y * 0.002)?;
435 /// platform.position.x += 0.1; // Move terrain before advancing the motor.
436 /// let tick = motor.step(&[platform][..], shape, Default::default(), Default::default(), 1. / 120.)?;
437 /// let carry = tick.motion.support_motion.unwrap();
438 /// assert_eq!(carry.id, 7);
439 /// assert!((carry.applied.x - 0.1).abs() < 1e-5);
440 /// assert!(!carry.blocked);
441 /// assert_eq!(tick.carried, carry.applied);
442 /// # Ok::<(), ferravex_physics::character::CharacterError>(())
443 /// ```
444 pub fn step<T: Terrain + ?Sized>(
445 &mut self,
446 world: &T,
447 shape: CharacterShape,
448 settings: CharacterSettings,
449 input: CharacterInput,
450 dt: f32,
451 ) -> Result<CharacterStep, CharacterError> {
452 if !dt.is_finite()
453 || !(0. ..=0.1).contains(&dt)
454 || dt == 0.
455 || !settings.valid()
456 || !shape.valid()
457 || !bounded(self.position)
458 || !bounded(self.velocity)
459 || !self.ground_normal.is_finite()
460 || !input.direction.is_finite()
461 || !self.jump.valid()
462 || (shape.planar() && (self.position.z != 0. || self.velocity.z != 0.))
463 || self
464 .support
465 .is_some_and(|s| !bounded(s.local_anchor) || !bounded(s.previous_anchor))
466 {
467 return Err(CharacterError::InvalidInput);
468 }
469 let mut next = *self;
470 let mut q = Queries {
471 world,
472 shape,
473 settings,
474 candidates: 0,
475 ignored: None,
476 recovery: Recovery::default(),
477 };
478 let mut carry = Vec3::ZERO;
479 let mut support_motion = None;
480 if let Some(support) = next.support
481 && let Some(o) = world.obstacle(support.id)
482 {
483 if o.id != support.id || !o.valid() {
484 return Err(CharacterError::InvalidObstacle);
485 }
486 if !o.sensor && o.membership & settings.membership_mask != 0 {
487 // Validate planar support before ignoring it in the carry sweep.
488 geometry::separation(shape, next.position, o)?;
489 let delta =
490 o.position + o.rotation * support.local_anchor - support.previous_anchor;
491 if !bounded(delta) || (shape.planar() && delta.z != 0.) {
492 return Err(CharacterError::InvalidInput);
493 }
494 q.ignored = Some(o.id);
495 let recovery_before = q.recovery.translation;
496 let motion = move_inner(&mut q, next.position, delta, false, false)?;
497 q.ignored = None;
498 next.position = motion.position;
499 let recovered = q.recovery.translation - recovery_before;
500 let applied = motion.translation - recovered;
501 carry = applied / dt;
502 support_motion = Some(SupportMotion {
503 id: o.id,
504 requested: delta,
505 applied,
506 blocked: motion.blocked,
507 });
508 }
509 }
510 next.position = q.recover(next.position)?;
511 let on_ground = next.velocity.y <= 0.
512 && ground(&mut q, next.position, settings.ground_snap + settings.skin)?.is_some();
513 let was_grounded = next.grounded || on_ground;
514 next.jump.coyote = if was_grounded {
515 settings.coyote_time
516 } else {
517 (next.jump.coyote - dt).max(0.)
518 };
519 next.jump.buffer = if input.jump && !next.jump.held {
520 settings.jump_buffer.max(dt)
521 } else {
522 (next.jump.buffer - dt).max(0.)
523 };
524 next.jump.held = input.jump;
525 let jumped = next.jump.buffer > 0. && (was_grounded || next.jump.coyote > 0.);
526 let wish = Vec3::new(
527 input.direction.x,
528 0.,
529 if shape.planar() {
530 0.
531 } else {
532 input.direction.z
533 },
534 )
535 .clamp_length_max(1.)
536 * settings.speed;
537 let horizontal = Vec3::new(next.velocity.x, 0., next.velocity.z);
538 let acceleration = if was_grounded {
539 settings.ground_acceleration
540 } else {
541 settings.air_acceleration
542 };
543 next.velocity += (wish - horizontal).clamp_length_max(acceleration * dt);
544 if jumped {
545 next.velocity.y = settings.jump_speed;
546 next.velocity += carry;
547 next.jump.buffer = 0.;
548 next.jump.coyote = 0.;
549 next.grounded = false;
550 }
551 next.velocity.y = (next.velocity.y - settings.gravity * dt).max(-settings.terminal_speed);
552 let mut motion = move_inner(
553 &mut q,
554 next.position,
555 next.velocity * dt,
556 was_grounded && !jumped,
557 true,
558 )?;
559 motion.support_motion = support_motion;
560 next.position = motion.position;
561 next.grounded = motion.grounded;
562 next.ground_normal = motion.ground_normal;
563 next.support = motion.support;
564 for normal in &motion.normals[..motion.normal_count] {
565 next.velocity = slide(next.velocity, *normal, settings.min_ground_normal);
566 }
567 if next.grounded {
568 next.velocity.y = 0.;
569 }
570 if !bounded(next.velocity) {
571 return Err(CharacterError::InvalidInput);
572 }
573 *self = next;
574 Ok(CharacterStep {
575 motion,
576 jumped,
577 carried: support_motion.map_or(Vec3::ZERO, |support| support.applied),
578 })
579 }
580}
581#[derive(Clone, Copy, Debug)]
582pub struct CharacterStep {
583 pub motion: Motion,
584 pub jumped: bool,
585 /// Applied platform carry, excluding initial-overlap correction and ground snap.
586 /// See [`Motion::support_motion`] for the requested displacement and blockage.
587 pub carried: Vec3,
588}