64-bit hashes (#126)

- ContactEvent sample
- Improved shadows
- #120 
- Triangle collision fixes
This commit is contained in:
Erin Catto 2026-08-11 18:08:34 -07:00 • committed by GitHub
commit f42be210a2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
49 changed files with 19835 additions and 17544 deletions

View file

@ -115,7 +115,7 @@ void b3Log( const char* format, ... )
b3Version b3GetVersion( void )
{
return (b3Version){ 0, 1, 0 };
return (b3Version){ 0, 2, 0 };
}
bool b3IsDoublePrecision( void )
@ -253,3 +253,39 @@ void b3StrCpy( char* dst, int size, const char* src )
memset( dst, 0, size );
}
}
// Fowler/Noll/Vo FNV-1a salted by length, then the splitmix64 finalizer so tiny inputs
// still spread across all bits.
uint64_t b3Hash64NonZero( const uint8_t* bytes, int n )
{
uint64_t h = 0xcbf29ce484222325ull ^ (uint64_t)(uint32_t)n;
const uint64_t prime = 0x100000001b3ull;
int i = 0;
while ( i + 8 <= n )
{
uint64_t word;
memcpy( &word, bytes + i, sizeof( word ) );
#if defined( __BYTE_ORDER__ ) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
word = ( ( word & 0x00000000000000FFULL ) << 56 ) | ( ( word & 0x000000000000FF00ULL ) << 40 ) |
( ( word & 0x0000000000FF0000ULL ) << 24 ) | ( ( word & 0x00000000FF000000ULL ) << 8 ) |
( ( word & 0x000000FF00000000ULL ) >> 8 ) | ( ( word & 0x0000FF0000000000ULL ) >> 24 ) |
( ( word & 0x00FF000000000000ULL ) >> 40 ) | ( ( word & 0xFF00000000000000ULL ) >> 56 );
#endif
h = ( h ^ word ) * prime;
i += 8;
}
while ( i < n )
{
h = ( h ^ (uint64_t)bytes[i] ) * prime;
i += 1;
}
h ^= h >> 30;
h *= 0xbf58476d1ce4e5b9ull;
h ^= h >> 27;
h *= 0x94d049bb133111ebull;
h ^= h >> 31;
return h == 0 ? 1 : h;
}

View file

@ -140,12 +140,6 @@ void* b3GrowAlloc( void* oldMem, int oldSize, int newSize );
B3_PRINTF_FORMAT( 1, 2 )
void b3Log( const char* format, ... );
// Geometry content hashes reserve zero to mean unhashed
static inline uint32_t b3NonZeroHash( uint32_t hash )
{
return hash != 0 ? hash : 1;
}
typedef struct b3Mutex b3Mutex;
b3Mutex* b3CreateMutex( void );
void b3DestroyMutex( b3Mutex* m );
@ -165,3 +159,6 @@ b3Thread* b3CreateThread( b3ThreadFunction* function, void* context, const char*
void b3JoinThread( b3Thread* t );
void b3StrCpy( char* dst, int size, const char* src );
// Good quality 64-bit hash that never returns 0.
uint64_t b3Hash64NonZero( const uint8_t* bytes, int n );

View file

@ -468,9 +468,8 @@ b3HeightFieldData* b3CreateHeightField( const b3HeightFieldDef* data )
b3Free( decompressedHeights, heightCount * sizeof( float ) );
// Content hash over the whole blob with the hash field zeroed, like b3HullData/b3MeshData.
hf->hash = 0;
hf->hash = b3NonZeroHash( b3Hash( B3_HASH_INIT, (const uint8_t*)hf, hf->byteCount ) );
hf->hash = b3Hash64NonZero( (const uint8_t*)hf, hf->byteCount );
return hf;
}

View file

