Ghost collision improvements (#61)

- flag to disable hull-mesh speculative collision
- faster atomics #55 
- fix triangle vs hull logic
- fix #58 and #59
- improved shadows in samples app, a bit more expensive
This commit is contained in:
Erin Catto 2026-07-08 23:53:06 -07:00 • committed by GitHub
commit ef8ef0187a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
39 changed files with 16639 additions and 12086 deletions

View file

@ -248,6 +248,11 @@ void b3CreateContact( b3World* world, b3Shape* shapeA, b3Shape* shapeB, int chil
contact->flags |= b3_contactEnableContactEvents;
}
if ( ( shapeA->flags & b3_enableSpeculative ) && ( shapeB->flags & b3_enableSpeculative ) )
{
contact->flags |= b3_enableSpeculativePoints;
}
// Connect to body A
{
contact->edges[0].bodyId = shapeA->bodyId;

View file

@ -65,8 +65,11 @@ enum b3ContactFlags
// This is a mesh contact
b3_simMeshContact = 0x00400000,
// Relative transform is cached for contact recycling
b3_relativeTransformValid = 0x00800000,
// Enable speculative contact points
b3_enableSpeculativePoints = 0x01000000,
};
// A contact edge is used to connect bodies and contacts together

View file

@ -561,6 +561,7 @@ bool b3ComputeMeshManifolds( b3World* world, int workerIndex, b3Contact* contact
// It leads to a small visual gap but seems to improve the quality of mesh
// collision, especially for hull versus mesh.
float restOffset = B3_MESH_REST_OFFSET;
bool enableSpeculative = contact->flags & b3_enableSpeculativePoints;
// Make room for clip points
int pointBufferCapacity = B3_MAX_POINTS_PER_TRIANGLE * triangleCount;
@ -618,8 +619,8 @@ bool b3ComputeMeshManifolds( b3World* world, int workerIndex, b3Contact* contact
cache->satCache = (b3SATCache){ 0 };
}
b3CollideHullAndTriangle( manifold, pointCapacity, hullB, vertices[0], vertices[1], vertices[2],
triangle.flags, &cache->satCache );
b3CollideHullAndTriangle( manifold, pointCapacity, hullB, vertices[0], vertices[1], vertices[2], triangle.flags,
&cache->satCache, enableSpeculative );
context->satCallCount += 1;
context->satCacheHitCount += cache->satCache.hit;
break;

View file

@ -31,18 +31,24 @@ static inline void b3AtomicStoreInt( b3AtomicInt* a, int value )
#elif defined( __GNUC__ ) || defined( __clang__ )
__atomic_store_n( &a->value, value, __ATOMIC_SEQ_CST );
#else
#error "Unsupported platform"
#error "Unsupported platform"
#endif
}
static inline int b3AtomicLoadInt( b3AtomicInt* a )
{
#if defined( _MSC_VER )
return _InterlockedOr( (long*)&a->value, 0 );
#if defined( _MSC_VER ) && !defined( __clang__ )
int value = __iso_volatile_load32( (volatile __int32*)&a->value );
#if defined( _M_ARM ) || defined( _M_ARM64 ) || defined( _M_ARM64EC )
__dmb( 0xB );
#else
_ReadWriteBarrier();
#endif
return value;
#elif defined( __GNUC__ ) || defined( __clang__ )
return __atomic_load_n( &a->value, __ATOMIC_SEQ_CST );
#else
#error "Unsupported platform"
#error "Unsupported platform"
#endif
}
@ -53,7 +59,7 @@ static inline int b3AtomicFetchAddInt( b3AtomicInt* a, int increment )
#elif defined( __GNUC__ ) || defined( __clang__ )
return __atomic_fetch_add( &a->value, increment, __ATOMIC_SEQ_CST );
#else
#error "Unsupported platform"
#error "Unsupported platform"
#endif
}
@ -65,7 +71,7 @@ static inline bool b3AtomicCompareExchangeInt( b3AtomicInt* a, int expected, int
// The value written to expected is ignored
return __atomic_compare_exchange_n( &a->value, &expected, desired, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST );
#else
#error "Unsupported platform"
#error "Unsupported platform"
#endif
}
@ -76,17 +82,23 @@ static inline void b3AtomicStoreU32( b3AtomicU32* a, uint32_t value )
#elif defined( __GNUC__ ) || defined( __clang__ )
__atomic_store_n( &a->value, value, __ATOMIC_SEQ_CST );
#else
#error "Unsupported platform"
#error "Unsupported platform"
#endif
}
static inline uint32_t b3AtomicLoadU32( b3AtomicU32* a )
{
#if defined( _MSC_VER )
return (uint32_t)_InterlockedOr( (long*)&a->value, 0 );
#if defined( _MSC_VER ) && !defined( __clang__ )
uint32_t value = (uint32_t)__iso_volatile_load32( (volatile __int32*)&a->value );
#if defined( _M_ARM ) || defined( _M_ARM64 ) || defined( _M_ARM64EC )
__dmb( 0xB );
#else
_ReadWriteBarrier();
#endif
return value;
#elif defined( __GNUC__ ) || defined( __clang__ )
return __atomic_load_n( &a->value, __ATOMIC_SEQ_CST );
#else
#error "Unsupported platform"
#error "Unsupported platform"
#endif
}

