linear-sim 0.12.0

Minimal linear 3D simulation library
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
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
//! Collision detection and resolution

use std;
#[cfg(feature = "debug_dump")]
use std::sync::atomic;
use std::cmp::Reverse;
use either::Either;
use log;
use sorted_vec::{SortedSet, ReverseSortedSet};
use vec_map::VecMap;
#[cfg(feature = "derive_serdes")]
use serde::{Deserialize, Serialize};

use geometry::Aabb3;
use math::*;

use crate::{constraint, event, geometry, math, Constraint};
use crate::constraint::contact::CONTACT_DISTANCE;
use crate::object::{self, InternalId, ObjectPair};

pub mod proximity;
pub mod intersection;
mod broad;

pub use self::proximity::Proximity;
pub use self::intersection::Intersection;
use self::broad::Broad;

////////////////////////////////////////////////////////////////////////////////////////
//  constants                                                                         //
////////////////////////////////////////////////////////////////////////////////////////

#[cfg(feature = "debug_dump")]
#[cfg_attr(docsrs, doc(cfg(feature="debug_dump")))]
pub static DEBUG_DUMP : atomic::AtomicBool = atomic::AtomicBool::new (false);
#[cfg(feature = "debug_dump")]
#[cfg_attr(docsrs, doc(cfg(feature="debug_dump")))]
pub const DEBUG_DUMP_DETECT_RESOLVE_MAX_ITERS : u64 = 200;

////////////////////////////////////////////////////////////////////////////////////////
//  structs                                                                           //
////////////////////////////////////////////////////////////////////////////////////////

/// Collision subsystem
#[cfg_attr(feature = "derive_serdes", derive(Deserialize, Serialize))]
#[derive(Clone, Debug, Default)]
pub(crate) struct Collision {
  /// Broad-phase detection subsystem
  broad : Broad,
  /// Collision pipeline data: broad, mid, and narrow phase results.
  ///
  /// The pipeline should always be empty at the beginning and end of each collision
  /// step and is skipped when serializing the collision state resulting in a default
  /// initialized (empty) pipeline when deserialized.
  #[cfg_attr(feature = "derive_serdes", serde(skip))]
  pipeline : Pipeline,
  /// Count maximum iterations of collision detect/resolve main loop
  #[cfg(debug_assertions)]
  detect_resolve_max_iter_count : u64,
  /// Count maximum iterations of narrow phase loop
  #[cfg(debug_assertions)]
  narrow_toi_max_iter_count : u64
}

/// Collision pipeline data.
///
/// A collision detection step should begin and end with all vectors empty.
#[derive(Clone, Debug, Default, PartialEq)]
struct Pipeline {
  /// Counts iterations of the `detect_resolve` loop; reset to zero at the beginning of
  /// a collision step
  pub detect_resolve_iter : u64,
  /// Broad phase AABB overlaps on all three axes
  pub broad_overlap_pairs : Vec <ObjectPair>,
  /// Sorted in *reverse order* by start time
  pub mid_toi_pairs       :
    ReverseSortedSet <(Normalized <f64>, Normalized <f64>, ObjectPair)>,
  /// Sorted in *reverse order* by TOI
  pub narrow_toi_contacts :
    ReverseSortedSet <(Normalized <f64>, ObjectPair, constraint::Contact)>,
  pub resolved_collisions : Vec <event::CollisionResolve>,
  /// Nocollide intersections
  pub overlaps            : Vec <event::Overlap>,
}

////////////////////////////////////////////////////////////////////////////////////////
//  functions                                                                         //
////////////////////////////////////////////////////////////////////////////////////////

pub fn report_sizes() {
  use std::mem::size_of;
  println!("collision report sizes...");

  println!("  size of Collision: {}", size_of::<Collision>());

  println!("...collision report sizes");
}

////////////////////////////////////////////////////////////////////////////////////////
//  impls                                                                             //
////////////////////////////////////////////////////////////////////////////////////////

impl Collision {
  pub(crate) const fn broad (&self) -> &Broad {
    &self.broad
  }
  /// Attempt to add a new static object to the collision subsystem.
  ///
  /// Queries distance to each dynamic object and if any intersections are
  /// found, the object is not added and the intersections are returned.
  ///
  /// Only counts intersections if both objects are collidable.
  pub(crate) fn try_add_object_static (&mut self,
    objects_dynamic : &VecMap <object::Dynamic>,
    object          : &object::Static,
    key             : object::Key
  ) -> Result <(), Vec <(object::Id, Intersection)>> {
    let mut intersections = Vec::new();
    if object.collidable {
      let aabb_discrete = object.aabb_dilated();
      let overlaps : Vec <object::Id> = self.broad.overlaps_discrete (aabb_discrete)
        .into_iter().map (object::Id::from).collect::<Vec <_>>();
      for object_id in overlaps {
        let proximity = match object_id.kind {
          object::Kind::Static  => continue,  // skip static/static checks
          object::Kind::Dynamic => {
            let object_dynamic = &objects_dynamic[object_id.key.index()];
            if !object_dynamic.collidable {
              continue                    // skip non-collidable dynamic objects
            }
            Proximity::query (object_dynamic, object)
          }
          object::Kind::Nodetect => unreachable!()
        };
        if let Ok (intersection) = proximity.try_into() {
          intersections.push ((object_id, intersection));
        }
      }
    }
    if intersections.is_empty() {
      self.add_object_static (object, key);
      Ok  (())
    } else {
      Err (intersections)
    }
  }

  #[inline]
  pub(crate) fn remove_object_static (&mut self, object_key : object::Key) {
    debug_assert!(self.pipeline.is_empty());
    let id = InternalId::new_static (object_key);
    self.broad.remove_object (id);
  }

  /// Attempts to add a new dynamic object.
  ///
  /// Queries distance to each static and dynamic object and if any intersections are
  /// found, the object is not added and the intersections are returned.
  ///
  /// Only counts intersections if both objects are collidable.
  pub(crate) fn try_add_object_dynamic (&mut self,
    pseudo_velocities : &mut VecMap <Vector3 <f64>>,
    objects_static    : &VecMap <object::Static>,
    objects_dynamic   : &VecMap <object::Dynamic>,
    object            : &object::Dynamic,
    key               : object::Key
  ) -> Result <(), Vec <(object::Id, Intersection)>> {
    let mut intersections = Vec::new();
    if object.collidable {
      let aabb_discrete     = object.aabb_dilated();
      let overlaps : Vec <object::Id> = self.broad.overlaps_discrete (aabb_discrete)
        .into_iter().map (object::Id::from).collect::<Vec <_>>();
      for object_id in overlaps {
        let proximity = match object_id.kind {
          object::Kind::Static  => {
            let object_static = &objects_static[object_id.key.index()];
            if !object_static.collidable {
              continue  // skip non-collidable static objects
            }
            Proximity::query (object_static, object)
          }
          object::Kind::Dynamic => {
            let object_dynamic = &objects_dynamic[object_id.key.index()];
            if !object_dynamic.collidable {
              continue  // skip non-collidable dynamic objects
            }
            Proximity::query (object_dynamic, object)
          }
          object::Kind::Nodetect => unreachable!()
        };
        if let Ok (intersection) = proximity.try_into() {
          intersections.push ((object_id, intersection));
        }
      }
    }
    if intersections.is_empty() {
      self.add_object_dynamic (pseudo_velocities, object, key);
      Ok  (())
    } else {
      Err (intersections)
    }
  }

