Skip to main content

crcbl_phys/system/
joints.rs

1//! [`PhysicsSystem`]'s joints and solver groups: rung 5 of
2//! the contact solver (`docs/notes/simulation.md`). See [`crate::joint`] for
3//! the joints and `crate::contact::group` for the groups.
4
5use crcbl_ecs::Entity;
6use glam::DVec3;
7
8use super::{BodyId, PhysicsSystem};
9use crate::contact::joint;
10use crate::joint::{Joint, JointBreak, JointDrift, JointError, JointId};
11
12impl PhysicsSystem {
13    /// Adds `joint` and wakes both its bodies — decision 4's "a new joint"
14    /// wake rule. Unless it lets them collide, every contact between them is
15    /// ended.
16    ///
17    /// # Errors
18    ///
19    /// [`JointError::UnknownBody`] if either entity is not registered — a
20    /// fixed anchor is an entity given a transform with
21    /// [`set_transform`](Self::set_transform) — [`JointError::SameBody`] if
22    /// the two are one, and [`JointError::Invalid`] for a setting out of
23    /// range.
24    ///
25    /// # Panics
26    ///
27    /// Panics if this system has no contacts: joints are constraints in the
28    /// contact solver. Build it [`with_contacts`](Self::with_contacts).
29    pub fn add_joint(&mut self, joint: Joint) -> Result<JointId, JointError> {
30        assert!(
31            self.contacts.is_some(),
32            "joints are contact-solver constraints: build the system with_contacts"
33        );
34        let (a, b) = self.joint_bodies(&joint)?;
35        self.wake(a);
36        self.wake(b);
37        let pipeline = self.contacts.as_mut().expect("asserted above");
38        if !joint.collide_connected {
39            pipeline.destroy_contacts_between(a, b);
40        }
41        Ok(pipeline.joints.insert(joint, a, b))
42    }
43
44    /// Takes joint `id` out, waking both its bodies, and returns it; `None`
45    /// if it is not there — never added, removed, or broken.
46    pub fn remove_joint(&mut self, id: JointId) -> Option<Joint> {
47        self.take_out_joint(id)
48    }
49
50    /// Joint `id`, if it is there.
51    #[must_use]
52    pub fn joint(&self, id: JointId) -> Option<&Joint> {
53        self.contacts
54            .as_ref()?
55            .joints
56            .get(id)
57            .map(|record| &record.joint)
58    }
59
60    /// Replaces joint `id` with `joint` — a new motor speed, new limits,
61    /// other bodies — waking its bodies old and new. What it carries is kept
62    /// for the warm start while it stays the same kind between the same
63    /// bodies. Returns `Ok(false)` if `id` names no joint.
64    ///
65    /// # Errors
66    ///
67    /// As [`add_joint`](Self::add_joint)'s, and the joint is left as it was.
68    pub fn set_joint(&mut self, id: JointId, joint: Joint) -> Result<bool, JointError> {
69        let Some(old) = self.joint(id).copied() else {
70            return Ok(false);
71        };
72        let (a, b) = self.joint_bodies(&joint)?;
73        let (old_a, old_b) = self.joint_bodies(&old)?;
74        for body in [a, b, old_a, old_b] {
75            self.wake(body);
76        }
77        if old.collide_connected != joint.collide_connected || (old_a, old_b) != (a, b) {
78            self.let_collide(old_a, old_b);
79        }
80        let pipeline = self.contacts.as_mut().expect("a joint lives in one");
81        if !joint.collide_connected {
82            pipeline.destroy_contacts_between(a, b);
83        }
84        Ok(pipeline.joints.replace(id, joint, a, b))
85    }
86
87    /// Every joint and its id, in the order they were added into the pool's
88    /// slots.
89    pub fn joints(&self) -> impl Iterator<Item = (JointId, &Joint)> {
90        self.contacts
91            .iter()
92            .flat_map(|pipeline| pipeline.joints.iter())
93            .map(|(id, record)| (id, &record.joint))
94    }
95
96    /// How many joints there are.
97    #[must_use]
98    pub fn joint_count(&self) -> usize {
99        self.contacts
100            .as_ref()
101            .map_or(0, |pipeline| pipeline.joints.len())
102    }
103
104    /// The force, in newtons, and torque, in newton-metres, joint `id`
105    /// carried over the last substep it was solved in: what its thresholds
106    /// are held to.
107    #[must_use]
108    pub fn joint_reaction(&self, id: JointId) -> Option<(f64, f64)> {
109        self.contacts.as_ref()?.joints.reaction(id)
110    }
111
112    /// Where joint `id`'s frames are in the world now: its anchor on body A
113    /// and its anchor on body B, which it holds together or apart.
114    #[must_use]
115    pub fn joint_anchors(&self, id: JointId) -> Option<(DVec3, DVec3)> {
116        let joint = self.joint(id)?;
117        let at = |entity: Entity, local: DVec3| {
118            let transform = self.transform(entity)?;
119            Some(transform.position + transform.rotation * local)
120        };
121        Some((
122            at(joint.body_a, joint.frame_a.position)?,
123            at(joint.body_b, joint.frame_b.position)?,
124        ))
125    }
126
127    /// How far joint `id` is from holding, with its bodies where they are
128    /// now: see [`JointDrift`].
129    #[must_use]
130    pub fn joint_drift(&self, id: JointId) -> Option<JointDrift> {
131        let joint = self.joint(id)?;
132        Some(joint::drift(
133            joint,
134            self.transform(joint.body_a)?,
135            self.transform(joint.body_b)?,
136        ))
137    }
138
139    /// The joints the last [`step`](Self::step) broke, and took out.
140    #[must_use]
141    pub fn broken_joints(&self) -> &[JointBreak] {
142        self.contacts
143            .as_ref()
144            .map_or(&[], |pipeline| pipeline.joints.broken.as_slice())
145    }
146
147    /// Asks the solver to give `entity`'s body `substeps` substeps a tick,
148    /// and every body it is joined to by a contact or a joint the same:
149    /// decision 1's extra substeps per group. A group runs the most any of
150    /// its bodies asked for, and never fewer than
151    /// [`crate::ContactSettings::substeps`], so zero is the system's own;
152    /// its constraints are stiffer in proportion — see the solver's groups
153    /// in `crates/crcbl-phys/src/contact/group.rs`. Returns `false` if the
154    /// entity is not registered.
155    ///
156    /// A bridge's planks or a tall column ask for more, and the rest of the
157    /// system pays nothing for it.
158    pub fn set_substeps(&mut self, entity: Entity, substeps: u32) -> bool {
159        let Some(&id) = self.entity_to_body.get(&entity) else {
160            return false;
161        };
162        self.wake(id);
163        match self.records.get_mut(id) {
164            Some(record) => {
165                record.substeps = substeps;
166                true
167            }
168            None => false,
169        }
170    }
171
172    /// The substeps `entity` asked for with
173    /// [`set_substeps`](Self::set_substeps), or `None` if it is not
174    /// registered.
175    #[must_use]
176    pub fn substeps(&self, entity: Entity) -> Option<u32> {
177        self.record(entity).map(|record| record.substeps)
178    }
179
180    /// Takes joint `id` out: wakes its bodies, tells their island it may be
181    /// in pieces, and lets them collide again if it kept them apart.
182    pub(crate) fn take_out_joint(&mut self, id: JointId) -> Option<Joint> {
183        let record = self.contacts.as_mut()?.joints.remove(id)?;
184        for body in [record.a, record.b] {
185            self.wake(body);
186            if let Some(island) = self.records.get(body).and_then(|r| r.island) {
187                self.islands.mark_removed(island);
188            }
189        }
190        if !record.joint.collide_connected {
191            self.let_collide(record.a, record.b);
192        }
193        Some(record.joint)
194    }
195
196    /// Takes out every joint of body `id`: what removing its entity does.
197    pub(super) fn take_out_joints_of(&mut self, id: BodyId) {
198        let Some(pipeline) = self.contacts.as_ref() else {
199            return;
200        };
201        for joint in pipeline.joints.of_body(id) {
202            self.take_out_joint(joint);
203        }
204    }
205
206    /// Has the broadphase look again for pairs between `a` and `b`, which a
207    /// joint no longer keeps apart.
208    pub(super) fn let_collide(&mut self, a: BodyId, b: BodyId) {
209        let Some(pipeline) = self.contacts.as_mut() else {
210            return;
211        };
212        for body in [a, b] {
213            if let Some(record) = self.records.get(body) {
214                pipeline.rediscover(&record.proxies);
215            }
216        }
217    }
218
219    /// Both bodies of `joint`, if it can be added.
220    fn joint_bodies(&self, joint: &Joint) -> Result<(BodyId, BodyId), JointError> {
221        if let Some(why) = joint.invalid() {
222            return Err(JointError::Invalid(why));
223        }
224        let id = |entity: Entity| {
225            self.entity_to_body
226                .get(&entity)
227                .copied()
228                .ok_or(JointError::UnknownBody(entity))
229        };
230        let (a, b) = (id(joint.body_a)?, id(joint.body_b)?);
231        if a == b {
232            return Err(JointError::SameBody);
233        }
234        Ok((a, b))
235    }
236}