ferravex_physics/character/
mod.rs

1//! Kinematic upright capsules and planar boxes, shared by games and prediction.
2//! Positive Y is up. Positions are feet/sole centers. Move terrain first, then motors.
3//!
4//! [`Character::reset`] clears motion/support/jump history at checked coordinates;
5//! [`Character::teleport`] additionally resolves destination overlaps and acquires
6//! current walkable support. After either succeeds, hosts must set **both** previous
7//! and current interpolation poses to the resolved character position, including
8//! camera history on a restart. Do not interpolate across the old and new locations.
9//! Discard pending host gameplay edges on restart; neither method advances a tick.
10//! [`Motion::recovery`] separates overlap correction from gameplay movement, and
11//! [`Motion::support_motion`] reports attempted versus applied platform carry.
12//! [`check_clearance`] and [`Character::try_set_height`] never recover, snap or
13//! advance time. Height changes preserve the sole position and all motor history;
14//! the caller continues to pass the accepted shape to subsequent motor steps.
15mod geometry;
16mod motion;
17use ferravex_math::{Quat, Vec2, Vec3};
18pub use geometry::check_clearance;
19pub use motion::{
20    Character, CharacterInput, CharacterStep, JumpState, Motion, Recovery, Support, SupportMotion,
21    move_and_slide,
22};
23
24#[derive(Clone, Copy, Debug, PartialEq)]
25pub enum CharacterShape {
26    Capsule {
27        radius: f32,
28        height: f32,
29    },
30    /// Axis-aligned planar rectangle, half extents in XY; Z remains zero.
31    Box2 {
32        half: Vec2,
33    },
34}
35impl CharacterShape {
36    pub fn valid(self) -> bool {
37        match self {
38            Self::Capsule { radius, height } => {
39                radius.is_finite()
40                    && height.is_finite()
41                    && radius >= 0.001
42                    && height >= radius * 2.
43                    && height <= 1000.
44            }
45            Self::Box2 { half } => {
46                half.is_finite() && half.min_element() >= 0.001 && half.max_element() <= 1000.
47            }
48        }
49    }
50    pub fn half_extents(self) -> Vec3 {
51        match self {
52            Self::Capsule { radius, height } => Vec3::new(radius, height * 0.5, radius),
53            Self::Box2 { half } => Vec3::new(half.x, half.y, 0.),
54        }
55    }
56    fn planar(self) -> bool {
57        matches!(self, Self::Box2 { .. })
58    }
59    fn center(self, feet: Vec3) -> Vec3 {
60        feet + Vec3::Y * self.half_extents().y
61    }
62    pub fn bounds(self, feet: Vec3) -> QueryBounds {
63        let center = self.center(feet);
64        let half = self.half_extents();
65        QueryBounds {
66            min: center - half,
67            max: center + half,
68        }
69    }
70}
71
72#[derive(Clone, Copy, Debug)]
73pub struct QueryBounds {
74    pub min: Vec3,
75    pub max: Vec3,
76}
77impl QueryBounds {
78    pub fn intersects(self, other: Self) -> bool {
79        (0..3).all(|i| self.min[i] <= other.max[i] && self.max[i] >= other.min[i])
80    }
81    pub fn expanded(self, amount: f32) -> Self {
82        Self {
83            min: self.min - Vec3::splat(amount),
84            max: self.max + Vec3::splat(amount),
85        }
86    }
87    fn union(self, other: Self) -> Self {
88        Self {
89            min: self.min.min(other.min),
90            max: self.max.max(other.max),
91        }
92    }
93}
94#[derive(Clone, Copy, Debug)]
95pub enum ObstacleShape {
96    Box {
97        half: Vec3,
98    },
99    Ball {
100        radius: f32,
101    },
102    Capsule {
103        a: Vec3,
104        b: Vec3,
105        radius: f32,
106    },
107    Cylinder {
108        half_height: f32,
109        radius: f32,
110    },
111    /// An infinite solid half-space, with local outward unit normal.
112    Plane {
113        normal: Vec3,
114    },
115}
116#[derive(Clone, Copy, Debug)]
117pub struct Obstacle {
118    /// Stable, unique identity within a terrain. Reuse requires a new generation/id.
119    pub id: u64,
120    pub shape: ObstacleShape,
121    pub position: Vec3,
122    pub rotation: Quat,
123    pub membership: u32,
124    pub sensor: bool,
125}
126impl Obstacle {
127    pub fn cuboid(id: u64, position: Vec3, half: Vec3) -> Self {
128        Self {
129            id,
130            position,
131            shape: ObstacleShape::Box { half },
132            rotation: Quat::IDENTITY,
133            membership: u32::MAX,
134            sensor: false,
135        }
136    }
137    pub fn valid(self) -> bool {
138        if !bounded(self.position)
139            || !self.rotation.is_finite()
140            || (self.rotation.length_squared() - 1.).abs() > 0.001
141        {
142            return false;
143        }
144        let radius_valid = |r: f32| r.is_finite() && (0.001..=1000.).contains(&r);
145        match self.shape {
146            ObstacleShape::Box { half } => {
147                half.is_finite() && half.min_element() > 0. && half.max_element() <= 10000.
148            }
149            ObstacleShape::Ball { radius } => radius_valid(radius),
150            ObstacleShape::Capsule { a, b, radius } => {
151                bounded(a) && bounded(b) && (a - b).length() <= 2000. && radius_valid(radius)
152            }
153            ObstacleShape::Cylinder {
154                half_height,
155                radius,
156            } => radius_valid(half_height) && radius_valid(radius),
157            ObstacleShape::Plane { normal } => {
158                normal.is_finite() && (normal.length_squared() - 1.).abs() < 0.001
159            }
160        }
161    }
162    pub fn bounds(self) -> QueryBounds {
163        let (center, half) = match self.shape {
164            ObstacleShape::Box { half } => (
165                self.position,
166                (self.rotation * Vec3::X).abs() * half.x
167                    + (self.rotation * Vec3::Y).abs() * half.y
168                    + (self.rotation * Vec3::Z).abs() * half.z,
169            ),
170            ObstacleShape::Ball { radius } => (self.position, Vec3::splat(radius)),
171            ObstacleShape::Capsule { a, b, radius } => {
172                let a = self.position + self.rotation * a;
173                let b = self.position + self.rotation * b;
174                ((a + b) * 0.5, (a - b).abs() * 0.5 + Vec3::splat(radius))
175            }
176            ObstacleShape::Cylinder {
177                half_height,
178                radius,
179            } => {
180                let y = self.rotation * Vec3::Y;
181                (
182                    self.position,
183                    Vec3::new(
184                        (1. - y.x * y.x).max(0.).sqrt(),
185                        (1. - y.y * y.y).max(0.).sqrt(),
186                        (1. - y.z * y.z).max(0.).sqrt(),
187                    ) * radius
188                        + y.abs() * half_height,
189                )
190            }
191            ObstacleShape::Plane { .. } => (Vec3::ZERO, Vec3::splat(2e6)),
192        };
193        QueryBounds {
194            min: center - half,
195            max: center + half,
196        }
197    }
198}
199/// The visitor receives current poses. Implementations may use their broadphase;
200/// they must visit every obstacle intersecting bounds, in deterministic order.
201/// Character queries allocate no scratch buffers. Sensors/layers are filtered by the motor.
202pub trait Terrain {
203    fn visit(&self, bounds: QueryBounds, visitor: &mut dyn FnMut(Obstacle));
204    /// Current pose for a previously reported support; None releases a removed platform.
205    fn obstacle(&self, id: u64) -> Option<Obstacle>;
206}
207impl Terrain for [Obstacle] {
208    fn visit(&self, bounds: QueryBounds, visitor: &mut dyn FnMut(Obstacle)) {
209        for &o in self {
210            if !o.valid() || bounds.intersects(o.bounds()) {
211                visitor(o);
212            }
213        }
214    }
215    fn obstacle(&self, id: u64) -> Option<Obstacle> {
216        self.iter().find(|o| o.id == id).copied()
217    }
218}
219#[derive(Clone, Copy, Debug)]
220pub struct CharacterSettings {
221    pub skin: f32,
222    pub ground_snap: f32,
223    pub step_height: f32,
224    pub min_ground_normal: f32,
225    pub max_iterations: u32,
226    pub max_candidates: usize,
227    /// Maximum cumulative length of overlap corrections per public operation.
228    /// Reaching this limit with unresolved overlap returns an error without
229    /// committing character state. Zero permits only already-clear positions.
230    pub max_recovery: f32,
231    pub membership_mask: u32,
232    pub speed: f32,
233    pub ground_acceleration: f32,
234    pub air_acceleration: f32,
235    pub gravity: f32,
236    pub terminal_speed: f32,
237    pub jump_speed: f32,
238    pub coyote_time: f32,
239    pub jump_buffer: f32,
240}
241impl Default for CharacterSettings {
242    fn default() -> Self {
243        Self {
244            skin: 0.002,
245            ground_snap: 0.08,
246            step_height: 0.25,
247            min_ground_normal: 0.7,
248            max_iterations: 8,
249            max_candidates: 16384,
250            max_recovery: 1.,
251            membership_mask: u32::MAX,
252            speed: 7.,
253            ground_acceleration: 55.,
254            air_acceleration: 14.,
255            gravity: 24.,
256            terminal_speed: 50.,
257            jump_speed: 8.6,
258            coyote_time: 0.1,
259            jump_buffer: 0.12,
260        }
261    }
262}
263impl CharacterSettings {
264    pub fn valid(self) -> bool {
265        let nonnegative = |v: f32, max: f32| v.is_finite() && (0. ..=max).contains(&v);
266        self.skin.is_finite()
267            && (1e-5..=1.).contains(&self.skin)
268            && nonnegative(self.ground_snap, 100.)
269            && nonnegative(self.step_height, 100.)
270            && self.min_ground_normal.is_finite()
271            && (0.01..=1.).contains(&self.min_ground_normal)
272            && (1..=16).contains(&self.max_iterations)
273            && (1..=1_000_000).contains(&self.max_candidates)
274            && nonnegative(self.max_recovery, 1000.)
275            && nonnegative(self.speed, 100000.)
276            && nonnegative(self.ground_acceleration, 1e6)
277            && nonnegative(self.air_acceleration, 1e6)
278            && nonnegative(self.gravity, 1e6)
279            && nonnegative(self.terminal_speed, 100000.)
280            && nonnegative(self.jump_speed, 100000.)
281            && nonnegative(self.coyote_time, 0.5)
282            && nonnegative(self.jump_buffer, 0.5)
283    }
284}
285#[derive(Clone, Copy, Debug, PartialEq, Eq)]
286pub enum CharacterError {
287    InvalidInput,
288    InvalidObstacle,
289    QueryBudget,
290    SweepBudget,
291    UnresolvedPenetration,
292}
293/// A complete, nonpenetrating clearance query. Touching is allowed, using the
294/// motor's existing `1e-5` penetration tolerance; skin is not added to the shape.
295#[derive(Clone, Copy, Debug, PartialEq, Eq)]
296pub struct Clearance {
297    /// All visited candidates, including sensors and excluded membership layers.
298    pub candidates: usize,
299}
300/// Failure of a clearance query or checked height change. This separate type
301/// preserves exhaustive matches on the existing [`CharacterError`].
302#[derive(Clone, Copy, Debug, PartialEq, Eq)]
303pub enum ClearanceError {
304    /// Invalid shape, feet, motor state, height or candidate limit.
305    InvalidInput,
306    /// An included obstacle is malformed or unsupported for the queried shape.
307    InvalidObstacle,
308    /// More candidates were visited than the supplied limit. No partial result
309    /// authorizes a height change, even if a blocker was already encountered.
310    QueryBudget,
311    /// A complete query found penetration beyond the motor's tolerance.
312    Blocked {
313        /// Smallest stable obstacle ID among the blocking candidates.
314        obstacle: u64,
315    },
316}
317impl std::fmt::Display for ClearanceError {
318    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
319        write!(f, "character clearance: {self:?}")
320    }
321}
322impl std::error::Error for ClearanceError {}
323impl std::fmt::Display for CharacterError {
324    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
325        write!(f, "character controller: {self:?}")
326    }
327}
328impl std::error::Error for CharacterError {}
329fn bounded(p: Vec3) -> bool {
330    p.is_finite() && p.abs().max_element() <= 1e6
331}
332
333// The rigid world adapter reads current poses and excludes the character's own
334// body through the query mask/sensor flag when applications also store a proxy.
335impl<B: crate::body::Access> Terrain for crate::world::World<B> {
336    fn visit(&self, bounds: QueryBounds, visitor: &mut dyn FnMut(Obstacle)) {
337        for (handle, collider) in self.colliders.iter() {
338            if let Some(o) = self.character_obstacle(handle, collider)
339                && bounds.intersects(o.bounds())
340            {
341                visitor(o);
342            }
343        }
344    }
345    fn obstacle(&self, id: u64) -> Option<Obstacle> {
346        let handle = crate::ColliderHandle {
347            index: (id & 0xffff_ffff) as usize,
348            generation: (id >> 32) as u32,
349        };
350        self.character_obstacle(handle, self.colliders.get(handle)?)
351    }
352}
353impl<B: crate::body::Access> crate::world::World<B> {
354    fn character_obstacle(
355        &self,
356        handle: crate::ColliderHandle,
357        collider: &crate::Collider,
358    ) -> Option<Obstacle> {
359        let core = self.bodies.get(collider.parent?)?.core();
360        let shape = match collider.shape {
361            crate::body::Shape::Ball(radius) => ObstacleShape::Ball { radius },
362            crate::body::Shape::Box(half) => ObstacleShape::Box { half },
363            #[cfg(feature = "dim2")]
364            crate::body::Shape::Capsule { a, b, radius } => ObstacleShape::Capsule { a, b, radius },
365            #[cfg(feature = "dim3")]
366            crate::body::Shape::Cylinder {
367                half_height,
368                radius,
369            } => ObstacleShape::Cylinder {
370                half_height,
371                radius,
372            },
373        };
374        let pose = collider.pose(core);
375        Some(Obstacle {
376            id: (u64::from(handle.generation) << 32) | handle.index as u64,
377            shape,
378            position: pose.position,
379            rotation: pose.rotation,
380            membership: collider.membership,
381            sensor: collider.sensor,
382        })
383    }
384}
385
386#[cfg(test)]
387mod tests;