@series-inc/rundot-syncplay 6.0.0-rc.60 → 6.0.0-rc.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,6 +3,7 @@
3
3
 
4
4
  #include <algorithm>
5
5
  #include <cmath>
6
+ #include <cstdlib>
6
7
  #include <stdexcept>
7
8
 
8
9
  namespace rundot::kinetix::physics {
@@ -552,17 +553,25 @@ bool finiteSixDofValues(const std::array<double, Size>& values) {
552
553
  });
553
554
  }
554
555
 
555
- bool validSixDofPreparedRow(const ConstraintRow6& row) {
556
+ // Every row field except the accumulated impulse.
557
+ bool validSixDofPreparedRowFields(const ConstraintRow6& row) {
556
558
  const auto& scalar = row.scalar;
557
559
  return finiteSixDofValues(row.jacobianA) && finiteSixDofValues(row.jacobianB)
558
560
  && finiteSixDofValues(row.angularResponseA) && finiteSixDofValues(row.angularResponseB)
559
561
  && std::isfinite(scalar.effectiveMass) && std::isfinite(scalar.bias)
560
562
  && std::isfinite(scalar.massScale) && std::isfinite(scalar.impulseScale)
561
- && std::isfinite(scalar.accumulatedImpulse)
562
563
  && !std::isnan(scalar.lower) && !std::isnan(scalar.upper)
563
564
  && scalar.lower <= scalar.upper;
564
565
  }
565
566
 
567
+ bool validSixDofPreparedRow(const ConstraintRow6& row) {
568
+ return validSixDofPreparedRowFields(row) && std::isfinite(row.scalar.accumulatedImpulse);
569
+ }
570
+
571
+ SixDofResponseStatus recordSixDofConstraintImpulseChecked(
572
+ SixDofConstraintImpulseHistory& history, const ConstraintRow6& row,
573
+ const SixDofConstraintRowMetadata& metadata, double appliedImpulse, bool rowFieldsValid);
574
+
566
575
  } // namespace
567
576
 
