use std::f64::consts::{PI, TAU};
use glam::DVec3;
use super::{Body, CharacterController, GroundProbe, MIN_MOVE, SlideContact, UP, WorldReader};
use crate::broadphase::Segment;
use crate::collider::LyingCapsule;
use crate::world::{ColliderId, PhysicsWorld};
const MAX_TURN_STEPS: u32 = 64;
const MAX_BISECTIONS: u32 = 48;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LyingMoveOutcome {
pub body: LyingCapsule,
pub motion: DVec3,
pub grounded: bool,
pub hit_wall: bool,
pub hit_ceiling: bool,
pub slides: u32,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LyingTurnOutcome {
pub body: LyingCapsule,
pub turned: f64,
pub fraction: f64,
pub blocker: Option<ColliderId>,
}
#[derive(Debug, Clone, Copy)]
struct TurnStop {
reached: f64,
blocker: Option<ColliderId>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Pivot {
Head,
Feet,
}
impl CharacterController {
pub fn move_lying(
&mut self,
world: &mut PhysicsWorld,
body: &LyingCapsule,
motion: DVec3,
) -> LyingMoveOutcome {
self.move_prone(world, body, motion, None)
}
pub fn move_lying_into(
&mut self,
world: &mut PhysicsWorld,
body: &LyingCapsule,
motion: DVec3,
contacts: &mut Vec<SlideContact>,
) -> LyingMoveOutcome {
contacts.clear();
self.move_prone(world, body, motion, Some(contacts))
}
fn move_prone(
&mut self,
world: &mut PhysicsWorld,
body: &LyingCapsule,
motion: DVec3,
contacts: Option<&mut Vec<SlideContact>>,
) -> LyingMoveOutcome {
if body.head != self.position {
self.set_position(body.head);
}
let start = self.position;
let was_grounded = self.ground.is_some();
let motion = self.ground_adjusted(motion, was_grounded);
let report = self.slide(
&mut WorldReader::of(world),
motion,
was_grounded,
Body::Lying(*body),
contacts,
);
let slid = LyingCapsule {
head: self.position,
..*body
};
let settled = self.settle_lying(world, slid, self.settle_reach(was_grounded, motion));
self.position = settled.head;
if let Some(collider) = self.self_collider {
world.set_capsule(collider, self.capsule());
}
LyingMoveOutcome {
body: settled,
motion: self.position - start,
grounded: self.ground.is_some(),
hit_wall: report.hit_wall,
hit_ceiling: report.hit_ceiling,
slides: report.slides,
}
}
#[must_use]
pub fn turn_lying(
&self,
world: &mut PhysicsWorld,
body: &LyingCapsule,
yaw: f64,
) -> LyingTurnOutcome {
assert!(
yaw.is_finite() && body.yaw.is_finite(),
"a lying body turns from a finite yaw to a finite yaw, not {} to {yaw}",
body.yaw,
);
let whole = (yaw - body.yaw).rem_euclid(TAU);
let delta = if whole > PI { whole - TAU } else { whole };
let plane = self
.ground
.filter(|_| body.head == self.position)
.map(|ground| ground.normal);
let slope_along = |normal: DVec3, yaw: f64| {
let facing = LyingCapsule { yaw, ..*body }.facing();
let gradient = -(normal.x * facing.x + normal.z * facing.z) / normal.y;
gradient / (1.0 + gradient * gradient).sqrt()
};
let pose = |turned: f64| {
let pitch_sine = plane.map_or(body.pitch_sine, |normal| {
let change = slope_along(normal, turned) - slope_along(normal, body.yaw);
(body.pitch_sine + change).clamp(-1.0, 1.0)
});
LyingCapsule {
yaw: turned,
pitch_sine,
..*body
}
};
let full = LyingTurnOutcome {
body: LyingCapsule {
yaw,
..pose(body.yaw + delta)
},
turned: delta,
fraction: 1.0,
blocker: None,
};
if delta == 0.0 {
return full;
}
let cosine = plane.map_or(1.0, |normal| normal.y);
let from_blocked = self.lying_blocker(world, body).is_some();
let stop = self.turn_until_blocked(
world,
(body.yaw, body.yaw + delta),
cosine,
from_blocked,
pose,
);
let Some(blocker) = stop.blocker else {
return full;
};
let turned = stop.reached - body.yaw;
LyingTurnOutcome {
body: pose(stop.reached),
turned,
fraction: (turned / delta).clamp(0.0, 1.0),
blocker: Some(blocker),
}
}
fn settle_lying(
&mut self,
world: &mut PhysicsWorld,
body: LyingCapsule,
reach: f64,
) -> LyingCapsule {
let feet = body.feet();
let limit = self.steepest_pitch_sine();
let swing = |sine: f64| reach + body.length * sine.max(0.0);
let under_head = self.probe_end(
world,
body.head,
body.radius,
swing(limit + body.pitch_sine),
);
let under_feet = self.probe_end(world, feet, body.radius, swing(limit - body.pitch_sine));
self.ground = None;
let near = |probe: &GroundProbe| probe.distance <= reach;
if !under_head.iter().chain(&under_feet).any(near) {
return body;
}
self.ground = under_head
.filter(|probe| probe.walkable)
.or(under_feet.filter(|probe| probe.walkable))
.map(|probe| probe.contact);
let skin = self.config.skin_width;
let rest = |end: DVec3, probe: GroundProbe| {
let lift = if probe.walkable { -skin } else { 0.0 };
end.y - (probe.distance - skin).max(lift)
};
let level = body.length * (1.0 - body.pitch_sine * body.pitch_sine).max(0.0).sqrt();
let pitch_sine = match (under_head, under_feet) {
(None, None) => return body,
_ if level <= MIN_MOVE => body.pitch_sine,
(Some(head), Some(feet_probe)) => {
self.resting_pitch(rest(body.head, head), rest(feet, feet_probe), level)
}
(Some(_), None) => limit,
(None, Some(_)) => -limit,
};
let turned = LyingCapsule { pitch_sine, ..body };
let rise = turned.head.y - turned.feet().y;
let shift = turned.feet() - feet;
let on_head = under_head.map(|probe| rest(body.head, probe));
let on_feet = under_feet.map(|probe| {
let normal = probe.contact.normal;
let along = if normal.y > MIN_MOVE {
(normal.x * shift.x + normal.z * shift.z) / normal.y
} else {
0.0
};
rest(feet, probe) - along + rise
});
let height = on_head
.into_iter()
.chain(on_feet)
.fold(f64::NEG_INFINITY, f64::max);
let resting = LyingCapsule {
head: DVec3::new(body.head.x, height, body.head.z),
..turned
};
if self.lying_blocker(world, &resting).is_none() {
return resting;
}
let about_head = self.turn_to_rest(world, &resting, Pivot::Head);
let about_feet = self.turn_to_rest(world, &resting, Pivot::Feet);
let turn = |pose: &LyingCapsule| (pose.pitch_sine - resting.pitch_sine).abs();
match (about_head, about_feet) {
(Some(head), Some(feet)) if turn(&feet) < turn(&head) => feet,
(Some(head), _) => head,
(None, Some(feet)) => feet,
(None, None) => body,
}
}
fn resting_pitch(&self, head_rest: f64, feet_rest: f64, level: f64) -> f64 {
let limit = self.steepest_pitch_sine();
let gradient = (head_rest - feet_rest) / level;
(gradient / (1.0 + gradient * gradient).sqrt()).clamp(-limit, limit)
}
fn steepest_pitch_sine(&self) -> f64 {
let cosine = self.config.min_ground_normal_y.clamp(0.0, 1.0);
(1.0 - cosine * cosine).sqrt()
}
fn turn_to_rest(
&self,
world: &mut PhysicsWorld,
resting: &LyingCapsule,
pivot: Pivot,
) -> Option<LyingCapsule> {
let limit = self.steepest_pitch_sine();
let feet_height = resting.feet().y;
let pose = |pitch_sine: f64| {
let head_height = match pivot {
Pivot::Head => resting.head.y,
Pivot::Feet => feet_height + resting.length * pitch_sine,
};
LyingCapsule {
head: DVec3::new(resting.head.x, head_height, resting.head.z),
pitch_sine,
..*resting
}
};
let top = match pivot {
Pivot::Head => -limit,
Pivot::Feet => limit,
};
let span = resting.pitch_sine - top;
if span.abs() <= MIN_MOVE || self.lying_blocker(world, &pose(top)).is_some() {
return None;
}
let steepest = top.abs().max(resting.pitch_sine.abs());
let cosine = (1.0 - steepest * steepest).sqrt();
let stop = self.turn_until_blocked(world, (top, resting.pitch_sine), cosine, false, pose);
Some(pose(stop.reached))
}
fn turn_until_blocked(
&self,
world: &mut PhysicsWorld,
(from, to): (f64, f64),
cosine: f64,
from_blocked: bool,
pose: impl Fn(f64) -> LyingCapsule,
) -> TurnStop {
let shape = pose(from);
let span = to - from;
let steps = (shape.length * span.abs() / (shape.radius * cosine))
.ceil()
.clamp(1.0, f64::from(MAX_TURN_STEPS));
let (mut clear, mut stuck, mut blocked) = (from, from_blocked, None);
for step in 1..=MAX_TURN_STEPS {
let share = f64::from(step) / steps;
if share > 1.0 {
break;
}
let at = from + span * share;
match self.lying_blocker(world, &pose(at)) {
Some(collider) if !stuck => {
blocked = Some((at, collider));
break;
}
Some(_) => {}
None => (clear, stuck) = (at, false),
}
}
let Some((mut at, mut blocker)) = blocked else {
return TurnStop {
reached: clear,
blocker: None,
};
};
for _ in 0..MAX_BISECTIONS {
if shape.length * (at - clear).abs() <= 0.5 * self.config.skin_width {
break;
}
let middle = 0.5 * (clear + at);
match self.lying_blocker(world, &pose(middle)) {
Some(collider) => (at, blocker) = (middle, collider),
None => clear = middle,
}
}
TurnStop {
reached: clear,
blocker: Some(blocker),
}
}
fn probe_end(
&self,
world: &mut PhysicsWorld,
centre: DVec3,
radius: f64,
distance: f64,
) -> Option<GroundProbe> {
let found = world.sweep_sphere_filtered(
&Segment::new(centre, centre - UP * distance),
radius,
self.filter(),
)?;
Some(self.ground_probe(found, distance))
}
}