  #[inline]
  pub(crate) fn remove_object_dynamic (&mut self, key : object::Key) {
    debug_assert!(self.pipeline.is_empty());
    let id = InternalId::new_dynamic (key);
    self.broad.remove_object (id);
  }

  #[inline]
  pub(crate) fn update_object_static (&mut self,
    object : &object::Static, key : object::Key
  ) {
    debug_assert!(self.pipeline.is_empty());
    self.broad.update_aabb_static (object.aabb_dilated(), key);
    unimplemented!("TODO: collision detect and resolve any overlaps caused by \
      updating the static object")
  }

  #[inline]
  pub(crate) fn update_object_dynamic (&mut self,
    object : &object::Dynamic, key : object::Key
  ) {
    debug_assert!(self.pipeline.is_empty());
    let aabb = object.aabb_dilated();
    self.broad.update_aabb_dynamic_discrete (aabb, key);
    // TODO: why is the continuous AABB the same as discrete here?
    self.broad.update_aabb_dynamic_continuous (aabb, key);
    log::warn!("TODO: collision detect and resolve any overlaps caused by \
      updating the dynamic object")
  }

  //
  //  Collision::detect_resolve_loop
  //
  /// Main collision loop.
  ///
  /// Before the loop starts, `begin_step()`:
  ///
  /// 1. Update broad-phase AABB data
  ///
  /// Inside the collision loop:
  ///
  /// 1. Perform continuous detection
  /// 2. Resolve earliest detected collision
  ///
  /// After collision loop:
  ///
  /// 1. Drain pipeline outputs (collisions, overlaps, contacts)
  /// 2. Zero pseudovelocities
  pub(crate) fn detect_resolve_loop (&mut self,
    constraint_manager : &mut constraint::Manager,
    objects_static     : &VecMap <object::Static>,
    objects_dynamic    : &mut VecMap <object::Dynamic>,
    step               : u64,
    output             : &mut Vec <event::Output>
  ) {
    log::trace!(step; "detect/resolve loop");

    // initialize collision for the current step
    debug_assert!(self.pipeline.is_empty());
    self.pipeline.detect_resolve_iter = 0;

    // broad: update AABBs based on the given dynamic objects state
    //
    // the continuous (swept) AABBs are calculated from min/max of the previous
    // 'discrete' (instantaneous) AABB and the new "current" discrete AABB
    self.broad.begin_step (objects_dynamic, step);

    // main detect/resolve loop: resolve one collision per iteration
    loop {
      log::debug!(iter=self.pipeline.detect_resolve_iter;
        "detect/resolve loop iteration");
      // detect collisions (TOI contacts)
      self.detect_continuous (constraint_manager, objects_static, objects_dynamic);
      // resolve earliest collision: resolve a velocity constraint at TOI and a
      // position constraint at t==1.0
      if !self.resolve_first_collision (
        constraint_manager, objects_static, objects_dynamic
      ) {
        debug_assert!(self.pipeline.mid_toi_pairs.is_empty());
        debug_assert!(self.pipeline.narrow_toi_contacts.is_empty());
        break
      }
      self.pipeline.detect_resolve_iter += 1;
    }

    log::trace!(iters=self.pipeline.detect_resolve_iter+1;
      "detect/resolve loop complete");
    #[cfg(debug_assertions)]
    {
      if self.detect_resolve_max_iter_count
        < (self.pipeline.detect_resolve_iter + 1)
      {
        #[cfg(feature = "debug_dump")]
        if self.pipeline.detect_resolve_iter >
          DEBUG_DUMP_DETECT_RESOLVE_MAX_ITERS
        {
          DEBUG_DUMP.store (true, atomic::Ordering::SeqCst);
        }
        self.detect_resolve_max_iter_count = self.pipeline.detect_resolve_iter;
      }
      log::debug!(max_iter_count=self.detect_resolve_max_iter_count;
        "detect/resolve loop max iters");
    }

    // output collision events
    for collision_resolve in self.pipeline.resolved_collisions.drain (..) {
      output.push (collision_resolve.into());
    }
    for overlap in self.pipeline.overlaps.drain (..) {
      output.push (overlap.into());
    }

    // output contacts
    constraint_manager.output_contacts (output);

    // zero pseudovelocities
    for (_, pseudovelocity) in constraint_manager.pseudo_velocities.iter_mut() {
      *pseudovelocity = Vector3::zero();
    }

    // done
    debug_assert!(self.pipeline.is_empty());
  }

  //
  //  private methods
  //

  /// Detect TOI (time-of-impact) contacts, i.e. *collisions*.
  fn detect_continuous (&mut self,
    constraint_manager : &constraint::Manager,
    objects_static     : &VecMap <object::Static>,
    objects_dynamic    : &VecMap <object::Dynamic>
  ) {
    // collect broad overlap pairs
    self.broad_overlap_pairs_continuous();
    // mid-phase TOI pairs
    self.mid_toi_pairs (constraint_manager, objects_dynamic);
    // narrow-phase TOI pairs
    self.narrow_toi_contacts (objects_static, objects_dynamic,
      &constraint_manager.pseudo_velocities);
  }

  /// Resolve the first collision (TOI contact pair) in the pipeline, if any, and
  /// returns true, otherwise returns false.
  ///
  /// If impulses do not prevent intersection at t==1.0, post-impulse position
  /// correction will move objects to a distance of `0.5 * CONTACT_DISTANCE` by applying
  /// a pseudo-velocity impulse at the collision TOI.
  ///
  /// This function will be called multiple times in the `detect_resolve_loop()`.
  fn resolve_first_collision (&mut self,
    constraint_manager : &mut constraint::Manager,
    objects_static     : &VecMap <object::Static>,
    objects_dynamic    : &mut VecMap <object::Dynamic>
  ) -> bool {
    if let Some (Reverse ((toi, object_pair, contact))) =
      self.pipeline.narrow_toi_contacts.pop()
    {
      // process the first narrow toi contact (collision): the container is
      // reverse-sorted so we use pop
      let (object_id_a, object_id_b) = object_pair.into();
      let kind_a  = object_id_a.kind();
      let kind_b  = object_id_b.kind();
      let index_a = object_id_a.key().index();
      let index_b = object_id_b.key().index();
      // if one or both objects are not collidable, we report overlap and return
      let collidable = {
        let collidable_a = match kind_a {
          object::Kind::Static   => objects_static[index_a].collidable,
          object::Kind::Dynamic  => objects_dynamic[index_a].collidable,
          object::Kind::Nodetect => unreachable!()
        };
        debug_assert_eq!(kind_b, object::Kind::Dynamic);
        let collidable_b = objects_dynamic[index_b].collidable;
        collidable_a && collidable_b
      };
      if !collidable {
        let overlap = event::Overlap {
          object_id_a: object_id_a.into(),
          object_id_b: object_id_b.into()
        };
        log::debug!(toi=*toi, overlap:?; "nocollide overlap");
        self.pipeline.overlaps.push (overlap);
        return true
      }
      log::debug!(toi=*toi, object_pair:?=(object_id_a, object_id_b);
        "resolve collision");
      // get persistant contact islands
      let maybe_island_a = constraint_manager.get_island_key (object_id_a);
      let maybe_island_b = {
        let maybe_island_b = constraint_manager.get_island_key (object_id_b);
        if maybe_island_a == maybe_island_b {
          // if the islands are the same, then just use island a
          None
        } else {
          maybe_island_b
        }
      };
      // resolve collision
      let collision_resolve = self.resolve_collision (
        constraint_manager, objects_static, objects_dynamic, toi, object_id_a,
        object_id_b, contact, maybe_island_a, maybe_island_b);
      log::trace!(collision_resolve:?; "resolved collision");
      self.pipeline.resolved_collisions.push (collision_resolve);
      true
    } else {
      // no narrow toi contact to process, return false
      debug_assert!(self.pipeline.mid_toi_pairs.is_empty());
      false
    }
  }

