dynamis-world 0.7.0

Host scene registry, step orchestration, and readback
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
use super::World;
use super::commands::BodyCommand;
use super::ids::IdSpace;
use bytemuck::Zeroable;
use dynamis_abi::{
    BODY_CCD, BODY_KINEMATIC, BodyDescriptorRecord, BodyStateRecord, ColliderRecord,
    OVERRIDE_SLEEP_ANGULAR, OVERRIDE_SLEEP_LINEAR, PATCH_ANGULAR_VELOCITY, PATCH_ORIENTATION,
    PATCH_POSITION, PATCH_VELOCITY,
};
use dynamis_model::{
    BodyDesc, BodyHandle, BodyState, ColliderDesc, ContactEventMode, MassProperties, Shape,
};

pub(crate) const NEVER_REPORTED: u64 = u64::MAX;

#[derive(Clone)]
pub(crate) struct Bodies {
    pub(crate) alive: Vec<BodyHandle>,
    pub(crate) ids: IdSpace,
    pub(crate) index_of: Vec<u32>,
    pub(crate) collider_descs: Vec<Vec<ColliderDesc>>,
    pub(crate) masses: Vec<f32>,
    pub(crate) com_overrides: Vec<Option<[f32; 3]>>,
    pub(crate) inertia_overrides: Vec<Option<[f32; 6]>>,
    pub(crate) descriptors: Vec<BodyDescriptorRecord>,
    pub(crate) dynamic_count: usize,
    pub(crate) kinematic: Vec<bool>,
    pub(crate) ccd_count: u32,
    pub(crate) states: Vec<Option<BodyState>>,
    pub(crate) covered: Vec<u64>,
    pub(crate) device_count: u32,
    pub(crate) commands: Vec<BodyCommand>,
    pub(crate) dirty: Vec<u32>,
    pub(crate) last_moves: u32,
    pub(crate) last_edits: u32,
}

impl Bodies {
    pub(crate) const fn new() -> Self {
        Self {
            alive: Vec::new(),
            ids: IdSpace::new(),
            index_of: Vec::new(),
            collider_descs: Vec::new(),
            masses: Vec::new(),
            com_overrides: Vec::new(),
            inertia_overrides: Vec::new(),
            descriptors: Vec::new(),
            dynamic_count: 0,
            kinematic: Vec::new(),
            ccd_count: 0,
            states: Vec::new(),
            covered: Vec::new(),
            device_count: 0,
            commands: Vec::new(),
            dirty: Vec::new(),
            last_moves: 0,
            last_edits: 0,
        }
    }

    fn grow_to(&mut self, id: u32) {
        let rows = id as usize + 1;
        if rows <= self.index_of.len() {
            return;
        }
        self.index_of.resize(rows, u32::MAX);
        self.collider_descs.resize(rows, Vec::new());
        self.masses.resize(rows, 1.0);
        self.com_overrides.resize(rows, None);
        self.inertia_overrides.resize(rows, None);
        self.descriptors
            .resize(rows, BodyDescriptorRecord::zeroed());
        self.kinematic.resize(rows, false);
        self.states.resize(rows, None);
        self.covered.resize(rows, NEVER_REPORTED);
    }
}

impl World {
    pub fn spawn(&mut self, desc: BodyDesc) -> BodyHandle {
        let (id, generation) = self.bodies.ids.acquire();
        self.bodies.grow_to(id);
        let handle = BodyHandle { id, generation };
        let id = id as usize;
        self.validate_world_geometry(&desc);
        let mass = desc.effective_mass(|shape| self.shape_solid(shape));
        let mut spawn_desc = desc.clone();
        spawn_desc.mass = mass;
        self.bodies.masses[id] = mass;
        self.bodies.com_overrides[id] = desc.com;
        self.bodies.inertia_overrides[id] = desc.inertia;
        self.bodies.kinematic[id] = desc.kinematic;
        self.bodies.collider_descs[id] = desc.colliders.clone();
        for collider in &desc.colliders {
            self.retain_shape_ref(&collider.shape);
        }
        let mass_properties = self.mass_properties_of(id);
        self.bodies.descriptors[id] =
            BodyDescriptorRecord::build(&spawn_desc, mass_properties, &self.config);
        self.record_state(id, &spawn_desc);
        self.repool_colliders(id as u32);
        let state = BodyStateRecord::initial(&spawn_desc, id as u32, handle.generation);
        let slot = self.bodies.alive.len() as u32;
        self.bodies.index_of[id] = slot;
        self.bodies.alive.push(handle);
        self.bodies.dirty.push(slot);
        self.bodies
            .commands
            .push(BodyCommand::Add { row: slot, state });
        if spawn_desc.ccd {
            self.bodies.ccd_count += 1;
        }
        if mass > 0.0 || desc.kinematic {
            if (self.bodies.dynamic_count as u32) < slot {
                self.swap_slots(self.bodies.dynamic_count as u32, slot);
            }
            self.bodies.dynamic_count += 1;
        }
        handle
    }