568
577
  SixDofResponseStatus sixDofReactionMagnitudes(
@@ -659,9 +668,23 @@ SixDofResponseStatus refreshSixDofConstraintRows(
659
668
  SixDofResponseStatus recordSixDofConstraintImpulse(
660
669
  SixDofConstraintImpulseHistory& history, const ConstraintRow6& row,
661
670
  const SixDofConstraintRowMetadata& metadata, double appliedImpulse) {
671
+ return recordSixDofConstraintImpulseChecked(history, row, metadata, appliedImpulse,
672
+ validSixDofPreparedRowFields(row));
673
+ }
674
+
675
+ namespace {
676
+
677
+ // The solve loop records every row on every iteration, and the full row check was most of the
678
+ // record cost. rowFieldsValid is validSixDofPreparedRowFields(row), computed once per rebuild.
679
+ SixDofResponseStatus recordSixDofConstraintImpulseChecked(
680
+ SixDofConstraintImpulseHistory& history, const ConstraintRow6& row,
681
+ const SixDofConstraintRowMetadata& metadata, double appliedImpulse, bool rowFieldsValid) {
682
+ #if defined(RUNDOT_PHYSICS_DEBUG_INVARIANTS)
683
+ if (rowFieldsValid != validSixDofPreparedRowFields(row)) std::abort();
684
+ #endif
662
685
  const std::uint32_t slot = sixDofHistorySlot(metadata);
663
686
  if (slot == history.rows.size()) return SixDofResponseStatus::InvalidState;
664
- if (!std::isfinite(appliedImpulse) || !validSixDofPreparedRow(row)) {
687
+ if (!std::isfinite(appliedImpulse) || !rowFieldsValid || !std::isfinite(row.scalar.accumulatedImpulse)) {
665
688
  return SixDofResponseStatus::Unrepresentable;
666
689
  }
667
690
  // Stage only the values that change; `history` stays untouched on every failure path.
@@ -687,6 +710,8 @@ SixDofResponseStatus recordSixDofConstraintImpulse(
687
710
  return SixDofResponseStatus::Success;
688
711
  }
689
712
 
713
+ } // namespace
714
+
690
715
  SixDofSubstepParticipant::SixDofSubstepParticipant(
691
716
  std::span<const SixDofConstraint> constraints,
692
717
  std::span<SixDofConstraintOutput> outputs, bool eventCapable)
@@ -696,6 +721,8 @@ SixDofSubstepParticipant::SixDofSubstepParticipant(
696
721
  }
697
722
  rows_.reserve(constraints.size() * kMaxSixDofRows);
698
723
  metadata_.reserve(constraints.size() * kMaxSixDofRows);
724
+ // Preparation must not allocate (a retry after an allocation failure keeps no orphan rows).
725
+ rowFieldsValid_.reserve(constraints.size() * kMaxSixDofRows);
699
726
  ranges_.resize(constraints.size());
700
727
  stagedOutputs_.resize(constraints.size());
701
728
  if (eventCapable) {
@@ -753,6 +780,7 @@ std::int32_t SixDofSubstepParticipant::invoke(SubstepConstraintPhase phase,
753
780
  for (auto& row : state.rows_) {
754
781
  if (!prepareConstraintRow(row, context.mobility)) return 3;
755
782
  }
783
+ state.rowFieldsValid_.assign(state.rows_.size(), 0);
756
784
  state.phase_ = Phase::Ready;
757
785
  return 0;
758
786
  case SubstepConstraintPhase::RefreshEventGeometry:
@@ -778,6 +806,7 @@ std::int32_t SixDofSubstepParticipant::invoke(SubstepConstraintPhase phase,
778
806
  state.rows_.swap(state.stagedRows_);
779
807
  state.metadata_.swap(state.stagedMetadata_);
780
808
  state.ranges_.swap(state.stagedRanges_);
809
+ state.rowFieldsValid_.assign(state.rows_.size(), 0);
781
810
  state.geometryRefreshed_ = true;
782
811
  return 0;
783
812
  case SubstepConstraintPhase::SolveIteration:
@@ -792,8 +821,10 @@ std::int32_t SixDofSubstepParticipant::invoke(SubstepConstraintPhase phase,
792
821
  const double applied = solveConstraintRow(row, context.bodies, context.mobility);
793
822
  if (!std::isfinite(row.scalar.accumulatedImpulse)) return 3;
794
823
  if (state.eventCapable_) {
795
- const auto status = recordSixDofConstraintImpulse(
796
- state.histories_[index], row, state.metadata_[offset], applied);
824
+ auto& known = state.rowFieldsValid_[offset];
825
+ if (known == 0) known = validSixDofPreparedRowFields(row) ? 1 : 2;
826
+ const auto status = recordSixDofConstraintImpulseChecked(
827
+ state.histories_[index], row, state.metadata_[offset], applied, known == 1);
797
828
  if (status != SixDofResponseStatus::Success) {
798
829
  return status == SixDofResponseStatus::Unrepresentable ? 7 : 3;
799
830
  }
@@ -826,8 +857,10 @@ std::int32_t SixDofSubstepParticipant::invoke(SubstepConstraintPhase phase,
826
857
  const double adjustment = row.scalar.accumulatedImpulse - previous;
827
858
  applyConstraintRowImpulse(row, context.bodies, context.mobility, adjustment);
828
859
  if (state.eventCapable_) {
829
- const auto status = recordSixDofConstraintImpulse(
830
- state.histories_[index], row, metadata, adjustment);
860
+ auto& known = state.rowFieldsValid_[offset];
861
+ if (known == 0) known = validSixDofPreparedRowFields(row) ? 1 : 2;
862
+ const auto status = recordSixDofConstraintImpulseChecked(
863
+ state.histories_[index], row, metadata, adjustment, known == 1);
831
864
  if (status != SixDofResponseStatus::Success) {
832
865
  return status == SixDofResponseStatus::Unrepresentable ? 7 : 3;
833
866
  }
@@ -186,6 +186,9 @@ class SixDofSubstepParticipant {
186
186
  std::vector<std::array<std::uint32_t, 2>> ranges_, stagedRanges_;
187
187
  std::vector<SixDofConstraintImpulseHistory> histories_;
188
188
  std::vector<SixDofConstraintOutput> stagedOutputs_;
189
+ // Per row: 0 not checked, 1 valid, 2 invalid, for every field except the accumulated impulse
190
+ // (the only field a solve iteration changes). Reset when the rows are rebuilt.
191
+ std::vector<std::uint8_t> rowFieldsValid_;
189
192
  double duration_ = 0.0;
190
193
  std::uint32_t substep_ = 0;
191
194
  bool eventCapable_ = false;
@@ -190,6 +190,15 @@ struct SolverOperation {
190
190
  const SubstepConstraintHook* proxyHook = nullptr;
191
191
  double restitutionThreshold = 0.0;
192
192
  std::uint32_t stepSubsteps = 1;
193
+ // Memo generation of this operation (0 until its first frozen-pair collide). See collide().
194
+ std::uint64_t collideMemoGeneration = 0;
195
+ // Motion enclosure memo generation of this operation (0 until first use). See encloseBodyMotionEpoch().
196
+ std::uint64_t enclosureMemoGeneration = 0;
197
+ // isSmallDynamicWorld() for the body array it was computed on; body kinds do not change
198
+ // within an operation, so the answer holds while the array is the same.
199
+ mutable const void* smallDynamicWorldBodies = nullptr;
200
+ mutable std::size_t smallDynamicWorldCount = 0;
201
+ mutable bool smallDynamicWorldValue = false;
193
202
  };
194
203
 
195
204
  struct JointConstraintState {
@@ -3927,6 +3936,18 @@ struct SolverStorage {
3927
3936
  std::vector<std::uint8_t> movingFoundation;
3928
3937
  // Dynamic-dynamic pairs that the collecting contact iteration solves after the support pairs.
3929
3938
  std::vector<std::uint64_t> deferredDynamicPairs;
3939
+ // collide() results of frozen pairs (see collide()), valid within one solver operation.
3940
+ struct CollideMemoEntry {
3941
+ std::uint64_t generation = 0;
3942
+ std::uint8_t flags = 0;
3943
+ Body a;
3944
+ Body b;
3945
+ Collision result;
3946
+ };
3947
+ std::vector<CollideMemoEntry> collideMemo;
3948
+ std::uint64_t collideMemoGeneration = 0;
3949
+ std::uint64_t collideMemoCountGeneration = 0;
3950
+ std::uint32_t collideMemoCount = 0;
3930
3951
  struct RestingSubstepPairCacheEntry {
3931
3952
  std::uint64_t pairKey = 0;
3932
3953
  std::uint32_t outputIndex = 0;
@@ -4789,6 +4810,8 @@ void SolverStorage::invalidate(bool keepBroadphaseTree) noexcept {
4789
4810
  contactSupported.clear();
4790
4811
  movingFoundation.clear();
4791
4812
  deferredDynamicPairs.clear();
4813
+ collideMemo.clear();
4814
+ collideMemoCount = 0;
4792
4815
  restingSubstepPairCount = 0;
4793
4816
  restingSubstepPairCursor = 0;
4794
4817
  firstSubstepOfTick = false;
@@ -4848,6 +4871,7 @@ std::uint64_t SolverStorage::retainedBytes() const noexcept {
4848
4871
  + retainedVectorBytes(contactSupported)
4849
4872
  + retainedVectorBytes(movingFoundation)
4850
4873
  + retainedVectorBytes(deferredDynamicPairs)
4874
+ + retainedVectorBytes(collideMemo)
4851
4875
  + retainedVectorBytes(restingSubstepPairCache)
4852
4876
  + retainedVectorBytes(componentHasJoint)
4853
4877
  + retainedVectorBytes(componentHasActive)
@@ -5609,7 +5633,7 @@ bool usesStackSolverPath(const SolverOperation& operation, std::uint32_t bodyCou
5609
5633
  && isSmallDynamicWorld(operation);
5610
5634
  }
5611
5635
 
5612
- bool isSmallDynamicWorld(const SolverOperation& operation) {
5636
+ bool computeSmallDynamicWorld(const SolverOperation& operation) {
5613
5637
  if (operation.storage.soaBodies.empty()) return false;
5614
5638
  if (operation.storage.soaBodies.size() <= 16) return true;
5615
5639
  std::uint32_t dynamicCount = 0;
@@ -5622,7 +5646,209 @@ bool isSmallDynamicWorld(const SolverOperation& operation) {
5622
5646
  return dynamicCount > 0;
5623
5647
  }
5624
5648
 
5649
+ // The narrowphase asks this once per box pair, compound children included, and the scan walks the
5650
+ // body array until it finds 17 dynamic bodies. Body kinds do not change within an operation, so the
5651
+ // answer is kept for the operation while its body array is the same.
5652
+ bool isSmallDynamicWorld(const SolverOperation& operation) {
5653
+ const auto& bodies = operation.storage.soaBodies;
5654
+ if (operation.smallDynamicWorldBodies != bodies.data()
5655
+ || operation.smallDynamicWorldCount != bodies.size()) {
5656
+ operation.smallDynamicWorldValue = computeSmallDynamicWorld(operation);
5657
+ operation.smallDynamicWorldBodies = bodies.data();
5658
+ operation.smallDynamicWorldCount = bodies.size();
5659
+ }
5660
+ RUNDOT_PHYSICS_DEBUG_ASSERT(operation.smallDynamicWorldValue == computeSmallDynamicWorld(operation));
5661
+ return operation.smallDynamicWorldValue;
5662
+ }
5663
+
5664
+ Collision collideUncached(SolverOperation& operation, const Body& a, const Body& b);
5665
+
5666
+ namespace {
5667
+
5668
+ // Nested collide() calls (compound children) do not use the memo.
5669
+ std::uint32_t g_collideDepth = 0;
5670
+
5671
+ struct CollideDepthScope {
5672
+ CollideDepthScope() { g_collideDepth += 1; }
5673
+ ~CollideDepthScope() { g_collideDepth -= 1; }
5674
+ CollideDepthScope(const CollideDepthScope&) = delete;
5675
+ CollideDepthScope& operator=(const CollideDepthScope&) = delete;
5676
+ };
5677
+
5678
+ // A body that cannot move during the operation: static, or dynamic and asleep, and not kinematic.
5679
+ bool frozenForCollideMemo(const Body& body) {
5680
+ return !body.kinematic && (!body.dynamic || body.sleeping);
5681
+ }
5682
+
5683
+ // The operation state that the triangle adapter changes inside collide(): every adapter step charges
5684
+ // the work meter, and the exact arithmetic and staging budget start lazily. A collide() that leaves
5685
+ // all of it unchanged had no side effect, so a later identical call may skip it.
5686
+ struct CollideSideEffects {
5687
+ std::uint64_t remainingWork = 0;
5688
+ std::uint64_t stagingRemaining = 0;
5689
+ std::size_t relativeContacts = 0;
5690
+ bool arithmetic = false;
5691
+ bool operator==(const CollideSideEffects&) const = default;
5692
+ };
5693
+
5694
+ CollideSideEffects collideSideEffects(const SolverOperation& operation) {
5695
+ return {operation.triangleQuota.remainingWork, operation.triangleStagingRemaining,
5696
+ operation.relativeContacts.size(), operation.triangleArithmetic.has_value()};
5697
+ }
5698
+
5699
+ bool sameBits(double left, double right) {
5700
+ return std::bit_cast<std::uint64_t>(left) == std::bit_cast<std::uint64_t>(right);
5701
+ }
5702
+
5703
+ // Every Body field except sleepTime, which the narrowphase does not read. Doubles compare by bits.
5704
+ bool sameCollideInput(const Body& l, const Body& r) {
5705
+ return l.geometryRecord == r.geometryRecord && l.geometrySource == r.geometrySource
5706
+ && l.geometryView.data() == r.geometryView.data() && l.geometryView.size() == r.geometryView.size()
5707
+ && l.geometryFeatureOffset == r.geometryFeatureOffset
5708
+ && std::memcmp(l.id.data, r.id.data, sizeof(l.id.data)) == 0
5709
+ && l.dynamic == r.dynamic && l.kinematic == r.kinematic && l.sensorLike == r.sensorLike
5710
+ && l.trigger == r.trigger && l.sensor == r.sensor && l.sleeping == r.sleeping
5711
+ && l.sleepEnabled == r.sleepEnabled && sameBits(l.sleepThreshold, r.sleepThreshold)
5712
+ && l.masksValid == r.masksValid && l.layer == r.layer && l.mask == r.mask
5713
+ && sameBits(l.mass, r.mass) && sameBits(l.gravityScale, r.gravityScale)
5714
+ && sameBits(l.linearDamping, r.linearDamping) && l.shape == r.shape
5715
+ && sameBits(l.x, r.x) && sameBits(l.y, r.y) && sameBits(l.z, r.z)
5716
+ && sameBits(l.vx, r.vx) && sameBits(l.vy, r.vy) && sameBits(l.vz, r.vz)
5717
+ && sameBits(l.angularVelX, r.angularVelX) && sameBits(l.angularVelY, r.angularVelY)
5718
+ && sameBits(l.angularVelZ, r.angularVelZ)
5719
+ && sameBits(l.orientationX, r.orientationX) && sameBits(l.orientationY, r.orientationY)
5720
+ && sameBits(l.orientationZ, r.orientationZ) && sameBits(l.orientationW, r.orientationW)
5721
+ && sameBits(l.angularDamping, r.angularDamping) && sameBits(l.friction, r.friction)
5722
+ && sameBits(l.restitution, r.restitution) && sameBits(l.rollingResistance, r.rollingResistance)
5723
+ && l.motionLocks == r.motionLocks && l.angularState == r.angularState && l.bullet == r.bullet
5724
+ && l.geometryFormat == r.geometryFormat
5725
+ && sameBits(l.inertiaXX, r.inertiaXX) && sameBits(l.inertiaYY, r.inertiaYY)
5726
+ && sameBits(l.inertiaZZ, r.inertiaZZ) && sameBits(l.inertiaXY, r.inertiaXY)
5727
+ && sameBits(l.inertiaXZ, r.inertiaXZ) && sameBits(l.inertiaYZ, r.inertiaYZ)
5728
+ && sameBits(l.centerOfMassX, r.centerOfMassX) && sameBits(l.centerOfMassY, r.centerOfMassY)
5729
+ && sameBits(l.centerOfMassZ, r.centerOfMassZ)
5730
+ && l.geometryOffset == r.geometryOffset && l.geometryCount == r.geometryCount
5731
+ && sameBits(l.shape0, r.shape0) && sameBits(l.shape1, r.shape1) && sameBits(l.shape2, r.shape2)
5732
+ && sameBits(l.shapeOffsetX, r.shapeOffsetX) && sameBits(l.shapeOffsetY, r.shapeOffsetY)
5733
+ && sameBits(l.shapeOffsetZ, r.shapeOffsetZ);
5734
+ }
5735
+
5736
+ std::uint64_t collideMemoHash(const Body& a, const Body& b) {
5737
+ std::uint64_t hash = 0xcbf29ce484222325ull;
5738
+ for (const double value : {a.x, a.y, a.z, b.x, b.y, b.z}) {
5739
+ hash = (hash ^ std::bit_cast<std::uint64_t>(value)) * 0x100000001b3ull;
5740
+ }
5741
+ return hash ^ (hash >> 29);
5742
+ }
5743
+
5744
+ #if defined(RUNDOT_PHYSICS_DEBUG_INVARIANTS)
5745
+ bool sameCollision(const Collision& l, const Collision& r) {
5746
+ if (l.hit != r.hit || l.pointCount != r.pointCount || l.coordinates.index() != r.coordinates.index()
5747
+ || l.geometryChildIndex != r.geometryChildIndex || l.geometryEndpointA != r.geometryEndpointA
5748
+ || l.featureIds != r.featureIds) return false;
5749
+ for (const auto& [x, y] : {std::pair{l.nx, r.nx}, {l.ny, r.ny}, {l.nz, r.nz}, {l.penetration, r.penetration},
5750
+ {l.pointX, r.pointX}, {l.pointY, r.pointY}, {l.pointZ, r.pointZ}}) {
5751
+ if (!sameBits(x, y)) return false;
5752
+ }
5753
+ for (std::size_t point = 0; point < l.points.size(); ++point) {
5754
+ for (std::size_t axis = 0; axis < 3; ++axis) {
5755
+ if (!sameBits(l.points[point][axis], r.points[point][axis])) return false;
5756
+ }
5757
+ }
5758
+ return true;
5759
+ }
5760
+ #endif
5761
+
5762
+ } // namespace
5763
+
5764
+ // Within one solver operation the same pair of frozen bodies is collided many times (warm start,
5765
+ // the collecting pass of every substep, wake discovery), with identical inputs. collide() returns
5766
+ // the earlier result when both bodies, compared field by field, and the world-level narrowphase
5767
+ // flags are unchanged. A miss computes it, and only a computation without side effects is kept,
5768
+ // so the memo never changes a result or the work meter.
5625
5769
  Collision collide(SolverOperation& operation, const Body& a, const Body& b) {
5770
+ if (g_collideDepth != 0 || operation.materialMotionEpochs != nullptr
5771
+ || !frozenForCollideMemo(a) || !frozenForCollideMemo(b)) {
5772
+ const CollideDepthScope depth;
5773
+ return collideUncached(operation, a, b);
5774
+ }
5775
+ auto& storage = operation.storage;
5776
+ if (operation.collideMemoGeneration == 0) operation.collideMemoGeneration = ++storage.collideMemoGeneration;
5777
+ if (storage.collideMemoCountGeneration != operation.collideMemoGeneration) {
5778
+ storage.collideMemoCountGeneration = operation.collideMemoGeneration;
5779
+ storage.collideMemoCount = 0;
5780
+ }
5781
+ const bool largeStack = !operation.fixedAxisQueryContacts
5782
+ && usesStackSolverPath(operation, static_cast<std::uint32_t>(storage.soaBodies.size()));
5783
+ const bool smallWorld = !operation.fixedAxisQueryContacts && (largeStack || isSmallDynamicWorld(operation));
5784
+ const std::uint8_t flags = static_cast<std::uint8_t>((operation.fixedAxisQueryContacts ? 1 : 0)
5785
+ | (largeStack ? 2 : 0) | (smallWorld ? 4 : 0) | (operation.proxyHook != nullptr ? 8 : 0));
5786
+ constexpr std::size_t kInitialSlots = 256;
5787
+ constexpr std::size_t kMaximumSlots = 4096;
5788
+ constexpr std::size_t kProbe = 8;
5789
+ if (storage.collideMemo.empty()) storage.collideMemo.resize(kInitialSlots);
5790
+ const std::uint64_t hash = collideMemoHash(a, b);
5791
+ const auto findSlot = [&](std::vector<SolverStorage::CollideMemoEntry>& table) -> std::size_t {
5792
+ const std::size_t mask = table.size() - 1;
5793
+ std::size_t open = table.size();
5794
+ for (std::size_t probe = 0; probe < kProbe; ++probe) {
5795
+ const std::size_t slot = (hash + probe) & mask;
5796
+ auto& entry = table[slot];
5797
+ if (entry.generation != operation.collideMemoGeneration) {
5798
+ if (open == table.size()) open = slot;
5799
+ continue;
5800
+ }
5801
+ if (entry.flags == flags && sameCollideInput(entry.a, a) && sameCollideInput(entry.b, b)) return slot;
5802
+ }
5803
+ return open == table.size() ? (hash & mask) : open;
5804
+ };
5805
+ std::size_t slot = findSlot(storage.collideMemo);
5806
+ auto* entry = &storage.collideMemo[slot];
5807
+ if (entry->generation == operation.collideMemoGeneration && entry->flags == flags
5808
+ && sameCollideInput(entry->a, a) && sameCollideInput(entry->b, b)) {
5809
+ #if defined(RUNDOT_PHYSICS_DEBUG_INVARIANTS)
5810
+ {
5811
+ const CollideDepthScope depth;
5812
+ RUNDOT_PHYSICS_DEBUG_ASSERT(sameCollision(entry->result, collideUncached(operation, a, b)));
5813
+ }
5814
+ #endif
5815
+ return entry->result;
5816
+ }
5817
+ Collision result;
5818
+ const CollideSideEffects before = collideSideEffects(operation);
5819
+ {
5820
+ const CollideDepthScope depth;
5821
+ result = collideUncached(operation, a, b);
5822
+ }
5823
+ // Keep only results that cost nothing beyond the return value and carry plain world coordinates.
5824
+ if (!(collideSideEffects(operation) == before) || !std::holds_alternative<WorldContactBasis>(result.coordinates)) {
5825
+ return result;
5826
+ }
5827
+ if (storage.collideMemoCount * 2 >= storage.collideMemo.size() && storage.collideMemo.size() < kMaximumSlots) {
5828
+ std::vector<SolverStorage::CollideMemoEntry> grown(storage.collideMemo.size() * 2);
5829
+ for (auto& old : storage.collideMemo) {
5830
+ if (old.generation != operation.collideMemoGeneration) continue;
5831
+ const std::uint64_t oldHash = collideMemoHash(old.a, old.b);
5832
+ const std::size_t mask = grown.size() - 1;
5833
+ for (std::size_t probe = 0; probe < kProbe; ++probe) {
5834
+ auto& target = grown[(oldHash + probe) & mask];
5835
+ if (target.generation != operation.collideMemoGeneration) { target = std::move(old); break; }
5836
+ }
5837
+ }
5838
+ storage.collideMemo.swap(grown);
5839
+ slot = findSlot(storage.collideMemo);
5840
+ entry = &storage.collideMemo[slot];
5841
+ }
5842
+ if (entry->generation != operation.collideMemoGeneration) storage.collideMemoCount += 1;
5843
+ entry->generation = operation.collideMemoGeneration;
5844
+ entry->flags = flags;
5845
+ entry->a = a;
5846
+ entry->b = b;
5847
+ entry->result = result;
5848
+ return result;
5849
+ }
5850
+
5851
+ Collision collideUncached(SolverOperation& operation, const Body& a, const Body& b) {
5626
5852
 
5627
5853
  if (operation.materialMotionEpochs != nullptr) return collideMaterialCurrent(operation, a, b);
5628
5854
  const auto triangleGeometry = [](const Body& body) { return body.shape == ShapeKind::Mesh || body.shape == ShapeKind::Heightfield || (body.shape == ShapeKind::Compound && body.geometryFormat == 5); };
@@ -11986,13 +12212,14 @@ void resolveSoAContacts(SolverOperation& operation, Body* bodies, std::uint32_t
11986
12212
  // Curved contacts move from tick to tick, so their warm start carries less than a box face's and
11987
12213
  // a stack of cylinders needs more iterations to converge. With six, a five-tire stack still crept
11988
12214
  // at frame 167 (Wreck Yard rc.59 finding 3). The last velocity iteration of a substep ends with
11989
- // enough more passes over the pairs with a cylinder to reach 12 iterations in total; pairs
11990
- // without one are unchanged. Twelve settled every jittered tire run in the corpus. A floor, not
11991
- // a fixed count, keeps every configured count off 8 and 9, where portal and direct pushes
11992
- // already differ (review 10). The owned (joint and portal) path runs one iteration per call, so
12215
+ // enough more passes over the pairs with a cylinder to reach 24 iterations in total; pairs
12216
+ // without one are unchanged. Twelve settled every jittered tire run in the corpus; 24 also
12217
+ // shortens the small-world (sweep) tail, where 8 of 192 runs took over 90 frames at 12 and 3 at
12218
+ // 24. A floor, not a fixed count, keeps every configured count off 8 and 9, where portal and
12219
+ // direct pushes already differ (review 10). The owned (joint and portal) path runs one iteration per call, so
11993
12220
  // its loop marks the last call, and the extra passes come before that iteration's joint and
11994
12221
  // portal work, as on the standalone path.
11995
- constexpr std::uint32_t kCylinderMinimumVelocityIterations = 12;
12222
+ constexpr std::uint32_t kCylinderMinimumVelocityIterations = 24;
11996
12223
  const std::uint32_t cylinderExtraVelocityIterations =
11997
12224
  options.velocityIterations < kCylinderMinimumVelocityIterations
11998
12225
  ? kCylinderMinimumVelocityIterations - options.velocityIterations : 0;
@@ -13341,9 +13568,123 @@ enum class MotionEnclosureStatus : std::uint8_t {
13341
13568
  Prepared, InvalidInput, Unresolved, ResourceExhausted,
13342
13569
  };
13343
13570
 
13571
+ MotionEnclosureStatus encloseBodyMotionEpochUncached(SolverOperation& operation,
13572
+ const BodyMotionEpoch& epoch, const Body& definition, double low, double high,
13573
+ MotionPoseEnclosure& output);
13574
+
13575
+ namespace {
13576
+
13577
+ bool sameEnclosureEpoch(const BodyMotionEpoch& l, const BodyMotionEpoch& r) {
13578
+ const auto same = [](const auto& a, const auto& b) {
13579
+ for (std::size_t index = 0; index < a.size(); ++index) {
13580
+ if (std::bit_cast<std::uint64_t>(a[index]) != std::bit_cast<std::uint64_t>(b[index])) return false;
13581
+ }
13582
+ return true;
13583
+ };
13584
+ return sameBits(l.originTime, r.originTime) && same(l.origin.position, r.origin.position)
13585
+ && same(l.origin.orientation, r.origin.orientation) && same(l.linearVelocity, r.linearVelocity)
13586
+ && same(l.angularVelocity, r.angularVelocity) && same(l.centerOfMass, r.centerOfMass)
13587
+ && l.motionLocks == r.motionLocks && l.dynamic == r.dynamic && l.kinematic == r.kinematic
13588
+ && l.sleeping == r.sleeping;
13589
+ }
13590
+
13591
+ struct EnclosureMemoEntry {
13592
+ std::uint64_t generation = 0;
13593
+ BodyMotionEpoch epoch;
13594
+ Body definition;
13595
+ double low = 0.0;
13596
+ double high = 0.0;
13597
+ std::uint64_t charged = 0;
13598
+ MotionPoseEnclosure result;
13599
+ };
13600
+
13601
+ // Unique per solver operation across every world, so no entry outlives its operation.
13602
+ std::uint64_t g_enclosureMemoGenerations = 0;
13603
+
13604
+ } // namespace
13605
+
13606
+ // The bullet-pair search encloses both bodies' motion over the substep interval, and every bullet
13607
+ // is paired with every body: a 500-body world with 4 bullets enclosed each bullet about 500 times
13608
+ // per substep over the same interval. Within one operation an enclosure is a pure function of the
13609
+ // epoch, the body and the interval, plus a work-meter charge. A repeat with bit-equal inputs returns
13610
+ // the earlier result and deducts the same charge, when the meter can pay all of it (the original
13611
+ // could not fail part way then). Otherwise, or after any other side effect, it is computed again.
13344
13612
  MotionEnclosureStatus encloseBodyMotionEpoch(SolverOperation& operation,
13345
13613
  const BodyMotionEpoch& epoch, const Body& definition, double low, double high,
13346
13614
  MotionPoseEnclosure& output) {
13615
+ thread_local std::vector<EnclosureMemoEntry> table;
13616
+ thread_local std::uint32_t counted = 0;
13617
+ thread_local std::uint64_t countedGeneration = 0;
13618
+ constexpr std::size_t kSlots = 1024;
13619
+ constexpr std::size_t kProbe = 8;
13620
+ if (operation.enclosureMemoGeneration == 0) operation.enclosureMemoGeneration = ++g_enclosureMemoGenerations;
13621
+ const std::uint64_t generation = operation.enclosureMemoGeneration;
13622
+ if (countedGeneration != generation) { countedGeneration = generation; counted = 0; }
13623
+ if (table.empty()) table.resize(kSlots);
13624
+ std::uint64_t hash = 0xcbf29ce484222325ull;
13625
+ for (const double value : {low, high, epoch.originTime, epoch.origin.position[0], epoch.origin.position[1],
13626
+ epoch.origin.position[2], definition.x, definition.y, definition.z}) {
13627
+ hash = (hash ^ std::bit_cast<std::uint64_t>(value)) * 0x100000001b3ull;
13628
+ }
13629
+ hash ^= hash >> 29;
13630
+ const std::size_t mask = table.size() - 1;
13631
+ std::size_t open = table.size();
13632
+ for (std::size_t probe = 0; probe < kProbe; ++probe) {
13633
+ EnclosureMemoEntry& entry = table[(hash + probe) & mask];
13634
+ if (entry.generation != generation) {
13635
+ if (open == table.size()) open = (hash + probe) & mask;
13636
+ continue;
13637
+ }
13638
+ if (!sameBits(entry.low, low) || !sameBits(entry.high, high) || !sameEnclosureEpoch(entry.epoch, epoch)
13639
+ || !sameCollideInput(entry.definition, definition)) continue;
13640
+ if (operation.triangleQuota.remainingWork < entry.charged) break;
13641
+ #if defined(RUNDOT_PHYSICS_DEBUG_INVARIANTS)
13642
+ {
13643
+ const std::uint64_t remaining = operation.triangleQuota.remainingWork;
13644
+ MotionPoseEnclosure reference;
13645
+ const auto status = encloseBodyMotionEpochUncached(operation, epoch, definition, low, high, reference);
13646
+ RUNDOT_PHYSICS_DEBUG_ASSERT(status == MotionEnclosureStatus::Prepared);
13647
+ RUNDOT_PHYSICS_DEBUG_ASSERT(remaining - operation.triangleQuota.remainingWork == entry.charged);
13648
+ for (unsigned axis = 0; axis < 3; ++axis) {
13649
+ RUNDOT_PHYSICS_DEBUG_ASSERT(sameBits(reference.position[axis].lower, entry.result.position[axis].lower)
13650
+ && sameBits(reference.position[axis].upper, entry.result.position[axis].upper));
13651
+ }
13652
+ for (unsigned axis = 0; axis < 4; ++axis) {
13653
+ RUNDOT_PHYSICS_DEBUG_ASSERT(sameBits(reference.orientation[axis].lower, entry.result.orientation[axis].lower)
13654
+ && sameBits(reference.orientation[axis].upper, entry.result.orientation[axis].upper));
13655
+ }
13656
+ operation.triangleQuota.remainingWork = remaining;
13657
+ }
13658
+ #endif
13659
+ operation.triangleQuota.remainingWork -= entry.charged;
13660
+ output = entry.result;
13661
+ return MotionEnclosureStatus::Prepared;
13662
+ }
13663
+ const std::uint64_t remainingBefore = operation.triangleQuota.remainingWork;
13664
+ const std::uint64_t stagingBefore = operation.triangleStagingRemaining;
13665
+ const std::size_t relativeBefore = operation.relativeContacts.size();
13666
+ const bool arithmeticBefore = operation.triangleArithmetic.has_value();
13667
+ const auto status = encloseBodyMotionEpochUncached(operation, epoch, definition, low, high, output);
13668
+ if (status != MotionEnclosureStatus::Prepared || operation.triangleStagingRemaining != stagingBefore
13669
+ || operation.relativeContacts.size() != relativeBefore
13670
+ || operation.triangleArithmetic.has_value() != arithmeticBefore
13671
+ || operation.triangleQuota.remainingWork > remainingBefore) return status;
13672
+ std::size_t slot = open == table.size() ? (hash & mask) : open;
13673
+ EnclosureMemoEntry& entry = table[slot];
13674
+ if (entry.generation != generation) counted += 1;
13675
+ entry.generation = generation;
13676
+ entry.epoch = epoch;
13677
+ entry.definition = definition;
13678
+ entry.low = low;
13679
+ entry.high = high;
13680
+ entry.charged = remainingBefore - operation.triangleQuota.remainingWork;
13681
+ entry.result = output;
13682
+ return status;
13683
+ }
13684
+
13685
+ MotionEnclosureStatus encloseBodyMotionEpochUncached(SolverOperation& operation,
13686
+ const BodyMotionEpoch& epoch, const Body& definition, double low, double high,
13687
+ MotionPoseEnclosure& output) {
13347
13688
  using Status = MotionEnclosureStatus;
13348
13689
  using Scalar = MotionIntervalScalar;
13349
13690
  if (!finite(epoch.originTime) || !finite(low) || !finite(high)