  #[expect(clippy::too_many_arguments)]
  fn resolve_collision (
    &mut self,
    constraint_manager : &mut constraint::Manager,
    objects_static     : &VecMap <object::Static>,
    objects_dynamic    : &mut VecMap <object::Dynamic>,
    toi                : Normalized <f64>,
    object_id_a        : InternalId,
    object_id_b        : InternalId,
    collision          : constraint::Contact,
    island_key_a       : Option <constraint::island::KeyType>,
    island_key_b       : Option <constraint::island::KeyType>
  ) -> event::CollisionResolve {
    // 1. lerp all involved dynamic objects to the TOI
    // 2. constrain velocities
    // 3. lerp to T==1.0
    // 4. constrain positions
    // 5. create or destroy persistent contacts from final proximity check
    // 6. update AABBs in broad pipeline
    use num::Zero;
    let mut dynamic_ids = SortedSet::new();
    if object_id_a.kind() == object::Kind::Dynamic {
      dynamic_ids.push (object_id_a);
    }
    dynamic_ids.push (object_id_b);
    let mut islands = constraint_manager.islands.take().unwrap();
    let island_a    = island_key_a.map (|key| &islands[key as usize]);
    let island_b    = island_key_b.map (|key| &islands[key as usize]);
    island_a.map (|island| dynamic_ids.extend (island.dynamic_ids().into_vec()));
    island_b.map (|island| dynamic_ids.extend (island.dynamic_ids().into_vec()));
    // track whether a dynamic object was modified; if so it will need to be removed
    // from intermediate results in the pipeline and checked for new collisions
    let mut dynamic_modified = SortedSet::new();
    // 1. lerp to TOI
    let lerp_objects = |objects_dynamic : &mut VecMap <object::Dynamic>, time_delta|
      for id in dynamic_ids.iter() {
        let index          = id.key().index();
        let object         = &mut objects_dynamic[index];
        let pseudovelocity = constraint_manager.pseudo_velocities[index];
        object::lerp (object, pseudovelocity, time_delta);
      };
    let (t_reverse, t_forward) = {
      let toi_f64 : f64 = *toi;   // [0.0, 1.0]
      (-1.0 + toi_f64, 1.0 - toi_f64)
    };
    lerp_objects (objects_dynamic, t_reverse);
    let toi_aabbs = dynamic_ids.iter().map (|id|{
      let index = id.key().index();
      objects_dynamic[index].aabb_dilated()
    }).collect::<Vec <_>>();
    // 2. constrain velocities
    let constrain_velocity = |
      objects_dynamic  : &mut VecMap <object::Dynamic>,
      pseudovelocities : &VecMap <Vector3 <f64>>,
      constraint       : constraint::Variant,
      colliding        : bool,
      object_id_a      : InternalId,
      object_id_b      : InternalId
    | {
      let key_a    = object_id_a.key();
      let key_b    = object_id_b.key();
      let index_a  = key_a.index();
      let index_b  = key_b.index();
      let (mut object_a, object_a_restitution) = match object_id_a.kind() {
        object::Kind::Static   => {
          let object      = objects_static[index_a].clone();
          let restitution = object.material.restitution;
          (Either::Left (object), restitution)
        }
        object::Kind::Dynamic  => {
          let object      = objects_dynamic[index_a].clone();
          let restitution = object.material.restitution;
          (Either::Right (object), restitution)
        }
        object::Kind::Nodetect => unreachable!()
      };
      debug_assert_eq!(object_id_b.kind(), object::Kind::Dynamic);
      let mut object_b = objects_dynamic[index_b].clone();
      let restitution  = if colliding {
        object_a_restitution * object_b.material.restitution
      } else {
        Normalized::zero()
      };
      let pseudovelocity_a = if object_id_a.kind() == object::Kind::Dynamic {
        Some (pseudovelocities[index_a])
      } else {
        None
      };
      let pseudovelocity_b = pseudovelocities[index_b];
      let maybe_impulses = match constraint {
        constraint::Variant::Contact (contact) =>
          contact.constrain_velocity_with_restitution (
            object_a.as_mut().map_left (|object_static| &*object_static),
            &mut object_b, pseudovelocity_a, pseudovelocity_b, restitution),
        constraint::Variant::Distance (distance) => distance.constrain_velocity (
          object_a.as_mut().map_left (|object_static| &*object_static),
          &mut object_b, pseudovelocity_a, pseudovelocity_b)
      };
      if maybe_impulses.is_some() {
        match object_a {
          Either::Right (object_a) => objects_dynamic[index_a] = object_a,
          Either::Left  (_)        => {}
        }
        objects_dynamic[index_b] = object_b;
      }
      maybe_impulses
    };
    let mut impulse_normal_a  = Vector3::zero();
    let mut impulse_normal_b  = Vector3::zero();
    let mut impulse_tangent_a = Vector3::zero();
    let mut impulse_tangent_b = Vector3::zero();
    let mut iter = 0;
    loop {
      let mut satisfied = true;
      if let Some (impulses) = constrain_velocity (
        objects_dynamic, &constraint_manager.pseudo_velocities, collision.clone().into(),
        true, object_id_a, object_id_b
      ) {
        impulse_normal_a  += impulses.impulse_normal_a;
        impulse_normal_b  += impulses.impulse_normal_b;
        impulse_tangent_a += impulses.impulse_tangent_a;
        impulse_tangent_b += impulses.impulse_tangent_b;
      }
      let mut constrain_island = |island : &constraint::Island| {
        for (object_pair, constraint) in island.constraints.iter().cloned() {
          let (object_id_a, object_id_b) = object_pair.into();
          if constrain_velocity (
            objects_dynamic, &constraint_manager.pseudo_velocities, constraint, false,
            object_id_a, object_id_b
          ).is_some() {
            if object_id_a.kind() == object::Kind::Dynamic {
              dynamic_modified.push (object_id_a);
            }
            dynamic_modified.push (object_id_b);
            satisfied = false;
          }
        }
      };
      if let Some (island) = island_a {
        constrain_island (island);
      }
      if let Some (island) = island_b {
        constrain_island (island);
      }
      iter += 1;
      if satisfied {
        log::debug!(iters=iter; "collision velocity constraint satisfied");
        break
      }
    }
    // 3. lerp to T==1.0
    lerp_objects (objects_dynamic, t_forward);
    // 4. constrain positions
    let constrain_position = |
      objects_dynamic  : &mut VecMap <object::Dynamic>,
      pseudovelocities : &mut VecMap <Vector3 <f64>>,
      constraint       : &mut constraint::Variant,
      object_id_a      : InternalId,
      object_id_b      : InternalId
    | {
      let key_a    = object_id_a.key();
      let key_b    = object_id_b.key();
      let index_a  = key_a.index();
      let index_b  = key_b.index();
      let mut object_a = match object_id_a.kind() {
        object::Kind::Static   => Either::Left  (objects_static[index_a].clone()),
        object::Kind::Dynamic  => Either::Right (objects_dynamic[index_a].clone()),
        object::Kind::Nodetect => unreachable!()
      };
      debug_assert_eq!(object_id_b.kind(), object::Kind::Dynamic);
      let mut object_b = objects_dynamic[index_b].clone();
      let mut pseudovelocity_a = if object_id_a.kind() == object::Kind::Dynamic {
        Some (pseudovelocities[index_a])
      } else {
        None
      };
      let mut pseudovelocity_b = pseudovelocities[index_b];
      let maybe_impulses = constraint.constrain_position (
        t_reverse, object_a.as_mut().map_left (|object_static| &*object_static),
        &mut object_b, pseudovelocity_a.as_mut(), &mut pseudovelocity_b);
      if maybe_impulses.is_some() {
        match object_a {
          Either::Right (object_a) => {
            objects_dynamic[index_a]  = object_a;
            pseudovelocities[index_a] = pseudovelocity_a.unwrap();
          }
          Either::Left  (_) => {}
        }
        objects_dynamic[index_b]  = object_b;
        pseudovelocities[index_b] = pseudovelocity_b;
      }
      maybe_impulses
    };
    // contact index and final proximity result
    let mut pseudo_impulse_a  = Vector3::zero();
    let mut pseudo_impulse_b  = Vector3::zero();
    let mut iter = 0;
    let mut collision_constraint = constraint::Variant::from (collision.clone());
    loop {
      let mut satisfied = true;
      let maybe_impulses = constrain_position (
        objects_dynamic, &mut constraint_manager.pseudo_velocities,
        &mut collision_constraint, object_id_a, object_id_b);
      if let Some (impulses) = maybe_impulses {
        pseudo_impulse_a += impulses.pseudo_impulse_a;
        pseudo_impulse_b += impulses.pseudo_impulse_b;
      }
      let mut constrain_island = |island : &mut constraint::Island|
        for (object_pair, constraint) in island.constraints.iter_mut() {
          let (object_id_a, object_id_b) = (*object_pair).into();
          let maybe_impulses = constrain_position (
            objects_dynamic, &mut constraint_manager.pseudo_velocities, constraint,
            object_id_a, object_id_b
          );
          if maybe_impulses.is_some() {
            if object_id_a.kind() == object::Kind::Dynamic {
              dynamic_modified.push (object_id_a);
            }
            dynamic_modified.push (object_id_b);
            satisfied = false;
          }
        };
      if let Some (key) = island_key_a {
        constrain_island (&mut islands[key as usize]);
      }
      if let Some (key) = island_key_b {
        constrain_island (&mut islands[key as usize]);
      }
      iter += 1;
      if satisfied {
        log::debug!(iters=iter; "collision position constraint satisfied");
        break
      }
    }
    constraint_manager.islands = Some (islands);
    // 5. create or destroy persistent contacts from final proximity check;
    // also add resolved pairs to the broad phase here since we are iterating over
    // constraint islands one last time
    let object_pair = (object_id_a, object_id_b).into();
    if !impulse_normal_b.is_zero() || !impulse_tangent_b.is_zero() ||
      !pseudo_impulse_b.is_zero()
    {
      if object_id_a.kind() == object::Kind::Dynamic {
        debug_assert!(!impulse_normal_a.is_zero() ||
          !impulse_tangent_a.is_zero() || !pseudo_impulse_a.is_zero());
        dynamic_modified.push (object_id_a);
      }
      dynamic_modified.push (object_id_b);
    }
    self.broad.add_resolved (object_pair);
    // wait until after updating islands to create the new contact in case the islands
    // are merged by adding the contact, which would invalidate one of the old island
    // keys
    let mut update_island = |island_key : constraint::island::KeyType| {
      let mut islands = constraint_manager.islands.take().unwrap();
      let island = &mut islands[island_key as usize];
      let mut remove_contacts = vec![];
      for (constraint_index, (object_pair, contact)) in island.constraints.iter()
        .enumerate().filter_map (|(index, (pair, constraint))|
          if let constraint::Variant::Contact (contact) = constraint {
            Some ((index, (pair, contact)))
          } else {
            None
          }
        )
      {
        self.broad.add_resolved (*object_pair);
        if contact.distance >= CONTACT_DISTANCE {
          remove_contacts.push (constraint_index as u32)
        }
      }
      if !remove_contacts.is_empty() {
        constraint_manager.remove_constraints (island, remove_contacts.as_slice());
        if island.constraints.is_empty() {
          let _ = islands.take (island_key as usize).unwrap();
        } else {
          let partitions = island.partition();
          if !partitions.is_empty() {
            let _ = islands.take (island_key as usize).unwrap();
            for new_island in partitions {
              let dynamic_ids = new_island.dynamic_ids();
              let island_key  = islands.put (new_island) as constraint::island::KeyType;
              for dynamic_id in dynamic_ids.into_vec() {
                constraint_manager.change_dynamic_island_key (dynamic_id, island_key);
              }
            }
          }
        }
      }
      constraint_manager.islands = Some (islands);
    };
    if let Some (island_key) = island_key_a {
      update_island (island_key);
    }
    if let Some (island_key) = island_key_b {
      update_island (island_key);
    }
    let constraint::Variant::Contact (contact) = collision_constraint
      else { unreachable!() };
    if contact.distance < CONTACT_DISTANCE {
      debug_assert!(contact.distance >= 0.0);
      log::trace!(object_pair:?, contact:?; "creating contact @ T==1.0");
      constraint_manager.add_constraint (object_pair, contact.into());
    }
    // 6. update AABBs in broad pipeline;
    // also remove resolved dynamic objects from intermediate pipeline results
    for id in dynamic_modified.iter() {
      let i = dynamic_ids.binary_search_by_key (&id, |x| x).unwrap();
      let key    = id.key();
      let index  = key.index();
      let object = &objects_dynamic[index];
      let aabb_discrete   = object.aabb_dilated();
      let aabb_continuous = Aabb3::union (toi_aabbs[i], aabb_discrete);
      self.broad.update_aabb_dynamic_discrete (aabb_discrete, key);
      self.broad.update_aabb_dynamic_continuous (aabb_continuous, key);
    }
    self.pipeline.remove_resolved_dynamic (&dynamic_modified);
    // TODO: update the modified set in-place ?
    self.broad.set_modified (dynamic_modified);
    // result
    let object_id_a = object_id_a.into();
    let object_id_b = object_id_b.into();
    event::CollisionResolve {
      toi, collision,
      object_id_a,       object_id_b,
      impulse_normal_a,  impulse_normal_b,
      impulse_tangent_a, impulse_tangent_b,
      pseudo_impulse_a,  pseudo_impulse_b
    }
  }