    pub fn remove(&mut self, handle: BodyHandle) {
        self.validate(handle);
        self.assert_no_constraints(handle);
        assert!(
            self.soft.attachment_refs(handle.id) == 0,
            "body handle {handle:?} still anchors a soft attachment"
        );
        let id = handle.id as usize;
        let slot = self.bodies.index_of[id];
        if (slot as usize) < self.bodies.dynamic_count {
            let tail_dynamic = (self.bodies.dynamic_count - 1) as u32;
            if slot != tail_dynamic {
                self.swap_slots(slot, tail_dynamic);
            }
            self.bodies.dynamic_count -= 1;
            let last = (self.bodies.alive.len() - 1) as u32;
            if tail_dynamic != last {
                self.swap_slots(tail_dynamic, last);
            }
        } else {
            let last = (self.bodies.alive.len() - 1) as u32;
            if slot != last {
                self.swap_slots(slot, last);
            }
        }
        self.discard_tail();
    }

    fn discard_tail(&mut self) {
        let last = (self.bodies.alive.len() - 1) as u32;
        let handle = self.bodies.alive[last as usize];
        let id = handle.id as usize;
        self.bodies.index_of[id] = u32::MAX;
        self.bodies.ids.release(handle.id);
        self.bodies.alive.pop();
        self.bodies.dirty.retain(|dirty| *dirty != last);
        let removed = std::mem::take(&mut self.bodies.collider_descs[id]);
        for collider in &removed {
            self.release_shape_ref(&collider.shape);
        }
        self.colliders.release(id as u32);
        self.bodies.states[id] = None;
        self.bodies.covered[id] = NEVER_REPORTED;
        self.view.forget(handle.id);
        self.bodies.kinematic[id] = false;
        if self.bodies.descriptors[id].flags & BODY_CCD != 0 {
            self.bodies.ccd_count -= 1;
        }
        self.bodies.descriptors[id] = BodyDescriptorRecord::zeroed();
        self.bodies.commands.push(BodyCommand::Remove {
            hole: last,
            tail: last,
        });
    }

    fn swap_slots(&mut self, first: u32, second: u32) {
        self.bodies.alive.swap(first as usize, second as usize);
        self.bodies.index_of[self.bodies.alive[first as usize].id as usize] = first;
        self.bodies.index_of[self.bodies.alive[second as usize].id as usize] = second;
        self.bodies
            .commands
            .push(BodyCommand::Swap { first, second });
        self.bodies.dirty.push(first);
        self.bodies.dirty.push(second);
    }

    fn migrate_partition(&mut self, handle: BodyHandle) {
        let id = handle.id as usize;
        let static_now = self.is_static_id(id);
        let slot = self.bodies.index_of[id];
        let in_dynamic = (slot as usize) < self.bodies.dynamic_count;
        if static_now == !in_dynamic {
            return;
        }
        if static_now {
            let tail = (self.bodies.dynamic_count - 1) as u32;
            if slot != tail {
                self.swap_slots(slot, tail);
            }
            self.bodies.dynamic_count -= 1;
            self.bodies.commands.push(BodyCommand::Patch {
                row: tail,
                mask: PATCH_VELOCITY,
                state: BodyStateRecord::zeroed(),
            });
            if let Some(state) = self.bodies.states[id].as_mut() {
                state.velocity = [0.0; 3];
                state.angular_velocity = [0.0; 3];
            }
            self.bodies.dirty.push(tail);
        } else {
            let boundary = self.bodies.dynamic_count as u32;
            if slot != boundary {
                self.swap_slots(slot, boundary);
            }
            self.bodies.dynamic_count += 1;
        }
        self.bodies.dirty.push(slot);
    }

