ferravex_physics/assembly.rs
1//! Bounded mechanisms inserted only after every ordinary error is preflighted.
2//!
3//! Descriptors own existing dimensional bodies, colliders and local `JointDesc`s;
4//! no second geometry representation or solver is involved. IDs are zero-based
5//! indices in one assembly's insertion order, **not** generational world handles
6//! or cross-plan tokens. A clone retains the same local indexing. Do not mix IDs
7//! from unrelated plans: equal indices intentionally name the local entry.
8//! Existing-world joint endpoints are excluded. Plans are consumed on insertion,
9//! including on error; clone a template or call `validate_assembly` first when
10//! needed. Validation is a snapshot, not a reservation against later world edits.
11//!
12//! A lab can author an unpowered compound rotor on a fixed support, validate it,
13//! publish its visual handles only after success, and rebuild from the template
14//! on reset. Checked constructors handle untrusted numeric input before staging:
15//!
16//! ```
17//! # #[cfg(feature = "dim2")] {
18//! use ferravex_physics::{Collider, assembly::Assembly, d2::{
19//! ColliderBuilder, JointBuilder, PhysicsWorld, RigidBody, RigidBodyBuilder,
20//! }};
21//! let mut template = Assembly::<RigidBody>::new();
22//! let support = template.add_body(RigidBodyBuilder::fixed(), [] as [Collider; 0]).unwrap();
23//! let rotor = template.add_body(RigidBodyBuilder::dynamic(), [
24//! ColliderBuilder::try_cuboid(0.7, 0.1).unwrap(),
25//! ColliderBuilder::try_ball(0.2).unwrap().translation([0.5, 0.].into()),
26//! ]).unwrap();
27//! let hinge = template.add_joint(support, rotor, JointBuilder::hinge()).unwrap();
28//! let mut world = PhysicsWorld::default();
29//! world.validate_assembly(&template).unwrap();
30//! let handles = world.insert_assembly(template.clone()).unwrap();
31//! assert_eq!(world.bodies[handles.body(rotor).unwrap()].colliders(),
32//! handles.colliders(rotor).unwrap());
33//! assert_eq!(handles.collider(rotor, 1), Some(handles.colliders(rotor).unwrap()[1]));
34//! assert_eq!(world.joints[handles.joint(hinge).unwrap()].bodies(),
35//! [handles.body(support).unwrap(), handles.body(rotor).unwrap()]);
36//! world.step(1. / 120.); // Insertion itself executes no simulation tick.
37//! for &body in handles.bodies() { assert!(world.remove_body(body)); }
38//! let reset = world.insert_assembly(template).unwrap();
39//! assert_ne!(reset.body(rotor), handles.body(rotor)); // Ordinary generation reuse.
40//! assert_eq!(reset.joints().len(), 1);
41//! # }
42//! ```
43//!
44//! Spatial assemblies use the same container with a different existing body type:
45//!
46//! ```
47//! # #[cfg(feature = "dim3")] {
48//! use ferravex_physics::{Collider, assembly::Assembly, d3::{
49//! ColliderBuilder, JointBuilder, PhysicsWorld, RigidBody, RigidBodyBuilder,
50//! }};
51//! let mut assembly = Assembly::<RigidBody>::default();
52//! let anchor = assembly.add_body(RigidBodyBuilder::fixed(), [] as [Collider; 0]).unwrap();
53//! let bob = assembly.add_body(RigidBodyBuilder::dynamic()
54//! .try_translation([0., -2., 0.].into()).unwrap(),
55//! [ColliderBuilder::try_ball(0.3).unwrap()]).unwrap();
56//! let spring = assembly.add_joint(anchor, bob, JointBuilder::spring(2., 20., 2.)).unwrap();
57//! assert_eq!((assembly.body_count(), assembly.collider_count(), assembly.joint_count()),
58//! (2, 1, 1));
59//! let mut world = PhysicsWorld::default();
60//! let handles = world.insert_assembly(assembly).unwrap();
61//! assert!(world.joints.get(handles.joint(spring).unwrap()).is_some());
62//! world.step(1. / 120.);
63//! assert!((world.bodies[handles.body(bob).unwrap()].translation().y + 2.).abs() < 1e-5);
64//! # }
65//! ```
66
67use crate::{
68 Collider, ColliderHandle, JointDesc, JointHandle, MAX_CHILDREN, MAX_COLLIDERS, MAX_JOINTS,
69 PhysicsError, RigidBodyHandle, body::Access, world::World,
70};
71use std::ops::Range;
72
73/// Maximum staged bodies, matching the existing world's 4096-body limit.
74pub const MAX_ASSEMBLY_BODIES: usize = 4096;
75
76/// Zero-based body index in an assembly. See the module recipe and lifetime rules.
77#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
78pub struct LocalBodyId(usize);
79impl LocalBodyId {
80 /// Explicit local index, allowing forward references. Insertion checks bounds.
81 pub const fn from_index(index: usize) -> Self {
82 Self(index)
83 }
84 /// Index in assembly body order (unrelated to arena slot order).
85 pub const fn index(self) -> usize {
86 self.0
87 }
88}
89
90/// Zero-based joint index in an assembly. See the module recipe.
91#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
92pub struct LocalJointId(usize);
93impl LocalJointId {
94 /// Explicit local index; mapping lookups return `None` for out-of-range IDs.
95 pub const fn from_index(index: usize) -> Self {
96 Self(index)
97 }
98 /// Index in assembly joint order.
99 pub const fn index(self) -> usize {
100 self.0
101 }
102}
103
104/// Ordinary preflight failure. No world state or arena identity is changed.
105/// Forward references must resolve inside the final plan:
106///
107/// ```
108/// # #[cfg(feature = "dim2")] {
109/// use ferravex_physics::{PhysicsError, assembly::{
110/// Assembly, AssemblyError, LocalBodyId, LocalJointId,
111/// }, d2::{JointBuilder, PhysicsWorld, RigidBody}};
112/// let mut plan = Assembly::<RigidBody>::new();
113/// let future = LocalBodyId::from_index(1);
114/// assert_eq!(future.index(), 1);
115/// let joint = plan.add_joint(LocalBodyId::from_index(0), future,
116/// JointBuilder::hinge()).unwrap();
117/// assert_eq!(joint, LocalJointId::from_index(0));
118/// assert_eq!(joint.index(), 0);
119/// let mut world = PhysicsWorld::default();
120/// assert_eq!(world.insert_assembly(plan), Err(AssemblyError::Joint {
121/// joint, error: PhysicsError::InvalidHandle,
122/// }));
123/// assert!(world.bodies.is_empty() && world.joints.is_empty());
124/// # }
125/// ```
126#[derive(Clone, Copy, Debug, PartialEq, Eq)]
127#[non_exhaustive]
128pub enum AssemblyError {
129 /// Combined staged/live body, collider or joint count exceeds its world cap.
130 Capacity(PhysicsError),
131 /// Invalid body, child geometry/settings, or dynamic mass.
132 Body {
133 body: LocalBodyId,
134 error: PhysicsError,
135 },
136 /// Invalid local endpoint (`InvalidHandle`) or descriptor/type pair
137 /// (`InvalidJoint`). Endpoints are checked before the descriptor.
138 Joint {
139 joint: LocalJointId,
140 error: PhysicsError,
141 },
142}
143impl std::fmt::Display for AssemblyError {
144 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
145 match self {
146 Self::Capacity(error) => write!(f, "assembly capacity: {error}"),
147 Self::Body { body, error } => write!(f, "assembly body {}: {error}", body.0),
148 Self::Joint { joint, error } => write!(f, "assembly joint {}: {error}", joint.0),
149 }
150 }
151}
152impl std::error::Error for AssemblyError {}
153
154#[derive(Clone, Debug)]
155struct Body<B> {
156 body: B,
157 children: Vec<Collider>,
158}
159#[derive(Clone, Copy, Debug)]
160struct Connection {
161 a: LocalBodyId,
162 b: LocalBodyId,
163 desc: JointDesc,
164}
165
166/// Owned, bounded authoring plan; see the executable module recipes.
167/// At most 4096 bodies, 16384 total colliders, 32 children per body and 4096
168/// joints. Storage grows on authoring; there is no steady-tick allocation promise.
169#[derive(Clone, Debug)]
170pub struct Assembly<B> {
171 bodies: Vec<Body<B>>,
172 joints: Vec<Connection>,
173 collider_count: usize,
174}
175impl<B> Default for Assembly<B> {
176 fn default() -> Self {
177 Self::new()
178 }
179}
180impl<B> Assembly<B> {
181 /// Empty plan. No storage is allocated until entries are staged.
182 pub const fn new() -> Self {
183 Self {
184 bodies: Vec::new(),
185 joints: Vec::new(),
186 collider_count: 0,
187 }
188 }
189 /// Stage an existing dimensional body and its ordered collider children.
190 /// Count errors leave the plan unchanged; rejected inputs are dropped.
191 /// Geometry/mass/dimension validation occurs at world preflight. Iteration
192 /// stops after the first excess child, even for an unbounded iterator.
193 /// Conversions and iterator/Drop panics are caller-code boundaries.
194 pub fn add_body<C: Into<Collider>>(
195 &mut self,
196 body: impl Into<B>,
197 children: impl IntoIterator<Item = C>,
198 ) -> Result<LocalBodyId, PhysicsError> {
199 if self.bodies.len() >= MAX_ASSEMBLY_BODIES {
200 return Err(PhysicsError::BodyCapacity);
201 }
202 let mut staged = Vec::new();
203 for child in children {
204 if staged.len() >= MAX_CHILDREN {
205 return Err(PhysicsError::ChildCapacity);
206 }
207 if self.collider_count + staged.len() >= MAX_COLLIDERS {
208 return Err(PhysicsError::ColliderCapacity);
209 }
210 staged.push(child.into());
211 }
212 let body = body.into();
213 let id = LocalBodyId(self.bodies.len());
214 self.collider_count += staged.len();
215 self.bodies.push(Body {
216 body,
217 children: staged,
218 });
219 Ok(id)
220 }
221 /// Stage a joint with assembly-local endpoints and ordinary local anchors.
222 /// Forward references are allowed; all endpoints/descriptors are validated
223 /// at insertion. `None` reference rotation captures insertion-time relative
224 /// body rotation, exactly as `insert_joint` does. Capacity errors retain the
225 /// plan; caller conversions and their panics occur before publication.
226 pub fn add_joint(
227 &mut self,
228 a: LocalBodyId,
229 b: LocalBodyId,
230 desc: impl Into<JointDesc>,
231 ) -> Result<LocalJointId, PhysicsError> {
232 if self.joints.len() >= MAX_JOINTS {
233 return Err(PhysicsError::JointCapacity);
234 }
235 let desc = desc.into();
236 let id = LocalJointId(self.joints.len());
237 self.joints.push(Connection { a, b, desc });
238 Ok(id)
239 }
240 /// Staged body count; see the module recipe.
241 pub fn body_count(&self) -> usize {
242 self.bodies.len()
243 }
244 /// Staged collider count across all bodies; see the module recipe.
245 pub fn collider_count(&self) -> usize {
246 self.collider_count
247 }
248 /// Staged joint count; see the module recipe.
249 pub fn joint_count(&self) -> usize {
250 self.joints.len()
251 }
252}
253
254/// Mappings in deterministic plan order, not sorted by recycled world slot.
255/// These are ordinary same-world generational handles; this result neither owns
256/// nor removes world objects. After removal, its copied handles are stale. Local
257/// collider IDs are `(LocalBodyId, child_index)` in the original child order.
258/// See the module recipe for lookups and template-based reset.
259#[derive(Clone, Debug, Default, PartialEq, Eq)]
260pub struct AssemblyHandles {
261 bodies: Vec<RigidBodyHandle>,
262 colliders: Vec<ColliderHandle>,
263 children: Vec<Range<usize>>,
264 joints: Vec<JointHandle>,
265}
266impl AssemblyHandles {
267 /// Resolve a plan-local body index, or `None` if out of range.
268 pub fn body(&self, id: LocalBodyId) -> Option<RigidBodyHandle> {
269 self.bodies.get(id.0).copied()
270 }
271 /// Bodies in local ID order, including collider-free anchors.
272 pub fn bodies(&self) -> &[RigidBodyHandle] {
273 &self.bodies
274 }
275 /// Resolve a body-local child index, or `None` if either index is invalid.
276 pub fn collider(&self, body: LocalBodyId, child: usize) -> Option<ColliderHandle> {
277 self.colliders(body)?.get(child).copied()
278 }
279 /// Ordered children for one body, including an empty slice for an anchor.
280 pub fn colliders(&self, body: LocalBodyId) -> Option<&[ColliderHandle]> {
281 self.children
282 .get(body.0)
283 .map(|range| &self.colliders[range.clone()])
284 }
285 /// Resolve a plan-local joint index, or `None` if out of range.
286 pub fn joint(&self, id: LocalJointId) -> Option<JointHandle> {
287 self.joints.get(id.0).copied()
288 }
289 /// Joints in local ID order.
290 pub fn joints(&self) -> &[JointHandle] {
291 &self.joints
292 }
293}
294
295impl<B: Access> World<B> {
296 /// Read-only, allocation-free snapshot of assembly validity and capacity.
297 /// Checks combined counts first, then every body/child and dynamic mass,
298 /// then every joint's local references, descriptor and endpoint kinds.
299 /// No wake/cache/filter/arena or plan edits occur. Existing insertion rules
300 /// apply; non-dynamic collider geometry is also checked. Use checked body
301 /// builders for untrusted velocities/settings, as for ordinary insertion.
302 /// A successful check reserves nothing. See the module's executable recipes.
303 pub fn validate_assembly(&self, assembly: &Assembly<B>) -> Result<(), AssemblyError> {
304 for (exceeded, error) in [
305 (
306 self.bodies.len() + assembly.bodies.len() > MAX_ASSEMBLY_BODIES,
307 PhysicsError::BodyCapacity,
308 ),
309 (
310 self.colliders.len() + assembly.collider_count > MAX_COLLIDERS,
311 PhysicsError::ColliderCapacity,
312 ),
313 (
314 self.joints.len() + assembly.joints.len() > MAX_JOINTS,
315 PhysicsError::JointCapacity,
316 ),
317 ] {
318 if exceeded {
319 return Err(AssemblyError::Capacity(error));
320 }
321 }
322 for (index, entry) in assembly.bodies.iter().enumerate() {
323 self.check_assembly_compound(&entry.body, &entry.children)
324 .map_err(|error| AssemblyError::Body {
325 body: LocalBodyId(index),
326 error,
327 })?;
328 }
329 for (index, joint) in assembly.joints.iter().enumerate() {
330 let id = LocalJointId(index);
331 let (Some(a), Some(b)) = (
332 assembly.bodies.get(joint.a.0),
333 assembly.bodies.get(joint.b.0),
334 ) else {
335 return Err(AssemblyError::Joint {
336 joint: id,
337 error: PhysicsError::InvalidHandle,
338 });
339 };
340 self.check_assembly_joint(&a.body, &b.body, joint.a == joint.b, joint.desc)
341 .map_err(|error| AssemblyError::Joint { joint: id, error })?;
342 }
343 Ok(())
344 }
345
346 /// Insert the whole owned assembly after preflighting every ordinary error.
347 /// Returned errors preserve all prior world state, free slots and arena
348 /// generations; no insert/remove rollback consumes identities. All mapping
349 /// buffers are staged before the first insertion. Success reuses unchanged
350 /// compound/joint insertion semantics, including mass, waking, reference
351 /// capture, collision filters and joint caches. It advances no simulation.
352 ///
353 /// This is **not** panic rollback or allocation-free insertion: staging,
354 /// arenas, child lists and joint refresh/filter storage may allocate. OOM,
355 /// allocator/iterator/conversion/Drop panics and inherited revision-exhaustion
356 /// panics are outside the guarantee. A panic after publication may leave a
357 /// partial mechanism and no returned mapping. Do not catch it and assume
358 /// the world is unchanged. No arbitrary user callback runs after preflight.
359 /// See the module recipe for a checked lab mechanism and reset handoff.
360 pub fn insert_assembly(
361 &mut self,
362 assembly: Assembly<B>,
363 ) -> Result<AssemblyHandles, AssemblyError> {
364 self.validate_assembly(&assembly)?;
365 let mut handles = AssemblyHandles {
366 bodies: Vec::with_capacity(assembly.bodies.len()),
367 colliders: Vec::with_capacity(assembly.collider_count),
368 children: Vec::with_capacity(assembly.bodies.len()),
369 joints: Vec::with_capacity(assembly.joints.len()),
370 };
371 for entry in assembly.bodies {
372 // Preflight used the same validators/capacities. No user conversion
373 // is repeated: both body and collider inputs are already owned.
374 let body = self
375 .insert_compound(entry.body, entry.children)
376 .expect("assembly compound passed complete preflight");
377 let start = handles.colliders.len();
378 handles
379 .colliders
380 .extend_from_slice(&self.bodies[body].core().colliders);
381 handles.children.push(start..handles.colliders.len());
382 handles.bodies.push(body);
383 }
384 for joint in assembly.joints {
385 let id = self
386 .insert_joint(
387 handles.bodies[joint.a.0],
388 handles.bodies[joint.b.0],
389 joint.desc,
390 )
391 .expect("assembly joint passed complete preflight");
392 handles.joints.push(id);
393 }
394 Ok(handles)
395 }
396}