  /// Detects AABB overlap pairs of static/dynamic and dynamic/dynamic objects.
  ///
  /// Excludes Nocollide pairs that were already detected but does not filter
  /// object pairs that are already in persistent contacts.
  #[inline]
  fn broad_overlap_pairs_continuous (&mut self) {
    self.broad.overlap_pairs_continuous (
      &mut self.pipeline.broad_overlap_pairs, self.pipeline.detect_resolve_iter);
    // exclude nocollide pairs that were already detected
    self.pipeline.broad_overlap_pairs.retain (
      |pair|{
        let (id_a, id_b) = (*pair).into();
        let id_a = object::Id::from (id_a);
        let id_b = object::Id::from (id_b);
        for event::Overlap { object_id_a, object_id_b } in
          self.pipeline.overlaps.iter()
        {
          if object_id_a == &id_a && object_id_b == &id_b {
            return false
          }
        }
        true
      }
    );
    log::trace!(overlap_pairs:?=self.pipeline.broad_overlap_pairs;
      "broad overlap pairs");
  }

  /// Collects swept AABB TOIs from broad overlap pairs.
  ///
  /// Filters pairs that are already in persistent contact.
  ///
  /// Note that the algorithm will aim for a distance of `0.5 * CONTACT_DISTANCE` at
  /// each TOI.
  fn mid_toi_pairs (&mut self,
    constraint_manager : &constraint::Manager,
    objects_dynamic    : &VecMap <object::Dynamic>
  ) {
    use sorted_vec::FindOrInsert;
    let last_toi = self.pipeline.resolved_collisions.last()
      .map_or (0.0, |collision_resolve| *collision_resolve.toi);
    'outer: for object_pair in self.pipeline.broad_overlap_pairs.drain (..) {
      let (object_id_a, object_id_b) = object_pair.into();
      debug_assert_eq!(object_id_b.kind(), object::Kind::Dynamic);
      match object_id_a.kind() {
        //
        //  static v. dynamic
        //
        object::Kind::Static => {
          let id_static     = object::Id::from (object_id_a);
          let id_dynamic    = object::Id::from (object_id_b);
          let key_static    = id_static.key;
          let key_dynamic   = id_dynamic.key;
          let _index_static = key_static.index();
          let index_dynamic = key_dynamic.index();
          if let (Some (static_contact_count), Some (dynamic_island_key)) = (
            constraint_manager.get_constraint_count (object_id_a),
            constraint_manager.get_island_key (object_id_b)
          ) {
            debug_assert!(static_contact_count > 0);
            let island = constraint_manager.get_island (dynamic_island_key).unwrap();
            for (pair, _) in island.constraints.iter() {
              if *pair == object_pair {
                continue 'outer
              }
            }
          }
          // should be safe to unwrap
          let dynamic_object         = &objects_dynamic[index_dynamic];
          let dynamic_velocity       = dynamic_object.derivatives.velocity;
          let dynamic_pseudovelocity = constraint_manager.pseudo_velocities[index_dynamic];
          let dynamic_velocity_effective = dynamic_velocity + dynamic_pseudovelocity;
          let static_aabb            = self.broad.get_aabb_static (key_static);
          let dynamic_aabb_current   = self.broad
            .get_aabb_dynamic_discrete (key_dynamic);
          let _dynamic_aabb_swept    = self.broad
            .get_aabb_dynamic_continuous (key_dynamic);
          let dynamic_aabb_previous  = Aabb3::with_minmax_unchecked (
            dynamic_aabb_current.min() - dynamic_velocity_effective,
            dynamic_aabb_current.max() - dynamic_velocity_effective);
          // NB: div by zero will result in `inf` values
          let dynamic_velocity_effective_reciprocal = dynamic_velocity_effective.recip();
          // these values adjust start/end times to avoid getting too close
          let t_margin_x =
            (0.5 * CONTACT_DISTANCE * dynamic_velocity_effective_reciprocal.x).abs();
          let t_margin_y =
            (0.5 * CONTACT_DISTANCE * dynamic_velocity_effective_reciprocal.y).abs();
          let t_margin_z =
            (0.5 * CONTACT_DISTANCE * dynamic_velocity_effective_reciprocal.z).abs();

          let (interval_start_x, interval_end_x) = if
            dynamic_velocity_effective.x == 0.0
          {
            debug_assert!(
              dynamic_aabb_current.max().0.x > static_aabb.min().0.x &&
              static_aabb.max().0.x > dynamic_aabb_current.min().0.x);
            debug_assert!(
              dynamic_aabb_previous.max().0.x > static_aabb.min().0.x &&
              static_aabb.max().0.x > dynamic_aabb_previous.min().0.x);
            (f64::NEG_INFINITY, f64::INFINITY)
          } else if dynamic_velocity_effective.x > 0.0 {
            ( //(static_aabb.min().0.x - dynamic_aabb_previous.max().0.x) *
              //  dynamic_velocity_effective_reciprocal.x - t_margin_x,
              (static_aabb.min().0.x - dynamic_aabb_previous.max().0.x)
                .mul_add (dynamic_velocity_effective_reciprocal.x, -t_margin_x),
              //(static_aabb.max().0.x - dynamic_aabb_previous.min().0.x) *
              //  dynamic_velocity_effective_reciprocal.x + t_margin_x
              (static_aabb.max().0.x - dynamic_aabb_previous.min().0.x)
                .mul_add (dynamic_velocity_effective_reciprocal.x, t_margin_x)
            )
          } else {
            debug_assert!(dynamic_velocity_effective.x < 0.0);
            ( //(static_aabb.max().0.x - dynamic_aabb_previous.min().0.x) *
              //  dynamic_velocity_effective_reciprocal.x - t_margin_x,
              (static_aabb.max().0.x - dynamic_aabb_previous.min().0.x)
                .mul_add (dynamic_velocity_effective_reciprocal.x, -t_margin_x),
              //(static_aabb.min().0.x - dynamic_aabb_previous.max().0.x) *
              //  dynamic_velocity_effective_reciprocal.x + t_margin_x
              (static_aabb.min().0.x - dynamic_aabb_previous.max().0.x)
                .mul_add (dynamic_velocity_effective_reciprocal.x, t_margin_x)
            )
          };

          let (interval_start_y, interval_end_y) = if
            dynamic_velocity_effective.y == 0.0
          {
            debug_assert!(
              dynamic_aabb_current.max().0.y > static_aabb.min().0.y &&
              static_aabb.max().0.y > dynamic_aabb_current.min().0.y);
            debug_assert!(
              dynamic_aabb_previous.max().0.y > static_aabb.min().0.y &&
              static_aabb.max().0.y > dynamic_aabb_previous.min().0.y);
            (f64::NEG_INFINITY, f64::INFINITY)
          } else if dynamic_velocity_effective.y > 0.0 {
            ( //dynamic_velocity_effective_reciprocal.y *
              //  (static_aabb.min().0.y - dynamic_aabb_previous.max().0.y) - t_margin_y,
              dynamic_velocity_effective_reciprocal.y.mul_add (
                static_aabb.min().0.y - dynamic_aabb_previous.max().0.y, -t_margin_y),
              //dynamic_velocity_effective_reciprocal.y *
              //  (static_aabb.max().0.y - dynamic_aabb_previous.min().0.y) + t_margin_y
              dynamic_velocity_effective_reciprocal.y.mul_add (
                static_aabb.max().0.y - dynamic_aabb_previous.min().0.y, t_margin_y)
            )
          } else {
            debug_assert!(dynamic_velocity_effective.y < 0.0);
            ( //dynamic_velocity_effective_reciprocal.y *
              //  (static_aabb.max().0.y - dynamic_aabb_previous.min().0.y) - t_margin_y,
              dynamic_velocity_effective_reciprocal.y.mul_add (
                static_aabb.max().0.y - dynamic_aabb_previous.min().0.y, -t_margin_y),
              //dynamic_velocity_effective_reciprocal.y *
              //  (static_aabb.min().0.y - dynamic_aabb_previous.max().0.y) + t_margin_y
              dynamic_velocity_effective_reciprocal.y.mul_add (
                static_aabb.min().0.y - dynamic_aabb_previous.max().0.y, t_margin_y)
            )
          };

          let (interval_start_z, interval_end_z) = if
            dynamic_velocity_effective.z == 0.0
          {
            debug_assert!(
              dynamic_aabb_current.max().0.z > static_aabb.min().0.z &&
              static_aabb.max().0.z > dynamic_aabb_current.min().0.z);
            debug_assert!(
              dynamic_aabb_previous.max().0.z > static_aabb.min().0.z &&
              static_aabb.max().0.z > dynamic_aabb_previous.min().0.z);
            (f64::NEG_INFINITY, f64::INFINITY)
          } else if dynamic_velocity_effective.z > 0.0 {
            ( //dynamic_velocity_effective_reciprocal.z *
              //  (static_aabb.min().0.z - dynamic_aabb_previous.max().0.z) - t_margin_z,
              dynamic_velocity_effective_reciprocal.z.mul_add (
                static_aabb.min().0.z - dynamic_aabb_previous.max().0.z, -t_margin_z),
              //dynamic_velocity_effective_reciprocal.z *
              //  (static_aabb.max().0.z - dynamic_aabb_previous.min().0.z) + t_margin_z
              dynamic_velocity_effective_reciprocal.z.mul_add (
                static_aabb.max().0.z - dynamic_aabb_previous.min().0.z, t_margin_z)
            )
          } else {
            debug_assert!(dynamic_velocity_effective.z < 0.0);
            ( //dynamic_velocity_effective_reciprocal.z *
              //  (static_aabb.max().0.z - dynamic_aabb_previous.min().0.z) - t_margin_z,
              dynamic_velocity_effective_reciprocal.z.mul_add (
                static_aabb.max().0.z - dynamic_aabb_previous.min().0.z, -t_margin_z),
              //dynamic_velocity_effective_reciprocal.z *
              //  (static_aabb.min().0.z - dynamic_aabb_previous.max().0.z) + t_margin_z
              dynamic_velocity_effective_reciprocal.z.mul_add (
                static_aabb.min().0.z - dynamic_aabb_previous.max().0.z, t_margin_z)
            )
          };

          let interval = {
            let interval_xy =
              if interval_start_x < interval_end_y && interval_start_y < interval_end_x {
                Some ((
                  f64::max (interval_start_x, interval_start_y),
                  f64::min (interval_end_x, interval_end_y)
                ))
              } else {
                None
              };
            if let Some ((interval_start_xy, interval_end_xy)) = interval_xy {
              if interval_start_xy < interval_end_z &&
                 interval_start_z  < interval_end_xy
              {
                Some ((
                  f64::max (interval_start_xy, interval_start_z),
                  f64::min (interval_end_xy, interval_end_z)
                ))
              } else {
                None
              }
            } else {
              None
            }
          };

          if let Some ((interval_start, interval_end)) = interval &&
            interval_start < 1.0 && 0.0 < interval_end
          {
            let mid_toi_pair = (
              Normalized::clamp (f64::max (interval_start, last_toi)),
              Normalized::clamp (interval_end),
              object_pair
            );
            match self.pipeline.mid_toi_pairs.find_or_insert (Reverse (mid_toi_pair)) {
              FindOrInsert::Inserted (_) => {}
              FindOrInsert::Found    (_) => unreachable!()
            }
          }
        }
        //
        //  dynamic v. dynamic
        //
        object::Kind::Dynamic => {
          let key_a   = object_id_a.key();
          let key_b   = object_id_b.key();
          let index_a = key_a.index();
          let index_b = key_b.index();
          if let (Some (island_key_a), Some (island_key_b)) = (
            constraint_manager.get_island_key (object_id_a),
            constraint_manager.get_island_key (object_id_b)
          ) && island_key_a == island_key_b {
            let island = constraint_manager.get_island (island_key_a).unwrap();
            for (pair, _) in island.constraints.iter() {
              if *pair == object_pair {
                continue 'outer
              }
            }
          }
          // should be safe to unwrap: objects should not be destroyed during
          // collision detection
          let object_a          = &objects_dynamic[index_a];
          let object_b          = &objects_dynamic[index_b];
          let velocity_a        = object_a.derivatives.velocity;
          let velocity_b        = object_b.derivatives.velocity;
          let pseudovelocity_a  = constraint_manager.pseudo_velocities[key_a.index()];
          let pseudovelocity_b  = constraint_manager.pseudo_velocities[key_b.index()];
          let velocity_effective_a = velocity_a + pseudovelocity_a;
          let velocity_effective_b = velocity_b + pseudovelocity_b;
          let velocity_effective_relative =
            velocity_effective_a - velocity_effective_b;
          let velocity_effective_relative_reciprocal =
            velocity_effective_relative.recip();
          let aabb_current_a    = self.broad.get_aabb_dynamic_discrete   (key_a);
          let aabb_current_b    = self.broad.get_aabb_dynamic_discrete   (key_b);
          let _aabb_swept_a     = self.broad.get_aabb_dynamic_continuous (key_a);
          let _aabb_swept_b     = self.broad.get_aabb_dynamic_continuous (key_b);
          let aabb_previous_a   = Aabb3::with_minmax_unchecked (
            aabb_current_a.min() - velocity_effective_a,
            aabb_current_a.max() - velocity_effective_a);
          let aabb_previous_b   = Aabb3::with_minmax_unchecked (
            aabb_current_b.min() - velocity_effective_b,
            aabb_current_b.max() - velocity_effective_b);

          // compute overlap time start/end interval for the given axis
          let overlap_interval_axis = |axis : Axis3| {
            let axis_index = axis as usize;
            // div by zero will result in `inf` values; t_margin adjusts
            // start/end times to avoid getting too close
            let t_margin = (0.5 * CONTACT_DISTANCE *
              velocity_effective_relative_reciprocal[axis_index]).abs();
            let velocity_relative = velocity_effective_relative[axis_index];
            let velocity_relative_reciprocal =
              velocity_effective_relative_reciprocal[axis_index];
            let prev_a_min = aabb_previous_a.min().0[axis_index];
            let prev_a_max = aabb_previous_a.max().0[axis_index];
            let prev_b_min = aabb_previous_b.min().0[axis_index];
            let prev_b_max = aabb_previous_b.max().0[axis_index];
            if velocity_relative == 0.0 {
              // NOTE: even though the relative velocity is zero, the previous AABBs may
              // not be overlapping due to rounding errors; we will still consider the
              // begin/end time to be infinite
              geometry::Interval::with_minmax_unchecked (
                f64::NEG_INFINITY, f64::INFINITY)
            } else if velocity_relative > 0.0 {
              geometry::Interval::with_minmax_unchecked (
                //(prev_b_min - prev_a_max) * velocity_relative_reciprocal - t_margin,
                (prev_b_min - prev_a_max)
                  .mul_add (velocity_relative_reciprocal, -t_margin),
                //(prev_b_max - prev_a_min) * velocity_relative_reciprocal + t_margin
                (prev_b_max - prev_a_min)
                  .mul_add (velocity_relative_reciprocal, t_margin)
              )
            } else {
              debug_assert!(velocity_relative < 0.0);
              geometry::Interval::with_minmax_unchecked (
                //(prev_b_max - prev_a_min) * velocity_relative_reciprocal - t_margin,
                (prev_b_max - prev_a_min)
                  .mul_add (velocity_relative_reciprocal, -t_margin),
                //(prev_b_min - prev_a_max) * velocity_relative_reciprocal + t_margin
                (prev_b_min - prev_a_max)
                  .mul_add (velocity_relative_reciprocal, t_margin)
              )
            }
          };
          let overlap_interval_x = overlap_interval_axis (Axis3::X);
          let overlap_interval_y = overlap_interval_axis (Axis3::Y);
          let overlap_interval_z = overlap_interval_axis (Axis3::Z);

          if let Some (interval) = overlap_interval_x.intersection (overlap_interval_y)
            .and_then (|overlap_interval_xy|
              overlap_interval_xy.intersection (overlap_interval_z))
            && interval.min() < 1.0 && 0.0 < interval.max()
          {
            let mid_toi_pair = (
              Normalized::clamp (f64::max (interval.min(), last_toi)),
              Normalized::clamp (interval.max()),
              object_pair
            );
            match self.pipeline.mid_toi_pairs.find_or_insert (Reverse (mid_toi_pair)) {
              FindOrInsert::Inserted (_) => {}
              FindOrInsert::Found    (_) => unreachable!()
            }
          }
        }
        object::Kind::Nodetect => unreachable!()
      }
    }