    pub fn read_state(&self, handle: BodyHandle) -> BodyState {
        self.validate(handle);
        assert!(
            self.body_current(handle.id),
            "a body state older than the last step requires wait() or an observation of that body"
        );
        self.bodies.states[handle.id as usize].expect("body state is unavailable")
    }

    fn record_state(&mut self, id: usize, desc: &BodyDesc) {
        self.bodies.states[id] = Some(BodyState {
            position: desc.position,
            prev_position: desc.position,
            orientation: desc.orientation,
            velocity: desc.velocity,
            angular_velocity: desc.angular_velocity,
            inverse_mass: self.bodies.descriptors[id].inverse_mass,
            com: self.bodies.descriptors[id].com,
            sleeping: false,
            step: self.clock.step,
        });
        self.bodies.covered[id] = self.clock.step;
    }

    fn validate_world_geometry(&self, desc: &BodyDesc) {
        for collider in &desc.colliders {
            if collider.shape.is_world_geometry() && (desc.mass > 0.0 && !desc.kinematic) {
                panic!("world geometry colliders must be static or kinematic");
            }
        }
    }

    fn is_static_id(&self, id: usize) -> bool {
        self.bodies.masses[id] <= 0.0 && !self.bodies.kinematic[id]
    }

    fn patch_descriptor(
        &mut self,
        handle: BodyHandle,
        edit: impl FnOnce(&mut BodyDescriptorRecord),
    ) {
        self.validate(handle);
        let id = handle.id as usize;
        edit(&mut self.bodies.descriptors[id]);
        self.bodies.dirty.push(self.bodies.index_of[id]);
    }

    fn refresh_descriptor(&mut self, handle: BodyHandle) {
        let id = handle.id as usize;
        let mass = self.mass_properties_of(id);
        let kinematic = self.bodies.kinematic[id];
        let inverse_mass = if kinematic || self.bodies.masses[id] <= 0.0 {
            0.0
        } else {
            1.0 / self.bodies.masses[id]
        };
        let descriptor = &mut self.bodies.descriptors[id];
        descriptor.com = mass.com;
        descriptor.inverse_inertia = mass.inverse_inertia;
        descriptor.inverse_mass = inverse_mass;
        descriptor.flags =
            (descriptor.flags & !BODY_KINEMATIC) | if kinematic { BODY_KINEMATIC } else { 0 };
        let row = *descriptor;
        self.bodies.dirty.push(self.bodies.index_of[id]);
        if let Some(state) = self.bodies.states[id].as_mut() {
            state.inverse_mass = row.inverse_mass;
            state.com = row.com;
        }
    }

    fn apply_mass(&mut self, handle: BodyHandle, mass: f32) {
        self.bodies.masses[handle.id as usize] = mass;
        self.refresh_descriptor(handle);
    }

    fn command_slot(&self, handle: BodyHandle) -> u32 {
        self.validate(handle);
        self.bodies.index_of[handle.id as usize]
    }

    fn schedule_patch(&mut self, handle: BodyHandle, mask: u32, state: BodyStateRecord) {
        let slot = self.command_slot(handle);
        self.bodies.commands.push(BodyCommand::Patch {
            row: slot,
            mask,
            state,
        });
    }

    pub fn set_position(&mut self, handle: BodyHandle, position: [f32; 3]) {
        self.validate(handle);
        if let Some(state) = self.bodies.states[handle.id as usize].as_mut() {
            state.position = position;
            state.prev_position = position;
        }
        let mut payload = BodyStateRecord::zeroed();
        payload.position = position;
        self.schedule_patch(handle, PATCH_POSITION, payload);
        self.bodies
            .dirty
            .push(self.bodies.index_of[handle.id as usize]);
    }

    pub fn set_orientation(&mut self, handle: BodyHandle, orientation: [f32; 4]) {
        self.assert_unit(orientation);
        self.validate(handle);
        if let Some(state) = self.bodies.states[handle.id as usize].as_mut() {
            state.orientation = orientation;
        }
        let mut payload = BodyStateRecord::zeroed();
        payload.orientation = orientation;
        self.schedule_patch(handle, PATCH_ORIENTATION, payload);
        self.bodies
            .dirty
            .push(self.bodies.index_of[handle.id as usize]);
    }

