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

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.
@@ -1278,6 +1278,9 @@ Collision collide(SolverOperation& operation, const Body& a, const Body& b);
1278
1278
  Collision collideMaterialCurrent(SolverOperation& operation, const Body& a, const Body& b);
1279
1279
  Collision convexSupportCollision(SolverOperation& operation, const Body& a, const Body& b);
1280
1280
  bool robustConvexBodiesOverlap(SolverOperation& operation, const Body& a, const Body& b);
1281
+ bool triangleSoupBody(const Body& body);
1282
+ bool triangleSoupPartner(const Body& body);
1283
+ Collision triangleSoupCollision(SolverOperation& operation, const Body& geometry, const Body& convex);
1281
1284
  struct ToiDistance {
1282
1285
  double distance = 0.0;
1283
1286
  Vec3 normal;
@@ -1988,6 +1991,12 @@ Collision boundsPair(
1988
1991
  }
1989
1992
 
1990
1993
  Collision geometryPair(SolverOperation& operation, const Body& geometryA, const Body& geometryB) {
1994
+ if (!operation.fixedAxisQueryContacts) {
1995
+ if (triangleSoupBody(geometryA) && triangleSoupPartner(geometryB))
1996
+ return triangleSoupCollision(operation, geometryA, geometryB);
1997
+ if (triangleSoupBody(geometryB) && triangleSoupPartner(geometryA))
1998
+ return flipCollision(triangleSoupCollision(operation, geometryB, geometryA));
1999
+ }
1991
2000
  if (geometryA.shape == ShapeKind::Mesh && geometryA.geometryFormat == 2
1992
2001
  && geometryA.geometryCount >= 3 && geometryA.geometryCount % 3 == 0) {
1993
2002
  Collision best;
@@ -2070,6 +2079,8 @@ Collision geometryPair(SolverOperation& operation, const Body& geometryA, const
2070
2079
  }
2071
2080
 
2072
2081
  Collision geometryBox(SolverOperation& operation, const Body& geometry, const Body& box) {
2082
+ if (!operation.fixedAxisQueryContacts && triangleSoupBody(geometry))
2083
+ return triangleSoupCollision(operation, geometry, box);
2073
2084
  if (geometry.shape == ShapeKind::Heightfield && geometry.geometryFormat == 3) {
2074
2085
  if (geometry.geometryCount < 5) return {};
2075
2086
  const std::uint32_t metadata = geometry.geometryOffset * 3;
@@ -2327,12 +2338,12 @@ void collectSupportAxes(const Body& a, const Body& b, const Vec3& centerA, const
2327
2338
  }
2328
2339
  }
2329
2340
 
2330
- bool curvedConvexPair(const Body& a, const Body& b);
2331
- Collision curvedConvexCollision(SolverOperation& operation, const Body& a, const Body& b);
2341
+ bool exactConvexPair(const Body& a, const Body& b);
2342
+ Collision exactConvexCollision(SolverOperation& operation, const Body& a, const Body& b);
2332
2343
 
2333
2344
  Collision convexSupportCollision(SolverOperation& operation, const Body& a, const Body& b) {
2334
2345
  if (!robustConvexBodiesOverlap(operation, a, b)) return {};
2335
- if (curvedConvexPair(a, b) && !operation.fixedAxisQueryContacts) return curvedConvexCollision(operation, a, b);
2346
+ if (exactConvexPair(a, b) && !operation.fixedAxisQueryContacts) return exactConvexCollision(operation, a, b);
2336
2347
 
2337
2348
  const Vec3 centerA{a.x + a.shapeOffsetX, a.y + a.shapeOffsetY, a.z + a.shapeOffsetZ};
2338
2349
  const Vec3 centerB{b.x + b.shapeOffsetX, b.y + b.shapeOffsetY, b.z + b.shapeOffsetZ};
@@ -2360,7 +2371,7 @@ Collision convexSupportCollision(SolverOperation& operation, const Body& a, cons
2360
2371
  // position correction pushes the pair apart with no velocity response
2361
2372
  // left. The closest-core direction is the exact normal. It goes last, so a
2362
2373
  // matching axis above keeps its place and its result. (Simulation contacts
2363
- // with cylinders, cones and tapered capsules take curvedConvexCollision
2374
+ // with cylinders, cones and tapered capsules take exactConvexCollision
2364
2375
  // instead. Overlap and shape cast queries still come here.)
2365
2376
  const bool sphereA = a.shape == ShapeKind::Sphere;
2366
2377
  const bool sphereB = b.shape == ShapeKind::Sphere;
@@ -2419,6 +2430,18 @@ Collision convexSupportCollision(SolverOperation& operation, const Body& a, cons
2419
2430
  const double sign = sphereA ? 1.0 : -1.0;
2420
2431
  bestPointA = addVec3(center, scaleVec3(bestNormal, sign * (sphereA ? radius : coreDistance)));
2421
2432
  bestPointB = addVec3(center, scaleVec3(bestNormal, sign * (sphereA ? coreDistance : radius)));
2433
+ } else if (sphereA != sphereB && !operation.fixedAxisQueryContacts) {
2434
+ // On any other axis the sphere center still fixes both points. The
2435
+ // support midpoint is wrong there: a thin hull wall has a whole side as
2436
+ // its support, so the point lay up to a wall size off the sphere and the
2437
+ // impulse turned into spin (a sphere passed a 0.02 m hull wall at 15 m/s).
2438
+ const Vec3 center = sphereA ? centerA : centerB;
2439
+ const double radius = sphereA ? a.shape0 : b.shape0;
2440
+ const double sign = sphereA ? 1.0 : -1.0;
2441
+ const Vec3 surface = addVec3(center, scaleVec3(bestNormal, sign * radius));
2442
+ const Vec3 inner = subtractVec3(surface, scaleVec3(bestNormal, sign * std::max(0.0, minPenetration)));
2443
+ bestPointA = sphereA ? surface : inner;
2444
+ bestPointB = sphereA ? inner : surface;
2422
2445
  }
2423
2446
 
2424
2447
  return {
@@ -2770,25 +2793,28 @@ bool robustConvexBodiesOverlap(SolverOperation& operation, const Body& a, const
2770
2793
 
2771
2794
  void contactTangentBasis(const Vec3& normal, Vec3& first, Vec3& second);
2772
2795
 
2773
- // Curved convex contacts.
2774
- //
2775
- // The fixed SAT axes above miss the contact normal of a cylinder, cone or
2776
- // tapered capsule in general, so the depth they report is too deep. Bodies
2777
- // on the split contact path (any joint, every portal clone) then lose their
2778
- // velocity response: the position pass pushes the pair fully apart and the
2779
- // velocity pass finds no contact. Pairs with a curved shape therefore also
2780
- // test the exact normal (the closest-core normal when a sphere or capsule
2781
- // core is outside the other shape, else the EPA normal), and build their
2782
- // contact points from the support features along the chosen normal.
2796
+ // Exact convex contacts. The fixed SAT axes above miss the normal of a curved
2797
+ // shape and every hull face, and their support midpoint can lie metres from
2798
+ // both bodies (a far corner of a large hull floor). Pairs with a curved shape
2799
+ // or a hull (a mesh or heightfield triangle is a three-point hull) also test
2800
+ // the exact normal (closest core, else EPA) and take their points from the
2801
+ // support features. Hull-sphere keeps the exact sphere route above.
2783
2802
 
2784
2803
  bool curvedConvexShape(ShapeKind shape) {
2785
2804
  return shape == ShapeKind::Cylinder || shape == ShapeKind::Cone
2786
2805
  || shape == ShapeKind::TaperedCapsule;
2787
2806
  }
2788
2807
 
2789
- bool curvedConvexPair(const Body& a, const Body& b) {
2790
- return (curvedConvexShape(a.shape) || curvedConvexShape(b.shape))
2791
- && toiSupported(a) && toiSupported(b);
2808
+ bool exactConvexPair(const Body& a, const Body& b) {
2809
+ if (!toiSupported(a) || !toiSupported(b)) return false;
2810
+ if (curvedConvexShape(a.shape) || curvedConvexShape(b.shape)) return true;
2811
+ return (a.shape == ShapeKind::Hull || b.shape == ShapeKind::Hull)
2812
+ && a.shape != ShapeKind::Sphere && b.shape != ShapeKind::Sphere;
2813
+ }
2814
+
2815
+ // A hull of three points is a triangle of a mesh or heightfield.
2816
+ bool triangleHull(const Body& body) {
2817
+ return body.shape == ShapeKind::Hull && body.geometryFormat == 0 && body.geometryCount == 3;
2792
2818
  }
2793
2819
 
2794
2820
  Vec3 minkowskiSupport(SolverOperation& operation, const Body& a, const Body& b, const Vec3& direction) {
@@ -3143,6 +3169,23 @@ void hullFeature(SolverOperation& operation, const Body& body, const Vec3& direc
3143
3169
  if (feature.count >= 3) {
3144
3170
  feature.face = true;
3145
3171
  feature.faceNormal = direction;
3172
+ // The true face normal (Newell), not the support direction: the choice
3173
+ // of the reference face compares the two face normals with the contact
3174
+ // normal, and a direction one ulp off flipped that choice between calls,
3175
+ // so the feature ids of one contact changed and its episodes broke.
3176
+ Vec3 newell{};
3177
+ for (std::uint32_t index = 0; index < feature.count; index += 1) {
3178
+ const Vec3& current = feature.points[index];
3179
+ const Vec3& next = feature.points[(index + 1) % feature.count];
3180
+ newell.x += (current.y - next.y) * (current.z + next.z);
3181
+ newell.y += (current.z - next.z) * (current.x + next.x);
3182
+ newell.z += (current.x - next.x) * (current.y + next.y);
3183
+ }
3184
+ const double lengthSq = dotVec3(newell, newell);
3185
+ if (lengthSq > 1e-30) {
3186
+ newell = scaleVec3(newell, 1.0 / solverSqrt(lengthSq));
3187
+ feature.faceNormal = dotVec3(newell, direction) < 0.0 ? scaleVec3(newell, -1.0) : newell;
3188
+ }
3146
3189
  }
3147
3190
  }
3148
3191
 
@@ -3518,7 +3561,7 @@ std::uint32_t diskPatchPoints(const ContactFeature& from, const ContactFeature&
3518
3561
  }
3519
3562
 
3520
3563
  // Contact points for a pair on a known normal (a to b) and depth.
3521
- Collision curvedConvexManifold(SolverOperation& operation, const Body& a, const Body& b,
3564
+ Collision convexFeatureManifold(SolverOperation& operation, const Body& a, const Body& b,
3522
3565
  const Vec3& normal, double penetration) {
3523
3566
  const Vec3 supportA = supportPointForBody(operation, a, normal);
3524
3567
  const Vec3 supportB = supportPointForBody(operation, b, scaleVec3(normal, -1.0));
@@ -3683,13 +3726,33 @@ Collision curvedConvexManifold(SolverOperation& operation, const Body& a, const
3683
3726
  return result;
3684
3727
  }
3685
3728
 
3686
- Collision curvedConvexCollision(SolverOperation& operation, const Body& a, const Body& b) {
3729
+ Collision exactConvexCollision(SolverOperation& operation, const Body& a, const Body& b) {
3687
3730
  const Vec3 centerA{a.x + a.shapeOffsetX, a.y + a.shapeOffsetY, a.z + a.shapeOffsetZ};
3688
3731
  const Vec3 centerB{b.x + b.shapeOffsetX, b.y + b.shapeOffsetY, b.z + b.shapeOffsetZ};
3689
3732
  const Vec3 centerDiff = subtractVec3(centerB, centerA);
3690
3733
  std::array<Vec3, 24> axes{};
3691
3734
  std::uint32_t axisCount = 0;
3692
3735
  collectSupportAxes(a, b, centerA, centerB, centerDiff, axes, axisCount);
3736
+ // A triangle face is an axis too, toward the side of the other center: a
3737
+ // body that rests on a triangle has that face normal as its contact normal.
3738
+ // It is exact, so a near axis does not replace it: on a large triangle an
3739
+ // axis 0.2 degrees off reports a depth 30 times too deep.
3740
+ for (const Body* body : {&a, &b}) {
3741
+ if (!triangleHull(*body) || axisCount >= axes.size()) continue;
3742
+ const auto values = geometryForBody(operation, *body);
3743
+ const std::uint32_t first = body->geometryOffset * 3;
3744
+ std::array<Vec3, 3> corner{};
3745
+ for (std::uint32_t point = 0; point < 3; point += 1) {
3746
+ corner[point] = rotateByOrientation(*body, {values[first + point * 3],
3747
+ values[first + point * 3 + 1], values[first + point * 3 + 2]});
3748
+ }
3749
+ const Vec3 face = crossVec3(subtractVec3(corner[1], corner[0]), subtractVec3(corner[2], corner[0]));
3750
+ const double lengthSq = dotVec3(face, face);
3751
+ if (lengthSq <= 1e-24) continue;
3752
+ Vec3 unit = scaleVec3(face, 1.0 / solverSqrt(lengthSq));
3753
+ if (dotVec3(unit, centerDiff) < 0.0) unit = scaleVec3(unit, -1.0);
3754
+ axes[axisCount++] = unit;
3755
+ }
3693
3756
  if (axisCount == 0) axes[axisCount++] = {1.0, 0.0, 0.0};
3694
3757
 
3695
3758
  double minPenetration = std::numeric_limits<double>::infinity();
@@ -3709,10 +3772,13 @@ Collision curvedConvexCollision(SolverOperation& operation, const Body& a, const
3709
3772
 
3710
3773
  // The exact normal. A sphere or capsule core outside the other shape
3711
3774
  // gives it directly; otherwise EPA finds it. A fixed axis that is as good
3712
- // keeps its place.
3775
+ // keeps its place. A hull pair that touches without overlap (a resting
3776
+ // hull, depth zero) also takes the closest-point normal: EPA needs the
3777
+ // origin enclosed and fails there, and no fixed axis is a hull face.
3713
3778
  Vec3 exact{};
3714
3779
  bool haveExact = false;
3715
- if (toiRadius(a) > 0.0 || toiRadius(b) > 0.0) {
3780
+ const bool hullPair = a.shape == ShapeKind::Hull || b.shape == ShapeKind::Hull;
3781
+ if (toiRadius(a) > 0.0 || toiRadius(b) > 0.0 || hullPair) {
3716
3782
  const ToiDistance core = toiCoreDistance(operation, a, b);
3717
3783
  const double lengthSq = dotVec3(core.normal, core.normal);
3718
3784
  if (!core.overlap && lengthSq > 1e-24) {
@@ -3729,7 +3795,7 @@ Collision curvedConvexCollision(SolverOperation& operation, const Body& a, const
3729
3795
  bestNormal = exact;
3730
3796
  }
3731
3797
  }
3732
- return curvedConvexManifold(operation, a, b, bestNormal, std::max(0.0, minPenetration));
3798
+ return convexFeatureManifold(operation, a, b, bestNormal, std::max(0.0, minPenetration));
3733
3799
  }
3734
3800
 
3735
3801
 
@@ -3933,6 +3999,11 @@ struct SolverStorage {
3933
3999
  std::vector<ContactConstraintBlock> contactConstraints;
3934
4000
  std::vector<double> contactCacheOutput;
3935
4001
  std::vector<std::uint8_t> contactSupported;
4002
+ // Support contacts (lower << 32 | upper) seen by the collecting iteration of this substep. The
4003
+ // first frozen pass marks every body that rests on support through a chain of them
4004
+ // (propagateContactSupport); the collecting order alone missed crates visited before their support.
4005
+ std::vector<std::uint64_t> supportEdges;
4006
+ bool supportPropagated = false;
3936
4007
  std::vector<std::uint8_t> movingFoundation;
3937
4008
  // Dynamic-dynamic pairs that the collecting contact iteration solves after the support pairs.
3938
4009
  std::vector<std::uint64_t> deferredDynamicPairs;
@@ -4808,6 +4879,8 @@ void SolverStorage::invalidate(bool keepBroadphaseTree) noexcept {
4808
4879
  contactConstraints.clear();
4809
4880
  contactCacheOutput.clear();
4810
4881
  contactSupported.clear();
4882
+ supportEdges.clear();
4883
+ supportPropagated = false;
4811
4884
  movingFoundation.clear();
4812
4885
  deferredDynamicPairs.clear();
4813
4886
  collideMemo.clear();
@@ -4869,6 +4942,7 @@ std::uint64_t SolverStorage::retainedBytes() const noexcept {
4869
4942
  + retainedVectorBytes(contactConstraints)
4870
4943
  + retainedVectorBytes(contactCacheOutput)
4871
4944
  + retainedVectorBytes(contactSupported)
4945
+ + retainedVectorBytes(supportEdges)
4872
4946
  + retainedVectorBytes(movingFoundation)
4873
4947
  + retainedVectorBytes(deferredDynamicPairs)
4874
4948
  + retainedVectorBytes(collideMemo)
@@ -5621,11 +5695,215 @@ Collision finalizeCompoundManifold(
5621
5695
  return best;
5622
5696
  }
5623
5697
 
5698
+ // A mesh or heightfield: triangles in a fixed order.
5699
+ bool triangleSoupBody(const Body& body) {
5700
+ return (body.shape == ShapeKind::Mesh && body.geometryFormat == 2 && body.geometryCount >= 3)
5701
+ || (body.shape == ShapeKind::Heightfield && body.geometryFormat == 3 && body.geometryCount >= 5);
5702
+ }
5703
+
5704
+ // The shapes that meet a triangle on the exact convex path. A sphere and a
5705
+ // capsule have their own exact triangle routines.
5706
+ bool triangleSoupPartner(const Body& body) {
5707
+ return toiSupported(body) && body.shape != ShapeKind::Sphere && body.shape != ShapeKind::Capsule;
5708
+ }
5709
+
5710
+ struct SoupTriangle {
5711
+ std::uint32_t index = 0;
5712
+ std::array<Vec3, 3> corner{};
5713
+ };
5714
+
5715
+ // The contact patch of a convex body on the triangles that lie in the contact
5716
+ // plane. The body's support feature against the plane is clipped to each such
5717
+ // triangle, and points within the feature tolerance count, as for one face. So
5718
+ // a patch over a shared triangle edge keeps all its corners, even where the
5719
+ // test of one triangle alone reads a touch at depth zero as a miss (a corner
5720
+ // then went missing and the impulse spun the body). Unclipped points keep the
5721
+ // body feature ids, so the points solve in the order of one face contact.
5722
+ // Returns nothing when no triangle lies in the plane (an edge contact).
5723
+ std::optional<Collision> triangleSoupPatch(SolverOperation& operation, const Body& convex, const Collision& best,
5724
+ std::span<const SoupTriangle> triangles) {
5725
+ const Vec3 normal{best.nx, best.ny, best.nz};
5726
+ const ContactFeature body = supportFeature(operation, convex, scaleVec3(normal, -1.0));
5727
+ struct Point { Vec3 position; std::uint32_t id; double depth; };
5728
+ std::vector<Point> points;
5729
+ for (const SoupTriangle& triangle : triangles) {
5730
+ Vec3 face = crossVec3(subtractVec3(triangle.corner[1], triangle.corner[0]),
5731
+ subtractVec3(triangle.corner[2], triangle.corner[0]));
5732
+ const double lengthSq = dotVec3(face, face);
5733
+ if (lengthSq <= 1e-24) continue;
5734
+ face = scaleVec3(face, 1.0 / solverSqrt(lengthSq));
5735
+ if (dotVec3(face, normal) < 0.0) face = scaleVec3(face, -1.0);
5736
+ const double alignment = dotVec3(face, normal);
5737
+ if (alignment < 0.98) continue;
5738
+ ContactFeature reference;
5739
+ reference.face = true;
5740
+ reference.faceNormal = face;
5741
+ for (std::uint32_t corner = 0; corner < 3; corner += 1) addFeaturePoint(reference, triangle.corner[corner], corner);
5742
+ std::array<FeatureClipVertex, 32> clipped{};
5743
+ const std::uint32_t count = clipFeatureToFace(body, reference, normal, clipped);
5744
+ const double surface = dotVec3(face, triangle.corner[0]);
5745
+ for (std::uint32_t index = 0; index < count; index += 1) {
5746
+ const Vec3& point = clipped[index].point;
5747
+ const double depth = (surface - dotVec3(face, point)) / alignment;
5748
+ if (depth < -featureTolerance) continue;
5749
+ bool bodyFeature = false;
5750
+ for (std::uint32_t corner = 0; corner < body.count; corner += 1) bodyFeature = bodyFeature || body.ids[corner] == clipped[index].id;
5751
+ std::uint32_t id = bodyFeature ? clipped[index].id
5752
+ : clipped[index].id ^ ((triangle.index + 1u) * 2166136261u);
5753
+ const Vec3 position = addVec3(point, scaleVec3(normal, 0.5 * depth));
5754
+ bool coincident = false;
5755
+ for (const Point& other : points) {
5756
+ const Vec3 delta = subtractVec3(position, other.position);
5757
+ coincident = coincident || dotVec3(delta, delta) <= 1e-12;
5758
+ }
5759
+ if (coincident) continue;
5760
+ // The ids of one manifold are distinct (each keys a contact episode). A
5761
+ // body corner inside two triangles that are not coplanar gives two
5762
+ // places with one id; the later one takes the triangle index.
5763
+ for (bool taken = true; taken;) {
5764
+ taken = false;
5765
+ for (const Point& other : points) taken = taken || other.id == id;
5766
+ if (taken) id = (id * 16777619u) ^ ((triangle.index + 1u) * 2166136261u);
5767
+ }
5768
+ points.push_back({position, id, depth});
5769
+ }
5770
+ }
5771
+ if (points.empty()) return std::nullopt;
5772
+ Collision result = best;
5773
+ result.pointCount = 0;
5774
+ // Keep the deepest point, then the points that spread the patch most.
5775
+ std::array<std::size_t, 4> selected{};
5776
+ std::uint32_t selectedCount = 0;
5777
+ while (selectedCount < std::min<std::size_t>(4, points.size())) {
5778
+ std::size_t chosen = 0;
5779
+ double bestScore = -1.0;
5780
+ bool found = false;
5781
+ for (std::size_t index = 0; index < points.size(); index += 1) {
5782
+ bool used = false;
5783
+ for (std::uint32_t taken = 0; taken < selectedCount; taken += 1) used = used || selected[taken] == index;
5784
+ if (used) continue;
5785
+ double score = points[index].depth;
5786
+ if (selectedCount != 0) {
5787
+ score = std::numeric_limits<double>::infinity();
5788
+ for (std::uint32_t taken = 0; taken < selectedCount; taken += 1) {
5789
+ const Vec3 delta = subtractVec3(points[index].position, points[selected[taken]].position);
5790
+ score = std::min(score, dotVec3(delta, delta));
5791
+ }
5792
+ }
5793
+ if (!found || score > bestScore || (score == bestScore && points[index].id < points[chosen].id)) {
5794
+ chosen = index;
5795
+ bestScore = score;
5796
+ found = true;
5797
+ }
5798
+ }
5799
+ selected[selectedCount++] = chosen;
5800
+ }
5801
+ std::sort(selected.begin(), selected.begin() + selectedCount,
5802
+ [&](std::size_t left, std::size_t right) { return points[left].id < points[right].id; });
5803
+ if (selectedCount == 1) {
5804
+ result.pointX = points[selected[0]].position.x;
5805
+ result.pointY = points[selected[0]].position.y;
5806
+ result.pointZ = points[selected[0]].position.z;
5807
+ return result;
5808
+ }
5809
+ Vec3 sum{};
5810
+ for (std::uint32_t index = 0; index < selectedCount; index += 1) {
5811
+ const Point& point = points[selected[index]];
5812
+ result.points[index] = {point.position.x, point.position.y, point.position.z};
5813
+ result.featureIds[index] = point.id;
5814
+ sum = addVec3(sum, point.position);
5815
+ }
5816
+ result.pointCount = selectedCount;
5817
+ const Vec3 average = scaleVec3(sum, 1.0 / static_cast<double>(selectedCount));
5818
+ result.pointX = average.x;
5819
+ result.pointY = average.y;
5820
+ result.pointZ = average.z;
5821
+ return result;
5822
+ }
5823
+
5824
+ // Contacts of a convex body with a mesh or heightfield (simulation only). Each
5825
+ // triangle near the body is a three-point hull on the exact convex path; the
5826
+ // deepest result gives the normal and depth, and the patch on the triangles in
5827
+ // that contact plane gives the points. The collision points from the geometry
5828
+ // to the convex body.
5829
+ Collision triangleSoupCollision(SolverOperation& operation, const Body& geometry, const Body& convex) {
5830
+ const BroadphaseBounds bounds = queryProxyBounds(operation, convex);
5831
+ constexpr double margin = featureTolerance;
5832
+ std::vector<SoupTriangle> near;
5833
+ Collision best;
5834
+ const auto test = [&](std::uint32_t index, const Vec3& first, const Vec3& second, const Vec3& third) {
5835
+ if (std::min({first.x, second.x, third.x}) > bounds.maxX + margin
5836
+ || std::max({first.x, second.x, third.x}) < bounds.minX - margin
5837
+ || std::min({first.y, second.y, third.y}) > bounds.maxY + margin
5838
+ || std::max({first.y, second.y, third.y}) < bounds.minY - margin
5839
+ || std::min({first.z, second.z, third.z}) > bounds.maxZ + margin
5840
+ || std::max({first.z, second.z, third.z}) < bounds.minZ - margin) return;
5841
+ near.push_back({index, {first, second, third}});
5842
+ const Vec3 centroid = scaleVec3(addVec3(addVec3(first, second), third), 1.0 / 3.0);
5843
+ std::array<double, 9> local{};
5844
+ for (std::uint32_t corner = 0; corner < 3; corner += 1) {
5845
+ const Vec3 offset = subtractVec3(corner == 0 ? first : corner == 1 ? second : third, centroid);
5846
+ local[corner * 3] = offset.x;
5847
+ local[corner * 3 + 1] = offset.y;
5848
+ local[corner * 3 + 2] = offset.z;
5849
+ }
5850
+ Body triangle = geometry;
5851
+ triangle.shape = ShapeKind::Hull;
5852
+ triangle.geometryRecord = nullptr;
5853
+ triangle.geometrySource = GeometryInputSource::OwnedRecord;
5854
+ triangle.geometryView = std::span<const double>(local.data(), local.size());
5855
+ triangle.geometryFeatureOffset = 0;
5856
+ triangle.geometryFormat = 0;
5857
+ triangle.geometryOffset = 0;
5858
+ triangle.geometryCount = 3;
5859
+ triangle.x = centroid.x;
5860
+ triangle.y = centroid.y;
5861
+ triangle.z = centroid.z;
5862
+ triangle.shapeOffsetX = 0.0;
5863
+ triangle.shapeOffsetY = 0.0;
5864
+ triangle.shapeOffsetZ = 0.0;
5865
+ triangle.orientationX = 0.0;
5866
+ triangle.orientationY = 0.0;
5867
+ triangle.orientationZ = 0.0;
5868
+ triangle.orientationW = 1.0;
5869
+ triangle.shape0 = 0.0;
5870
+ triangle.shape1 = 0.0;
5871
+ triangle.shape2 = 0.0;
5872
+ const Collision candidate = convexSupportCollision(operation, triangle, convex);
5873
+ if (candidate.hit && (!best.hit || candidate.penetration > best.penetration)) best = candidate;
5874
+ };
5875
+ if (geometry.shape == ShapeKind::Mesh) {
5876
+ for (std::uint32_t point = 0; point + 2 < geometry.geometryCount; point += 3) {
5877
+ test(point / 3, geometryPoint(operation, geometry, point),
5878
+ geometryPoint(operation, geometry, point + 1), geometryPoint(operation, geometry, point + 2));
5879
+ }
5880
+ } else {
5881
+ const std::uint32_t metadata = geometry.geometryOffset * 3;
5882
+ const std::uint32_t columns = static_cast<std::uint32_t>(geometryForBody(operation, geometry)[metadata]);
5883
+ const std::uint32_t rows = static_cast<std::uint32_t>(geometryForBody(operation, geometry)[metadata + 1]);
5884
+ if (columns < 2 || rows < 2 || columns * rows + 1 > geometry.geometryCount) return {};
5885
+ for (std::uint32_t row = 0; row + 1 < rows; ++row) {
5886
+ for (std::uint32_t column = 0; column + 1 < columns; ++column) {
5887
+ const std::uint32_t first = row * columns + column;
5888
+ const Vec3 a = geometryPoint(operation, geometry, first);
5889
+ const Vec3 b = geometryPoint(operation, geometry, first + columns);
5890
+ const Vec3 c = geometryPoint(operation, geometry, first + 1);
5891
+ const Vec3 d = geometryPoint(operation, geometry, first + columns + 1);
5892
+ test(first * 2, a, b, c);
5893
+ test(first * 2 + 1, d, c, b);
5894
+ }
5895
+ }
5896
+ }
5897
+ if (!best.hit) return {};
5898
+ return triangleSoupPatch(operation, convex, best, near).value_or(best);
5899
+ }
5900
+
5624
5901
  bool isSmallDynamicWorld(const SolverOperation& operation);
5625
5902
 
5626
- // The stack solver path. Above 360 bodies it is always on. A world with few dynamic bodies also
5627
- // takes it while the dynamic tree runs its broadphase: the tree visits pairs in body-index order,
5628
- // and the small-world path is not stable in that order (a ten-box column drifts and never sleeps).
5903
+ // The stack solver path. Above 360 bodies it is always on, and it is on while the dynamic tree
5904
+ // runs the broadphase: the tree visits pairs in body-index order, and the small-world path is not
5905
+ // stable in that order (a ten-box column drifts and never sleeps). The number of dynamic bodies
5906
+ // does not select a path, so a distant body that changes kind cannot change a stack elsewhere.
5629
5907
  bool usesStackSolverPath(const SolverOperation& operation, std::uint32_t bodyCount) {
5630
5908
  if (operation.stepSubsteps <= 1) return false;
5631
5909
  if (bodyCount > 360) return true;
@@ -5633,17 +5911,16 @@ bool usesStackSolverPath(const SolverOperation& operation, std::uint32_t bodyCou
5633
5911
  && isSmallDynamicWorld(operation);
5634
5912
  }
5635
5913
 
5914
+ // True for every world that can move a body. Before rc.62 a world with more than 16 dynamic bodies
5915
+ // and at most 360 bodies returned false here and took a third solver path without cross-substep
5916
+ // constraint retention, where a ten-box column collapses (sweep broadphase) or never sleeps (tree).
5636
5917
  bool computeSmallDynamicWorld(const SolverOperation& operation) {
5637
5918
  if (operation.storage.soaBodies.empty()) return false;
5638
5919
  if (operation.storage.soaBodies.size() <= 16) return true;
5639
- std::uint32_t dynamicCount = 0;
5640
5920
  for (const Body& body : operation.storage.soaBodies) {
5641
- if (body.dynamic) {
5642
- dynamicCount += 1;
5643
- if (dynamicCount > 16) return false;
5644
- }
5921
+ if (body.dynamic) return true;
5645
5922
  }
5646
- return dynamicCount > 0;
5923
+ return false;
5647
5924
  }
5648
5925
 
5649
5926
  // The narrowphase asks this once per box pair, compound children included, and the scan walks the
@@ -6022,6 +6299,13 @@ Collision collideUncached(SolverOperation& operation, const Body& a, const Body&
6022
6299
  if (isGeometryShape(a.shape) && isGeometryShape(b.shape)) {
6023
6300
  return geometryPair(operation, a, b);
6024
6301
  }
6302
+ // Simulation contacts of a triangle with a box, hull or curved shape, and of
6303
+ // a hull with a capsule, take the exact convex path.
6304
+ if (!operation.fixedAxisQueryContacts) {
6305
+ if (triangleSoupBody(a) && triangleSoupPartner(b)) return triangleSoupCollision(operation, a, b);
6306
+ if (triangleSoupBody(b) && triangleSoupPartner(a)) return flipCollision(triangleSoupCollision(operation, b, a));
6307
+ if (exactConvexPair(a, b)) return convexSupportCollision(operation, a, b);
6308
+ }
6025
6309
  // Compounds use child recursion. The capsule/heightfield box approximation
6026
6310
  // misses occupied vertices. Keep the terrain-capsule regression until repaired.
6027
6311
  const auto recursableCompound = [](const Body& body) {
@@ -8451,6 +8735,17 @@ inline bool solvePreparedContact(
8451
8735
  applyContactImpulse(
8452
8736
  a, b, mobilityA, mobilityB, movableA, movableB, rA, rB, impulse);
8453
8737
  };
8738
+ // A frozen support body takes no normal impulse, so a stack cannot press it down, but friction
8739
+ // acts on both bodies. Friction against a frozen body moved the upper body with the lower one and
8740
+ // gave nothing back: a knocked or torch-cut crate stack kept moving at about 0.1 m/s forever.
8741
+ const bool frictionMovableA = a.dynamic && !a.sleeping;
8742
+ const bool frictionMovableB = b.dynamic && !b.sleeping;
8743
+ const auto applyFrictionImpulse = [&](const Vec3& impulse) {
8744
+ captureStartingContactApplication(operation, &constraint, rA, rB, impulse);
8745
+ captureContactApplication(applications, rA, rB, impulse);
8746
+ applyContactImpulse(
8747
+ a, b, mobilityA, mobilityB, frictionMovableA, frictionMovableB, rA, rB, impulse);
8748
+ };
8454
8749
 
8455
8750
  const Vec3 S{constraint.materialVelocity[0], constraint.materialVelocity[1], constraint.materialVelocity[2]};
8456
8751
  const Vec3 relative = subtractVec3(contactRelativeVelocity(a, b, rA, rB), S);
@@ -8470,7 +8765,7 @@ inline bool solvePreparedContact(
8470
8765
  contactTangentBasis(normal, tangent1, tangent2);
8471
8766
  if (normalTotal <= 0.0) {
8472
8767
  if (constraint.impulses[1] != 0.0 || constraint.impulses[2] != 0.0) {
8473
- applyImpulse(addVec3(
8768
+ applyFrictionImpulse(addVec3(
8474
8769
  scaleVec3(tangent1, -constraint.impulses[1]),
8475
8770
  scaleVec3(tangent2, -constraint.impulses[2])));
8476
8771
  constraint.impulses[1] = 0.0;
@@ -8485,8 +8780,8 @@ inline bool solvePreparedContact(
8485
8780
  const double postNormalVelocity = dotVec3(postRelative, normal);
8486
8781
  const Vec3 tangent = subtractVec3(
8487
8782
  postRelative, scaleVec3(normal, postNormalVelocity));
8488
- const double tangentMass1 = effectiveMass(tangent1, constraint.tangentMass1);
8489
- const double tangentMass2 = effectiveMass(tangent2, constraint.tangentMass2);
8783
+ const double tangentMass1 = constraint.tangentMass1;
8784
+ const double tangentMass2 = constraint.tangentMass2;
8490
8785
  const double oldTangent1 = constraint.impulses[1];
8491
8786
  const double oldTangent2 = constraint.impulses[2];
8492
8787
  double tangentTotal1 = oldTangent1
@@ -8505,7 +8800,7 @@ inline bool solvePreparedContact(
8505
8800
  constraint.impulses[2] = tangentTotal2;
8506
8801
  tangentTotal1Output = tangentTotal1;
8507
8802
  tangentTotal2Output = tangentTotal2;
8508
- applyImpulse(addVec3(
8803
+ applyFrictionImpulse(addVec3(
8509
8804
  scaleVec3(tangent1, tangentTotal1 - oldTangent1),
8510
8805
  scaleVec3(tangent2, tangentTotal2 - oldTangent2)));
8511
8806
  if (phase == ContactResponsePhase::Fresh) {
@@ -11045,6 +11340,27 @@ void warmStartSoAContacts(SolverOperation& operation, Body* bodies, std::uint32_
11045
11340
  }
11046
11341
  }
11047
11342
 
11343
+ // Appends the warm-start row of one contact to the contact cache, the only way a row is made. A
11344
+ // row holds an accumulated contact impulse, and the cache contract is a normal impulse that is not
11345
+ // negative (the step rejects any other row). An impulse that the motion clock re-expresses in a
11346
+ // contact frame that turned against the response frame can have a negative normal part. It is no
11347
+ // warm start for the next step, so its row holds no impulse.
11348
+ void appendContactCacheRow(std::vector<double>& cache, const ContactConstraintBlock& contact,
11349
+ const std::array<double, 3>& point) {
11350
+ const bool pushes = !(contact.impulses[0] < 0.0);
11351
+ cache.insert(cache.end(), {
11352
+ static_cast<double>(contact.bodyA),
11353
+ static_cast<double>(contact.bodyB),
11354
+ static_cast<double>(contact.featureId),
11355
+ pushes ? contact.impulses[0] : 0.0,
11356
+ pushes ? contact.impulses[1] : 0.0,
11357
+ pushes ? contact.impulses[2] : 0.0,
11358
+ point[0],
11359
+ point[1],
11360
+ point[2],
11361
+ });
11362
+ }
11363
+
11048
11364
  void finalizeContactCache(SolverOperation& operation) {
11049
11365
  operation.storage.contactCacheOutput.clear();
11050
11366
  operation.storage.contactCacheOutput.reserve(
@@ -11054,19 +11370,7 @@ void finalizeContactCache(SolverOperation& operation) {
11054
11370
  index < operation.storage.contactConstraintCount; index += 1) {
11055
11371
  const ContactConstraintBlock& constraint = operation.storage.contactConstraints[index];
11056
11372
  if (!constraint.activeForVelocityPhase && !constraint.preserveForCache) continue;
11057
- operation.storage.contactCacheOutput.insert(
11058
- operation.storage.contactCacheOutput.end(),
11059
- {
11060
- static_cast<double>(constraint.bodyA),
11061
- static_cast<double>(constraint.bodyB),
11062
- static_cast<double>(constraint.featureId),
11063
- constraint.impulses[0],
11064
- constraint.impulses[1],
11065
- constraint.impulses[2],
11066
- constraint.point[0],
11067
- constraint.point[1],
11068
- constraint.point[2],
11069
- });
11373
+ appendContactCacheRow(operation.storage.contactCacheOutput, constraint, constraint.point);
11070
11374
  }
11071
11375
  }
11072
11376
 
@@ -11244,6 +11548,8 @@ void resolveSoAContacts(SolverOperation& operation, Body* bodies, std::uint32_t
11244
11548
  operation.storage.contactSolvePairCount = 0;
11245
11549
  std::fill(operation.storage.contactSupported.begin(),
11246
11550
  operation.storage.contactSupported.end(), 0);
11551
+ operation.storage.supportEdges.clear();
11552
+ operation.storage.supportPropagated = false;
11247
11553
  operation.storage.firstSubstepOfTick = firstTickSubstep;
11248
11554
  if (firstTickSubstep) {
11249
11555
  operation.storage.restingSubstepPairCount = 0;
@@ -11702,6 +12008,9 @@ void resolveSoAContacts(SolverOperation& operation, Body* bodies, std::uint32_t
11702
12008
  Vec3 tangent1;
11703
12009
  Vec3 tangent2;
11704
12010
  contactTangentBasis(normal, tangent1, tangent2);
12011
+ // Friction acts on both bodies even when the support body is frozen (see solvePreparedContact).
12012
+ const bool frictionMovableA = a.dynamic && !a.sleeping;
12013
+ const bool frictionMovableB = b.dynamic && !b.sleeping;
11705
12014
  std::array<double, 4> errT1List{};
11706
12015
  std::array<double, 4> errT2List{};
11707
12016
  double errT1Avg = 0.0;
@@ -11722,9 +12031,9 @@ void resolveSoAContacts(SolverOperation& operation, Body* bodies, std::uint32_t
11722
12031
  maxErrTDiff = std::max(maxErrTDiff, std::max(std::abs(errT1List[i] - errT1Avg), std::abs(errT2List[i] - errT2Avg)));
11723
12032
  }
11724
12033
  const double centroidT1Mass = effectiveContactMass(
11725
- mobilityA, mobilityB, movableA, movableB, rAAvg, rBAvg, tangent1);
12034
+ mobilityA, mobilityB, frictionMovableA, frictionMovableB, rAAvg, rBAvg, tangent1);
11726
12035
  const double centroidT2Mass = effectiveContactMass(
11727
- mobilityA, mobilityB, movableA, movableB, rAAvg, rBAvg, tangent2);
12036
+ mobilityA, mobilityB, frictionMovableA, frictionMovableB, rAAvg, rBAvg, tangent2);
11728
12037
  const double symDeltaT1 = centroidT1Mass > 0.0 ? (-errT1Avg / centroidT1Mass) * invCount : 0.0;
11729
12038
  const double symDeltaT2 = centroidT2Mass > 0.0 ? (-errT2Avg / centroidT2Mass) * invCount : 0.0;
11730
12039
  if (symDeltaT1 != 0.0 || symDeltaT2 != 0.0) {
@@ -11767,12 +12076,12 @@ void resolveSoAContacts(SolverOperation& operation, Body* bodies, std::uint32_t
11767
12076
  sumTorqueA = snapSmallVec(sumTorqueA);
11768
12077
  sumTorqueB = snapSmallVec(sumTorqueB);
11769
12078
  }
11770
- const Vec3 linA = inverseLinearMass(mobilityA, movableA);
11771
- const Vec3 linB = inverseLinearMass(mobilityB, movableB);
12079
+ const Vec3 linA = inverseLinearMass(mobilityA, frictionMovableA);
12080
+ const Vec3 linB = inverseLinearMass(mobilityB, frictionMovableB);
11772
12081
  a.vx -= sumImpT.x * linA.x; a.vy -= sumImpT.y * linA.y; a.vz -= sumImpT.z * linA.z;
11773
12082
  b.vx += sumImpT.x * linB.x; b.vy += sumImpT.y * linB.y; b.vz += sumImpT.z * linB.z;
11774
- const Vec3 angA = inverseAngularMass(mobilityA, movableA, sumTorqueA);
11775
- const Vec3 angB = inverseAngularMass(mobilityB, movableB, sumTorqueB);
12083
+ const Vec3 angA = inverseAngularMass(mobilityA, frictionMovableA, sumTorqueA);
12084
+ const Vec3 angB = inverseAngularMass(mobilityB, frictionMovableB, sumTorqueB);
11776
12085
  a.angularVelX -= angA.x; a.angularVelY -= angA.y; a.angularVelZ -= angA.z;
11777
12086
  b.angularVelX += angB.x; b.angularVelY += angB.y; b.angularVelZ += angB.z;
11778
12087
  outTangent1Delta += sumDT1;
@@ -11941,6 +12250,10 @@ void resolveSoAContacts(SolverOperation& operation, Body* bodies, std::uint32_t
11941
12250
  && bodies[matched->upper].dynamic) {
11942
12251
  operation.storage.contactSupported[supportIndex(matched->upper)] = 1;
11943
12252
  }
12253
+ if (bodies[matched->upper].dynamic) {
12254
+ operation.storage.supportEdges.push_back(
12255
+ (static_cast<std::uint64_t>(matched->lower) << 32) | matched->upper);
12256
+ }
11944
12257
  }
11945
12258
  if (operation.storage.contactConstraintCount + matched->newConstraintCount
11946
12259
  > operation.storage.maximumContactConstraintCount) {
@@ -12017,6 +12330,10 @@ void resolveSoAContacts(SolverOperation& operation, Body* bodies, std::uint32_t
12017
12330
  && bodies[supportUpper].dynamic) {
12018
12331
  operation.storage.contactSupported[supportIndex(supportUpper)] = 1;
12019
12332
  }
12333
+ if (bodies[supportUpper].dynamic) {
12334
+ operation.storage.supportEdges.push_back(
12335
+ (static_cast<std::uint64_t>(supportLower) << 32) | supportUpper);
12336
+ }
12020
12337
  }
12021
12338
  }
12022
12339
  const std::uint32_t pointCount = contactPointCount(contact);
@@ -12196,7 +12513,27 @@ void resolveSoAContacts(SolverOperation& operation, Body* bodies, std::uint32_t
12196
12513
  operation.storage.contactSolvePairCount = writeOrder;
12197
12514
  }
12198
12515
  };
12516
+ const auto propagateContactSupport = [&]() {
12517
+ if (operation.storage.supportPropagated) return;
12518
+ operation.storage.supportPropagated = true;
12519
+ bool changed = true;
12520
+ while (changed) {
12521
+ changed = false;
12522
+ for (const std::uint64_t edge : operation.storage.supportEdges) {
12523
+ const auto lower = static_cast<std::uint32_t>(edge >> 32);
12524
+ const auto upper = static_cast<std::uint32_t>(edge);
12525
+ auto& upperSupported = operation.storage.contactSupported[supportIndex(upper)];
12526
+ if (upperSupported != 0) continue;
12527
+ if (!bodies[lower].dynamic || bodies[lower].kinematic
12528
+ || operation.storage.contactSupported[supportIndex(lower)] != 0) {
12529
+ upperSupported = 1;
12530
+ changed = true;
12531
+ }
12532
+ }
12533
+ }
12534
+ };
12199
12535
  const auto solvePreparedConstraints = [&](bool stabilizeSupported) {
12536
+ if (stabilizeSupported) propagateContactSupport();
12200
12537
  for (std::uint32_t order = operation.storage.contactSolvePairCount;
12201
12538
  order > 0; order -= 1) {
12202
12539
  const std::uint32_t begin = operation.storage.contactSolvePairBegin[order - 1];
@@ -12215,10 +12552,18 @@ void resolveSoAContacts(SolverOperation& operation, Body* bodies, std::uint32_t
12215
12552
  // enough more passes over the pairs with a cylinder to reach 24 iterations in total; pairs
12216
12553
  // without one are unchanged. Twelve settled every jittered tire run in the corpus; 24 also
12217
12554
  // 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
12555
+ // 24. In rc.61 and rc.62 the floor also hid portal parity defects at 8 and 9 iterations (review 10).
12556
+ // Now a portal clone moves like the direct body at every count, with or without the floor,
12557
+ // except at half-quantum ties (tests/portal-parity-ratchet.test.ts). The floor is for settling
12558
+ // only. The owned (joint and portal) path runs one iteration per call, so
12220
12559
  // its loop marks the last call, and the extra passes come before that iteration's joint and
12221
12560
  // portal work, as on the standalone path.
12561
+ //
12562
+ // A pair inside a supported structure (each body static, kinematic, or resting on support, the
12563
+ // structure the frozen-support rule acts on, side contacts included) gets the same floor. With
12564
+ // friction acting on both bodies, a 400-crate stack left out of line by a torch cut or a knock
12565
+ // settles at 24 iterations; at 6, 12, 16 and 18 a few crates kept creeping above the sleep
12566
+ // threshold, so the stack never slept.
12222
12567
  constexpr std::uint32_t kCylinderMinimumVelocityIterations = 24;
12223
12568
  const std::uint32_t cylinderExtraVelocityIterations =
12224
12569
  options.velocityIterations < kCylinderMinimumVelocityIterations
@@ -12227,7 +12572,14 @@ void resolveSoAContacts(SolverOperation& operation, Body* bodies, std::uint32_t
12227
12572
  && cylinderExtraVelocityIterations != 0
12228
12573
  && (pass == ContactPass::StandaloneFirstTick || pass == ContactPass::StandaloneLaterSubstep
12229
12574
  || (lastOwnedVelocityIteration && pass == ContactPass::OwnedContinueVelocity));
12575
+ const auto isSupportPair = [&](std::uint32_t first, std::uint32_t second) {
12576
+ const auto supported = [&](std::uint32_t body) {
12577
+ return !bodies[body].dynamic || operation.storage.contactSupported[supportIndex(body)] != 0;
12578
+ };
12579
+ return (bodies[first].dynamic || bodies[second].dynamic) && supported(first) && supported(second);
12580
+ };
12230
12581
  const auto solvePreparedCylinderConstraints = [&]() {
12582
+ propagateContactSupport();
12231
12583
  for (std::uint32_t order = operation.storage.contactSolvePairCount;
12232
12584
  order > 0; order -= 1) {
12233
12585
  const std::uint32_t begin = operation.storage.contactSolvePairBegin[order - 1];
@@ -12237,7 +12589,8 @@ void resolveSoAContacts(SolverOperation& operation, Body* bodies, std::uint32_t
12237
12589
  operation.storage.contactConstraints[begin];
12238
12590
  const std::uint32_t first = firstConstraint.bodyA;
12239
12591
  const std::uint32_t second = firstConstraint.bodyB;
12240
- if (bodies[first].shape != ShapeKind::Cylinder && bodies[second].shape != ShapeKind::Cylinder) continue;
12592
+ if (bodies[first].shape != ShapeKind::Cylinder && bodies[second].shape != ShapeKind::Cylinder
12593
+ && !isSupportPair(first, second)) continue;
12241
12594
  solvePair(first, second, false, true, begin, end);
12242
12595
  }
12243
12596
  };
@@ -12878,16 +13231,21 @@ void updateJointIslandMembership(SolverOperation& operation,
12878
13231
 
12879
13232
  for (const auto& connection : connections) {
12880
13233
  if (connection[0] < bodyCount && connection[1] < bodyCount && connection[0] != connection[1]) {
13234
+ // A proxy link joins one rigid body, so it is not a constraint. If it
13235
+ // set the joint flag, a portal clone and its original would solve their
13236
+ // contacts on the joint path, and the same body without a portal on the
13237
+ // standalone path. Above the slop the two paths give different results.
13238
+ const bool constraint = !hook.isProxyLink(connection);
12881
13239
  if (bodies[connection[0]].dynamic) {
12882
13240
  const std::uint32_t rootA = sleepFind(operation, connection[0]);
12883
- componentHasJoint[rootA] = 1;
13241
+ if (constraint) componentHasJoint[rootA] = 1;
12884
13242
  if (bodies[connection[1]].kinematic || (bodies[connection[1]].dynamic && !bodies[connection[1]].sleeping)) {
12885
13243
  componentHasActive[rootA] = 1;
12886
13244
  }
12887
13245
  }
12888
13246
  if (bodies[connection[1]].dynamic) {
12889
13247
  const std::uint32_t rootB = sleepFind(operation, connection[1]);
12890
- componentHasJoint[rootB] = 1;
13248
+ if (constraint) componentHasJoint[rootB] = 1;
12891
13249
  if (bodies[connection[0]].kinematic || (bodies[connection[0]].dynamic && !bodies[connection[0]].sleeping)) {
12892
13250
  componentHasActive[rootB] = 1;
12893
13251
  }
@@ -20504,11 +20862,140 @@ bool sameMotionSearchBody(const Body& a, const Body& b) {
20504
20862
  && a.geometryOffset == b.geometryOffset && a.geometryCount == b.geometryCount;
20505
20863
  }
20506
20864
 
20865
+ // The contact skin of the native motion clock. It is equal to the contact slop of the solver.
20866
+ // The clock used the same zero-distance test to start and to end a contact. A pair that rests,
20867
+ // slides or grazes then touched and separated again after a few units in the last place of the clock
20868
+ // time, and a search for a contact that stays near zero distance divided the substep into slabs as
20869
+ // narrow as the gap. The skin bounds both: a pair keeps its contact episodes until its gap is larger
20870
+ // than the skin, and a search stops dividing a slab when the bodies move less than a quarter of the
20871
+ // skin across it.
20872
+ constexpr double kMotionContactSkin = 0.005;
20873
+
20874
+ // Returns `body` with its shape grown (`delta` > 0) or shrunk (`delta` < 0) by |delta| on every side,
20875
+ // or nothing when the body is not a sphere, capsule or box, or when the shrunk shape would be empty.
20876
+ // A grown shape contains every point within `delta` of the shape. Every point of a shrunk shape is at
20877
+ // least |delta| inside the shape.
20878
+ std::optional<Body> offsetMotionPrimitive(Body body, double delta) {
20879
+ switch (body.shape) {
20880
+ case ShapeKind::Sphere:
20881
+ case ShapeKind::Capsule:
20882
+ if (!(body.shape0 + delta > 0.0)) return std::nullopt;
20883
+ body.shape0 += delta;
20884
+ return body;
20885
+ case ShapeKind::Box:
20886
+ if (!(body.shape0 + delta > 0.0) || !(body.shape1 + delta > 0.0) || !(body.shape2 + delta > 0.0))
20887
+ return std::nullopt;
20888
+ body.shape0 += delta;
20889
+ body.shape1 += delta;
20890
+ body.shape2 += delta;
20891
+ return body;
20892
+ default: return std::nullopt;
20893
+ }
20894
+ }
20895
+
20896
+ // A box body that contains the world bounds of `body` grown by `delta` on every side.
20897
+ Body motionBoundsBox(SolverOperation& operation, const Body& body, double delta) {
20898
+ const BroadphaseBounds bounds = queryProxyBounds(operation, body);
20899
+ Body box;
20900
+ box.id = body.id;
20901
+ box.dynamic = false;
20902
+ box.layer = body.layer;
20903
+ box.mask = body.mask;
20904
+ box.masksValid = body.masksValid;
20905
+ box.shape = ShapeKind::Box;
20906
+ box.x = (bounds.minX + bounds.maxX) * 0.5;
20907
+ box.y = (bounds.minY + bounds.maxY) * 0.5;
20908
+ box.z = (bounds.minZ + bounds.maxZ) * 0.5;
20909
+ box.orientationX = 0.0;
20910
+ box.orientationY = 0.0;
20911
+ box.orientationZ = 0.0;
20912
+ box.orientationW = 1.0;
20913
+ // The half extents round up so that the box contains the bounds after the center rounds.
20914
+ box.shape0 = std::nextafter((bounds.maxX - bounds.minX) * 0.5 + delta, std::numeric_limits<double>::infinity());
20915
+ box.shape1 = std::nextafter((bounds.maxY - bounds.minY) * 0.5 + delta, std::numeric_limits<double>::infinity());
20916
+ box.shape2 = std::nextafter((bounds.maxZ - bounds.minZ) * 0.5 + delta, std::numeric_limits<double>::infinity());
20917
+ return box;
20918
+ }
20919
+
20920
+ // Returns true when the shapes of `a` and `b` are not certainly farther apart than the skin. A miss
20921
+ // of collide() with one shape grown by the skin proves a gap larger than the skin. A sphere, capsule
20922
+ // or box grows exactly. Any other shape grows through its world bounds box, which contains the shape:
20923
+ // that test is conservative, so a pair of two such shapes leaves contact when the bounds box of one
20924
+ // body, grown by the skin, misses the other body.
20925
+ bool withinMotionContactSkin(SolverOperation& operation, const Body& a, const Body& b) {
20926
+ triangle_adapter_private::work(operation);
20927
+ if (const auto first = offsetMotionPrimitive(a, kMotionContactSkin)) return collide(operation, *first, b).hit;
20928
+ if (const auto second = offsetMotionPrimitive(b, kMotionContactSkin)) return collide(operation, a, *second).hit;
20929
+ triangle_adapter_private::work(operation, 2);
20930
+ return collide(operation, motionBoundsBox(operation, a, kMotionContactSkin), b).hit
20931
+ && collide(operation, a, motionBoundsBox(operation, b, kMotionContactSkin)).hit;
20932
+ }
20933
+
20934
+ // How the watch of an engaged pair finds the time at which the pair is `depth` deep.
20935
+ // - ShrunkBody: the body `endpoint` (a sphere, capsule or box) shrunk by `depth` touches the other
20936
+ // body only where the pair is at least `depth` deep.
20937
+ // - ReportedDepth: a pair with no sphere, capsule or box (hull, mesh, heightfield, compound,
20938
+ // cylinder, cone) is `depth` deep where collide() reports a depth larger than `depth`. These pairs
20939
+ // take the exact convex contact (fixed axes and EPA), so the reported depth is the true depth.
20940
+ struct ShrunkBody {
20941
+ unsigned endpoint = 0;
20942
+ double depth = 0.0;
20943
+ };
20944
+ struct ReportedDepth {
20945
+ double depth = 0.0;
20946
+ };
20947
+ using MotionPairErosion = std::variant<ShrunkBody, ReportedDepth>;
20948
+
20949
+ bool motionPrimitive(const Body& body) {
20950
+ return body.shape == ShapeKind::Sphere || body.shape == ShapeKind::Capsule || body.shape == ShapeKind::Box;
20951
+ }
20952
+
20953
+ // Chooses how to watch an engaged pair at `depth`: shrink a sphere, capsule or box that stays
20954
+ // nonempty, the thicker one first; else read the reported depth of a pair with no sphere or capsule
20955
+ // (a hull, mesh, compound or cylinder, or one of them against a thin box wall). Returns nothing when
20956
+ // no body can be shrunk by `depth` and the pair has a sphere or capsule (their triangle and sphere
20957
+ // routes do not report the true depth) or is two boxes.
20958
+ std::optional<MotionPairErosion> erodedMotionPair(const Body& a, const Body& b, double depth) {
20959
+ const auto rounded = [](const Body& body) {
20960
+ return body.shape == ShapeKind::Sphere || body.shape == ShapeKind::Capsule;
20961
+ };
20962
+ const bool reportedDepthPair = !rounded(a) && !rounded(b)
20963
+ && !(a.shape == ShapeKind::Box && b.shape == ShapeKind::Box);
20964
+ if (!motionPrimitive(a) && !motionPrimitive(b)) return ReportedDepth{depth};
20965
+ const auto margin = [&](const Body& body) -> std::optional<double> {
20966
+ if (!offsetMotionPrimitive(body, -depth)) return std::nullopt;
20967
+ return body.shape == ShapeKind::Box ? std::min({body.shape0, body.shape1, body.shape2}) : body.shape0;
20968
+ };
20969
+ const auto first = margin(a), second = margin(b);
20970
+ if (!first && !second) return reportedDepthPair ? std::optional<MotionPairErosion>{ReportedDepth{depth}} : std::nullopt;
20971
+ if (first && (!second || *first >= *second)) return ShrunkBody{0, depth};
20972
+ return ShrunkBody{1, depth};
20973
+ }
20974
+
20975
+ // An upper bound of the speed of every point of a primitive body (sphere, capsule or box) that
20976
+ // follows its motion epoch. The center of mass moves at the linear velocity, and every point turns
20977
+ // about it at most at |angular velocity| times its distance. The bound adds the offsets and the full
20978
+ // shape radius to that distance, so it holds for each shape-offset convention.
20979
+ double motionPointSpeedBound(const BodyMotionEpoch& epoch, const Body& body) {
20980
+ if ((!epoch.dynamic && !epoch.kinematic) || (epoch.dynamic && epoch.sleeping)) return 0.0;
20981
+ const auto length = [](double x, double y, double z) { return solverSqrt(x * x + y * y + z * z); };
20982
+ const double linear = length((epoch.motionLocks & 1u) == 0 ? epoch.linearVelocity[0] : 0.0,
20983
+ (epoch.motionLocks & 2u) == 0 ? epoch.linearVelocity[1] : 0.0,
20984
+ (epoch.motionLocks & 4u) == 0 ? epoch.linearVelocity[2] : 0.0);
20985
+ const double angular = length(epoch.angularVelocity[0], epoch.angularVelocity[1], epoch.angularVelocity[2]);
20986
+ const double extent = body.shape == ShapeKind::Box ? length(body.shape0, body.shape1, body.shape2)
20987
+ : body.shape == ShapeKind::Capsule ? body.shape0 + body.shape1 : body.shape0;
20988
+ const double radius = extent + length(body.shapeOffsetX, body.shapeOffsetY, body.shapeOffsetZ)
20989
+ + length(epoch.centerOfMass[0], epoch.centerOfMass[1], epoch.centerOfMass[2]);
20990
+ return linear + angular * radius;
20991
+ }
20992
+
20507
20993
  class MotionContactSearch {
20508
20994
  public:
20509
20995
  MotionContactSearch(SolverOperation& operation, std::uint32_t first, std::uint32_t second,
20510
- MotionContactTransition transition = MotionContactTransition::Entry)
20511
- : operation_(operation), pair_{first, second}, transition_(transition) {}
20996
+ MotionContactTransition transition = MotionContactTransition::Entry,
20997
+ std::optional<MotionPairErosion> erosion = std::nullopt)
20998
+ : operation_(operation), pair_{first, second}, transition_(transition), erosion_(erosion) {}
20512
20999
  MotionContactSearch(const MotionContactSearch&) = delete;
20513
21000
  MotionContactSearch& operator=(const MotionContactSearch&) = delete;
20514
21001
  MotionContactSearch(MotionContactSearch&&) = delete;
@@ -20562,8 +21049,30 @@ class MotionContactSearch {
20562
21049
  if (evaluated != Status::Clear) return fail(evaluated);
20563
21050
  if (!sameSearchBody(current, bodies_[endpoint])) return fail(Status::InvalidInput);
20564
21051
  }
21052
+ searched_ = bodies_;
21053
+ if (erosion_) {
21054
+ // An eroded search watches an engaged pair on the native clock: it finds the first time at
21055
+ // which the pair is `depth` deep, as an entry of the shrunk body or of the reported depth.
21056
+ if (operation_.materialMotionEpochs != nullptr || transition_ != MotionContactTransition::Entry)
21057
+ return fail(Status::InvalidInput);
21058
+ if (const auto* shrink = std::get_if<ShrunkBody>(&*erosion_)) {
21059
+ if (shrink->endpoint > 1 || !finite(shrink->depth) || !(shrink->depth > 0.0)) return fail(Status::InvalidInput);
21060
+ const auto shrunk = offsetMotionPrimitive(bodies_[shrink->endpoint], -shrink->depth);
21061
+ if (!shrunk) return fail(Status::InvalidInput);
21062
+ searched_[shrink->endpoint] = *shrunk;
21063
+ } else {
21064
+ const double depth = std::get<ReportedDepth>(*erosion_).depth;
21065
+ if (!finite(depth) || !(depth > 0.0) || (motionPrimitive(bodies_[0]) && motionPrimitive(bodies_[1])))
21066
+ return fail(Status::InvalidInput);
21067
+ for (const Body& body : bodies_)
21068
+ if (body.shape == ShapeKind::Sphere || body.shape == ShapeKind::Capsule) return fail(Status::InvalidInput);
21069
+ reportedDepth_ = depth;
21070
+ }
21071
+ }
20565
21072
  const bool sampledNativeSearch = operation_.materialMotionEpochs == nullptr
20566
21073
  && motionContactPairKind(bodies_[0], bodies_[1]) == MotionContactPairKind::Unsupported;
21074
+ // The reported depth is a point test, so only the sampled search can read it.
21075
+ if (reportedDepth_ && !sampledNativeSearch) return fail(Status::InvalidInput);
20567
21076
  if (!sampledNativeSearch
20568
21077
  && motionContactPairKind(bodies_[0], bodies_[1]) == MotionContactPairKind::Unsupported)
20569
21078
  return fail(Status::UnsupportedGeometry);
@@ -20591,6 +21100,17 @@ class MotionContactSearch {
20591
21100
  using Slab = std::array<double, 2>;
20592
21101
  std::vector<Slab> pending;
20593
21102
  if (now_ != end_) triangle_adapter_private::append(operation_, pending, Slab{now_, end_});
21103
+ // A native slab that the classifier cannot resolve is a leaf when no point of the pair moves
21104
+ // more than a quarter of the contact skin across it (the factor 2 covers the error of the
21105
+ // orientation step). A leaf is decided by the point test at its ends. A contact that starts
21106
+ // and ends inside a leaf penetrates less than the contact slop, so the search may ignore it,
21107
+ // and the number of leaves is at most about 8 * duration * speed / skin. If an event of another
21108
+ // pair falls inside that contact, the next batch finds the pair touching without episodes and
21109
+ // gives it episodes at once (MotionContactEventKind::StartContact).
21110
+ const double speed = std::holds_alternative<NativeSearchGeometry>(geometry_)
21111
+ ? motionPointSpeedBound(epochs_[0], bodies_[0]) + motionPointSpeedBound(epochs_[1], bodies_[1]) : 0.0;
21112
+ if (!finite(speed)) return fail(Status::Unresolved);
21113
+ const double grazeSlab = speed > 0.0 ? kMotionContactSkin * 0.25 / speed : 0.0;
20594
21114
  while (!pending.empty()) {
20595
21115
  triangle_adapter_private::work(operation_);
20596
21116
  const Slab slab = pending.back();
@@ -20599,7 +21119,7 @@ class MotionContactSearch {
20599
21119
  const auto* material = std::get_if<MaterialSearchGeometry>(&geometry_);
20600
21120
  const auto rejection = material != nullptr
20601
21121
  ? classifyMaterialMotionContactInterval(operation_, *material->sources[0], *material->sources[1], slab[0], slab[1])
20602
- : classifyMotionContactInterval(operation_, epochs_[0], bodies_[0], epochs_[1], bodies_[1], slab[0], slab[1]);
21122
+ : classifyMotionContactInterval(operation_, epochs_[0], searched_[0], epochs_[1], searched_[1], slab[0], slab[1]);
20603
21123
  switch (rejection) {
20604
21124
  case MotionContactIntervalStatus::Separated:
20605
21125
  if (!departing) {
@@ -20621,15 +21141,35 @@ class MotionContactSearch {
20621
21141
  case MotionContactIntervalStatus::Unresolved: break;
20622
21142
  }
20623
21143
  triangle_adapter_private::work(operation_);
20624
- if (slab[0] == slab[1] || std::nextafter(slab[0], slab[1]) == slab[1]) {
20625
- const auto low = captureContact(slab[0]);
21144
+ const bool adjacent = slab[0] == slab[1] || std::nextafter(slab[0], slab[1]) == slab[1];
21145
+ if (adjacent || (material == nullptr && slab[1] - slab[0] <= grazeSlab)) {
21146
+ auto low = captureContact(slab[0]);
20626
21147
  if (const auto failure = std::get_if<Status>(&low)) return fail(*failure);
20627
21148
  if (std::get<Collision>(low).hit != departing) return fail(Status::Unresolved);
20628
- const auto high = captureContact(slab[1]);
21149
+ auto high = captureContact(slab[1]);
20629
21150
  if (const auto failure = std::get_if<Status>(&high)) return fail(*failure);
21151
+ // Divide a leaf that changes state by the point test only, down to adjacent times.
21152
+ Slab bracket = slab;
21153
+ while (std::get<Collision>(high).hit != departing && std::nextafter(bracket[0], bracket[1]) != bracket[1]) {
21154
+ triangle_adapter_private::work(operation_);
21155
+ const double middle = bracket[0] + (bracket[1] - bracket[0]) * 0.5;
21156
+ if (!(bracket[0] < middle && middle < bracket[1])) return fail(Status::Unresolved);
21157
+ auto sample = captureContact(middle);
21158
+ if (const auto failure = std::get_if<Status>(&sample)) return fail(*failure);
21159
+ if (std::get<Collision>(sample).hit != departing) { bracket[1] = middle; high = std::move(sample); }
21160
+ else { bracket[0] = middle; low = std::move(sample); }
21161
+ }
20630
21162
  if (const auto& collision = std::get<Collision>(high); collision.hit != departing) {
20631
- result_.bracket = slab;
21163
+ result_.certifiedEnd = bracket[0];
21164
+ result_.bracket = bracket;
20632
21165
  result_.collision = departing ? std::get<Collision>(low) : collision;
21166
+ if (erosion_) {
21167
+ auto real = captureContact(bracket[1], false);
21168
+ if (const auto failure = std::get_if<Status>(&real)) return fail(*failure);
21169
+ // The shrunk body lies inside the body, so the pair touches where the shrunk body does.
21170
+ if (!std::get<Collision>(real).hit) return fail(Status::Unresolved);
21171
+ result_.collision = std::get<Collision>(std::move(real));
21172
+ }
20633
21173
  if (material != nullptr && slab[0] < slab[1]
20634
21174
  && !hasMaterialAngularMotion(material->sources[0]->body().origin)
20635
21175
  && !hasMaterialAngularMotion(material->sources[1]->body().origin)) {
@@ -20734,6 +21274,12 @@ class MotionContactSearch {
20734
21274
  result_.certifiedEnd = low;
20735
21275
  result_.bracket = {low, high};
20736
21276
  result_.collision = departing ? std::move(lowCollision) : std::move(highCollision);
21277
+ if (erosion_) {
21278
+ auto real = captureContact(high, false);
21279
+ if (const auto* failure = std::get_if<Status>(&real)) return fail(*failure);
21280
+ if (!std::get<Collision>(real).hit) return fail(Status::Unresolved);
21281
+ result_.collision = std::get<Collision>(std::move(real));
21282
+ }
20737
21283
  return finish(departing ? Status::Departure : Status::Entry);
20738
21284
  }
20739
21285
  result_.certifiedEnd = end_;
@@ -20796,7 +21342,8 @@ class MotionContactSearch {
20796
21342
  }
20797
21343
  return Status::Clear;
20798
21344
  }
20799
- std::variant<Collision, MotionContactSearchStatus> captureContact(double time) {
21345
+ // The contact of the pair at `time`. An eroded search tests the shrunk body unless `eroded` is false.
21346
+ std::variant<Collision, MotionContactSearchStatus> captureContact(double time, bool eroded = true) {
20800
21347
  using Status = MotionContactSearchStatus;
20801
21348
  if (const auto* material = std::get_if<MaterialSearchGeometry>(&geometry_)) {
20802
21349
  std::shared_ptr<const MaterialContactWitness> witness;
@@ -20816,11 +21363,13 @@ class MotionContactSearch {
20816
21363
  std::array<Body, 2> trials;
20817
21364
  for (unsigned endpoint = 0; endpoint < 2; ++endpoint) {
20818
21365
  triangle_adapter_private::work(operation_);
20819
- if (!evaluateBodyMotionEpoch(epochs_[endpoint], bodies_[endpoint], time, trials[endpoint]))
21366
+ if (!evaluateBodyMotionEpoch(epochs_[endpoint], eroded ? searched_[endpoint] : bodies_[endpoint], time, trials[endpoint]))
20820
21367
  return Status::Unresolved;
20821
21368
  }
20822
21369
  triangle_adapter_private::work(operation_);
20823
21370
  const Collision collision = collide(operation_, trials[0], trials[1]);
21371
+ // A watch on the reported depth counts a contact only where it is deeper than the watched depth.
21372
+ if (eroded && reportedDepth_ && collision.hit && !(collision.penetration > *reportedDepth_)) return Collision{};
20824
21373
  if (collision.hit) {
20825
21374
  triangle_adapter_private::work(operation_);
20826
21375
  if (collision.pointCount > 4) return Status::Unresolved;
@@ -20836,7 +21385,11 @@ class MotionContactSearch {
20836
21385
  SolverOperation& operation_;
20837
21386
  const std::array<std::uint32_t, 2> pair_;
20838
21387
  const MotionContactTransition transition_;
21388
+ const std::optional<MotionPairErosion> erosion_;
21389
+ std::optional<double> reportedDepth_;
20839
21390
  std::array<Body, 2> bodies_;
21391
+ // The bodies that the classifier and the point tests use: `bodies_` with the erosion applied.
21392
+ std::array<Body, 2> searched_;
20840
21393
  std::array<BodyMotionEpoch, 2> epochs_;
20841
21394
  std::variant<NativeSearchGeometry, MaterialSearchGeometry> geometry_;
20842
21395
  const Body* bodyData_ = nullptr;
@@ -20856,11 +21409,22 @@ enum class MotionContactEventBatchStatus : std::uint8_t {
20856
21409
  Selected, Complete, InvalidInput, StaleInput, Unresolved, ResourceExhausted,
20857
21410
  AllocationFailure, UnsupportedGeometry, Consumed,
20858
21411
  };
21412
+ // What a native batch event starts. A pair leaves contact through the contact skin (see
21413
+ // withinMotionContactSkin), not through an event.
21414
+ enum class MotionContactEventKind : std::uint8_t {
21415
+ // A pair without contact episodes touches at `bracket[1]`, after the batch time.
21416
+ Entry,
21417
+ // A pair without contact episodes touches at the batch time. `bracket` is {now, now}.
21418
+ StartContact,
21419
+ // A pair with contact episodes becomes one contact skin deeper at `bracket[1]` than it was at the
21420
+ // batch time. Its current contact features that have no episode get one.
21421
+ Deepening,
21422
+ };
20859
21423
  struct MotionContactBatchEvent {
20860
21424
  std::array<std::uint32_t, 2> pair;
20861
- MotionContactTransition transition;
20862
21425
  std::array<double, 2> bracket;
20863
21426
  Collision collision;
21427
+ MotionContactEventKind kind = MotionContactEventKind::Entry;
20864
21428
  };
20865
21429
  struct MotionContactEventBatchView {
20866
21430
  double time = 0.0;
@@ -20977,6 +21541,18 @@ class MotionContactEventBatch {
20977
21541
  MotionContactEventBatch& operator=(MotionContactEventBatch&&) = delete;
20978
21542
  Status retireDepartures(ContactEventPhaseOwner& phase);
20979
21543
  Status activateEntries(ContactEventPhaseOwner& phase);
21544
+ // Selects the earliest events. On the native path a bullet pair is engaged when it has contact
21545
+ // episodes (in operation.contactPhaseOwner) and stays within the contact skin; a pair stops being
21546
+ // engaged only when its gap is larger than the skin.
21547
+ // - A pair that touches now and is not engaged is a StartContact event now: a touching pair always
21548
+ // has episodes, so it always gets a response. The next batch at the same time finds it engaged.
21549
+ // - A pair that touches now and is engaged is watched: an eroded search finds when it becomes one
21550
+ // skin deeper than now (Deepening). So a touching pair cannot sink or pass through a thin body
21551
+ // between two responses.
21552
+ // - A pair that does not touch now and is not engaged is searched for an entry.
21553
+ // Each Entry after the first of a pair needs a closing motion of the full skin, each Deepening
21554
+ // needs a deepening motion of the full skin, and a StartContact needs a pair that touches without
21555
+ // episodes, which happens at most once per batch time. So the number of events in a substep is finite.
20980
21556
  Status run() {
20981
21557
  if (ran_) return Status::Consumed;
20982
21558
  ran_ = true;
@@ -21022,22 +21598,28 @@ class MotionContactEventBatch {
21022
21598
  if ((!a.bullet && !b.bullet) || !bodiesCanCollide(a, b)
21023
21599
  || collisionDisabled(operation_, first, second)) continue;
21024
21600
  triangle_adapter_private::work(operation_);
21025
- const auto transition = collide(operation_, a, b).hit
21026
- ? MotionContactTransition::Departure : MotionContactTransition::Entry;
21027
- MotionContactSearch search(operation_, first, second, transition);
21028
- const auto result = search.run();
21029
- if (result == MotionContactSearchStatus::Clear
21030
- || result == MotionContactSearchStatus::ContactThroughEnd) continue;
21031
- if (result != MotionContactSearchStatus::Entry && result != MotionContactSearchStatus::Departure)
21032
- return fail(searchFailure(result));
21033
- MotionContactSearchView view;
21034
- const auto checked = search.read(operation_, view);
21035
- if (checked != result) return fail(searchFailure(checked));
21036
- if (view.timeDomain != MotionTimeDomain::NativeBinary64) return fail(Status::Unresolved);
21037
- if (view.bracket[1] > native.time) continue;
21038
- if (view.bracket[1] < native.time) { native.events.clear(); native.time = view.bracket[1]; }
21039
- triangle_adapter_private::append(operation_, native.events,
21040
- MotionContactBatchEvent{{first, second}, transition, view.bracket, view.collision});
21601
+ const Collision touching = collide(operation_, a, b);
21602
+ const bool engaged = hasEpisodes(operation_, first, second);
21603
+ if (touching.hit && !engaged) {
21604
+ if (native.now < native.time) { native.events.clear(); native.time = native.now; }
21605
+ triangle_adapter_private::append(operation_, native.events, MotionContactBatchEvent{
21606
+ {first, second}, {native.now, native.now}, touching, MotionContactEventKind::StartContact});
21607
+ continue;
21608
+ }
21609
+ if (!touching.hit && engaged) {
21610
+ if (withinMotionContactSkin(operation_, a, b)) continue;
21611
+ triangle_adapter_private::append(operation_, native.separated, std::array<std::uint32_t, 2>{first, second});
21612
+ }
21613
+ // A StartContact event decides the batch time, so no later event can be selected.
21614
+ if (native.time == native.now) continue;
21615
+ if (touching.hit) {
21616
+ const auto status = watchEngagedPair(native, first, second, touching);
21617
+ if (status != Status::Complete) return fail(status);
21618
+ continue;
21619
+ }
21620
+ MotionContactSearch search(operation_, first, second, MotionContactTransition::Entry);
21621
+ const auto status = selectSearchEvent(native, search, search.run(), first, second, MotionContactEventKind::Entry);
21622
+ if (status != Status::Complete) return fail(status);
21041
21623
  }
21042
21624
  }
21043
21625
  const auto checked = validateSource();
@@ -21074,7 +21656,48 @@ class MotionContactEventBatch {
21074
21656
  return readMaterialAtPhase(operation, output, true);
21075
21657
  }
21076
21658
  private:
21659
+ static bool hasEpisodes(SolverOperation& operation, std::uint32_t first, std::uint32_t second);
21077
21660
  struct Source { Body body; BodyMotionEpoch epoch; };
21661
+ struct NativeSelection;
21662
+ // Adds the event of a search that returned `result` to the selection if it is not later than the
21663
+ // selected time.
21664
+ Status selectSearchEvent(NativeSelection& native, MotionContactSearch& search, MotionContactSearchStatus result,
21665
+ std::uint32_t first, std::uint32_t second, MotionContactEventKind kind) {
21666
+ if (result == MotionContactSearchStatus::Clear) return Status::Complete;
21667
+ if (result != MotionContactSearchStatus::Entry) return searchFailure(result);
21668
+ MotionContactSearchView view;
21669
+ const auto checked = search.read(operation_, view);
21670
+ if (checked != result) return searchFailure(checked);
21671
+ if (view.timeDomain != MotionTimeDomain::NativeBinary64 || !(view.bracket[1] > native.now)) return Status::Unresolved;
21672
+ if (view.bracket[1] > native.time) return Status::Complete;
21673
+ if (view.bracket[1] < native.time) { native.events.clear(); native.time = view.bracket[1]; }
21674
+ triangle_adapter_private::append(operation_, native.events,
21675
+ MotionContactBatchEvent{{first, second}, view.bracket, view.collision, kind});
21676
+ return Status::Complete;
21677
+ }
21678
+ // Watches an engaged pair that touches now: a Deepening event is the first time at which the pair
21679
+ // is one contact skin deeper than its depth now. The depth that collide() reports can be smaller
21680
+ // than the depth at which the shrunk body touches (a mesh pair reports the depth of one triangle),
21681
+ // so the watch doubles the extra depth until the shrunk body does not touch now. A pair with no
21682
+ // sphere, capsule or box is watched on its reported depth (ReportedDepth). A pair that is deeper
21683
+ // than its shrunk bodies can measure is not watched: it already overlaps more than the thinner
21684
+ // measurable body.
21685
+ Status watchEngagedPair(NativeSelection& native, std::uint32_t first, std::uint32_t second, const Collision& touching) {
21686
+ if (!finite(touching.penetration)) return Status::Unresolved;
21687
+ const auto& a = native.sources[first].body;
21688
+ const auto& b = native.sources[second].body;
21689
+ const double depth = std::max(touching.penetration, 0.0);
21690
+ for (double extra = kMotionContactSkin; finite(extra); extra *= 2.0) {
21691
+ triangle_adapter_private::work(operation_);
21692
+ const auto erosion = erodedMotionPair(a, b, depth + extra);
21693
+ if (!erosion) return Status::Complete;
21694
+ MotionContactSearch search(operation_, first, second, MotionContactTransition::Entry, erosion);
21695
+ const auto result = search.run();
21696
+ if (result == MotionContactSearchStatus::StartContact) continue;
21697
+ return selectSearchEvent(native, search, result, first, second, MotionContactEventKind::Deepening);
21698
+ }
21699
+ return Status::Unresolved;
21700
+ }
21078
21701
  struct NativeSelection {
21079
21702
  const Body* bodyData = nullptr;
21080
21703
  const BodyMotionEpoch* epochData = nullptr;
@@ -21084,6 +21707,8 @@ class MotionContactEventBatch {
21084
21707
  std::vector<Source> sources;
21085
21708
  std::vector<std::array<std::uint32_t, 2>> disabled;
21086
21709
  std::vector<MotionContactBatchEvent> events;
21710
+ // Pairs that have episodes but are farther apart than the contact skin at `now`.
21711
+ std::vector<std::array<std::uint32_t, 2>> separated;
21087
21712
  };
21088
21713
  using TimeOwner = std::shared_ptr<const MaterialTime>;
21089
21714
  using MotionOwner = std::shared_ptr<const MaterialMotionSource>;
@@ -22193,11 +22818,7 @@ class ContactEventPhaseOwner {
22193
22818
  const auto& material = accepted ? accepted->material : warm->material;
22194
22819
  const auto& point = sameContactFrame(material.frame, geometry.frame)
22195
22820
  ? episode.constraint.point : contact.point;
22196
- staged.insert(staged.end(), {
22197
- static_cast<double>(contact.bodyA), static_cast<double>(contact.bodyB),
22198
- static_cast<double>(contact.featureId), contact.impulses[0], contact.impulses[1],
22199
- contact.impulses[2], point[0], point[1], point[2],
22200
- });
22821
+ appendContactCacheRow(staged, contact, point);
22201
22822
  }
22202
22823
  triangle_adapter_private::work(operation_);
22203
22824
  operation_.storage.contactCacheOutput.swap(staged);
@@ -22628,6 +23249,15 @@ MaterialBoundsStatus adoptMaterialContactResponses(SolverOperation& operation) {
22628
23249
  std::terminate();
22629
23250
  }
22630
23251
 
23252
+ // The contact episodes of a step live in its phase owner. Without a phase owner, no pair has episodes.
23253
+ bool MotionContactEventBatch::hasEpisodes(SolverOperation& operation, std::uint32_t first, std::uint32_t second) {
23254
+ auto* phase = operation.contactPhaseOwner;
23255
+ if (phase == nullptr) return false;
23256
+ const auto index = phase->findEpisode(first, second, 0);
23257
+ return index < phase->episodes_.size() && std::get<0>(phase->episodes_[index].key) == first
23258
+ && std::get<1>(phase->episodes_[index].key) == second;
23259
+ }
23260
+
22631
23261
  MotionContactEventBatchStatus MotionContactEventBatch::retireDepartures(ContactEventPhaseOwner& phase) {
22632
23262
  const auto reject = [&](Status status) {
22633
23263
  transfer_ = FailedEpisodeTransfer{status};
@@ -22675,15 +23305,17 @@ MotionContactEventBatchStatus MotionContactEventBatch::retireDepartures(ContactE
22675
23305
  transfer_ = RetiredEpisodes{&phase};
22676
23306
  return Status::Selected;
22677
23307
  }
23308
+ // A pair that was farther apart than the contact skin when the batch ran leaves contact here.
23309
+ // Its entry search proved that it does not touch before this event time. If it touches at this
23310
+ // time, activateEntries gives it new episodes.
22678
23311
  std::vector<std::array<std::size_t, 2>> ranges;
22679
23312
  std::uint64_t eraseWork = 0;
22680
- for (const auto& event : std::get<NativeSelection>(selection_).events) {
22681
- if (event.transition != MotionContactTransition::Departure) continue;
22682
- const auto first = phase.findEpisode(event.pair[0], event.pair[1], 0);
23313
+ for (const auto& pair : std::get<NativeSelection>(selection_).separated) {
23314
+ const auto first = phase.findEpisode(pair[0], pair[1], 0);
22683
23315
  std::size_t last = first;
22684
23316
  while (last < phase.episodes_.size()
22685
- && std::get<0>(phase.episodes_[last].key) == event.pair[0]
22686
- && std::get<1>(phase.episodes_[last].key) == event.pair[1]) {
23317
+ && std::get<0>(phase.episodes_[last].key) == pair[0]
23318
+ && std::get<1>(phase.episodes_[last].key) == pair[1]) {
22687
23319
  triangle_adapter_private::work(operation_);
22688
23320
  ++last;
22689
23321
  }
@@ -22757,14 +23389,22 @@ MotionContactEventBatchStatus MotionContactEventBatch::activateEntries(ContactEv
22757
23389
  }
22758
23390
  }
22759
23391
  } else for (const auto& event : std::get<NativeSelection>(selection_).events) {
22760
- if (event.transition != MotionContactTransition::Entry) continue;
22761
23392
  const auto& a = operation_.storage.soaBodies[event.pair[0]];
22762
23393
  const auto& b = operation_.storage.soaBodies[event.pair[1]];
22763
23394
  const auto& collision = event.collision;
22764
23395
  const Vec3 normal{collision.nx, collision.ny, collision.nz};
22765
23396
  const auto count = contactPointCount(collision);
23397
+ // A pair that touches without episodes must get at least one, or its batch time cannot pass.
23398
+ if (!collision.hit || (event.kind != MotionContactEventKind::Deepening && count == 0)) return reject(Status::Unresolved);
22766
23399
  for (std::uint32_t pointIndex = 0; pointIndex < count; ++pointIndex) {
22767
23400
  triangle_adapter_private::work(operation_);
23401
+ // A deepening pair keeps the episodes of the features that it already has.
23402
+ if (event.kind == MotionContactEventKind::Deepening) {
23403
+ const auto feature = contactFeatureId(collision, pointIndex);
23404
+ const auto index = phase.findEpisode(event.pair[0], event.pair[1], feature);
23405
+ if (index < phase.episodes_.size() && phase.episodes_[index].key == std::tuple{event.pair[0], event.pair[1], feature})
23406
+ continue;
23407
+ }
22768
23408
  const auto point = contactPoint(collision, a, b, pointIndex);
22769
23409
  const auto levers = triangle_adapter_private::collisionLevers(operation_, collision, pointIndex, a, b, point);
22770
23410
  const auto velocity = dotVec3(contactRelativeVelocity(a, b, levers[0], levers[1]), normal);
@@ -22956,7 +23596,14 @@ ContactEventPhaseOwner::ClockStatus ContactEventPhaseOwner::advanceMotionClock(
22956
23596
  MotionContactEventBatchView selected;
22957
23597
  const auto read = batch.read(operation_, selected);
22958
23598
  if (read != status) return batchFailure(read);
22959
- if (!(selected.time > operation_.committedMotionTime)
23599
+ // Only pairs that touch without episodes stop the clock without a time step. They get episodes
23600
+ // here, so the next batch at the same time cannot select them again.
23601
+ const bool startsNow = status == MotionContactEventBatchStatus::Selected && !selected.events.empty()
23602
+ && std::all_of(selected.events.begin(), selected.events.end(), [](const MotionContactBatchEvent& event) {
23603
+ return event.kind == MotionContactEventKind::StartContact;
23604
+ });
23605
+ if (!(selected.time > operation_.committedMotionTime
23606
+ || (startsNow && selected.time == operation_.committedMotionTime))
22960
23607
  || !stageBodyMotionAtTime(operation_, selected.time)
22961
23608
  || !publishStagedBodyMotion(operation_)) return reject(ClockStatus::Unresolved);
22962
23609
  }
@@ -24881,32 +25528,13 @@ std::int32_t stepSoAWithJointsInternal(
24881
25528
  }
24882
25529
  }
24883
25530
  }
25531
+ // A world with a bullet body always steps on the native motion clock. The material motion clock
25532
+ // has no contact skin, so a bullet that rests or rolls on it uses all the geometry work of a step,
25533
+ // and it moves bodies only by translation, so a bullet that starts to rotate stops its next search.
25534
+ // A world without a bullet keeps its material pose.
24884
25535
  const auto materialMotionPairsSupported = [&] {
24885
- bool hasBullet = false;
24886
- for (std::uint32_t index = 0; index < bodyCount; ++index) {
24887
- if (operation.storage.soaBodies[index].bullet) {
24888
- hasBullet = true;
24889
- break;
24890
- }
24891
- }
24892
- if (!hasBullet) return true;
24893
- // A pure predicate over pairs that contain a bullet, so the visit order does not matter.
24894
- for (std::uint32_t bullet = 0; bullet < bodyCount; ++bullet) {
24895
- if (!operation.storage.soaBodies[bullet].bullet) continue;
24896
- for (std::uint32_t other = 0; other < bodyCount; ++other) {
24897
- if (other == bullet || (operation.storage.soaBodies[other].bullet && other < bullet)) continue;
24898
- const std::uint32_t first = std::min(bullet, other);
24899
- const std::uint32_t second = std::max(bullet, other);
24900
- const auto& a = operation.storage.soaBodies[first];
24901
- const auto& b = operation.storage.soaBodies[second];
24902
- if ((!a.bullet && !b.bullet) || !bodiesCanCollide(a, b)
24903
- || collisionDisabled(operation, first, second)) continue;
24904
- if ((a.bullet && a.angularState && a.shape != ShapeKind::Sphere)
24905
- || (b.bullet && b.angularState && b.shape != ShapeKind::Sphere)) return false;
24906
- if (motionContactPairKind(a, b) == MotionContactPairKind::Unsupported) return false;
24907
- }
24908
- }
24909
- return true;
25536
+ return std::none_of(operation.storage.soaBodies.begin(), operation.storage.soaBodies.begin() + bodyCount,
25537
+ [](const Body& body) { return body.bullet; });
24910
25538
  };
24911
25539
  WorldPose admittedPose = pose;
24912
25540
  if (!materialMotionPairsSupported()) {