@ -3,8 +3,9 @@
// Dirk Gregorius contributed portions of this code
#include "algorithm.h"
#include "hull.h"
#include "algorithm.h"
#include "math_internal.h"
#include "shape.h"
@ -2258,7 +2259,7 @@ b3HullData* b3CreateHull( const b3Vec3* points, int pointCount, int maxVertexCou
}
hull->hash = 0;
hull->hash = b3NonZeroHash( b3Hash( B3_HASH_INIT, (uint8_t*)hull, hull->byteCount ) );
hull->hash = b3Hash64NonZero( (uint8_t*)hull, hull->byteCount );
return hull;
}
@ -2270,7 +2271,7 @@ b3HullData* b3CloneHull( const b3HullData* hull )
return NULL;
}
b3HullData* clone = (b3HullData*)b3Alloc( hull->byteCount );
b3HullData* clone = b3Alloc( hull->byteCount );
memcpy( clone, hull, hull->byteCount );
return clone;
@ -2278,9 +2279,7 @@ b3HullData* b3CloneHull( const b3HullData* hull )
uint64_t b3HashHullData( const b3HullData* hull )
{
// The baked content hash already covers byteCount. Spread the 32 bits across 64 so the table
// can use the high bits for its fast reject fragment.
return (uint64_t)hull->hash * 0x9E3779B97F4A7C15ull;
return hull->hash;
}
bool b3CompareHullData( const b3HullData* hull1, const b3HullData* hull2 )
@ -2301,7 +2300,7 @@ bool b3CompareHullData( const b3HullData* hull1, const b3HullData* hull2 )
// Hull identity covers every byte, so the structs carry explicit padding. These lock
// the layout, re-audit padding if a size changes.
_Static_assert( sizeof( b3HullData ) == 144, "unexpected hull data size" );
_Static_assert( sizeof( b3BoxHull ) == 648, "unexpected box hull size" );
_Static_assert( sizeof( b3BoxHull ) == 640, "unexpected box hull size" );
// Implement b3HullMap.
#define NAME b3HullMap
@ -2494,8 +2493,9 @@ b3HullData* b3CloneAndTransformHull( const b3HullData* original, b3Transform tra
return NULL;
}
// Must ensure the hash is 0 so it doesn't contribute to itself.
hull->hash = 0;
hull->hash = b3NonZeroHash( b3Hash( B3_HASH_INIT, (uint8_t*)hull, hull->byteCount ) );
hull->hash = b3Hash64NonZero( (uint8_t*)hull, hull->byteCount );
B3_VALIDATE( b3IsValidHull( hull ) );
@ -2863,8 +2863,9 @@ b3BoxHull b3MakeTransformedBoxHull( float hx, float hy, float hz, b3Transform tr
boxHull.nz[6] = 0.0f;
boxHull.nz[7] = 0.0f;
// Must ensure the hash is 0 so it doesn't contribute to itself.
boxHull.base.hash = 0;
boxHull.base.hash = b3NonZeroHash( b3Hash( B3_HASH_INIT, (uint8_t*)&boxHull, sizeof( b3BoxHull ) ) );
boxHull.base.hash = b3Hash64NonZero( (uint8_t*)&boxHull.base, boxHull.base.byteCount );
return boxHull;
}

View file

@ -7,8 +7,6 @@
#include <stddef.h>
// Content hash and equality over the whole baked hull. Shared by every hull
// de-duplication map so they agree on identity.
uint64_t b3HashHullData( const b3HullData* hull );
bool b3CompareHullData( const b3HullData* hull1, const b3HullData* hull2 );

View file

@ -1762,7 +1762,7 @@ b3MeshData* b3CreateMesh( const b3MeshDef* def, int* degenerateTriangleIndices,
b3Array_Destroy( vertices );
mesh->hash = 0;
mesh->hash = b3NonZeroHash( b3Hash( B3_HASH_INIT, (uint8_t*)mesh, mesh->byteCount ) );
mesh->hash = b3Hash64NonZero((uint8_t*)mesh, mesh->byteCount );
return mesh;
}

View file