    pub fn set_velocity(&mut self, handle: BodyHandle, velocity: [f32; 3]) {
        self.validate(handle);
        if let Some(state) = self.bodies.states[handle.id as usize].as_mut() {
            state.velocity = velocity;
        }
        let mut payload = BodyStateRecord::zeroed();
        payload.velocity = velocity;
        self.schedule_patch(handle, PATCH_VELOCITY, payload);
    }

    pub fn set_angular_velocity(&mut self, handle: BodyHandle, angular_velocity: [f32; 3]) {
        self.validate(handle);
        if let Some(state) = self.bodies.states[handle.id as usize].as_mut() {
            state.angular_velocity = angular_velocity;
        }
        let mut payload = BodyStateRecord::zeroed();
        payload.angular_velocity = angular_velocity;
        self.schedule_patch(handle, PATCH_ANGULAR_VELOCITY, payload);
    }

    pub fn set_mass(&mut self, handle: BodyHandle, mass: f32) {
        assert!(mass >= 0.0, "mass must be non-negative");
        self.validate(handle);
        self.apply_mass(handle, mass);
        self.migrate_partition(handle);
    }

    pub fn set_density(&mut self, handle: BodyHandle, density: f32) {
        assert!(density >= 0.0, "density must be non-negative");
        self.validate(handle);
        let volume = dynamis_model::solid_volume_of(
            &self.bodies.collider_descs[handle.id as usize],
            |shape| self.shape_solid(shape),
        );
        self.apply_mass(handle, density * volume);
        self.migrate_partition(handle);
    }

    pub fn set_com(&mut self, handle: BodyHandle, com: [f32; 3]) {
        self.validate(handle);
        self.bodies.com_overrides[handle.id as usize] = Some(com);
        self.refresh_descriptor(handle);
    }

    pub fn set_inertia(&mut self, handle: BodyHandle, inertia: [f32; 6]) {
        assert!(
            inertia.iter().all(|value| value.is_finite()),
            "inertia tensor must be finite"
        );
        self.validate(handle);
        self.bodies.inertia_overrides[handle.id as usize] = Some(inertia);
        self.refresh_descriptor(handle);
    }

    pub fn set_linear_damping(&mut self, handle: BodyHandle, damping: f32) {
        assert!(damping >= 0.0, "damping must be non-negative");
        self.patch_descriptor(handle, |row| row.linear_damping = damping);
    }

    pub fn set_angular_damping(&mut self, handle: BodyHandle, damping: f32) {
        assert!(damping >= 0.0, "angular damping must be non-negative");
        self.patch_descriptor(handle, |row| row.angular_damping = damping);
    }

    pub fn set_gravity_scale(&mut self, handle: BodyHandle, gravity_scale: f32) {
        self.patch_descriptor(handle, |row| row.gravity_scale = gravity_scale);
    }

    pub fn set_sleep_thresholds(
        &mut self,
        handle: BodyHandle,
        velocity: f32,
        angular_velocity: f32,
    ) {
        assert!(velocity >= 0.0, "sleep velocity must be non-negative");
        assert!(
            angular_velocity >= 0.0,
            "sleep angular velocity must be non-negative"
        );
        self.patch_descriptor(handle, |row| {
            row.sleep_velocity = velocity;
            row.sleep_angular_velocity = angular_velocity;
            row.flags |= OVERRIDE_SLEEP_LINEAR | OVERRIDE_SLEEP_ANGULAR;
        });
    }

    pub fn set_collision_group(&mut self, handle: BodyHandle, group: u32) {
        self.patch_descriptor(handle, |row| row.collision_group = group);
    }

    pub fn set_collision_mask(&mut self, handle: BodyHandle, mask: u32) {
        self.patch_descriptor(handle, |row| row.collision_mask = mask);
    }

    pub fn set_ccd(&mut self, handle: BodyHandle, ccd: bool) {
        self.validate(handle);
        let enabled = self.bodies.descriptors[handle.id as usize].flags & BODY_CCD != 0;
        if enabled == ccd {
            return;
        }
        self.bodies.ccd_count = if ccd {
            self.bodies.ccd_count + 1
        } else {
            self.bodies.ccd_count - 1
        };
        self.patch_descriptor(handle, |row| {
            row.flags = (row.flags & !BODY_CCD) | if ccd { BODY_CCD } else { 0 };
        });
    }