    log::trace!(mid_toi_pairs:?=self.pipeline.mid_toi_pairs; "mid TOI pairs");

    self.pipeline.broad_overlap_pairs.clear();
  }

  /// Returns narrow TOI pairs.
  ///
  /// Note that the algorithm will aim for a distance of `0.5 * CONTACT_DISTANCE` at
  /// each TOI.
  fn narrow_toi_contacts (&mut self,
    objects_static    : &VecMap <object::Static>,
    objects_dynamic   : &VecMap <object::Dynamic>,
    pseudo_velocities : &VecMap <Vector3 <f64>>
  ) {
    use sorted_vec::FindOrInsert;

    let narrow_toi_contacts = &mut self.pipeline.narrow_toi_contacts;
    while let Some (mid_toi_pair) = self.pipeline.mid_toi_pairs.last().copied() {
      let earliest_toi_contact = if !narrow_toi_contacts.is_empty() {
        narrow_toi_contacts[0].0.0
      } else {
        Normalized::clamp (1.0)
      };

      if mid_toi_pair.0.0 < earliest_toi_contact {
        let (mid_toi_start, _mid_toi_end, object_pair) = mid_toi_pair.0;
        let (object_id_a, object_id_b) = object_pair.into();
        let kind_a  = object_id_a.kind();
        let kind_b  = object_id_b.kind();
        match (kind_a, kind_b) {
          (object::Kind::Static, object::Kind::Dynamic) => {
            let key_static    = object_id_a.key();
            let key_dynamic   = object_id_b.key();
            let index_static  = key_static.index();
            let index_dynamic = key_dynamic.index();
            // safe to unwrap
            let mut dynamic_object         = objects_dynamic[index_dynamic].clone();
            let dynamic_velocity           = dynamic_object.derivatives.velocity;
            let dynamic_pseudovelocity     = pseudo_velocities[index_dynamic];
            let dynamic_velocity_effective = dynamic_velocity - dynamic_pseudovelocity;
            let static_object              = objects_static[index_static].clone();
            let mut narrow_toi             = *mid_toi_start;
            // rewind object to the narrow_toi: the object is currently at
            // t==1.0, so we are lerping a negative value
            object::lerp (&mut dynamic_object, dynamic_pseudovelocity, -1.0 + narrow_toi);
            let mut t_remaining = 1.0 - narrow_toi;
            #[expect(clippy::used_underscore_binding)]
            let mut _iter       = 0;
            loop {
              #[cfg(debug_assertions)]
              if self.narrow_toi_max_iter_count < _iter {
                self.narrow_toi_max_iter_count = _iter;
              }
              let proximity = Proximity::query (&static_object, &dynamic_object);
              if cfg!(debug_assertions) &&
                dynamic_object.collidable && static_object.collidable
              {
                debug_assert!(proximity.distance >= 0.0,
                  "objects should not be overlapping, distance: {}", proximity.distance);
              }
              let dynamic_velocity_effective_normal =
                dynamic_velocity_effective.dot (-*proximity.normal);
              if dynamic_velocity_effective_normal > 0.0 &&
                dynamic_object.collidable && static_object.collidable
              {
                // no collision: separating velocity zero or positive
                log::trace!(
                  t=narrow_toi, velocity=dynamic_velocity_effective_normal;
                  "collision rejected, separating velocity");
                break
              } else if proximity.distance < CONTACT_DISTANCE {
                debug_assert!(dynamic_velocity_effective_normal <= 0.0 ||
                  !dynamic_object.collidable || !static_object.collidable);
                // collision: toi contact
                log::trace!(t=narrow_toi, proximity:?; "collision detected");
                // TODO: it appears that sometimes the proximity distance can be
                // negative here, is that correct?
                // let collision = constraint::Contact::try_from (proximity).unwrap();
                let collision = constraint::Contact {
                  normal:   proximity.normal,
                  distance: proximity.distance
                };
                let narrow_toi_contact = Reverse ((
                  Normalized::noisy (narrow_toi), object_pair, collision
                ));
                match narrow_toi_contacts.find_or_insert (narrow_toi_contact) {
                  FindOrInsert::Inserted (_) => {}
                  FindOrInsert::Found    (_) => unreachable!()
                }
                break
              } else if dynamic_velocity_effective_normal == 0.0 {
                log::trace!(
                  t=narrow_toi, velocity=dynamic_velocity_effective_normal;
                  "collision rejected, zero relative velocity and objects not \
                  in contact");
                break
              }
              let dynamic_velocity_effective_normal_reciprocal =
                1.0 / dynamic_velocity_effective_normal;
              let toi_axis =
                //narrow_toi +
                //(proximity.distance - 0.5 * CONTACT_DISTANCE) *
                //(-dynamic_velocity_effective_normal_reciprocal);
                0.5f64.mul_add (-CONTACT_DISTANCE, proximity.distance)
                  .mul_add (-dynamic_velocity_effective_normal_reciprocal, narrow_toi);
              debug_assert!(toi_axis > narrow_toi ||
                !dynamic_object.collidable || !static_object.collidable);
              if toi_axis > 1.0 || toi_axis < 0.0 {
                // no collision this step
                log::trace!(t=narrow_toi, proximity:?;
                  "collision rejected, final proximity");
                break
              }
              let t_advance = toi_axis - narrow_toi;
              object::lerp (&mut dynamic_object, dynamic_pseudovelocity, t_advance);
              narrow_toi    = toi_axis;
              t_remaining   -= t_advance;
              debug_assert!(t_remaining > 0.0);
              _iter += 1;
            }
          }

          (object::Kind::Dynamic, object::Kind::Dynamic) => {
            let key_a   = object_id_a.key();
            let key_b   = object_id_b.key();
            let index_a = key_a.index();
            let index_b = key_b.index();
             // safe to unwrap: objects should not be destroyed during collision
             // detection
            let mut object_a         = objects_dynamic[index_a].clone();
            let mut object_b         = objects_dynamic[index_b].clone();
            let pseudovelocity_a     = pseudo_velocities[index_a];
            let pseudovelocity_b     = pseudo_velocities[index_b];
            let velocity_a           = object_a.derivatives.velocity;
            let velocity_b           = object_b.derivatives.velocity;
            let velocity_effective_a = velocity_a + pseudovelocity_a;
            let velocity_effective_b = velocity_b + pseudovelocity_b;
            let velocity_effective_relative =
              velocity_effective_a - velocity_effective_b;
            let mut narrow_toi  = *mid_toi_start;
            let mut t_remaining = 1.0 - narrow_toi;
            object::lerp (&mut object_a, pseudovelocity_a, -1.0 + narrow_toi);
            object::lerp (&mut object_b, pseudovelocity_b, -1.0 + narrow_toi);
            loop {
              debug_assert!(narrow_toi <= 1.0);
              debug_assert!(t_remaining >= 0.0);
              let proximity = Proximity::query (&object_a, &object_b);
              if cfg!(debug_assertions) && object_a.collidable && object_b.collidable {
                debug_assert!(proximity.distance >= 0.0);
              }
              let velocity_effective_relative_normal =
                velocity_effective_relative.dot (*proximity.normal);
              if velocity_effective_relative_normal > 0.0 &&
                object_a.collidable && object_b.collidable
              {
                // no collision: separating velocity zero or positive
                log::trace!(
                  t=narrow_toi, velocity=velocity_effective_relative_normal;
                  "collision rejected, separating velocity");
                break
              } else if proximity.distance < CONTACT_DISTANCE {
                debug_assert!(velocity_effective_relative_normal <= 0.0 ||
                  !object_a.collidable || !object_b.collidable);
                // collision: toi contact
                log::trace!(t=narrow_toi, proximity:?; "collision detected");
                let contact = constraint::Contact::try_from (proximity).unwrap();
                let narrow_toi_contact = Reverse ((
                  Normalized::noisy (narrow_toi), object_pair, contact
                ));
                match narrow_toi_contacts.find_or_insert (narrow_toi_contact) {
                  FindOrInsert::Inserted (_) => {}
                  FindOrInsert::Found    (_) => unreachable!()
                }
                break
              } else if velocity_effective_relative_normal == 0.0 {
                log::trace!(
                  t=narrow_toi, velocity=velocity_effective_relative_normal;
                  "collision rejected, zero relative velocity and objects not in \
                  contact");
                break
              }
              let velocity_effective_relative_normal_reciprocal =
                1.0 / velocity_effective_relative_normal;
              let toi_axis =
                //narrow_toi +
                //(proximity.distance - 0.5 * CONTACT_DISTANCE) *
                //(-velocity_effective_relative_normal_reciprocal);
                0.5f64.mul_add (-CONTACT_DISTANCE, proximity.distance)
                  .mul_add (-velocity_effective_relative_normal_reciprocal, narrow_toi);
              debug_assert!(toi_axis > narrow_toi ||
                !object_a.collidable || !object_b.collidable);
              if toi_axis > 1.0 || toi_axis < 0.0 {
                // no collision this step
                log::trace!(t=narrow_toi, proximity:?;
                  "collision rejected, final proximity");
                break
              }
              let t_advance = toi_axis - narrow_toi;
              object::lerp (&mut object_a, pseudovelocity_a, t_advance);
              object::lerp (&mut object_b, pseudovelocity_b, t_advance);
              narrow_toi    = toi_axis;
              t_remaining   -= t_advance;
            }
          }
          _ => unreachable!()
        }
        self.pipeline.mid_toi_pairs.pop();
      } else { break }
    }
    #[cfg(debug_assertions)]
    log::debug!(max_iter_count=self.narrow_toi_max_iter_count;
      "narrow TOI max iters");
    log::trace!(contacts:?=narrow_toi_contacts; "narrow TOI contacts");
  }

  #[inline]
  fn add_object_static (&mut self,
    object     : &object::Static,
    object_key : object::Key,
  ) {
    self.broad.add_object_static (object.aabb_dilated(), object_key);
  }

  #[inline]
  fn add_object_dynamic (&mut self,
    pseudo_velocities : &mut VecMap <Vector3 <f64>>,
    object            : &object::Dynamic,
    object_key        : object::Key
  ) {
    let aabb_discrete   = object.aabb_dilated();
    let aabb_continuous = Aabb3::with_minmax_unchecked (
      aabb_discrete.min() - object.derivatives.velocity,
      aabb_discrete.max() - object.derivatives.velocity);
    // NOTE: this swept AABB should not be seen by the next continuous collision
    // detection/resolution loop since `begin_step()` will re-calculate for the next
    // frame
    self.broad.add_object_dynamic (aabb_discrete, aabb_continuous, object_key);
    assert!(pseudo_velocities.insert (object_key.index(), Vector3::zero()).is_none());
  }

}