@ -658,6 +658,10 @@ static void b3CollideTask( int startIndex, int endIndex, int workerIndex, void*
if ( ( isFast == false || isMeshContact == false ) && recycleDistance > 0.0f &&
( contact->flags & b3_relativeTransformValid ) && ( contact->flags & b3_contactRecycleFlag ) )
{
// The scalar part of b3InvMulQuat is just the quaternion dot product.
// cos(relative_angle/2) = scalar(conj(q1) * q2) = dot(q1, q2)
// A small relative angle means this value is close to 1. Need to use abs or square
// due to double cover.
float angleA = b3DotQuat( transformA.q, contact->cachedRotationA );
float angleB = b3DotQuat( transformB.q, contact->cachedRotationB );
float angularDistance = b3MinFloat( angleA * angleA, angleB * angleB );
@ -1433,17 +1437,19 @@ void b3World_Draw( b3WorldId worldId, b3DebugDraw* draw, uint64_t maskBits )
}
}
if ( draw->drawMass && body->type == b3_dynamicBody )
if ( draw->drawMass )
{
b3Vec3 offset = { 0.05f, 0.05f, 0.05f };
b3WorldTransform transform = { bodySim->center, bodySim->transform.q };
draw->DrawTransformFcn( transform, draw->context );
b3Pos p = b3TransformWorldPoint( transform, offset );
char buffer[32];
snprintf( buffer, 32, "%.2f", body->mass );
draw->DrawStringFcn( p, buffer, b3_colorWhite, draw->context );
if (body->type == b3_dynamicBody)
{
b3Vec3 offset = { 0.05f, 0.05f, 0.05f };
b3Pos p = b3TransformWorldPoint( transform, offset );
char buffer[32];
snprintf( buffer, 32, "%.2f", body->mass );
draw->DrawStringFcn( p, buffer, b3_colorWhite, draw->context );
}
}
if ( draw->drawSleep )

View file

@ -735,45 +735,6 @@ void b3RecEndRecord( b3Recording* rec )
// Geometry registry
// Full 64-bit content hash, so distinct blobs of the same length get independent bits. A reseeded
// 32-bit djb2 cannot: djb2 is affine in its seed, so a same-length collision survives every seed and
// the high word would just track the low one. Word folded for speed, byte order normalized on
// big-endian to match b3Hash, then a splitmix64 finalizer so tiny inputs still spread across all bits.
// From Fowler/Noll/Vo FNV-1a salted by length, then the splitmix64 mix.
uint64_t b3Hash64Blob( const uint8_t* bytes, int n )
{
uint64_t h = 0xcbf29ce484222325ull ^ (uint64_t)(uint32_t)n;
const uint64_t prime = 0x100000001b3ull;
int i = 0;
while ( i + 8 <= n )
{
uint64_t word;
memcpy( &word, bytes + i, sizeof( word ) );
#if defined( __BYTE_ORDER__ ) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
word = ( ( word & 0x00000000000000FFULL ) << 56 ) | ( ( word & 0x000000000000FF00ULL ) << 40 ) |
( ( word & 0x0000000000FF0000ULL ) << 24 ) | ( ( word & 0x00000000FF000000ULL ) << 8 ) |
( ( word & 0x000000FF00000000ULL ) >> 8 ) | ( ( word & 0x0000FF0000000000ULL ) >> 24 ) |
( ( word & 0x00FF000000000000ULL ) >> 40 ) | ( ( word & 0xFF00000000000000ULL ) >> 56 );
#endif
h = ( h ^ word ) * prime;
i += 8;
}
while ( i < n )
{
h = ( h ^ (uint64_t)bytes[i] ) * prime;
i += 1;
}
h ^= h >> 30;
h *= 0xbf58476d1ce4e5b9ull;
h ^= h >> 27;
h *= 0x94d049bb133111ebull;
h ^= h >> 31;
return h;
}
// Content hash to chain head, so dedup is near O(1). Colliding hashes share a head and are walked
// through b3GeometryEntry::hashNext, so the byteCount + memcmp check always finds an existing blob.
#define NAME b3GeometryHashMap
@ -1186,7 +1147,7 @@ uint32_t b3RecInternHull( b3Recording* rec, const b3HullData* hull )
int byteCount = hull->byteCount;
uint8_t* bytes = b3Alloc( (size_t)byteCount );
memcpy( bytes, hull, (size_t)byteCount );
uint64_t h = b3Hash64Blob( bytes, byteCount );
uint64_t h = b3Hash64NonZero( bytes, byteCount );
return b3InternGeometry( &rec->registry, b3_geometryHull, h, bytes, byteCount );
}
@ -1195,7 +1156,7 @@ uint32_t b3RecInternMesh( b3Recording* rec, const b3MeshData* mesh )
int byteCount = mesh->byteCount;
uint8_t* bytes = b3Alloc( (size_t)byteCount );
memcpy( bytes, mesh, (size_t)byteCount );
uint64_t h = b3Hash64Blob( bytes, byteCount );
uint64_t h = b3Hash64NonZero( bytes, byteCount );
return b3InternGeometry( &rec->registry, b3_geometryMesh, h, bytes, byteCount );
}
@ -1204,7 +1165,7 @@ uint32_t b3RecInternHeightField( b3Recording* rec, const b3HeightFieldData* hf )
int byteCount = hf->byteCount;
uint8_t* bytes = b3Alloc( (size_t)byteCount );
memcpy( bytes, hf, (size_t)byteCount );
uint64_t h = b3Hash64Blob( bytes, byteCount );
uint64_t h = b3Hash64NonZero( bytes, byteCount );
return b3InternGeometry( &rec->registry, b3_geometryHeightField, h, bytes, byteCount );
}
@ -1216,7 +1177,7 @@ uint32_t b3RecInternCompound( b3Recording* rec, const b3CompoundData* compound )
// Null the tree node pointer in the copy so the canonical bytes are pointer-free.
// b3ConvertBytesToCompound fixes it back on load via nodeOffset.
( (b3CompoundData*)bytes )->tree.nodes = NULL;
uint64_t h = b3Hash64Blob( bytes, byteCount );
uint64_t h = b3Hash64NonZero( bytes, byteCount );
return b3InternGeometry( &rec->registry, b3_geometryCompound, h, bytes, byteCount );
}

