use glam::DVec3;
use crate::broadphase::{Ray, Segment};
use crate::collider::{Capsule, LyingCapsule};
use crate::query::{Penetration, ShapeHit};
use crate::world::{
ALL_LAYERS, ColliderId, OverlapQueries, PhysicsWorld, QueryFilter, QueryScratch,
};
mod lying;
mod preview;
mod skin;
mod slide_contact;
pub use lying::{LyingMoveOutcome, LyingTurnOutcome};
pub use preview::UprightPreview;
pub use slide_contact::SlideContact;
const UP: DVec3 = DVec3::Y;
const MIN_MOVE: f64 = 1e-9;
pub const MAX_PLANES: usize = 5;
const GROUND_PROBE_SKINS: f64 = 2.0;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CharacterConfig {
pub radius: f64,
pub half_height: f64,
pub min_ground_normal_y: f64,
pub step_offset: f64,
pub skin_width: f64,
pub max_slides: u32,
pub depenetration_passes: u32,
}
impl Default for CharacterConfig {
fn default() -> Self {
Self {
radius: 0.3,
half_height: 0.6,
min_ground_normal_y: std::f64::consts::FRAC_1_SQRT_2,
step_offset: 0.4,
skin_width: 0.01,
max_slides: 4,
depenetration_passes: 4,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GroundContact {
pub normal: DVec3,
pub point: DVec3,
pub collider: ColliderId,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GroundProbe {
pub contact: GroundContact,
pub distance: f64,
pub walkable: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct MoveOutcome {
pub motion: DVec3,
pub depenetration: DVec3,
pub grounded: bool,
pub hit_wall: bool,
pub hit_ceiling: bool,
pub stepped_up: bool,
pub slides: u32,
}
#[derive(Debug, Clone, Copy, Default)]
struct SlideReport {
hit_wall: bool,
hit_ceiling: bool,
stepped_up: bool,
slides: u32,
}
#[derive(Debug, Clone, Copy)]
enum Body {
Upright,
Lying(LyingCapsule),
}
struct WorldReader<'w, 's> {
view: OverlapQueries<'w>,
scratch: &'s mut QueryScratch,
}
impl<'w> WorldReader<'w, 'w> {
fn of(world: &'w mut PhysicsWorld) -> Self {
let (view, scratch) = world.overlap_queries_with_scratch();
Self { view, scratch }
}
}
#[derive(Debug, Clone, Copy)]
struct StepUp {
position: DVec3,
advance: DVec3,
}
#[derive(Debug, Clone)]
pub struct CharacterController {
config: CharacterConfig,
position: DVec3,
ground: Option<GroundContact>,
self_collider: Option<ColliderId>,
query_mask: u32,
contacts: Vec<(ColliderId, Penetration)>,
}
impl CharacterController {
#[must_use]
pub fn new(config: CharacterConfig, position: DVec3) -> Self {
Self {
config,
position,
ground: None,
self_collider: None,
query_mask: ALL_LAYERS,
contacts: Vec::new(),
}
}
#[must_use]
pub fn with_self_collider(mut self, collider: ColliderId) -> Self {
self.set_self_collider(Some(collider));
self
}
pub fn set_self_collider(&mut self, collider: Option<ColliderId>) {
self.self_collider = collider;
}
#[must_use]
pub fn with_query_mask(mut self, mask: u32) -> Self {
self.set_query_mask(mask);
self
}
pub fn set_query_mask(&mut self, mask: u32) {
self.query_mask = mask;
}
#[inline]
#[must_use]
pub fn query_mask(&self) -> u32 {
self.query_mask
}
#[inline]
#[must_use]
pub fn position(&self) -> DVec3 {
self.position
}
pub fn set_position(&mut self, position: DVec3) {
self.position = position;
self.ground = None;
}
#[inline]
#[must_use]
pub fn capsule(&self) -> Capsule {
Capsule::new(self.position, self.config.radius, self.config.half_height)
}
#[inline]
#[must_use]
pub fn config(&self) -> &CharacterConfig {
&self.config
}
#[inline]
#[must_use]
pub fn ground(&self) -> Option<&GroundContact> {
self.ground.as_ref()
}
#[inline]
#[must_use]
pub fn is_grounded(&self) -> bool {
self.ground.is_some()
}
#[must_use]
pub fn probe_ground(&self, world: &mut PhysicsWorld, distance: f64) -> Option<GroundProbe> {
self.probe_ground_at(world, self.position, distance)
}
#[must_use]
pub fn probe_ground_at(
&self,
world: &mut PhysicsWorld,
position: DVec3,
distance: f64,
) -> Option<GroundProbe> {
assert!(
distance.is_finite() && distance >= 0.0,
"a ground probe looks a finite, non-negative distance down, not {distance}",
);
self.probe_below(&mut WorldReader::of(world), position, distance)
}
#[must_use]
pub fn lying_blocker(
&self,
world: &mut PhysicsWorld,
capsule: &LyingCapsule,
) -> Option<ColliderId> {
world.lying_capsule_blocker(capsule, self.filter())
}
#[inline]
#[must_use]
pub fn is_walkable(&self, normal: DVec3) -> bool {
let rise = normal.dot(UP);
rise > 0.0 && rise >= self.config.min_ground_normal_y
}
#[inline]
#[must_use]
pub fn is_ceiling(&self, normal: DVec3) -> bool {
let rise = normal.dot(UP);
rise < 0.0 && -rise >= self.config.min_ground_normal_y
}
pub fn move_and_slide(&mut self, world: &mut PhysicsWorld, motion: DVec3) -> MoveOutcome {
self.move_upright(world, motion, None)
}
pub fn move_and_slide_into(
&mut self,
world: &mut PhysicsWorld,
motion: DVec3,
contacts: &mut Vec<SlideContact>,
) -> MoveOutcome {
contacts.clear();
self.move_upright(world, motion, Some(contacts))
}
fn move_upright(
&mut self,
world: &mut PhysicsWorld,
motion: DVec3,
contacts: Option<&mut Vec<SlideContact>>,
) -> MoveOutcome {
let outcome = self.solve_upright(&mut WorldReader::of(world), motion, contacts);
if let Some(collider) = self.self_collider {
world.set_capsule(collider, self.capsule());
}
outcome
}
fn solve_upright(
&mut self,
world: &mut WorldReader<'_, '_>,
motion: DVec3,
contacts: Option<&mut Vec<SlideContact>>,
) -> MoveOutcome {
let depenetration = self.depenetrate(world);
let start = self.position;
let was_grounded = self.ground.is_some();
let adjusted = self.ground_adjusted(motion, was_grounded);
let report = self.slide(world, adjusted, was_grounded, Body::Upright, contacts);
self.settle_on_ground(world, was_grounded, motion);
MoveOutcome {
motion: self.position - start,
depenetration,
grounded: self.ground.is_some(),
hit_wall: report.hit_wall,
hit_ceiling: report.hit_ceiling,
stepped_up: report.stepped_up,
slides: report.slides,
}
}
fn depenetrate(&mut self, world: &mut WorldReader<'_, '_>) -> DVec3 {
let mut total = DVec3::ZERO;
for _ in 0..self.config.depenetration_passes {
let capsule = self.capsule();
let mut contacts = std::mem::take(&mut self.contacts);
world.view.capsule_penetrations_filtered_into(
&capsule,
self.filter(),
world.scratch,
&mut contacts,
);
let deepest = contacts
.iter()
.max_by(|a, b| a.1.depth.total_cmp(&b.1.depth))
.map(|&(_, penetration)| penetration);
self.contacts = contacts;
let Some(penetration) = deepest else {
break;
};
let push = penetration.normal * (penetration.depth + self.config.skin_width);
self.position += push;
total += push;
}
total
}
fn ground_adjusted(&self, motion: DVec3, was_grounded: bool) -> DVec3 {
if !was_grounded || motion.dot(UP) > 0.0 {
return motion;
}
let Some(ground) = self.ground else {
return motion;
};
let flat = motion - UP * motion.dot(UP);
flat - UP * (ground.normal.dot(flat) / ground.normal.dot(UP))
}
fn slide(
&mut self,
world: &mut WorldReader<'_, '_>,
motion: DVec3,
was_grounded: bool,
body: Body,
mut contacts: Option<&mut Vec<SlideContact>>,
) -> SlideReport {
let mut record = |contact| {
if let Some(contacts) = contacts.as_deref_mut() {
contacts.push(contact);
}
};
let mut report = SlideReport::default();
let primal = motion;
let mut remaining = motion;
let mut clip_from = motion;
let mut planes = [DVec3::ZERO; MAX_PLANES];
let mut plane_count = 0usize;
for _ in 0..self.config.max_slides {
let distance = remaining.length();
if distance <= MIN_MOVE {
return report;
}
let direction = remaining / distance;
let target = self.position + remaining;
let Some(sweep) = self.sweep_body(world, body, remaining) else {
self.position = target;
return report;
};
let (collider, hit) = (sweep.collider, sweep.hit);
report.slides += 1;
let mut contact = SlideContact {
collider,
normal: hit.normal,
requested: remaining,
fraction: hit.t,
started_inside: hit.started_inside,
clearance_only: sweep.clearance.is_some(),
applied: DVec3::ZERO,
remaining: DVec3::ZERO,
stepped_up: false,
};
let wall = !self.is_ceiling(hit.normal) && !self.is_walkable(hit.normal);
let mut plane = hit.normal;
if wall && was_grounded && matches!(body, Body::Lying(_)) {
let flat = (plane - UP * plane.dot(UP)).normalize_or_zero();
if flat != DVec3::ZERO {
plane = flat;
}
}
let along = hit.t * distance;
let mut back_off = DVec3::ZERO;
let travel = if sweep.clearance.is_some() {
(!hit.started_inside).then_some(along)
} else {
self.skin_short(along, direction, plane)
};
if let Some(travel) = travel {
let travel = travel.min(distance);
let step = direction * travel;
self.position += step;
remaining -= step;
contact.applied = step;
if travel > MIN_MOVE {
clip_from = remaining;
plane_count = 0;
}
} else {
let approach = (along * -direction.dot(plane)).max(0.0);
let short = sweep.clearance.unwrap_or(self.config.skin_width - approach);
if short > MIN_MOVE {
back_off = plane * short;
}
}
if self.is_ceiling(hit.normal) {
report.hit_ceiling = true;
} else if wall {
report.hit_wall = true;
if was_grounded
&& !report.stepped_up
&& matches!(body, Body::Upright)
&& let Some(step) = self.try_step_up(world, remaining)
{
contact.applied += step.position - self.position;
self.position = step.position;
remaining -= step.advance;
clip_from = remaining;
plane_count = 0;
report.stepped_up = true;
record(SlideContact {
remaining,
stepped_up: true,
..contact
});
continue;
}
}
self.position += back_off;
contact.applied += back_off;
if plane_count == MAX_PLANES {
record(contact);
return report;
}
planes[plane_count] = plane;
plane_count += 1;
remaining = clip_to_planes(clip_from, &planes[..plane_count], remaining);
if remaining.dot(primal) <= 0.0 {
record(contact);
return report;
}
record(SlideContact {
remaining,
..contact
});
}
report
}
fn try_step_up(&self, world: &mut WorldReader<'_, '_>, remaining: DVec3) -> Option<StepUp> {
if self.config.step_offset <= 0.0 {
return None;
}
let forward = remaining - UP * remaining.dot(UP);
let forward_distance = forward.length();
if forward_distance <= MIN_MOVE {
return None;
}
let forward_direction = forward / forward_distance;
let rise = self.clear_travel(world, self.position, UP * self.config.step_offset);
if rise <= MIN_MOVE {
return None;
}
let raised = self.position + UP * rise;
let advance = self.clear_travel(world, raised, forward);
if advance <= MIN_MOVE {
return None;
}
let drop = rise + self.config.skin_width * GROUND_PROBE_SKINS;
let land = |world: &mut WorldReader<'_, '_>, advance: f64| {
let over = raised + forward_direction * advance;
let (_, landing) = world.view.sweep_upright_where(
&Capsule::new(over, self.config.radius, self.config.half_height),
over - UP * drop,
self.filter(),
world.scratch,
|hit| hit.normal.dot(UP) > MIN_MOVE,
)?;
(!landing.started_inside).then_some((advance, over, landing))
};
let (advance, over, landing) = land(world, advance)?;
if !self.is_walkable(landing.normal)
&& !self.perches_on(world, landing.point, over, forward_direction)
{
return None;
}
let feet = self.position.y - self.config.radius - self.config.half_height;
if landing.point.y - feet > self.config.step_offset {
return None;
}
let fall = (landing.t * drop - self.config.skin_width).clamp(0.0, drop);
Some(StepUp {
position: over - UP * fall,
advance: forward_direction * advance,
})
}
fn settle_on_ground(
&mut self,
world: &mut WorldReader<'_, '_>,
was_grounded: bool,
motion: DVec3,
) {
self.ground = None;
if motion.dot(UP) > 0.0 {
return;
}
let probe = self.settle_reach(was_grounded, motion);
let Some(mut found) = self.probe_below(world, self.position, probe) else {
return;
};
let ahead = DVec3::new(motion.x, 0.0, motion.z).normalize_or_zero();
let perched = !found.walkable
&& was_grounded
&& self.perches_on(
world,
found.contact.point,
self.position - UP * found.distance,
ahead,
);
if perched {
found.contact.normal = UP;
found.walkable = true;
}
if !found.walkable {
let Some((landed, below)) = self.slide_off_edge(world, probe, &found) else {
return;
};
self.position = landed;
found = below;
}
let fall = (found.distance - self.config.skin_width).clamp(-self.config.skin_width, probe);
self.position -= UP * fall;
self.ground = Some(found.contact);
}
fn perches_on(
&self,
world: &mut WorldReader<'_, '_>,
point: DVec3,
centre: DVec3,
ahead: DVec3,
) -> bool {
let feet = centre.y - self.config.radius - self.config.half_height;
let toward = DVec3::new(point.x - centre.x, 0.0, point.z - centre.z);
if toward.dot(ahead) <= MIN_MOVE || point.y - feet > self.config.step_offset {
return false;
}
let skin = self.config.skin_width;
let ray = Ray::new(point + ahead * skin + UP * skin, -UP).with_bounds(0.0, 2.0 * skin);
world
.view
.cast_ray_filtered(&ray, self.filter(), world.scratch)
.is_some_and(|(_, top)| !top.started_inside && self.is_walkable(top.normal))
}
fn slide_off_edge(
&self,
world: &mut WorldReader<'_, '_>,
reach: f64,
found: &GroundProbe,
) -> Option<(DVec3, GroundProbe)> {
let normal = found.contact.normal;
let down = (-UP + normal * normal.dot(UP)).normalize_or_zero();
let remaining = reach - found.distance;
if down.dot(UP) > -MIN_MOVE || remaining <= MIN_MOVE {
return None;
}
let start = self.position - UP * found.distance;
let length = remaining / -down.dot(UP);
let travel = match world.view.sweep_upright_where(
&Capsule::new(start, self.config.radius, self.config.half_height),
start + down * length,
self.filter(),
world.scratch,
|hit| down.dot(hit.normal) < -MIN_MOVE,
) {
None => length,
Some((_, hit)) => self.skin_short(hit.t * length, down, hit.normal)?,
};
let end = start + down * travel;
let below = self.probe_below(world, end, self.config.skin_width * GROUND_PROBE_SKINS)?;
below.walkable.then_some((end, below))
}
fn settle_reach(&self, was_grounded: bool, motion: DVec3) -> f64 {
let snap = if was_grounded && motion.dot(UP) <= 0.0 {
self.config.step_offset
} else {
0.0
};
snap + self.config.skin_width * GROUND_PROBE_SKINS
}
fn probe_below(
&self,
world: &mut WorldReader<'_, '_>,
from: DVec3,
distance: f64,
) -> Option<GroundProbe> {
let found = world.view.sweep_upright_where(
&Capsule::new(from, self.config.radius, self.config.half_height),
from - UP * distance,
self.filter(),
world.scratch,
|hit| hit.normal.dot(UP) > MIN_MOVE,
)?;
let probe = self.ground_probe(found, distance);
if probe.walkable {
return Some(probe);
}
Some(self.wedged_footing(world, from - UP * probe.distance, probe))
}
fn wedged_footing(
&self,
world: &mut WorldReader<'_, '_>,
at: DVec3,
probe: GroundProbe,
) -> GroundProbe {
let reach = Capsule::new(
at,
self.config.radius + self.config.skin_width * GROUND_PROBE_SKINS,
self.config.half_height,
);
let mut normals = Vec::new();
world
.view
.capsule_contact_normals_into(&reach, self.filter(), world.scratch, &mut normals);
let (count, sum) = normals
.iter()
.filter(|normal| normal.dot(UP) > MIN_MOVE)
.fold((0_usize, DVec3::ZERO), |(count, sum), normal| {
(count + 1, sum + *normal)
});
let combined = sum.normalize_or_zero();
if count < 2 || !self.is_walkable(combined) {
return probe;
}
GroundProbe {
contact: GroundContact {
normal: combined,
..probe.contact
},
walkable: true,
..probe
}
}
fn ground_probe(&self, (collider, hit): (ColliderId, ShapeHit), distance: f64) -> GroundProbe {
GroundProbe {
contact: GroundContact {
normal: hit.normal,
point: hit.point,
collider,
},
distance: hit.t * distance,
walkable: self.is_walkable(hit.normal),
}
}
fn clear_travel(&self, world: &mut WorldReader<'_, '_>, from: DVec3, delta: DVec3) -> f64 {
let distance = delta.length();
if distance <= MIN_MOVE {
return 0.0;
}
world
.view
.sweep_upright_where(
&Capsule::new(
from,
self.config.radius + self.config.skin_width,
self.config.half_height,
),
from + delta,
self.filter(),
world.scratch,
|hit| delta.dot(hit.normal) < -MIN_MOVE,
)
.map_or(distance, |(_, hit)| hit.t * distance)
}
fn skin_short(&self, along: f64, direction: DVec3, normal: DVec3) -> Option<f64> {
let closing = -direction.dot(normal);
(along * closing > self.config.skin_width).then(|| along - self.config.skin_width / closing)
}
fn sweep(
&self,
world: &mut WorldReader<'_, '_>,
from: DVec3,
to: DVec3,
) -> Option<(ColliderId, ShapeHit)> {
world.view.sweep_capsule_filtered(
&Segment::new(from, to),
self.config.radius,
self.config.half_height,
self.filter(),
world.scratch,
)
}
fn filter(&self) -> QueryFilter {
QueryFilter::excluding(self.self_collider).with_mask(self.query_mask)
}
}
fn clip_to_planes(motion: DVec3, planes: &[DVec3], current: DVec3) -> DVec3 {
for (i, &plane) in planes.iter().enumerate() {
let clipped = motion - plane * motion.dot(plane);
if planes
.iter()
.enumerate()
.all(|(j, &other)| j == i || clipped.dot(other) >= 0.0)
{
return clipped;
}
}
if let [first, second] = planes {
let crease = first.cross(*second).normalize_or_zero();
return crease * crease.dot(current);
}
DVec3::ZERO
}
#[cfg(test)]
mod tests {
use super::*;
use crate::collider::{BoxCollider, Sphere};
const DOME_RADIUS: f64 = 1000.0;
fn centre_for_feet(config: &CharacterConfig, feet: f64) -> f64 {
feet + config.radius + config.half_height
}
fn flat_world() -> PhysicsWorld {
let mut world = PhysicsWorld::new();
world.add_box(BoxCollider::new(
DVec3::new(0.0, -1.0, 0.0),
DVec3::new(50.0, 1.0, 50.0),
));
world
}
fn standing(world: &mut PhysicsWorld, config: CharacterConfig) -> CharacterController {
let mut character =
CharacterController::new(config, DVec3::new(0.0, centre_for_feet(&config, 0.0), 0.0));
character.move_and_slide(world, DVec3::ZERO);
assert!(character.is_grounded(), "the fixture starts on the floor");
character
}
pub(super) fn dome_world() -> PhysicsWorld {
let mut world = PhysicsWorld::new();
world.add_sphere(Sphere::new(DVec3::new(0.0, -DOME_RADIUS, 0.0), DOME_RADIUS));
world
}
pub(super) fn on_dome(config: &CharacterConfig, angle: f64) -> DVec3 {
let normal = DVec3::new(
crcbl_core::trig::sin(angle),
crcbl_core::trig::cos(angle),
0.0,
);
DVec3::new(0.0, -DOME_RADIUS + config.half_height, 0.0)
+ normal * (DOME_RADIUS + config.radius)
}
pub(super) fn stepped_world(height: f64) -> PhysicsWorld {
let mut world = PhysicsWorld::new();
world.add_box(BoxCollider::new(
DVec3::new(-25.0, -1.0, 0.0),
DVec3::new(25.0, 1.0, 5.0),
));
world.add_box(BoxCollider::new(
DVec3::new(25.0, (height - 2.0) * 0.5, 0.0),
DVec3::new(25.0, (height + 2.0) * 0.5, 5.0),
));
world
}
fn feet_of(character: &CharacterController) -> f64 {
character.position().y - character.config().radius - character.config().half_height
}
#[test]
fn an_unobstructed_move_covers_the_whole_displacement_and_slides_none() {
let mut world = flat_world();
let mut character = standing(&mut world, CharacterConfig::default());
let outcome = character.move_and_slide(&mut world, DVec3::new(0.2, 0.0, -0.1));
assert_eq!(outcome.slides, 0, "nothing was in the way");
assert!(
(outcome.motion - DVec3::new(0.2, 0.0, -0.1)).length() < 1e-12,
"asked for (0.2, 0, -0.1) and got {:?}",
outcome.motion,
);
assert!(outcome.grounded);
assert!(!outcome.hit_wall && !outcome.hit_ceiling && !outcome.stepped_up);
}
#[test]
fn walking_into_a_wall_at_an_angle_keeps_the_whole_speed_along_it() {
let mut world = flat_world();
world.add_box(BoxCollider::new(
DVec3::new(4.5, 2.0, 0.0),
DVec3::new(4.5, 3.0, 10.0),
));
let config = CharacterConfig::default();
let mut character = standing(&mut world, config);
character.set_position(DVec3::new(-0.35, centre_for_feet(&config, 0.0), 0.0));
character.move_and_slide(&mut world, DVec3::ZERO);
let asked = DVec3::new(0.1, 0.0, 0.1);
let outcome = character.move_and_slide(&mut world, asked);
assert!(outcome.hit_wall, "the wall's -X face is 0.05 away");
assert!(
outcome.motion.x < asked.x,
"the wall must have taken something off the approach, and x moved {}",
outcome.motion.x,
);
assert!(
(outcome.motion.z - asked.z).abs() < 1e-12,
"the speed along the wall is {} and was asked to be {}",
outcome.motion.z,
asked.z,
);
}
#[test]
fn a_move_far_longer_than_the_obstacle_does_not_pass_through_it() {
let mut world = flat_world();
let pane_x = 5.0;
let pane_half_thickness = 0.005;
world.add_box(BoxCollider::new(
DVec3::new(pane_x, 2.0, 0.0),
DVec3::new(pane_half_thickness, 3.0, 10.0),
));
let config = CharacterConfig::default();
let mut character = standing(&mut world, config);
let outcome = character.move_and_slide(&mut world, DVec3::new(50.0, 0.0, 0.0));
assert!(outcome.hit_wall);
let front = pane_x - pane_half_thickness - config.radius;
assert!(
character.position().x <= front,
"the capsule's flank is at {} and the pane's near face at {front}",
character.position().x + config.radius,
);
}
#[test]
fn the_slope_the_controller_stops_walking_is_the_one_it_was_configured_with() {
let config = CharacterConfig::default();
let step_degrees = 0.1;
let gravity = DVec3::new(0.0, -0.05, 0.0);
let mut last_still: Option<f64> = None;
let mut first_creep: Option<f64> = None;
for tenth in 0..900 {
let degrees = f64::from(tenth) * step_degrees;
let mut world = dome_world();
let mut character =
CharacterController::new(config, on_dome(&config, degrees.to_radians()));
character.move_and_slide(&mut world, DVec3::ZERO);
let start = character.position();
for _ in 0..60 {
character.move_and_slide(&mut world, gravity);
}
let drift = (character.position() - start).x;
if first_creep.is_none() {
if drift == 0.0 {
last_still = Some(degrees);
} else {
first_creep = Some(degrees);
}
}
}
let (Some(last_still), Some(first_creep)) = (last_still, first_creep) else {
panic!(
"the sweep never crossed a boundary: {last_still:?} was the last still \
slope and {first_creep:?} the first creeping one",
);
};
#[expect(
clippy::disallowed_methods,
reason = "the platform's arccosine is the oracle"
)]
let limit = config.min_ground_normal_y.acos().to_degrees();
assert!(
last_still <= limit && limit <= first_creep,
"the boundary was measured at {last_still}° still / {first_creep}° creeping, \
and the configured limit is {limit}° — the two samples are one \
{step_degrees}° step apart, so the limit has to fall between them",
);
}
#[test]
fn a_surface_exactly_at_the_limit_is_walkable() {
let config = CharacterConfig::default();
let character = CharacterController::new(config, DVec3::ZERO);
let rise = config.min_ground_normal_y;
let exactly = DVec3::new((1.0 - rise * rise).sqrt(), rise, 0.0);
assert_eq!(
exactly.y, rise,
"the test's own normal must carry the configured rise unrounded"
);
assert!(
character.is_walkable(exactly),
"a surface whose rise is exactly {rise} must be walkable, because the \
comparison is `>=` and the limit is the last slope you can stand on"
);
}
#[test]
#[expect(
clippy::disallowed_methods,
reason = "the platform's tangent is the oracle"
)]
fn a_walkable_slope_is_climbed_without_losing_horizontal_ground() {
let config = CharacterConfig::default();
let angle = 30.0_f64.to_radians();
let mut world = dome_world();
let mut character = CharacterController::new(config, on_dome(&config, angle));
character.move_and_slide(&mut world, DVec3::ZERO);
assert!(character.is_grounded(), "30° is inside the default limit");
let asked = DVec3::new(-0.05, 0.0, 0.0);
let before = character.position();
let outcome = character.move_and_slide(&mut world, asked);
let moved = character.position() - before;
assert!(
(moved.x - asked.x).abs() < 1e-6,
"the horizontal ground covered was {} and the request was {}",
moved.x,
asked.x,
);
assert!(
(moved.y - asked.x.abs() * angle.tan()).abs() < 1e-4,
"climbing 0.05 m of a 30° slope should rise {}, and it rose {}",
asked.x.abs() * angle.tan(),
moved.y,
);
assert!(outcome.grounded);
}
#[test]
fn the_step_the_controller_stops_climbing_is_the_offset_it_was_configured_with() {
let config = CharacterConfig::default();
let step_metres = 0.001;
let mut last_climbed: Option<f64> = None;
let mut first_blocked: Option<f64> = None;
for milli in 0..=600 {
let height = f64::from(milli) * step_metres;
let mut world = stepped_world(height);
let mut character = CharacterController::new(
config,
DVec3::new(-1.0, centre_for_feet(&config, 0.0), 0.0),
);
character.move_and_slide(&mut world, DVec3::ZERO);
for _ in 0..30 {
character.move_and_slide(&mut world, DVec3::new(0.05, 0.0, 0.0));
}
let climbed =
character.position().x > 0.2 && (feet_of(&character) - height).abs() < 0.02;
if first_blocked.is_none() {
if climbed {
last_climbed = Some(height);
} else {
first_blocked = Some(height);
}
}
}
let last_climbed = last_climbed.expect("a zero-height step is walked straight over");
let first_blocked = first_blocked.expect("a 0.6 m step is not a step");
assert!(
last_climbed >= config.step_offset,
"a step of exactly the configured offset must be climbed, and the last \
one climbed was {last_climbed}",
);
assert!(
first_blocked <= config.step_offset + config.skin_width + step_metres,
"the first step refused was {first_blocked}, which is more than one skin \
width above the configured offset of {}",
config.step_offset,
);
}
#[test]
fn walking_off_a_lip_within_the_step_offset_never_leaves_the_ground() {
let config = CharacterConfig::default();
let drop = 0.3;
let mut world = stepped_world(-drop);
let mut character =
CharacterController::new(config, DVec3::new(-1.0, centre_for_feet(&config, 0.0), 0.0));
character.move_and_slide(&mut world, DVec3::ZERO);
for tick in 0..30 {
let outcome = character.move_and_slide(&mut world, DVec3::new(0.05, 0.0, 0.0));
assert!(
outcome.grounded,
"tick {tick} left the ground at x = {}, y = {}",
character.position().x,
character.position().y,
);
}
assert!(character.position().x > 0.2, "it walked past the lip");
assert!(
(feet_of(&character) + drop).abs() < config.skin_width * 2.0,
"it should be standing on the lower floor at {}, and its feet are at {}",
-drop,
feet_of(&character),
);
}
#[test]
fn walking_off_a_drop_past_the_step_offset_leaves_the_ground() {
let config = CharacterConfig::default();
let mut world = stepped_world(-(config.step_offset * 2.0));
let mut character =
CharacterController::new(config, DVec3::new(-1.0, centre_for_feet(&config, 0.0), 0.0));
character.move_and_slide(&mut world, DVec3::ZERO);
let mut left_the_ground = false;
for _ in 0..30 {
left_the_ground |= !character
.move_and_slide(&mut world, DVec3::new(0.05, 0.0, 0.0))
.grounded;
}
assert!(
left_the_ground,
"the character walked over a {} m drop without ever falling",
config.step_offset * 2.0,
);
}
#[test]
fn a_character_pressed_into_a_corner_does_not_climb_it() {
let config = CharacterConfig::default();
let mut world = flat_world();
world.add_box(BoxCollider::new(
DVec3::new(5.5, 2.0, 0.0),
DVec3::new(5.0, 3.0, 10.0),
));
world.add_box(BoxCollider::new(
DVec3::new(0.0, 2.0, 5.5),
DVec3::new(10.0, 3.0, 5.0),
));
let mut character = standing(&mut world, config);
let resting_feet = feet_of(&character);
let mut planes_at_once = 0;
for _ in 0..60 {
let outcome = character.move_and_slide(&mut world, DVec3::new(0.05, 0.0, 0.05));
planes_at_once = planes_at_once.max(outcome.slides);
assert!(
feet_of(&character) <= resting_feet + config.skin_width,
"the character rose to {} from {resting_feet}",
feet_of(&character),
);
assert!(
!outcome.stepped_up,
"a corner is not a step, and it was climbed at y = {}",
character.position().y,
);
}
assert!(
character.position().x > 0.1 && character.position().z > 0.1,
"the character should have slid along both walls before wedging, and \
stopped at {:?}",
character.position(),
);
assert!(
planes_at_once >= 2,
"the corner never presented two planes in one move, so the clipping \
this is about never ran",
);
}
#[test]
fn a_capsule_that_starts_inside_a_box_is_pushed_out_of_the_nearest_face() {
let config = CharacterConfig::default();
let mut world = PhysicsWorld::new();
let half = DVec3::new(1.0, 1.0, 1.0);
world.add_box(BoxCollider::new(DVec3::ZERO, half));
let inside = DVec3::new(half.x - 0.2, 0.0, 0.0);
let mut character = CharacterController::new(config, inside);
let outcome = character.move_and_slide(&mut world, DVec3::ZERO);
let mut still_inside = Vec::new();
world.capsule_penetrations_into(&character.capsule(), None, &mut still_inside);
assert!(
still_inside.is_empty(),
"the capsule is still inside {still_inside:?} after being pushed out",
);
let expected = DVec3::X * (config.radius + 0.2 + config.skin_width);
assert!(
(outcome.depenetration - expected).length() < 1e-12,
"expected a push of {expected:?} and got {:?}",
outcome.depenetration,
);
}
#[test]
fn a_capsule_clear_of_the_world_is_not_pushed_at_all() {
let config = CharacterConfig::default();
let mut world = flat_world();
let mut character = CharacterController::new(
config,
DVec3::new(0.0, centre_for_feet(&config, config.skin_width), 0.0),
);
let outcome = character.move_and_slide(&mut world, DVec3::ZERO);
assert_eq!(
outcome.depenetration,
DVec3::ZERO,
"a capsule a skin width clear of its floor is inside nothing",
);
assert!(
outcome.grounded,
"and it is standing on the floor it is clear of"
);
}
#[test]
fn an_upward_move_covers_its_whole_rise() {
let mut world = flat_world();
let mut character = standing(&mut world, CharacterConfig::default());
let before = character.position().y;
character.move_and_slide(&mut world, DVec3::new(0.0, 0.2, 0.0));
assert!(
(character.position().y - before - 0.2).abs() < 1e-12,
"asked to rise 0.2 and rose {}",
character.position().y - before,
);
}
#[test]
fn an_upward_move_is_not_pulled_back_by_the_ground_snap() {
let config = CharacterConfig::default();
for rise in [config.skin_width * 0.1, 0.2] {
let mut world = flat_world();
let mut character = standing(&mut world, config);
for _ in 0..2 {
let motion = DVec3::new(0.005, rise, 0.0);
let outcome = character.move_and_slide(&mut world, motion);
assert!(
!outcome.grounded,
"the floor reached up and took the jump back: rise={rise}"
);
assert!((outcome.motion - motion).length() < 1e-12);
}
}
}
#[test]
fn gravity_alone_does_not_walk_a_grounded_character_down_a_slope() {
let config = CharacterConfig::default();
let mut world = dome_world();
let mut character =
CharacterController::new(config, on_dome(&config, 40.0_f64.to_radians()));
character.move_and_slide(&mut world, DVec3::ZERO);
assert!(character.is_grounded(), "40° is inside the default limit");
let before = character.position();
for tick in 0..60 {
let outcome = character.move_and_slide(&mut world, DVec3::new(0.0, -0.05, 0.0));
assert_eq!(
(outcome.motion.x, outcome.motion.z),
(0.0, 0.0),
"tick {tick} walked sideways",
);
assert!(outcome.grounded, "tick {tick} left the slope");
}
let drift = character.position() - before;
assert_eq!(
(drift.x, drift.z),
(0.0, 0.0),
"it ended up downhill by {drift:?}"
);
assert!(
drift.y.abs() < config.skin_width,
"it sank {} into the slope, which is more than the gap it settles to",
-drift.y,
);
}
#[test]
fn clearing_self_collider_preserves_ground_and_movement_state() {
let config = CharacterConfig::default();
let mut world = flat_world();
let mut character =
CharacterController::new(config, DVec3::new(0.0, centre_for_feet(&config, 0.0), 0.0));
character.move_and_slide(&mut world, DVec3::ZERO);
assert!(character.is_grounded());
let position = character.position();
let ground = character.ground().cloned();
let body = world.add_capsule(character.capsule());
character.set_self_collider(Some(body));
assert_eq!(character.self_collider, Some(body));
assert_eq!(character.position(), position);
assert_eq!(character.ground(), ground.as_ref());
character.set_self_collider(None);
assert_eq!(character.self_collider, None);
assert_eq!(character.position(), position);
assert_eq!(character.ground(), ground.as_ref());
assert!(world.remove(body));
let moved = character.move_and_slide(&mut world, DVec3::new(0.2, 0.0, 0.0));
assert!((moved.motion.x - 0.2).abs() < 1e-12);
assert!(moved.grounded);
}
#[test]
fn a_character_registered_in_the_world_is_left_out_of_its_own_sweeps() {
let config = CharacterConfig::default();
let mut world = flat_world();
let body = world.add_capsule(Capsule::new(
DVec3::new(0.0, centre_for_feet(&config, 0.0), 0.0),
config.radius,
config.half_height,
));
let mut character =
CharacterController::new(config, DVec3::new(0.0, centre_for_feet(&config, 0.0), 0.0))
.with_self_collider(body);
character.move_and_slide(&mut world, DVec3::ZERO);
let outcome = character.move_and_slide(&mut world, DVec3::new(0.2, 0.0, 0.0));
assert!(
(outcome.motion.x - 0.2).abs() < 1e-12,
"its own body blocked it: it moved {}",
outcome.motion.x,
);
let aabb = world.aabb_of(body).expect("the body is still registered");
assert!(
(aabb.centre() - character.position()).length() < 1e-12,
"the world's copy is at {:?} and the character at {:?}",
aabb.centre(),
character.position(),
);
}
fn standing_probe(config: &CharacterConfig) -> f64 {
config.skin_width * GROUND_PROBE_SKINS
}
#[test]
fn a_probe_under_a_settled_character_finds_its_floor_a_skin_width_down() {
let config = CharacterConfig::default();
let mut world = PhysicsWorld::new();
let floor = world.add_box(BoxCollider::new(
DVec3::new(0.0, -1.0, 0.0),
DVec3::new(50.0, 1.0, 50.0),
));
let character = standing(&mut world, config);
let found = character
.probe_ground(&mut world, standing_probe(&config))
.expect("a settled character is standing on its floor");
assert_eq!(found.contact.collider, floor);
assert!(
(found.contact.normal - DVec3::Y).length() < 1e-12,
"the floor faces up, and the probe reported {:?}",
found.contact.normal,
);
assert!(
(found.distance - config.skin_width).abs() < 1e-9,
"a settled capsule floats one skin width ({}) up, and the probe \
measured {}",
config.skin_width,
found.distance,
);
assert!(found.walkable);
assert_eq!(
Some(&found.contact),
character.ground(),
"the move and the probe share one sweep, so they name the same contact",
);
}
#[test]
fn a_probe_from_above_its_distance_finds_nothing() {
let config = CharacterConfig::default();
let mut world = flat_world();
let height = 1.0;
let character = CharacterController::new(
config,
DVec3::new(0.0, centre_for_feet(&config, height), 0.0),
);
assert_eq!(
character.probe_ground(&mut world, standing_probe(&config)),
None,
"the floor is {height} m down and the probe looked {} m",
standing_probe(&config),
);
let far = character
.probe_ground(&mut world, height * 2.0)
.expect("a long enough probe reaches the floor");
assert!(
(far.distance - height).abs() < 1e-9,
"the floor is {height} m below the feet and the probe measured {}",
far.distance,
);
}
#[test]
fn a_probe_on_a_slope_past_the_limit_reads_as_not_walkable() {
let config = CharacterConfig::default();
let mut world = dome_world();
let at = |degrees: f64| on_dome(&config, degrees.to_radians()) + UP * config.skin_width;
let character = CharacterController::new(config, DVec3::ZERO);
let steep = character
.probe_ground_at(&mut world, at(60.0), standing_probe(&config))
.expect("the dome is a skin width under the capsule");
assert!(
!steep.walkable,
"60° is past the default 45° limit, and the probe called it walkable \
with normal {:?}",
steep.contact.normal,
);
assert!(steep.contact.normal.y < config.min_ground_normal_y);
let gentle = character
.probe_ground_at(&mut world, at(30.0), standing_probe(&config))
.expect("the dome is a skin width under the capsule");
assert!(gentle.walkable, "30° is inside the default limit");
}
#[test]
fn a_probe_leaves_the_controller_and_its_world_body_where_they_were() {
let config = CharacterConfig::default();
let mut world = flat_world();
let body = world.add_capsule(Capsule::new(
DVec3::new(0.0, centre_for_feet(&config, 0.0), 0.0),
config.radius,
config.half_height,
));
let mut character =
CharacterController::new(config, DVec3::new(0.0, centre_for_feet(&config, 0.0), 0.0))
.with_self_collider(body);
character.move_and_slide(&mut world, DVec3::ZERO);
let position = character.position();
let ground = character.ground().copied();
let aabb = world.aabb_of(body);
assert!(ground.is_some(), "the fixture starts on the floor");
let here = character.probe_ground(&mut world, standing_probe(&config));
let aloft = character.probe_ground_at(
&mut world,
DVec3::new(3.0, centre_for_feet(&config, 2.0), 0.0),
standing_probe(&config),
);
assert_ne!(
here.map(|found| found.contact.collider),
Some(body),
"the probe found the character's own body",
);
assert!(here.is_some_and(|found| found.walkable));
assert_eq!(aloft, None);
assert_eq!(character.position(), position);
assert_eq!(character.ground().copied(), ground);
assert_eq!(world.aabb_of(body), aabb);
}
#[test]
fn a_probe_sees_a_removed_floor_that_ground_still_reports() {
let config = CharacterConfig::default();
let mut world = PhysicsWorld::new();
let floor = world.add_box(BoxCollider::new(
DVec3::new(0.0, -1.0, 0.0),
DVec3::new(50.0, 1.0, 50.0),
));
let character = standing(&mut world, config);
assert!(
character
.probe_ground(&mut world, standing_probe(&config))
.is_some_and(|found| found.walkable)
);
let position = character.position();
assert!(world.remove(floor));
assert!(
character.is_grounded(),
"ground() is the last move's record"
);
assert_eq!(
character.probe_ground(&mut world, standing_probe(&config)),
None
);
assert_eq!(character.position(), position);
}
#[test]
fn a_character_spawned_a_tenth_of_a_metre_up_has_no_support() {
let config = CharacterConfig::default();
let mut world = flat_world();
let character =
CharacterController::new(config, DVec3::new(0.0, centre_for_feet(&config, 0.1), 0.0));
assert_eq!(
character.probe_ground(&mut world, standing_probe(&config)),
None
);
}
#[test]
#[should_panic(expected = "non-negative distance")]
fn a_probe_refuses_a_negative_distance() {
let mut world = flat_world();
let character = standing(&mut world, CharacterConfig::default());
let _ = character.probe_ground(&mut world, -0.1);
}
}
#[cfg(test)]
#[path = "character/query_mask_tests.rs"]
mod query_mask_tests;
#[cfg(test)]
#[path = "character/lying_tests.rs"]
mod lying_tests;
#[cfg(test)]
#[path = "character/lying_move_tests.rs"]
mod lying_move_tests;
#[cfg(test)]
#[path = "character/lying_turn_tests.rs"]
mod lying_turn_tests;
#[cfg(test)]
#[path = "character/lying_contact_tests.rs"]
mod lying_contact_tests;
#[cfg(test)]
#[path = "character/slide_contact_tests.rs"]
mod slide_contact_tests;
#[cfg(test)]
#[path = "character/crease_tests.rs"]
mod crease_tests;
#[cfg(test)]
#[path = "character/edge_tests.rs"]
mod edge_tests;
#[cfg(test)]
#[path = "character/rest_tests.rs"]
mod rest_tests;
#[cfg(test)]
#[path = "character/skin_tests.rs"]
mod skin_tests;
#[cfg(test)]
#[path = "character/preview_tests.rs"]
mod preview_tests;