impl Pipeline {
  #[inline]
  fn is_empty (&self) -> bool {
    self.broad_overlap_pairs.is_empty() &&
    self.mid_toi_pairs.is_empty() &&
    self.narrow_toi_contacts.is_empty() &&
    self.resolved_collisions.is_empty() &&
    self.overlaps.is_empty()
  }

  /// After a collision is resolved, all modified (dynamic) objects should be removed
  /// from intermediate results in the pipeline:
  ///
  /// - `mid_toi_pairs`
  /// - `narrow_toi_contacts`
  ///
  /// These objects will be checked for overlaps in the broad phase of the next
  /// detect/resolve loop iteration.
  // TODO: because we are only removing resolved dynamic objects and the resolved list
  // is sorted, we could be slicing the resolved set to only contain the dynamic ids and
  // exclude the static ids from binary search
  #[inline]
  fn remove_resolved_dynamic (&mut self, resolved : &SortedSet <InternalId>) {
    debug_assert!(self.broad_overlap_pairs.is_empty());

    let (mut i, mut len);

    // remove intermediate mid TOI pairs
    i   = 0;
    len = self.mid_toi_pairs.len();
    while i < len {
      let (_, _, object_pair) = self.mid_toi_pairs[i].0;
      let (id_a, id_b) = object_pair.into();
      if id_a.kind() == object::Kind::Dynamic && resolved.binary_search (&id_a).is_ok() {
        self.mid_toi_pairs.remove_index (i);
        len -= 1;
        continue
      }
      debug_assert_eq!(id_b.kind(), object::Kind::Dynamic);
      if resolved.binary_search (&id_b).is_ok() {
        self.mid_toi_pairs.remove_index (i);
        len -= 1;
        continue
      }
      i += 1;
    }

    // remove intermediate narrow TOI contacts
    i   = 0;
    len = self.narrow_toi_contacts.len();
    while i < len {
      let (_, object_pair, _) = self.narrow_toi_contacts[i].clone().0;
      let (id_a, id_b) = object_pair.into();
      if id_a.kind() == object::Kind::Dynamic && resolved.binary_search (&id_a).is_ok() {
        self.narrow_toi_contacts.remove_index (i);
        len -= 1;
        continue
      }
      debug_assert_eq!(id_b.kind(), object::Kind::Dynamic);
      if resolved.binary_search (&id_b).is_ok() {
        self.narrow_toi_contacts.remove_index (i);
        len -= 1;
        continue
      }
      i += 1;
    }
  }
}