View file

@ -373,8 +373,6 @@ uint32_t b3RecInternMesh( b3Recording* rec, const b3MeshData* mesh );
uint32_t b3RecInternHeightField( b3Recording* rec, const b3HeightFieldData* hf );
uint32_t b3RecInternCompound( b3Recording* rec, const b3CompoundData* compound );
uint64_t b3Hash64Blob( const uint8_t* bytes, int n );
// Lifecycle engine-side hooks
void b3StartRecordingIntoBuffer( b3World* world, b3Recording* recording );
void b3StopRecordingInternal( b3World* world );

View file

@ -8,7 +8,6 @@
#include "recording_replay.h"
#include "body.h"
#include "compound.h"
#include "physics_world.h"
#include "world_snapshot.h"
@ -2176,7 +2175,7 @@ static int b3RecDispatchOne( b3RecReader* rdr )
bool b3ValidateReplay( const void* data, int size, int workerCount )
{
b3RecPlayer* player = b3RecPlayer_Create( data, size, workerCount );
b3RecPlayer* player = b3CreatePlayer( data, size, workerCount );
if ( player == NULL )
{
return false;
@ -2191,7 +2190,7 @@ bool b3ValidateReplay( const void* data, int size, int workerCount )
}
bool ok = player->rdr.ok && player->rdr.diverged == false;
b3RecPlayer_Destroy( player );
b3DestroyPlayer( player );
return ok;
}
@ -2600,7 +2599,7 @@ static void b3RecSeedKeyframeRegistry( b3RecPlayer* player )
{
memcpy( copy, slot->bytes, (size_t)slot->byteCount );
}
uint64_t h = b3Hash64Blob( slot->bytes, slot->byteCount );
uint64_t h = b3Hash64NonZero( slot->bytes, slot->byteCount );
uint32_t id = b3AppendGeometry( reg, slot->kind, h, copy, slot->byteCount );
// Seeding in order without dedup keeps id == slot index.
B3_ASSERT( id == (uint32_t)i );
@ -2724,7 +2723,7 @@ static b3WorldId b3RecPlayerCreateWorld( const b3RecPlayer* player )
return b3CreateWorld( &worldDef );
}
b3RecPlayer* b3RecPlayer_Create( const void* data, int size, int workerCount )
b3RecPlayer* b3CreatePlayer( const void* data, int size, int workerCount )
{
if ( data == NULL || size < (int)sizeof( b3RecHeader ) )
{
@ -2878,7 +2877,7 @@ b3RecPlayer* b3RecPlayer_Create( const void* data, int size, int workerCount )
return player;
}
void b3RecPlayer_Destroy( b3RecPlayer* player )
void b3DestroyPlayer( b3RecPlayer* player )
{
if ( player == NULL )
{

View file

@ -141,7 +141,7 @@ static bool b3ClipSegmentToTriangleFace( b3ClipVertex segment[2], const b3Vec3*
}
// If the points are on different sides of the plane
if ( distance1 * distance2 < 0.0f )
if ( ( distance1 > 0.0f ) != ( distance2 > 0.0f ) )
{
// Find intersection point of edge and plane
float t = distance1 / ( distance1 - distance2 );
@ -199,6 +199,7 @@ static b3SeparatingAxis b3QueryTriangleAndCapsuleEdges( const b3Vec3* vertices,
float squaredTolerance = 0.005f * 0.005f;
int edgeIndex = 2;
float a = b3Dot( capsuleEdge, plane.normal );
b3Vec3 v1 = vertices[2];
for ( int index = 0; index < 3; ++index )
{
@ -209,12 +210,13 @@ static b3SeparatingAxis b3QueryTriangleAndCapsuleEdges( const b3Vec3* vertices,
// Pretend the triangle edge embeds a zero area face with a side normal. This
// provides a way to find an edge-edge normal that points outward from
// the triangle.
float a = b3Dot( capsuleEdge, plane.normal );
float b = b3Dot( capsuleEdge, sideNormal );
// Is the capsule edge parallel to the triangle edge? If so, face contact can handle it.
if ( a * a + b * b < squaredTolerance * b3LengthSquared( capsuleEdge ) )
{
v1 = v2;
edgeIndex = index;
continue;
}
@ -346,9 +348,8 @@ static void b3BuildTriangleAndCapsuleEdgeContact( b3LocalManifold* manifold, con
return;
}
b3Vec3 point = b3Lerp( b3MulSub( result.point1, capsule->radius, normal ), result.point2, 0.5f );
b3Vec3 point = b3Lerp( result.point1, b3MulSub( result.point2, capsule->radius, normal ), 0.5f );
float separation = b3Dot( normal, b3Sub( p1, v1 ) );
B3_VALIDATE( b3AbsFloat( separation - query.separation ) < B3_LINEAR_SLOP );
manifold->normal = normal;
manifold->pointCount = 1;
@ -448,7 +449,7 @@ void b3CollideTriangleAndCapsule( b3LocalManifold* manifold, int capacity, const
}
// Create contact from closest points.
b3Vec3 point = b3MulSV( 0.5f, b3Add( b3Sub( distanceOutput.pointA, b3MulSV( radius, delta ) ), distanceOutput.pointB ) );
b3Vec3 point = b3Lerp( distanceOutput.pointA, b3MulSub( distanceOutput.pointB, radius, delta ), 0.5f );
// Normal points from triangle to capsule.
manifold->normal = delta;
@ -489,6 +490,12 @@ void b3CollideTriangleAndCapsule( b3LocalManifold* manifold, int capacity, const
faceSeparation = b3MinFloat( manifold->points[0].separation, manifold->points[1].separation );
}
if ( edgeQuery.indexA == B3_NULL_INDEX )
{
// No valid edge contact.
return;
}
// Face contact can be empty if it does not realize the axis of minimum penetration.
// Create edge contact if face contact fails or edge contact is significantly better!
float linearSlop = B3_LINEAR_SLOP;
@ -926,10 +933,7 @@ static void b3CollideTriangleAndHullEdges( b3LocalManifold* manifold, int capaci
return;
}
// This can slide off the end from caching
float separation = b3Dot( query.normal, b3Sub( pB, pA ) );
B3_VALIDATE( b3AbsFloat( separation - query.separation ) < B3_LINEAR_SLOP );
b3Vec3 point = b3MulSV( 0.5f, b3Add( result.point1, result.point2 ) );
b3LocalManifoldPoint* pt = manifold->points + 0;