    pub(crate) fn ccd_active(&self) -> bool {
        debug_assert_eq!(
            self.bodies.ccd_count,
            self.bodies
                .descriptors
                .iter()
                .filter(|row| row.flags & BODY_CCD != 0)
                .count() as u32,
            "the ccd body count must mirror the body descriptors"
        );
        self.bodies.ccd_count > 0
    }

    pub fn set_kinematic(&mut self, handle: BodyHandle, kinematic: bool) {
        self.validate(handle);
        self.bodies.kinematic[handle.id as usize] = kinematic;
        self.refresh_descriptor(handle);
        self.migrate_partition(handle);
    }

    pub fn set_collider(&mut self, handle: BodyHandle, index: usize, collider: ColliderDesc) {
        self.validate(handle);
        let id = handle.id as usize;
        assert!(
            index < self.bodies.collider_descs[id].len(),
            "collider index out of range"
        );
        let existing = std::mem::replace(&mut self.bodies.collider_descs[id][index], collider);
        self.release_shape_ref(&existing.shape);
        self.retain_shape_ref(&collider.shape);
        self.repool_colliders(handle.id);
        self.refresh_descriptor(handle);
    }

    pub fn add_collider(&mut self, handle: BodyHandle, collider: ColliderDesc) {
        self.validate(handle);
        let id = handle.id as usize;
        self.retain_shape_ref(&collider.shape);
        self.bodies.collider_descs[id].push(collider);
        self.repool_colliders(handle.id);
        self.refresh_descriptor(handle);
    }

    pub fn remove_collider(&mut self, handle: BodyHandle, index: usize) {
        self.validate(handle);
        let id = handle.id as usize;
        assert!(
            index < self.bodies.collider_descs[id].len(),
            "collider index out of range"
        );
        assert!(
            self.bodies.collider_descs[id].len() > 1,
            "a body requires at least one collider"
        );
        let removed = self.bodies.collider_descs[id].swap_remove(index);
        self.release_shape_ref(&removed.shape);
        self.repool_colliders(handle.id);
        self.refresh_descriptor(handle);
    }

    pub fn set_shape(&mut self, handle: BodyHandle, shape: Shape) {
        self.validate(handle);
        let id = handle.id as usize;
        let replaced = std::mem::replace(&mut self.bodies.collider_descs[id][0].shape, shape);
        self.release_shape_ref(&replaced);
        self.retain_shape_ref(&shape);
        self.repool_colliders(handle.id);
        self.refresh_descriptor(handle);
    }

    pub fn set_restitution(&mut self, handle: BodyHandle, restitution: f32) {
        self.validate(handle);
        self.bodies.collider_descs[handle.id as usize][0].restitution = restitution;
        self.repool_colliders(handle.id);
        self.bodies
            .dirty
            .push(self.bodies.index_of[handle.id as usize]);
    }

    pub fn set_friction(&mut self, handle: BodyHandle, friction: f32) {
        assert!(friction >= 0.0, "friction must be non-negative");
        self.validate(handle);
        self.bodies.collider_descs[handle.id as usize][0].friction = friction;
        self.repool_colliders(handle.id);
        self.bodies
            .dirty
            .push(self.bodies.index_of[handle.id as usize]);
    }

    pub fn set_collider_events(
        &mut self,
        handle: BodyHandle,
        index: usize,
        events: ContactEventMode,
    ) {
        self.validate(handle);
        let id = handle.id as usize;
        assert!(
            index < self.bodies.collider_descs[id].len(),
            "collider index out of range"
        );
        self.bodies.collider_descs[id][index].events = events;
        self.repool_colliders(handle.id);
        self.bodies.dirty.push(self.bodies.index_of[id]);
    }

    pub fn apply_force(&mut self, handle: BodyHandle, force: [f32; 3]) {
        let slot = self.command_slot(handle);
        self.bodies
            .commands
            .push(BodyCommand::Force { row: slot, force });
    }

    pub fn apply_force_at_point(&mut self, handle: BodyHandle, force: [f32; 3], point: [f32; 3]) {
        let slot = self.command_slot(handle);
        self.bodies.commands.push(BodyCommand::ForceAtPoint {
            row: slot,
            force,
            point,
        });
    }