View file

@ -399,6 +399,7 @@ void b3RecW_SHAPEDEF( b3RecBuffer* buf, b3ShapeDef v )
b3RecW_BOOL( buf, v.enablePreSolveEvents );
b3RecW_BOOL( buf, v.invokeContactCreation );
b3RecW_BOOL( buf, v.updateBodyMass );
b3RecW_BOOL( buf, v.enableSpeculativeContact );
// internalValue omitted
}

View file

@ -46,8 +46,8 @@ typedef struct b3World b3World;
#define B3_REC_MAGIC 0x43523342u
// Major recording version is bumped when writers change.
// Major version 3 added shape names.
#define B3_REC_VERSION_MAJOR 3
// Major version 4 added b3ShapeDef::enableSpeculativeContact
#define B3_REC_VERSION_MAJOR 4
// Minor tracks op-stream additions that keep the 48 byte header shape.
// Minor version 3 added name cache.

View file

@ -483,6 +483,7 @@ b3ShapeDef b3RecR_SHAPEDEF( b3RecReader* rdr )
def.enablePreSolveEvents = b3RecR_BOOL( rdr );
def.invokeContactCreation = b3RecR_BOOL( rdr );
def.updateBodyMass = b3RecR_BOOL( rdr );
def.enableSpeculativeContact = b3RecR_BOOL( rdr );
def.userData = NULL;
return def;
}

View file

@ -181,6 +181,7 @@ static b3Shape* b3CreateShapeInternal( b3World* world, b3Body* body, b3WorldTran
shape->flags |= def->enableCustomFiltering ? b3_enableCustomFiltering : 0;
shape->flags |= def->enableHitEvents ? b3_enableHitEvents : 0;
shape->flags |= def->enablePreSolveEvents ? b3_enablePreSolveEvents : 0;
shape->flags |= def->enableSpeculativeContact ? b3_enableSpeculative : 0;
shape->proxyKey = B3_NULL_INDEX;
shape->localCentroid = b3GetShapeCentroid( shape );
shape->aabbMargin = b3ComputeShapeMargin( shape );

View file

@ -20,6 +20,7 @@ typedef enum b3ShapeFlags
b3_enableHitEvents = 0x08,
b3_enablePreSolveEvents = 0x10,
b3_enlargedAABB = 0x20,
b3_enableSpeculative = 0x40,
} b3ShapeFlags;
typedef struct b3Shape

View file

