From a2e4816b4359b32408d5623784a7fe2d7259d3d6 Mon Sep 17 00:00:00 2001 From: Erin Catto Date: Mon, 12 Oct 2026 21:46:51 -0700 Subject: [PATCH] Fixes for #175 (#187) See #175 It is LLM so verbose and lacking context, but it did find a couple things worth fixing. --- docs/faq.md | 35 ++++++++ include/box3d/box3d.h | 2 + src/contact.c | 16 ++-- src/convex_manifold.c | 6 +- test/test_determinism.c | 8 +- test/test_manifold.c | 112 ++++++++++++++++++++++++++ test/test_world.c | 172 ++++++++++++++++++++++++++++++++++++++++ 7 files changed, 339 insertions(+), 12 deletions(-) diff --git a/docs/faq.md b/docs/faq.md index f979165..246624c 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -121,6 +121,41 @@ approximately solve the differential equations. Box3D also does not have exact c moving shapes may have small overlap for a few time steps. In extreme stacking scenarios, shapes may have sustained overlap. +## Shapes + +### Why doesn't Box3D have a cylinder shape? + +Cylinders look simple but they are one of the hardest shapes to make work well in a 3D physics engine. Other engines +that support cylinders tend to document them as their least stable shape. A cylinder combines three kinds of geometry +that each need different handling: + +* flat caps, like a polytope +* a sharp circular rim, like an edge that is curved +* a curved side, like a capsule that has no rounded ends + +These cause several problems: + +**Collision algorithms don't fit.** The other shapes in Box3D fall into two families. Spheres and capsules are a point +or a segment with a radius, so their collision is closed form and exact. Convex hulls have a finite set of faces and +edges, so Box3D can find the separating axis directly and clip faces to build a contact manifold. A cylinder belongs to +neither family. Its side has infinitely many face normals, and the rim is a curved edge. Testing the rim against a box +edge means solving a quartic. So engines fall back on GJK with a support function, which converges slowly on smooth +shapes. They also need extra machinery such as EPA or shrunken cores with margins for overlapping shapes. + +GJK only gives one contact point but a cylinder resting on the end cap needs at least 4 points. Some physics engines +just clip a predefined polygon. In this case it is not really a cylinder being simulated. + +### What should I use instead of a cylinder? + +It depends on what the cylinder is for: +* **Barrels, logs, and pipes that roll:** a capsule rolls perfectly smoothly on its side. The rounded ends are often not + noticeable. Box3D supports rolling resistance for capsules as well. +* **Wheels:** use a sphere for the wheel collision, together with a wheel joint or revolute joint. A sphere rolls + perfectly and is the cheapest shape to collide. Box3D can reject ghost collisions between spheres and internal mesh edges. + Many vehicle setups instead skip wheel collision entirely and use ray casts or shape casts to find the ground. +* **Pillars, coins, and anything that mostly rests on its cap:** use a hull from `b3CreateCylinder()`. It makes a + tessellated cylinder along the y-axis with between 3 and 32 sides. Use the fewest sides that looks acceptable. + ## Making Games ### Tile / Voxel Based Environments diff --git a/include/box3d/box3d.h b/include/box3d/box3d.h index fb88062..65a9d47 100644 --- a/include/box3d/box3d.h +++ b/include/box3d/box3d.h @@ -47,6 +47,8 @@ B3_API int b3GetMaxWorldCount( void ); B3_API bool b3World_IsValid( b3WorldId id ); /// Simulate a world for one time step. This performs collision detection, integration, and constraint solution. +/// A time step of zero runs the broad-phase and collision, but skips the solver. So you can still get contact +/// and sensor events. /// @param worldId The world to simulate /// @param timeStep The amount of time to simulate, this should be a fixed number. Usually 1/60. /// @param subStepCount The number of sub-steps, increasing the sub-step count can increase accuracy. Usually 4. diff --git a/src/contact.c b/src/contact.c index 903c8b1..79436d9 100644 --- a/src/contact.c +++ b/src/contact.c @@ -213,12 +213,6 @@ void b3CreateContact( b3World* world, b3Shape* shapeA, b3Shape* shapeB, int chil contact->encodedBodySimA = b3EncodeBodySimIndex( bodyA ); contact->encodedBodySimB = b3EncodeBodySimIndex( bodyB ); - // Both bodies must enable recycling - if ( ( bodyA->flags & b3_bodyEnableContactRecycling ) != 0 && ( bodyB->flags & b3_bodyEnableContactRecycling ) != 0 ) - { - contact->flags |= b3_contactRecycleFlag; - } - if ( shapeA->type == b3_meshShape || shapeA->type == b3_heightShape ) { contact->flags |= b3_simMeshContact; @@ -255,6 +249,13 @@ void b3CreateContact( b3World* world, b3Shape* shapeA, b3Shape* shapeB, int chil contact->flags |= b3_enableSpeculativePoints; } + // Disabling speculative collision also disables recycling. + if ( ( bodyA->flags & b3_bodyEnableContactRecycling ) != 0 && ( bodyB->flags & b3_bodyEnableContactRecycling ) != 0 && + ( contact->flags & b3_enableSpeculativePoints ) != 0 ) + { + contact->flags |= b3_contactRecycleFlag; + } + // Connect to body A { contact->edges[0].bodyId = shapeA->bodyId; @@ -712,6 +713,9 @@ static bool b3UpdateConvexContact( b3World* world, int workerIndex, b3Contact* c b3FreeManifolds( world, contact->manifolds, contact->manifoldCount ); contact->manifolds = NULL; contact->manifoldCount = 0; + + // Invalidate recycling cache. + contact->flags &= ~b3_relativeTransformValid; return false; } } diff --git a/src/convex_manifold.c b/src/convex_manifold.c index a5dd0bd..6f84f44 100644 --- a/src/convex_manifold.c +++ b/src/convex_manifold.c @@ -218,10 +218,11 @@ void b3CollideSpheres( b3LocalManifold* manifold, int capacity, const b3Sphere* b3Vec3 center2 = b3TransformPoint( transformBtoA, sphereB->center ); float totalRadius = sphereA->radius + sphereB->radius; + float maxDistance = totalRadius + B3_SPECULATIVE_DISTANCE; b3Vec3 offset = b3Sub( center2, center1 ); float distanceSq = b3LengthSquared( offset ); - if ( distanceSq > totalRadius * totalRadius ) + if ( distanceSq > maxDistance * maxDistance ) { // We found a separating axis return; @@ -265,12 +266,13 @@ void b3CollideCapsuleAndSphere( b3LocalManifold* manifold, int capacity, const b b3Vec3 center2 = capsuleA->center2; float totalRadius = sphereB->radius + capsuleA->radius; + float maxDistance = totalRadius + B3_SPECULATIVE_DISTANCE; b3Vec3 closestPoint = b3PointToSegmentDistance( center1, center2, center ); b3Vec3 offset = b3Sub( center, closestPoint ); float distanceSq = b3LengthSquared( offset ); - if ( distanceSq > totalRadius * totalRadius ) + if ( distanceSq > maxDistance * maxDistance ) { // We found a separating axis return; diff --git a/test/test_determinism.c b/test/test_determinism.c index fee1efd..8e7a88a 100644 --- a/test/test_determinism.c +++ b/test/test_determinism.c @@ -21,8 +21,8 @@ #if defined( BOX3D_DOUBLE_PRECISION ) #define RAGDOLL_SLEEP_STEP 266 #define RAGDOLL_HASH 0x68FC7728 -#define WAVE_PILE_SLEEP_STEP 312 -#define WAVE_PILE_HASH 0xFD6BD36B +#define WAVE_PILE_SLEEP_STEP 322 +#define WAVE_PILE_HASH 0x81798F75 #define QUERY_SPAWN_SLEEP_STEP 242 #define QUERY_SPAWN_HASH 0x9B96A098 #define QUERY_SPAWN_HIT_COUNT 59 @@ -32,8 +32,8 @@ #else #define RAGDOLL_SLEEP_STEP 267 #define RAGDOLL_HASH 0x9BCA269D -#define WAVE_PILE_SLEEP_STEP 270 -#define WAVE_PILE_HASH 0xAD7C3901 +#define WAVE_PILE_SLEEP_STEP 281 +#define WAVE_PILE_HASH 0x23A90492 #define QUERY_SPAWN_SLEEP_STEP 242 #define QUERY_SPAWN_HASH 0xF1EDEF47 #define QUERY_SPAWN_HIT_COUNT 59 diff --git a/test/test_manifold.c b/test/test_manifold.c index d061c80..a304ef1 100644 --- a/test/test_manifold.c +++ b/test/test_manifold.c @@ -52,6 +52,11 @@ static b3Transform SlideX( float x ) return (b3Transform){ { x, 0.0f, 0.0f }, b3Quat_identity }; } +static b3Transform SlideY( float y ) +{ + return (b3Transform){ { 0.0f, y, 0.0f }, b3Quat_identity }; +} + static float MinSeparation( const b3LocalManifold* manifold ) { float minSeparation = FLT_MAX; @@ -1249,6 +1254,112 @@ static int HullCapsuleFaceDeepTest( void ) return 0; } +static int CheckSpeculativePoints( const b3LocalManifold* manifold, float gap ) +{ + ENSURE( manifold->pointCount > 0 ); + ENSURE_SMALL( MinSeparation( manifold ) - gap, 1e-4f ); + return 0; +} + +// Contact recycling treats a pair without points as separated by at least the speculative distance. +// Every manifold routine must report a pair inside that distance or recycling can skip real overlap. +// Discussion #175. +static int SpeculativeMarginTest( void ) +{ + float gaps[] = { 0.0f, 0.25f * B3_SPECULATIVE_DISTANCE, 0.75f * B3_SPECULATIVE_DISTANCE }; + int gapCount = sizeof( gaps ) / sizeof( gaps[0] ); + + b3Sphere sphere = { b3Vec3_zero, 0.25f }; + b3Sphere bigSphere = { b3Vec3_zero, 0.5f }; + b3Capsule capsuleX = { { -0.5f, 0.0f, 0.0f }, { 0.5f, 0.0f, 0.0f }, 0.25f }; + b3Capsule capsuleZ = { { 0.0f, 0.0f, -0.5f }, { 0.0f, 0.0f, 0.5f }, 0.25f }; + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + + // Normal is +y + b3Vec3 triangle[3] = { { -2.0f, 0.0f, -2.0f }, { 0.0f, 0.0f, 2.0f }, { 2.0f, 0.0f, -2.0f } }; + + b3LocalManifoldPoint points[B3_MAX_MANIFOLD_POINTS]; + b3LocalManifold manifold = { 0 }; + manifold.points = points; + + for ( int i = 0; i < gapCount; ++i ) + { + float gap = gaps[i]; + + manifold.pointCount = 0; + b3CollideSpheres( &manifold, B3_MAX_MANIFOLD_POINTS, &bigSphere, &sphere, SlideY( 0.75f + gap ) ); + ENSURE( CheckSpeculativePoints( &manifold, gap ) == 0 ); + + manifold.pointCount = 0; + b3CollideCapsuleAndSphere( &manifold, B3_MAX_MANIFOLD_POINTS, &capsuleX, &sphere, SlideY( 0.5f + gap ) ); + ENSURE( CheckSpeculativePoints( &manifold, gap ) == 0 ); + + manifold.pointCount = 0; + b3CollideCapsules( &manifold, B3_MAX_MANIFOLD_POINTS, &capsuleX, &capsuleZ, SlideY( 0.5f + gap ) ); + ENSURE( CheckSpeculativePoints( &manifold, gap ) == 0 ); + + { + manifold.pointCount = 0; + b3SimplexCache cache = { 0 }; + b3CollideHullAndSphere( &manifold, B3_MAX_MANIFOLD_POINTS, &box.base, &sphere, SlideY( 0.75f + gap ), &cache ); + ENSURE( CheckSpeculativePoints( &manifold, gap ) == 0 ); + } + + { + manifold.pointCount = 0; + b3SimplexCache cache = { 0 }; + b3CollideHullAndCapsule( &manifold, B3_MAX_MANIFOLD_POINTS, &box.base, &capsuleX, SlideY( 0.75f + gap ), &cache ); + ENSURE( CheckSpeculativePoints( &manifold, gap ) == 0 ); + } + + { + manifold.pointCount = 0; + b3SATCache cache = { 0 }; + b3CollideHulls( &manifold, B3_MAX_MANIFOLD_POINTS, &box.base, &box.base, SlideY( 1.0f + gap ), &cache ); + ENSURE( CheckSpeculativePoints( &manifold, gap ) == 0 ); + } + + { + manifold.pointCount = 0; + b3Sphere raised = { { 0.0f, 0.25f + gap, 0.0f }, 0.25f }; + b3CollideTriangleAndSphere( &manifold, B3_MAX_MANIFOLD_POINTS, triangle, &raised ); + ENSURE( CheckSpeculativePoints( &manifold, gap ) == 0 ); + } + + { + manifold.pointCount = 0; + b3Capsule raised = capsuleX; + raised.center1.y = 0.25f + gap; + raised.center2.y = 0.25f + gap; + b3SimplexCache cache = { 0 }; + b3CollideTriangleAndCapsule( &manifold, B3_MAX_MANIFOLD_POINTS, triangle, &raised, &cache ); + ENSURE( CheckSpeculativePoints( &manifold, gap ) == 0 ); + } + + { + manifold.pointCount = 0; + b3BoxHull raised = b3MakeTransformedBoxHull( 0.5f, 0.5f, 0.5f, SlideY( 0.5f + gap ) ); + b3SATCache cache = { 0 }; + b3CollideTriangleAndHull( &manifold, B3_MAX_MANIFOLD_POINTS, triangle[0], triangle[1], triangle[2], 0, &raised.base, + &cache, true ); + ENSURE( CheckSpeculativePoints( &manifold, gap ) == 0 ); + } + } + + // Beyond the speculative distance the closed form routines report nothing + float farGap = 1.5f * B3_SPECULATIVE_DISTANCE; + + manifold.pointCount = 0; + b3CollideSpheres( &manifold, B3_MAX_MANIFOLD_POINTS, &bigSphere, &sphere, SlideY( 0.75f + farGap ) ); + ENSURE( manifold.pointCount == 0 ); + + manifold.pointCount = 0; + b3CollideCapsuleAndSphere( &manifold, B3_MAX_MANIFOLD_POINTS, &capsuleX, &sphere, SlideY( 0.5f + farGap ) ); + ENSURE( manifold.pointCount == 0 ); + + return 0; +} + // The library reports the point count it was built with. A mismatch against the manifold // this translation unit sees means the app and the library disagree on b3Manifold. static int MaxPointCountTest( void ) @@ -1281,6 +1392,7 @@ int ManifoldTest( void ) RUN_SUBTEST( HullCapsuleFaceDeepTest ); RUN_SUBTEST( SphereHullSeamTest ); RUN_SUBTEST( CapsuleHullSeamTest ); + RUN_SUBTEST( SpeculativeMarginTest ); return 0; } diff --git a/test/test_world.c b/test/test_world.c index 7b31785..1078609 100644 --- a/test/test_world.c +++ b/test/test_world.c @@ -14,6 +14,7 @@ #include "box3d/constants.h" #include "box3d/math_functions.h" +#include #include #include @@ -974,6 +975,174 @@ static int EnableContactRecyclingTest( void ) return 0; } +// A slow sphere closes on a static round shape from just outside contact. The step is too short +// to make the sphere fast, so the pair is eligible for recycling. A routine without a speculative +// margin left the pair empty and recycling then let the sphere sink without a contact. Discussion #175. +static int RunRecycledApproach( bool capsuleTarget ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + worldDef.gravity = b3Vec3_zero; + b3WorldId worldId = b3CreateWorld( &worldDef ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_staticBody; + b3BodyId targetId = b3CreateBody( worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + float targetRadius = 0.5f; + if ( capsuleTarget ) + { + b3Capsule capsule = { { -1.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f }, targetRadius }; + b3CreateCapsuleShape( targetId, &shapeDef, &capsule ); + } + else + { + b3Sphere sphere = { b3Vec3_zero, targetRadius }; + b3CreateSphereShape( targetId, &shapeDef, &sphere ); + } + + float radius = 0.25f; + float totalRadius = targetRadius + radius; + float timeStep = 1.0f / 60.0f; + + // Half the speculative distance per step + float speed = 0.5f * B3_SPECULATIVE_DISTANCE / timeStep; + + bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = (b3Pos){ 0.0f, totalRadius + 0.25f * B3_SPECULATIVE_DISTANCE, 0.0f }; + bodyDef.linearVelocity = (b3Vec3){ 0.0f, -speed, 0.0f }; + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + + b3Sphere sphere = { b3Vec3_zero, radius }; + b3CreateSphereShape( bodyId, &shapeDef, &sphere ); + + float minSeparation = FLT_MAX; + for ( int i = 0; i < 20; ++i ) + { + b3World_Step( worldId, timeStep, 4 ); + + b3Pos p = b3Body_GetPosition( bodyId ); + minSeparation = b3MinFloat( minSeparation, (float)p.y - totalRadius ); + } + + b3DestroyWorld( worldId ); + + ENSURE( minSeparation > -B3_LINEAR_SLOP ); + + return 0; +} + +static int RecycledSphereApproachTest( void ) +{ + ENSURE( RunRecycledApproach( false ) == 0 ); + ENSURE( RunRecycledApproach( true ) == 0 ); + return 0; +} + +static bool PreSolveReject( b3ShapeId shapeIdA, b3ShapeId shapeIdB, b3Pos point, b3Vec3 normal, void* context ) +{ + (void)shapeIdA; + (void)shapeIdB; + (void)point; + (void)normal; + bool* reject = context; + return *reject == false; +} + +// A rejected pre-solve frees the manifold while the shapes may already touch. The next step must +// rebuild the contact and ask again instead of recycling the empty pair. +static int PreSolveRejectRecycleTest( void ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + worldDef.enableSleep = false; + b3WorldId worldId = b3CreateWorld( &worldDef ); + + bool reject = true; + b3World_SetPreSolveCallback( worldId, PreSolveReject, &reject ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_staticBody; + bodyDef.position = (b3Pos){ 0.0f, -0.5f, 0.0f }; + b3BodyId groundId = b3CreateBody( worldId, &bodyDef ); + b3BoxHull groundBox = b3MakeBoxHull( 10.0f, 0.5f, 10.0f ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( groundId, &shapeDef, &groundBox.base ); + + float radius = 0.25f; + bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = (b3Pos){ 0.0f, radius, 0.0f }; + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + + shapeDef.enablePreSolveEvents = true; + b3Sphere sphere = { b3Vec3_zero, radius }; + b3CreateSphereShape( bodyId, &shapeDef, &sphere ); + + b3World_Step( worldId, 1.0f / 60.0f, 4 ); + + reject = false; + + float minSeparation = FLT_MAX; + for ( int i = 0; i < 30; ++i ) + { + b3World_Step( worldId, 1.0f / 60.0f, 4 ); + + b3Pos p = b3Body_GetPosition( bodyId ); + minSeparation = b3MinFloat( minSeparation, (float)p.y - radius ); + } + + b3DestroyWorld( worldId ); + + ENSURE( minSeparation > -B3_LINEAR_SLOP ); + + return 0; +} + +static int CountRecycledResting( bool enableSpeculative ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + worldDef.enableSleep = false; + b3WorldId worldId = b3CreateWorld( &worldDef ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_staticBody; + bodyDef.position = (b3Pos){ 0.0f, -0.5f, 0.0f }; + b3BodyId groundId = b3CreateBody( worldId, &bodyDef ); + b3BoxHull groundBox = b3MakeBoxHull( 10.0f, 0.5f, 10.0f ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( groundId, &shapeDef, &groundBox.base ); + + bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = (b3Pos){ 0.0f, 0.5f, 0.0f }; + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + + shapeDef.enableSpeculativeContact = enableSpeculative; + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + + int recycledCount = 0; + for ( int i = 0; i < 60; ++i ) + { + b3World_Step( worldId, 1.0f / 60.0f, 4 ); + recycledCount += b3World_GetCounters( worldId ).recycledContactCount; + } + + b3DestroyWorld( worldId ); + + return recycledCount; +} + +// Without speculative points an empty pair may be closer than the speculative distance, so these +// contacts must never recycle +static int SpeculativeOffRecycleTest( void ) +{ + ENSURE( CountRecycledResting( true ) > 0 ); + ENSURE( CountRecycledResting( false ) == 0 ); + return 0; +} + static int CountMovedNodes( const b3DynamicTree* tree ) { int count = 0; @@ -1640,6 +1809,9 @@ int WorldTest( void ) RUN_SUBTEST( EnableSleepFlagSyncTest ); RUN_SUBTEST( EnableSleepNoopUnlockTest ); RUN_SUBTEST( EnableContactRecyclingTest ); + RUN_SUBTEST( RecycledSphereApproachTest ); + RUN_SUBTEST( PreSolveRejectRecycleTest ); + RUN_SUBTEST( SpeculativeOffRecycleTest ); RUN_SUBTEST( TestSetWorkerCount ); RUN_SUBTEST( TestHullDatabase ); RUN_SUBTEST( TestEnlargedProxyDestroyed );