    pub fn apply_torque(&mut self, handle: BodyHandle, torque: [f32; 3]) {
        let slot = self.command_slot(handle);
        self.bodies
            .commands
            .push(BodyCommand::Torque { row: slot, torque });
    }

    pub fn apply_impulse(&mut self, handle: BodyHandle, impulse: [f32; 3]) {
        let slot = self.command_slot(handle);
        self.bodies
            .commands
            .push(BodyCommand::Impulse { row: slot, impulse });
    }

    pub fn apply_impulse_at_point(
        &mut self,
        handle: BodyHandle,
        impulse: [f32; 3],
        point: [f32; 3],
    ) {
        let slot = self.command_slot(handle);
        self.bodies.commands.push(BodyCommand::ImpulseAtPoint {
            row: slot,
            impulse,
            point,
        });
    }

    pub fn apply_angular_impulse(&mut self, handle: BodyHandle, impulse: [f32; 3]) {
        let slot = self.command_slot(handle);
        self.bodies
            .commands
            .push(BodyCommand::AngularImpulse { row: slot, impulse });
    }

    pub fn wake(&mut self, handle: BodyHandle) {
        let slot = self.command_slot(handle);
        self.bodies.commands.push(BodyCommand::Wake { row: slot });
    }

    pub fn sleep(&mut self, handle: BodyHandle) {
        let slot = self.command_slot(handle);
        self.bodies.commands.push(BodyCommand::Sleep { row: slot });
    }

    pub(crate) fn repool_colliders(&mut self, id: u32) {
        let records = self.collider_block_of(id as usize);
        self.colliders.assign(id, &records);
    }

    pub(crate) fn collider_block_of(&self, id: usize) -> Vec<ColliderRecord> {
        self.bodies.collider_descs[id]
            .iter()
            .enumerate()
            .map(|(slot, collider)| self.collider_record(collider, slot as u32))
            .collect()
    }

    pub(super) fn validate(&self, handle: BodyHandle) {
        let id = handle.id as usize;
        if id >= self.bodies.ids.len() {
            panic!("body handle {handle:?} is out of range");
        }
        if self.bodies.ids.generation(handle.id) != handle.generation {
            panic!("body handle {handle:?} is stale");
        }
        if self.bodies.index_of[id] == u32::MAX {
            panic!("body handle {handle:?} is not alive");
        }
    }

    pub(super) fn assert_unit(&self, orientation: [f32; 4]) {
        assert!(
            (orientation[0] * orientation[0]
                + orientation[1] * orientation[1]
                + orientation[2] * orientation[2]
                + orientation[3] * orientation[3]
                - 1.0)
                .abs()
                < 1e-4,
            "orientation must be a unit quaternion"
        );
    }

    fn retain_shape_ref(&mut self, shape: &Shape) {
        if let Shape::Hull(handle) | Shape::Mesh(handle) | Shape::HeightField(handle) = shape {
            self.shapes.pool.retain(*handle);
        }
    }

    fn release_shape_ref(&mut self, shape: &Shape) {
        if let Shape::Hull(handle) | Shape::Mesh(handle) | Shape::HeightField(handle) = shape {
            self.shapes.pool.release(*handle);
        }
    }
}

impl World {
    pub(crate) fn state_snapshot(&self, id: usize) -> Option<BodyState> {
        assert!(
            self.body_current(id as u32),
            "a constraint frame requires a current body state; call wait() or observe the body"
        );
        self.bodies.states[id]
    }

    pub(crate) fn mass_properties_of(&self, id: usize) -> MassProperties {
        dynamis_model::mass_properties_of_intent(
            &self.bodies.collider_descs[id],
            self.bodies.masses[id],
            self.bodies.com_overrides[id],
            self.bodies.inertia_overrides[id],
            |shape| self.shape_solid(shape),
        )
    }

    pub(crate) fn collider_record(&self, desc: &ColliderDesc, slot: u32) -> ColliderRecord {
        let source = match desc.shape {
            Shape::Hull(handle) | Shape::Mesh(handle) | Shape::HeightField(handle) => handle.id,
            _ => 0,
        };
        ColliderRecord::build(desc, source, slot)
    }
}