@ -595,8 +595,8 @@ static b3EdgeQuery b3TestEdgePairs( const b3TriangleData* triangle, const b3Hull
return result;
}
static float b3CollideHullFace( b3LocalManifold* manifold, int pointCapacity, const b3TriangleData* triangle, const b3HullData* hull,
b3FaceQuery query, b3SATCache* cache )
static float b3CollideHullFace( b3LocalManifold* manifold, int pointCapacity, const b3TriangleData* triangle,
const b3HullData* hull, b3FaceQuery query, b3SATCache* cache, bool enableSpeculative )
{
manifold->pointCount = 0;
@ -663,23 +663,31 @@ static float b3CollideHullFace( b3LocalManifold* manifold, int pointCapacity, co
pointCount = b3MinInt( pointCount, pointCapacity );
float minSeparation = FLT_MAX;
int finalPointCount = 0;
for ( int i = 0; i < pointCount; ++i )
{
b3ClipVertex* clipPoint = input + i;
minSeparation = b3MinFloat( minSeparation, clipPoint->separation );
if ( enableSpeculative == false && clipPoint->separation > 0.0f )
{
continue;
}
// Move point onto hull face improved culling
b3Vec3 point = b3MulSub( clipPoint->position, clipPoint->separation, refPlane.normal );
b3LocalManifoldPoint* pt = manifold->points + i;
b3LocalManifoldPoint* pt = manifold->points + finalPointCount;
pt->point = point;
pt->separation = clipPoint->separation;
pt->pair = b3FlipPair( clipPoint->pair );
minSeparation = b3MinFloat( minSeparation, clipPoint->separation );
finalPointCount += 1;
}
if ( minSeparation > B3_SPECULATIVE_DISTANCE )
float speculativeDistance = enableSpeculative ? B3_SPECULATIVE_DISTANCE : 0.0f;
if ( minSeparation > speculativeDistance )
{
// This can occur with a stale SAT cache
manifold->pointCount = 0;
@ -687,7 +695,7 @@ static float b3CollideHullFace( b3LocalManifold* manifold, int pointCapacity, co
return minSeparation;
}
manifold->pointCount = pointCount;
manifold->pointCount = finalPointCount;
manifold->normal = b3Neg( refPlane.normal );
manifold->feature = b3_featureHullFace;
@ -700,7 +708,7 @@ static float b3CollideHullFace( b3LocalManifold* manifold, int pointCapacity, co
}
static float b3CollideTriangleFace( b3LocalManifold* manifold, int pointCapacity, const b3TriangleData* triangle,
const b3HullData* hull, b3FaceQuery query, b3SATCache* cache )
const b3HullData* hull, b3FaceQuery query, b3SATCache* cache, bool enableSpeculative )
{
B3_VALIDATE( manifold->pointCount == 0 );
@ -770,30 +778,38 @@ static float b3CollideTriangleFace( b3LocalManifold* manifold, int pointCapacity
float minSeparation = FLT_MAX;
int finalPointCount = 0;
for ( int i = 0; i < pointCount; ++i )
{
b3ClipVertex* clipPoint = input + i;
minSeparation = b3MinFloat( minSeparation, clipPoint->separation );
if ( enableSpeculative == false && clipPoint->separation > 0.0f )
{
continue;
}
// Move point onto triangle surface for improved culling
// b3Vec3 point = b3MulSub( clipPoint->position, clipPoint->separation, refPlane.normal );
b3Vec3 point = clipPoint->position;
b3LocalManifoldPoint* pt = manifold->points + i;
b3LocalManifoldPoint* pt = manifold->points + finalPointCount;
pt->point = point;
pt->separation = clipPoint->separation;
pt->pair = clipPoint->pair;
minSeparation = b3MinFloat( minSeparation, clipPoint->separation );
finalPointCount += 1;
}
if ( minSeparation >= B3_SPECULATIVE_DISTANCE )
float speculativeDistance = enableSpeculative ? B3_SPECULATIVE_DISTANCE : 0.0f;
if ( minSeparation >= speculativeDistance )
{
// This can happens if the objects move a part while re-using a cached axis
*cache = (b3SATCache){ 0 };
return minSeparation;
}
manifold->pointCount = pointCount;
manifold->pointCount = finalPointCount;
manifold->normal = refPlane.normal;
manifold->feature = b3_featureTriangleFace;
@ -853,7 +869,8 @@ static void b3CollideHullAndTriangleEdges( b3LocalManifold* manifold, int capaci
b3SegmentDistanceResult result = b3LineDistance( pA, eA, pB, eB );
// Is one of the closest points outside of the associated edge segment?
if ( capacity == 0 || result.fraction1 < 0.0f || 1.0f < result.fraction1 || result.fraction2 < 0.0f || 1.0f < result.fraction2 )
if ( capacity == 0 || result.fraction1 < 0.0f || 1.0f < result.fraction1 || result.fraction2 < 0.0f ||
1.0f < result.fraction2 )
{
// Invalid edge pair, no points generated
B3_ASSERT( manifold->pointCount == 0 );
@ -901,7 +918,7 @@ b3AtomicInt b3_triangleCacheHits;
// Computes the manifold in the local space of the hull
void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3HullData* hullA, b3Vec3 v1, b3Vec3 v2, b3Vec3 v3,
int triangleFlags, b3SATCache* cache )
int triangleFlags, b3SATCache* cache, bool enableSpeculative )
{
manifold->pointCount = 0;
manifold->feature = b3_featureNone;
@ -954,7 +971,7 @@ void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3
const b3Plane* hullPlanes = b3GetHullPlanes( hullA );
const b3Vec3* hullPoints = b3GetHullPoints( hullA );
float speculativeDistance = B3_SPECULATIVE_DISTANCE;
float speculativeDistance = enableSpeculative ? B3_SPECULATIVE_DISTANCE : 0.0f;
cache->hit = 1;
// Attempt to use the cache to speed up collision
@ -967,7 +984,7 @@ void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3
int vertexIndex = b3FindHullSupportVertex( hullA, b3Neg( trianglePlane.normal ) );
b3Vec3 support = hullPoints[vertexIndex];
float separation = b3PlaneSeparation( trianglePlane, support );
if ( separation >= speculativeDistance )
if ( separation > speculativeDistance )
{
// Cache hit, shapes are separated
return;
@ -980,7 +997,8 @@ void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3
// Read cache but don't modify it
b3SATCache localCache = *cache;
float clippedSeparation = b3CollideTriangleFace( manifold, capacity, &triangle, hullA, faceQuery, &localCache );
float clippedSeparation =
b3CollideTriangleFace( manifold, capacity, &triangle, hullA, faceQuery, &localCache, enableSpeculative );
if ( manifold->pointCount > 0 && b3AbsFloat( cache->separation - clippedSeparation ) < linearSlop )
{
@ -1017,7 +1035,7 @@ void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3
// Separation of triangle support point with hull plane
float separation = b3PlaneSeparation( plane, support );
if ( separation >= speculativeDistance )
if ( separation > speculativeDistance )
{
// Cache hit, shapes are separated
return;
@ -1038,7 +1056,8 @@ void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3
// Read cache but don't modify it
b3SATCache localCache = *cache;
float clippedSeparation = b3CollideHullFace( manifold, capacity, &triangle, hullA, faceQuery, &localCache );
float clippedSeparation =
b3CollideHullFace( manifold, capacity, &triangle, hullA, faceQuery, &localCache, enableSpeculative );
// Cache reuse is only successful if it creates contact points and the clipped separation didn't change much.
if ( manifold->pointCount > 0 && b3AbsFloat( cache->separation - clippedSeparation ) < linearSlop )
@ -1116,7 +1135,7 @@ void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3
case b3_manualFaceAxisA:
{
b3FaceQuery faceQueryA = b3QueryTriangleFace( &triangle, hullA );
b3CollideTriangleFace( manifold, capacity, &triangle, hullA, faceQueryA, cache );
b3CollideTriangleFace( manifold, capacity, &triangle, hullA, faceQueryA, cache, enableSpeculative );
return;
}
@ -1124,7 +1143,7 @@ void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3
case b3_manualFaceAxisB:
{
b3FaceQuery faceQueryB = b3QueryHullFace( &triangle, hullA );
b3CollideHullFace( manifold, capacity, &triangle, hullA, faceQueryB, cache );
b3CollideHullFace( manifold, capacity, &triangle, hullA, faceQueryB, cache, enableSpeculative );
return;
}
@ -1186,16 +1205,19 @@ void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3
float clippedFaceSeparation;
// Don't allow a hull face opposed to the triangle face.
// Don't admit a hull face significantly opposed to the triangle face.
// Need a tolerance to avoid ghost collisions.
// todo hull query skips faces that point along the triangle normal
b3Vec3 hullNormal = hullPlanes[faceQueryB.faceIndex].normal;
bool pushingUp = b3Dot( hullNormal, trianglePlane.normal ) < 0.0f;
if ( faceQueryB.separation > faceQueryA.separation + linearSlop && pushingUp )
bool pushingDown = b3Dot( hullNormal, trianglePlane.normal ) > 0.25f;
if ( faceQueryB.separation > faceQueryA.separation + linearSlop && pushingDown == false )
{
clippedFaceSeparation = b3CollideHullFace( manifold, capacity, &triangle, hullA, faceQueryB, cache );
clippedFaceSeparation = b3CollideHullFace( manifold, capacity, &triangle, hullA, faceQueryB, cache, enableSpeculative );
}
else
{
clippedFaceSeparation = b3CollideTriangleFace( manifold, capacity, &triangle, hullA, faceQueryA, cache );
clippedFaceSeparation =
b3CollideTriangleFace( manifold, capacity, &triangle, hullA, faceQueryA, cache, enableSpeculative );
}
// Does an edge axis exist?

View file

@ -75,6 +75,7 @@ b3ShapeDef b3DefaultShapeDef( void )
def.filter = b3DefaultFilter();
def.updateBodyMass = true;
def.invokeContactCreation = true;
def.enableSpeculativeContact = true;
def.internalValue = B3_SECRET_COOKIE;
return def;
}