Replay fixes (#17)

Fixes to work with our game.
Replay fixes and improvements.
Removed shape names (save memory).
B3_DEFAULT_CATEGORY_BITS  is now UINT64_MAX to make selection easier.
This commit is contained in:
Erin Catto 2026-06-26 21:10:10 -07:00 • committed by GitHub
commit 0c8ef46931
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
51 changed files with 5653 additions and 3853 deletions

View file

@ -1,17 +1,19 @@
// SPDX-FileCopyrightText: 2025 Erin Catto
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
#pragma once
#include <stddef.h>
#include <string.h>
#define B3_TYPE_OF( A ) __typeof__( A )
// Swap two same-size lvalues through a byte buffer. Avoids __typeof__ so it builds on any C compiler.
#define B3_SWAP( x, y ) \
do \
{ \
B3_TYPE_OF( x ) B3_SWAP_TEMP = x; \
x = y; \
y = B3_SWAP_TEMP; \
_Static_assert( sizeof( x ) == sizeof( y ), "size mismatch" ); \
char B3_SWAP_TEMP[sizeof( x )]; \
memcpy( B3_SWAP_TEMP, &( x ), sizeof( x ) ); \
memcpy( &( x ), &( y ), sizeof( x ) ); \
memcpy( &( y ), B3_SWAP_TEMP, sizeof( x ) ); \
} \
while ( 0 )

View file

@ -55,18 +55,9 @@ void* b3AllocateElement( b3BlockAllocator* allocator )
return element;
}
int startIndex = allocator->nextIndex;
int startOffset = startIndex & ( B3_BLOCK_SIZE - 1 );
int index = allocator->nextIndex++;
if ( startOffset + 1 > B3_BLOCK_SIZE )
{
startIndex = ( startIndex + B3_BLOCK_SIZE ) & ~( B3_BLOCK_SIZE - 1 );
}
allocator->nextIndex = startIndex + 1;
int lastIndex = allocator->nextIndex - 1;
int requiredBlockCount = ( lastIndex >> B3_BLOCK_EXPONENT ) + 1;
int requiredBlockCount = ( index >> B3_BLOCK_EXPONENT ) + 1;
if ( requiredBlockCount > allocator->blocks.count )
{
@ -79,8 +70,8 @@ void* b3AllocateElement( b3BlockAllocator* allocator )
}
}
int blockIndex = startIndex >> B3_BLOCK_EXPONENT;
int blockOffset = startIndex & ( B3_BLOCK_SIZE - 1 );
int blockIndex = index >> B3_BLOCK_EXPONENT;
int blockOffset = index & ( B3_BLOCK_SIZE - 1 );
return allocator->blocks.data[blockIndex].memory + blockOffset * allocator->elementSize;
}

View file

@ -30,6 +30,6 @@ typedef struct b3BlockAllocator
b3BlockAllocator b3CreateBlockAllocator( int elementSize, int initialCount );
void b3DestroyBlockAllocator( b3BlockAllocator* allocator );
// Elements are guaranteed contiguous.
// Returns one element of elementSize contiguous bytes. Address is stable until freed.
void* b3AllocateElement( b3BlockAllocator* allocator );
void b3FreeElement( b3BlockAllocator* allocator, void* element );

View file

@ -43,7 +43,7 @@
#define b3Array_CreateN( a, n ) \
do \
{ \
( a ).data = ( n ) > 0 ? (B3_TYPE_OF( ( a ).data ))b3GrowAlloc( NULL, 0, ( n ) * sizeof( *( a ).data ) ) : NULL; \
( a ).data = ( n ) > 0 ? b3GrowAlloc( NULL, 0, ( n ) * sizeof( *( a ).data ) ) : NULL; \
( a ).count = 0; \
( a ).capacity = ( n ); \
} \
@ -66,7 +66,7 @@
{ \
int oldSize = ( a ).capacity * sizeof( *( a ).data ); \
int newSize = ( n ) * sizeof( *( a ).data ); \
( a ).data = (B3_TYPE_OF( ( a ).data ))b3GrowAlloc( ( a ).data, oldSize, newSize ); \
( a ).data = b3GrowAlloc( ( a ).data, oldSize, newSize ); \
( a ).capacity = ( n ); \
} \
} \
@ -89,7 +89,7 @@
int oldSize = ( a ).capacity * sizeof( *( a ).data ); \
int newCapacity = ( a ).capacity == 0 ? 8 : 2 * ( a ).capacity; \
int newSize = newCapacity * sizeof( *( a ).data ); \
( a ).data = (B3_TYPE_OF( ( a ).data ))b3GrowAlloc( ( a ).data, oldSize, newSize ); \
( a ).data = b3GrowAlloc( ( a ).data, oldSize, newSize ); \
( a ).capacity = newCapacity; \
} \
( a ).data[( a ).count++] = ( value ); \
@ -101,7 +101,7 @@
// Create a new uninitialized element and return a pointer to it
#define b3Array_Emplace( a ) \
( (B3_TYPE_OF( ( a ).data ))b3EmplaceHelper( (void**)&( a ).data, &( a ).count, &( a ).capacity, sizeof( *( a ).data ) ) )
( b3EmplaceHelper( (void**)&( a ).data, &( a ).count, &( a ).capacity, sizeof( *( a ).data ) ) )
// Remove the last element and return it by value.
#define b3Array_Pop( a ) ( B3_ASSERT( 0 < ( a ).count ), ( a ).data[-1 + ( a ).count--] )
@ -121,7 +121,7 @@
int newCapacity = req > 2 ? req + ( req >> 1 ) : 8; \
int oldSize = ( a ).capacity * sizeof( *( a ).data ); \
int newSize = newCapacity * sizeof( *( a ).data ); \
( a ).data = (B3_TYPE_OF( ( a ).data ))b3GrowAlloc( ( a ).data, oldSize, newSize ); \
( a ).data = b3GrowAlloc( ( a ).data, oldSize, newSize ); \
( a ).capacity = newCapacity; \
} \
memcpy( ( a ).data + ( a ).count, ( src ), _n * sizeof( *( a ).data ) ); \

View file

@ -36,7 +36,7 @@
#include <stdio.h>
// This allows the user to change the length units at runtime
float b3_lengthUnitsPerMeter = 1.0f;
static float b3_lengthUnitsPerMeter = 1.0f;
void b3SetLengthUnitsPerMeter( float lengthUnits )
{
@ -49,6 +49,19 @@ float b3GetLengthUnitsPerMeter( void )
return b3_lengthUnitsPerMeter;
}
static float b3_stallThreshold = FLT_MAX;
void b3SetStallThreshold(float seconds)
{
B3_ASSERT( b3IsValidFloat( seconds ) && seconds > 0.0f );
b3_stallThreshold = seconds;
}
float b3GetStallThreshold(void)
{
return b3_stallThreshold;
}
static int b3DefaultAssertFcn( const char* condition, const char* fileName, int lineNumber )
{
printf( "BOX3D ASSERTION: %s, %s, line %d\n", condition, fileName, lineNumber );

View file

@ -345,11 +345,6 @@ b3Quat b3ComputeQuatBetweenUnitVectors( b3Vec3 v1, b3Vec3 v2 )
return b3NormalizeQuat( out );
}
//--------------------------------------------------------------------------------------------------
// Collision utilities
//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
b3SegmentDistanceResult b3LineDistance( b3Vec3 p1, b3Vec3 d1, b3Vec3 p2, b3Vec3 d2 )
{
b3SegmentDistanceResult result;
@ -389,7 +384,6 @@ b3SegmentDistanceResult b3LineDistance( b3Vec3 p1, b3Vec3 d1, b3Vec3 p2, b3Vec3
return result;
}
//--------------------------------------------------------------------------------------------------
b3SegmentDistanceResult b3SegmentDistance( b3Vec3 p1, b3Vec3 q1, b3Vec3 p2, b3Vec3 q2 )
{
b3SegmentDistanceResult result;

View file

@ -45,24 +45,6 @@ typedef struct b3ShapeExtent
b3TrianglePoint b3ClosestPointOnTriangle( b3Vec3 a, b3Vec3 b, b3Vec3 c, b3Vec3 q );
// The closest points between to segments or infinite lines.
typedef struct b3SegmentDistanceResult
{
b3Vec3 point1;
float fraction1;
b3Vec3 point2;
float fraction2;
} b3SegmentDistanceResult;
// Compute the closest point on the segment a-b to the target q
b3Vec3 b3PointToSegmentDistance( b3Vec3 a, b3Vec3 b, b3Vec3 q );
// Compute the closest points on two infinite lines
b3SegmentDistanceResult b3LineDistance( b3Vec3 p1, b3Vec3 d1, b3Vec3 p2, b3Vec3 d2 );
// Compute the closest points on two line segments
b3SegmentDistanceResult b3SegmentDistance( b3Vec3 p1, b3Vec3 q1, b3Vec3 p2, b3Vec3 q2 );
float b3IntersectSegmentTriangle( b3Vec3 p, b3Vec3 q, b3Vec3 a, b3Vec3 b, b3Vec3 c );
float b3IntersectSegmentSphere( b3Vec3 p, b3Vec3 q, b3Vec3 c, float r );
@ -489,28 +471,6 @@ static inline b3Matrix3 b3TransformInertia( b3Transform transform, b3Matrix3 cen
return inertia;
}
// Twist angle around the z-axis, used for twist limit and revolute angle limit
static inline float b3GetTwistAngle( b3Quat q )
{
// Account for polarity to keep the twist angle in range.
// This is simpler than asking the user to check polarity or unwinding.
float twist = q.s < 0.0f ? b3Atan2( -q.v.z, -q.s ) : b3Atan2( q.v.z, q.s );
twist *= 2.0f;
B3_ASSERT( -B3_PI <= twist && twist <= B3_PI );
return twist;
}
// Swing angle used for cone limit
static inline float b3GetSwingAngle( b3Quat q )
{
// Polarity should not matter because all terms are squared.
float x = sqrtf( q.v.z * q.v.z + q.s * q.s );
float y = sqrtf( q.v.x * q.v.x + q.v.y * q.v.y );
float swing = 2.0f * b3Atan2( y, x );
B3_ASSERT( 0.0f <= swing && swing <= B3_PI );
return swing;
}
// Add a point to an AABB.
static inline b3AABB b3AABB_AddPoint( b3AABB a, b3Vec3 point )
{

View file

@ -9,7 +9,6 @@
#include "bitset.h"
#include "body.h"
#include "broad_phase.h"
#include "compound.h"
#include "constraint_graph.h"
#include "contact.h"
#include "core.h"
@ -1366,7 +1365,8 @@ void b3World_Draw( b3WorldId worldId, b3DebugDraw* draw, uint64_t maskBits )
B3_ASSERT( b3IsValidAABB( draw->drawingBounds ) );
const float axisScale = 0.3f * b3GetLengthUnitsPerMeter();
float lengthScale = b3GetLengthUnitsPerMeter();
float axisScale = 0.3f * lengthScale;
b3HexColor farColor = b3_colorDarkBlue;
b3HexColor speculativeColor = b3_colorBlue;
b3HexColor addColor = b3_colorLimeGreen;
@ -1521,7 +1521,7 @@ void b3World_Draw( b3WorldId worldId, b3DebugDraw* draw, uint64_t maskBits )
b3Pos p1 = p;
b3Pos p2 = b3OffsetPos( p1, b3MulSV( draw->forceScale * force, normal ) );
draw->DrawSegmentFcn( p1, p2, impulseColor, draw->context );
snprintf( buffer, B3_ARRAY_COUNT( buffer ), " %.1f", force );
snprintf( buffer, B3_ARRAY_COUNT( buffer ), " %.1f", force );
draw->DrawStringFcn( p1, buffer, b3_colorWhite, draw->context );
}
else if ( draw->drawContactFeatures )
@ -1571,8 +1571,9 @@ void b3World_Draw( b3WorldId worldId, b3DebugDraw* draw, uint64_t maskBits )
draw->DrawSegmentFcn( p1, p2, frictionColor, draw->context );
draw->DrawPointFcn( p1, 5.0f, frictionColor, draw->context );
p1 = b3OffsetPos( p1, b3MulSV(0.05f * lengthScale, normal) );
char buffer[32];
snprintf( buffer, B3_ARRAY_COUNT( buffer ), " %.2f", b3Length( frictionForce ) );
snprintf( buffer, B3_ARRAY_COUNT( buffer ), "%.2f", b3Length( frictionForce ) );
draw->DrawStringFcn( p1, buffer, b3_colorWhite, draw->context );
}
}
@ -2593,7 +2594,7 @@ b3TreeStats b3World_OverlapAABB( b3WorldId worldId, b3AABB aabb, b3QueryFilter f
b3RecQueryWriter recWriter = { 0 };
if ( world->recording != NULL )
{
b3RecQueryBegin( &recWriter, context );
b3RecQueryBegin( &recWriter, context, filter.id, filter.name );
recWriter.userFcn.overlapFcn = fcn;
b3RecW_WORLDID( &recWriter.buf, worldId );
b3RecW_AABB( &recWriter.buf, aabb );
@ -2683,7 +2684,7 @@ b3TreeStats b3World_OverlapShape( b3WorldId worldId, b3Pos origin, const b3Shape
b3RecQueryWriter recWriter = { 0 };
if ( world->recording != NULL )
{
b3RecQueryBegin( &recWriter, context );
b3RecQueryBegin( &recWriter, context, filter.id, filter.name );
recWriter.userFcn.overlapFcn = fcn;
b3RecW_WORLDID( &recWriter.buf, worldId );
b3RecW_POSITION( &recWriter.buf, origin );
@ -2780,7 +2781,7 @@ void b3World_CollideMover( b3WorldId worldId, b3Pos origin, const b3Capsule* mov
b3RecQueryWriter recWriter = { 0 };
if ( world->recording != NULL )
{
b3RecQueryBegin( &recWriter, context );
b3RecQueryBegin( &recWriter, context, filter.id, filter.name );
recWriter.userFcn.planeFcn = fcn;
b3RecW_WORLDID( &recWriter.buf, worldId );
b3RecW_POSITION( &recWriter.buf, origin );
@ -2894,7 +2895,7 @@ b3TreeStats b3World_CastRay( b3WorldId worldId, b3Pos origin, b3Vec3 translation
b3RecQueryWriter recWriter = { 0 };
if ( world->recording != NULL )
{
b3RecQueryBegin( &recWriter, context );
b3RecQueryBegin( &recWriter, context, filter.id, filter.name );
recWriter.userFcn.castFcn = fcn;
b3RecW_WORLDID( &recWriter.buf, worldId );
b3RecW_POSITION( &recWriter.buf, origin );
@ -3002,7 +3003,7 @@ b3RayResult b3World_CastRayClosest( b3WorldId worldId, b3Pos origin, b3Vec3 tran
if ( world->recording != NULL )
{
b3RecQueryWriter recWriter = { 0 };
b3RecQueryBegin( &recWriter, NULL );
b3RecQueryBegin( &recWriter, NULL, filter.id, filter.name );
b3RecW_WORLDID( &recWriter.buf, worldId );
b3RecW_POSITION( &recWriter.buf, origin );
b3RecW_VEC3( &recWriter.buf, translation );
@ -3094,7 +3095,7 @@ b3TreeStats b3World_CastShape( b3WorldId worldId, b3Pos origin, const b3ShapePro
b3RecQueryWriter recWriter = { 0 };
if ( world->recording != NULL )
{
b3RecQueryBegin( &recWriter, context );
b3RecQueryBegin( &recWriter, context, filter.id, filter.name );
recWriter.userFcn.castFcn = fcn;
b3RecW_WORLDID( &recWriter.buf, worldId );
b3RecW_POSITION( &recWriter.buf, origin );
@ -3225,7 +3226,7 @@ float b3World_CastMover( b3WorldId worldId, b3Pos origin, const b3Capsule* mover
b3RecQueryWriter recWriter = { 0 };
if ( world->recording != NULL )
{
b3RecQueryBegin( &recWriter, context );
b3RecQueryBegin( &recWriter, context, filter.id, filter.name );
recWriter.userFcn.moverFilterFcn = fcn;
b3RecW_WORLDID( &recWriter.buf, worldId );
b3RecW_POSITION( &recWriter.buf, origin );

View file

@ -87,8 +87,8 @@ void b3RecW_U32( b3RecBuffer* buf, uint32_t v )
void b3RecW_U64( b3RecBuffer* buf, uint64_t v )
{
uint8_t b[8] = { (uint8_t)v, (uint8_t)( v >> 8 ), (uint8_t)( v >> 16 ), (uint8_t)( v >> 24 ),
(uint8_t)( v >> 32 ), (uint8_t)( v >> 40 ), (uint8_t)( v >> 48 ), (uint8_t)( v >> 56 ) };
uint8_t b[8] = { (uint8_t)v, (uint8_t)( v >> 8 ), (uint8_t)( v >> 16 ), (uint8_t)( v >> 24 ),
(uint8_t)( v >> 32 ), (uint8_t)( v >> 40 ), (uint8_t)( v >> 48 ), (uint8_t)( v >> 56 ) };
b3RecBufAppend( buf, b, 8 );
}
@ -316,29 +316,29 @@ void b3RecW_STR( b3RecBuffer* buf, const char* s )
// so the writer and reader both get updated. Only enforced on the 64-bit target; each def lists the
// single-precision and double-precision sizes (equal for most), so either build configuration passes.
_Static_assert( sizeof( void* ) != 8 || sizeof( b3ExplosionDef ) == 32 || sizeof( b3ExplosionDef ) == 48,
"b3ExplosionDef changed: update b3RecW_EXPLOSIONDEF and b3RecR_EXPLOSIONDEF together" );
"b3ExplosionDef changed: update b3RecW_EXPLOSIONDEF and b3RecR_EXPLOSIONDEF together" );
_Static_assert( sizeof( void* ) != 8 || sizeof( b3BodyDef ) == 104 || sizeof( b3BodyDef ) == 120,
"b3BodyDef changed: update b3RecW_BODYDEF and b3RecR_BODYDEF together" );
_Static_assert( sizeof( void* ) != 8 || sizeof( b3ShapeDef ) == 120,
"b3ShapeDef changed: update b3RecW_SHAPEDEF and b3RecR_SHAPEDEF together" );
"b3BodyDef changed: update b3RecW_BODYDEF and b3RecR_BODYDEF together" );
_Static_assert( sizeof( void* ) != 8 || sizeof( b3ShapeDef ) == 112,
"b3ShapeDef changed: update b3RecW_SHAPEDEF and b3RecR_SHAPEDEF together" );
_Static_assert( sizeof( void* ) != 8 || sizeof( b3ParallelJointDef ) == 128,
"b3ParallelJointDef changed: update b3RecW_PARALLELJOINTDEF and its reader together" );
"b3ParallelJointDef changed: update b3RecW_PARALLELJOINTDEF and its reader together" );
_Static_assert( sizeof( void* ) != 8 || sizeof( b3DistanceJointDef ) == 160,
"b3DistanceJointDef changed: update b3RecW_DISTANCEJOINTDEF and its reader together" );
"b3DistanceJointDef changed: update b3RecW_DISTANCEJOINTDEF and its reader together" );
_Static_assert( sizeof( void* ) != 8 || sizeof( b3FilterJointDef ) == 112,
"b3FilterJointDef changed: update b3RecW_FILTERJOINTDEF and its reader together" );
"b3FilterJointDef changed: update b3RecW_FILTERJOINTDEF and its reader together" );
_Static_assert( sizeof( void* ) != 8 || sizeof( b3MotorJointDef ) == 168,
"b3MotorJointDef changed: update b3RecW_MOTORJOINTDEF and its reader together" );
"b3MotorJointDef changed: update b3RecW_MOTORJOINTDEF and its reader together" );
_Static_assert( sizeof( void* ) != 8 || sizeof( b3PrismaticJointDef ) == 152,
"b3PrismaticJointDef changed: update b3RecW_PRISMATICJOINTDEF and its reader together" );
"b3PrismaticJointDef changed: update b3RecW_PRISMATICJOINTDEF and its reader together" );
_Static_assert( sizeof( void* ) != 8 || sizeof( b3RevoluteJointDef ) == 152,
"b3RevoluteJointDef changed: update b3RecW_REVOLUTEJOINTDEF and its reader together" );
"b3RevoluteJointDef changed: update b3RecW_REVOLUTEJOINTDEF and its reader together" );
_Static_assert( sizeof( void* ) != 8 || sizeof( b3SphericalJointDef ) == 184,
"b3SphericalJointDef changed: update b3RecW_SPHERICALJOINTDEF and its reader together" );
"b3SphericalJointDef changed: update b3RecW_SPHERICALJOINTDEF and its reader together" );
_Static_assert( sizeof( void* ) != 8 || sizeof( b3WeldJointDef ) == 128,
"b3WeldJointDef changed: update b3RecW_WELDJOINTDEF and its reader together" );
"b3WeldJointDef changed: update b3RecW_WELDJOINTDEF and its reader together" );
_Static_assert( sizeof( void* ) != 8 || sizeof( b3WheelJointDef ) == 184,
"b3WheelJointDef changed: update b3RecW_WHEELJOINTDEF and its reader together" );
"b3WheelJointDef changed: update b3RecW_WHEELJOINTDEF and its reader together" );
void b3RecW_EXPLOSIONDEF( b3RecBuffer* buf, b3ExplosionDef v )
{
@ -375,7 +375,6 @@ void b3RecW_BODYDEF( b3RecBuffer* buf, b3BodyDef v )
void b3RecW_SHAPEDEF( b3RecBuffer* buf, b3ShapeDef v )
{
b3RecW_STR( buf, v.name );
// userData: not preserved
b3RecW_U64( buf, 0u );
// Per-triangle materials: length-prefixed so the reader can rebuild the array.
@ -565,29 +564,52 @@ void b3RecPatchU32( b3RecBuffer* buf, int offset, uint32_t v )
p[3] = (uint8_t)( v >> 24 );
}
void b3RecCommitRecord( b3Recording* rec, uint8_t opcode, const uint8_t* payload, int payloadSize )
// Frame and append one record into the buffer. Caller holds rec->lock.
static void b3RecCommitRecordLocked( b3Recording* rec, uint8_t opcode, const uint8_t* payload, int payloadSize )
{
B3_ASSERT( payloadSize >= 0 && payloadSize < ( 1 << 24 ) );
b3LockMutex( rec->lock );
b3RecW_U8( &rec->buffer, opcode );
uint8_t sz[3] = { (uint8_t)payloadSize, (uint8_t)( payloadSize >> 8 ), (uint8_t)( payloadSize >> 16 ) };
b3RecBufAppend( &rec->buffer, sz, 3 );
b3RecBufAppend( &rec->buffer, payload, payloadSize );
}
void b3RecCommitRecord( b3Recording* rec, uint8_t opcode, const uint8_t* payload, int payloadSize )
{
b3LockMutex( rec->lock );
b3RecCommitRecordLocked( rec, opcode, payload, payloadSize );
b3UnlockMutex( rec->lock );
}
void b3RecQueryBegin( b3RecQueryWriter* w, void* context )
void b3RecQueryBegin( b3RecQueryWriter* w, void* context, uint64_t tagId, const char* tagName )
{
w->buf = ( b3RecBuffer ){ 0 };
w->buf = (b3RecBuffer){ 0 };
w->userFcn.overlapFcn = NULL;
w->userContext = context;
w->hitCount = 0;
w->countOffset = 0;
w->tagId = tagId;
w->tagName = tagName;
}
void b3RecQueryCommit( b3Recording* rec, uint8_t opcode, b3RecQueryWriter* w )
{
b3RecCommitRecord( rec, opcode, w->buf.data, w->buf.size );
b3LockMutex( rec->lock );
// A tagged query writes its identity key right before the query record, under one lock so the pair
// stays adjacent even with concurrent queries. The key is the hash of the caller (id, name), which
// are interned once into the trailing tag table so the viewer can show them.
bool tagged = w->tagId != 0 || ( w->tagName != NULL && w->tagName[0] != '\0' );
if ( tagged )
{
uint64_t key = b3HashQueryTag( w->tagId, w->tagName );
b3RecInternTag( rec, key, w->tagId, w->tagName );
b3RecBuffer tagBuf = { 0 };
b3RecW_U64( &tagBuf, key );
b3RecCommitRecordLocked( rec, b3_recOpQueryTag, tagBuf.data, tagBuf.size );
b3RecBufFree( &tagBuf );
}
b3RecCommitRecordLocked( rec, opcode, w->buf.data, w->buf.size );
b3UnlockMutex( rec->lock );
b3RecBufFree( &w->buf );
}
@ -669,13 +691,17 @@ void b3RecEndRecord( b3Recording* rec )
#undef B3_REC_OP
#undef ARG
// Codegen: full writers
// Codegen: full writers. Setters may run on threads that each own a distinct object,
// so hold the lock across the whole record. Without it a concurrent writer splices its bytes between
// our begin and end and the record desyncs replay. Same lock the query commit path takes.
#define B3_REC_OP( op, Name, RET, ... ) \
void b3RecWrite_##Name( b3Recording* rec, const b3RecArgs_##Name* a ) \
{ \
b3LockMutex( rec->lock ); \
b3RecBeginRecord( rec, (uint8_t)( op ) ); \
b3RecWriteArgs_##Name( rec, a ); \
b3RecEndRecord( rec ); \
b3UnlockMutex( rec->lock ); \
}
#include "recording_ops.inl"
#undef B3_REC_OP
@ -684,13 +710,15 @@ void b3RecEndRecord( b3Recording* rec )
#define B3_REC_RETWRITE( op, Name, idType, idW ) \
void b3RecWriteRet_##Name( b3Recording* rec, const b3RecArgs_##Name* a, idType id ) \
{ \
b3LockMutex( rec->lock ); \
b3RecBeginRecord( rec, (uint8_t)( op ) ); \
b3RecWriteArgs_##Name( rec, a ); \
idW( &rec->buffer, id ); \
b3RecEndRecord( rec ); \
b3UnlockMutex( rec->lock ); \
}
#define B3_REC_RETWRITE_RET_NONE( op, Name )
#define B3_REC_RETWRITE_RET_BODYID( op, Name ) B3_REC_RETWRITE( op, Name, b3BodyId, b3RecW_BODYID )
#define B3_REC_RETWRITE_RET_BODYID( op, Name ) B3_REC_RETWRITE( op, Name, b3BodyId, b3RecW_BODYID )
#define B3_REC_RETWRITE_RET_SHAPEID( op, Name ) B3_REC_RETWRITE( op, Name, b3ShapeId, b3RecW_SHAPEID )
#define B3_REC_RETWRITE_RET_JOINTID( op, Name ) B3_REC_RETWRITE( op, Name, b3JointId, b3RecW_JOINTID )
#define B3_REC_OP( op, Name, RET, ... ) B3_REC_RETWRITE_##RET( op, Name )
@ -704,16 +732,47 @@ void b3RecEndRecord( b3Recording* rec )
// Geometry registry
// Fold a 32-bit hash into 64 bits. Collisions are caught by the byteCount+memcmp fallback.
// 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 )
{
uint32_t h = b3Hash( B3_HASH_INIT, bytes, n );
return (uint64_t)h | ( (uint64_t)b3NonZeroHash( ~h ) << 32 );
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 entry id, so dedup is O(1) average instead of a linear scan. A 64-bit content-hash
// collision between distinct blobs is still caught by the byteCount + memcmp check, so it can never
// return the wrong id; the worst case is a missed dedup in that astronomically unlikely event.
// 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
#define KEY_TY uint64_t
#define VAL_TY uint32_t
@ -723,8 +782,50 @@ uint64_t b3Hash64Blob( const uint8_t* bytes, int n )
#define FREE_FN b3Free
#include "verstable.h"
uint32_t b3InternGeometry( b3GeometryRegistry* reg, b3GeometryKind kind, uint64_t contentHash,
uint8_t* bytes, int byteCount )
// Tag key to tag index, so interning a query tag is O(1) rather than a linear scan over the tag table.
#define NAME b3RecTagMap
#define KEY_TY uint64_t
#define VAL_TY uint32_t
#define HASH_FN vt_hash_integer
#define CMPR_FN vt_cmpr_integer
#define MALLOC_FN b3Alloc
#define FREE_FN b3Free
#include "verstable.h"
// Append a fresh entry and splice it onto the front of its hash chain. The map value is the chain head.
static uint32_t b3RegistryPush( b3GeometryRegistry* reg, b3GeometryHashMap* map, b3GeometryHashMap_itr itr, bool hashPresent,
b3GeometryKind kind, uint64_t contentHash, uint8_t* bytes, int byteCount )
{
if ( reg->count >= reg->capacity )
{
int newCap = reg->capacity < 8 ? 8 : reg->capacity * 2;
reg->entries = (b3GeometryEntry*)b3GrowAlloc( reg->entries, reg->capacity * (int)sizeof( b3GeometryEntry ),
newCap * (int)sizeof( b3GeometryEntry ) );
reg->capacity = newCap;
}
uint32_t id = (uint32_t)reg->count;
b3GeometryEntry* entry = reg->entries + reg->count;
entry->contentHash = contentHash;
entry->id = id;
entry->kind = kind;
entry->byteCount = byteCount;
entry->bytes = bytes; // take ownership
entry->hashNext = hashPresent ? (int)itr.data->val : B3_NULL_INDEX;
reg->count++;
if ( hashPresent )
{
itr.data->val = id;
}
else
{
b3GeometryHashMap_insert( map, contentHash, id );
}
return id;
}
static b3GeometryHashMap* b3RegistryMap( b3GeometryRegistry* reg )
{
if ( reg->dedupMap == NULL )
{
@ -732,48 +833,39 @@ uint32_t b3InternGeometry( b3GeometryRegistry* reg, b3GeometryKind kind, uint64_
b3GeometryHashMap_init( fresh );
reg->dedupMap = fresh;
}
b3GeometryHashMap* map = (b3GeometryHashMap*)reg->dedupMap;
return (b3GeometryHashMap*)reg->dedupMap;
}
uint32_t b3InternGeometry( b3GeometryRegistry* reg, b3GeometryKind kind, uint64_t contentHash, uint8_t* bytes, int byteCount )
{
b3GeometryHashMap* map = b3RegistryMap( reg );
b3GeometryHashMap_itr itr = b3GeometryHashMap_get( map, contentHash );
bool hashPresent = b3GeometryHashMap_is_end( itr ) == false;
if ( hashPresent )
{
b3GeometryEntry* e = reg->entries + itr.data->val;
if ( e->byteCount == byteCount && memcmp( e->bytes, bytes, (size_t)byteCount ) == 0 )
// Walk every entry sharing this hash so a collision still finds the identical blob.
for ( int idx = (int)itr.data->val; idx != B3_NULL_INDEX; idx = reg->entries[idx].hashNext )
{
// Duplicate: the caller transferred ownership; return existing id
b3Free( bytes, (size_t)byteCount );
return e->id;
b3GeometryEntry* e = reg->entries + idx;
if ( e->byteCount == byteCount && memcmp( e->bytes, bytes, (size_t)byteCount ) == 0 )
{
// Duplicate: the caller transferred ownership; return existing id
b3Free( bytes, (size_t)byteCount );
return e->id;
}
}
// Same hash, different bytes: a 64-bit collision. Store a new entry and leave the map pointing
// at the first, so only a later blob identical to this rare one would miss dedup.
}
// New entry — grow the array if needed
if ( reg->count >= reg->capacity )
{
int newCap = reg->capacity < 8 ? 8 : reg->capacity * 2;
reg->entries = (b3GeometryEntry*)b3GrowAlloc( reg->entries,
reg->capacity * (int)sizeof( b3GeometryEntry ),
newCap * (int)sizeof( b3GeometryEntry ) );
reg->capacity = newCap;
}
return b3RegistryPush( reg, map, itr, hashPresent, kind, contentHash, bytes, byteCount );
}
uint32_t id = (uint32_t)reg->count;
b3GeometryEntry* entry = reg->entries + reg->count;
entry->contentHash = contentHash;
entry->id = id;
entry->kind = kind;
entry->byteCount = byteCount;
entry->bytes = bytes; // take ownership
reg->count++;
// Only the first entry for a given hash goes in the map; a hash hit is verified by memcmp above.
if ( hashPresent == false )
{
b3GeometryHashMap_insert( map, contentHash, id );
}
return id;
uint32_t b3AppendGeometry( b3GeometryRegistry* reg, b3GeometryKind kind, uint64_t contentHash, uint8_t* bytes, int byteCount )
{
b3GeometryHashMap* map = b3RegistryMap( reg );
b3GeometryHashMap_itr itr = b3GeometryHashMap_get( map, contentHash );
bool hashPresent = b3GeometryHashMap_is_end( itr ) == false;
return b3RegistryPush( reg, map, itr, hashPresent, kind, contentHash, bytes, byteCount );
}
void b3FreeRegistry( b3GeometryRegistry* reg )
@ -791,13 +883,73 @@ void b3FreeRegistry( b3GeometryRegistry* reg )
b3GeometryHashMap_cleanup( (b3GeometryHashMap*)reg->dedupMap );
b3Free( reg->dedupMap, sizeof( b3GeometryHashMap ) );
}
reg->entries = NULL;
reg->count = 0;
reg->entries = NULL;
reg->count = 0;
reg->capacity = 0;
reg->dedupMap = NULL;
}
// Write the trailing registry block: u32 entryCount then per-entry { u8 kind, u32 byteCount, bytes }.
uint64_t b3HashQueryTag( uint64_t id, const char* name )
{
uint64_t h = B3_SNAP_FNV_INIT;
for ( int i = 0; i < 8; ++i )
{
h = ( h ^ ( ( id >> ( 8 * i ) ) & 0xFFu ) ) * B3_SNAP_FNV_PRIME;
}
if ( name != NULL )
{
for ( int i = 0; name[i] != '\0'; ++i )
{
h = ( h ^ (uint8_t)name[i] ) * B3_SNAP_FNV_PRIME;
}
}
// Never 0 so the key doubles as the tagged flag.
return h != 0 ? h : 1;
}
static b3RecTagMap* b3RecTags( b3Recording* rec )
{
if ( rec->tagMap == NULL )
{
b3RecTagMap* fresh = b3Alloc( sizeof( b3RecTagMap ) );
b3RecTagMap_init( fresh );
rec->tagMap = fresh;
}
return rec->tagMap;
}
void b3RecInternTag( b3Recording* rec, uint64_t key, uint64_t id, const char* name )
{
b3RecTagMap* map = b3RecTags( rec );
if ( b3RecTagMap_is_end( b3RecTagMap_get( map, key ) ) == false )
{
return; // first id/name for a key wins
}
if ( rec->tagCount == rec->tagCapacity )
{
int newCap = rec->tagCapacity == 0 ? 8 : 2 * rec->tagCapacity;
rec->tags = b3GrowAlloc( rec->tags, rec->tagCapacity * (int)sizeof( b3RecTag ), newCap * (int)sizeof( b3RecTag ) );
rec->tagCapacity = newCap;
}
uint32_t index = (uint32_t)rec->tagCount;
b3RecTag* tag = &rec->tags[rec->tagCount++];
tag->key = key;
tag->id = id;
int n = 0;
while ( name != NULL && name[n] != '\0' && n < B3_NAME_LENGTH )
{
tag->name[n] = name[n];
n++;
}
tag->name[n] = '\0';
b3RecTagMap_insert( map, key, index );
}
// Write the trailing registry block: u32 entryCount then per-entry { u8 kind, u32 byteCount, bytes },
// followed by the query-tag table { u32 tagCount, per-tag uu64 id, STR name }. A reader built before
// the tag table stops after the geometry entries and ignores the trailing tag bytes.
void b3RecWriteRegistry( b3Recording* rec )
{
b3RecW_U32( &rec->buffer, (uint32_t)rec->registry.count );
@ -808,6 +960,14 @@ void b3RecWriteRegistry( b3Recording* rec )
b3RecW_U32( &rec->buffer, (uint32_t)e->byteCount );
b3RecBufAppend( &rec->buffer, e->bytes, e->byteCount );
}
b3RecW_U32( &rec->buffer, (uint32_t)rec->tagCount );
for ( int i = 0; i < rec->tagCount; ++i )
{
b3RecW_U64( &rec->buffer, rec->tags[i].key );
b3RecW_U64( &rec->buffer, rec->tags[i].id );
b3RecW_STR( &rec->buffer, rec->tags[i].name );
}
}
// Lifecycle
@ -818,9 +978,9 @@ b3Recording* b3CreateRecording( int byteCapacity )
*rec = (b3Recording){ 0 };
int initCap = byteCapacity > 0 ? byteCapacity : 65536;
rec->buffer.data = (uint8_t*)b3Alloc( (size_t)initCap );
rec->buffer.data = (uint8_t*)b3Alloc( (size_t)initCap );
rec->buffer.capacity = initCap;
rec->buffer.size = 0;
rec->buffer.size = 0;
rec->lock = b3CreateMutex();
return rec;
}
@ -834,6 +994,15 @@ void b3DestroyRecording( b3Recording* recording )
b3RecBufFree( &recording->buffer );
b3FreeRegistry( &recording->registry );
if ( recording->tags != NULL )
{
b3Free( recording->tags, (size_t)recording->tagCapacity * sizeof( b3RecTag ) );
}
if ( recording->tagMap != NULL )
{
b3RecTagMap_cleanup( (b3RecTagMap*)recording->tagMap );
b3Free( recording->tagMap, sizeof( b3RecTagMap ) );
}
b3DestroyMutex( recording->lock );
b3Free( recording, sizeof( b3Recording ) );
}
@ -859,18 +1028,31 @@ void b3StartRecordingIntoBuffer( b3World* world, b3Recording* recording )
// Reset so a recording handle can be reused for a fresh session
recording->buffer.size = 0;
recording->recordStart = 0;
recording->haveBounds = false;
recording->haveBounds = false;
b3FreeRegistry( &recording->registry );
if ( recording->tags != NULL )
{
b3Free( recording->tags, (size_t)recording->tagCapacity * sizeof( b3RecTag ) );
recording->tags = NULL;
}
if ( recording->tagMap != NULL )
{
b3RecTagMap_cleanup( (b3RecTagMap*)recording->tagMap );
b3Free( recording->tagMap, sizeof( b3RecTagMap ) );
recording->tagMap = NULL;
}
recording->tagCount = 0;
recording->tagCapacity = 0;
b3RecHeader hdr = { 0 };
hdr.magic = B3_REC_MAGIC;
hdr.versionMajor = B3_REC_VERSION_MAJOR;
hdr.versionMinor = B3_REC_VERSION_MINOR;
hdr.pointerWidth = (uint8_t)sizeof( void* );
hdr.bigEndian = 0;
hdr.magic = B3_REC_MAGIC;
hdr.versionMajor = B3_REC_VERSION_MAJOR;
hdr.versionMinor = B3_REC_VERSION_MINOR;
hdr.pointerWidth = (uint8_t)sizeof( void* );
hdr.bigEndian = 0;
hdr.validationEnabled = B3_ENABLE_VALIDATION ? 1u : 0u;
hdr.lengthScale = b3GetLengthUnitsPerMeter();
hdr.registryOffset = 0; // backpatched in b3StopRecordingInternal
hdr.lengthScale = b3GetLengthUnitsPerMeter();
hdr.registryOffset = 0; // backpatched in b3StopRecordingInternal
hdr.registryByteCount = 0;
world->recording = recording;
@ -924,14 +1106,14 @@ void b3StopRecordingInternal( b3World* world )
// Backpatch registryOffset and registryByteCount into the header
uint8_t* hdrBytes = rec->buffer.data;
uint64_t regOff = (uint64_t)registryOffset;
uint64_t regSz = (uint64_t)registryByteCount;
uint64_t regSz = (uint64_t)registryByteCount;
// Little-endian backpatch in place; offsetof keeps this correct if the header layout shifts
uint8_t* pOff = hdrBytes + offsetof( b3RecHeader, registryOffset );
uint8_t* pSz = hdrBytes + offsetof( b3RecHeader, registryByteCount );
uint8_t* pSz = hdrBytes + offsetof( b3RecHeader, registryByteCount );
for ( int i = 0; i < 8; ++i )
{
pOff[i] = (uint8_t)( regOff >> ( 8 * i ) );
pSz[i] = (uint8_t)( regSz >> ( 8 * i ) );
pSz[i] = (uint8_t)( regSz >> ( 8 * i ) );
}
}

View file

@ -46,26 +46,27 @@ typedef struct b3World b3World;
#define B3_REC_MAGIC 0x43523342u
// Minor tracks op-stream additions that keep the 48 byte header shape (e.g. the spatial query ops).
#define B3_REC_VERSION_MAJOR 1
#define B3_REC_VERSION_MINOR 1
// Minor 2 added the QueryTag op and the interned query-tag table at the tail of the registry block.
#define B3_REC_VERSION_MAJOR 2
#define B3_REC_VERSION_MINOR 2
// File header, fixed 48 bytes, little-endian. Contains the registry locator so the player
// can load geometry before replaying any ops.
typedef struct b3RecHeader
{
uint32_t magic; // 'B3RC' = 0x43523342
uint16_t versionMajor; // B3_REC_VERSION_MAJOR
uint16_t versionMinor; // B3_REC_VERSION_MINOR
uint8_t pointerWidth; // sizeof(void*), gates POD-def struct layout
uint8_t bigEndian; // 0 on all supported targets
uint8_t validationEnabled; // 1 if built with BOX3D_VALIDATE, diagnostic only
uint8_t reserved;
float lengthScale; // b3GetLengthUnitsPerMeter()
uint32_t magic; // 'B3RC' = 0x43523342
uint16_t versionMajor; // B3_REC_VERSION_MAJOR
uint16_t versionMinor; // B3_REC_VERSION_MINOR
uint8_t pointerWidth; // sizeof(void*), gates POD-def struct layout
uint8_t bigEndian; // 0 on all supported targets
uint8_t validationEnabled; // 1 if built with BOX3D_VALIDATE, diagnostic only
uint8_t reserved;
float lengthScale; // b3GetLengthUnitsPerMeter()
uint32_t reserved2;
uint32_t reserved3; // explicit pad so the 64-bit fields align with no implicit gap
uint64_t snapshotSize; // bytes of snapshot blob after the header (0 in Phase 1)
uint64_t registryOffset; // absolute offset to trailing registry block, backpatched at stop
uint64_t registryByteCount; // size of the registry block
uint32_t reserved3; // explicit pad so the 64-bit fields align with no implicit gap
uint64_t snapshotSize; // bytes of snapshot blob after the header (0 in Phase 1)
uint64_t registryOffset; // absolute offset to trailing registry block, backpatched at stop
uint64_t registryByteCount; // size of the registry block
} b3RecHeader;
_Static_assert( sizeof( b3RecHeader ) == 48, "recording header must be 48 bytes" );
@ -75,9 +76,9 @@ _Static_assert( sizeof( b3RecHeader ) == 48, "recording header must be 48 bytes"
typedef struct b3RecBuffer
{
uint8_t* data;
int capacity;
int size;
bool countOnly;
int capacity;
int size;
bool countOnly;
} b3RecBuffer;
// Geometry kinds for the trailing registry section
@ -90,13 +91,16 @@ typedef enum b3GeometryKind
} b3GeometryKind;
// One entry per unique geometry blob. id == index in the entries array.
// hashNext chains entries that share a content hash so dedup stays exact under a hash collision,
// which the keyframe registry depends on to never grow during capture. B3_NULL_INDEX ends the chain.
typedef struct b3GeometryEntry
{
uint64_t contentHash;
uint32_t id;
uint64_t contentHash;
uint32_t id;
b3GeometryKind kind;
int byteCount;
uint8_t* bytes;
int byteCount;
uint8_t* bytes;
int hashNext;
} b3GeometryEntry;
// Growable array of geometry entries. Ids are array indices, so the array is serialized in order.
@ -104,68 +108,85 @@ typedef struct b3GeometryEntry
typedef struct b3GeometryRegistry
{
b3GeometryEntry* entries;
int count;
int capacity;
void* dedupMap;
int count;
int capacity;
void* dedupMap;
} b3GeometryRegistry;
// Query tag from b3QueryFilter.
// Stored once per key in the trailing block so a tagged query carries only the 8 byte key on the wire.
// Shared by the recorder (accumulate) and the player (load).
typedef struct b3RecTag
{
uint64_t key; // hash of (id, name)
uint64_t id; // entity/actor id
char name[B3_NAME_LENGTH + 1]; // query label
} b3RecTag;
// User-owned recording buffer. The world appends into it while active; the host saves and
// destroys it. Opaque across the public API.
typedef struct b3Recording
{
b3RecBuffer buffer;
int recordStart; // offset of the 3-byte size field for u24 backpatch
b3Mutex* lock; // serializes query commits from concurrent threads
b3RecBuffer buffer;
int recordStart; // offset of the 3-byte size field for u24 backpatch
b3Mutex* lock; // serializes record writes from concurrent threads
b3GeometryRegistry registry;
// Interned query tags accumulated during capture, written to the tail of the registry block at stop.
// tagMap maps a tag key to its index for O(1) dedup.
b3RecTag* tags;
int tagCount;
int tagCapacity;
void* tagMap;
// Union of world bounds over every recorded step, written at stop.
b3AABB accumulatedBounds;
bool haveBounds;
b3AABB accumulatedBounds;
bool haveBounds;
} b3Recording;
// C type aliases per TAG, used in the X-macro codegen arg structs
typedef bool b3RecCType_BOOL;
typedef int32_t b3RecCType_I32;
typedef uint8_t b3RecCType_U8;
typedef uint16_t b3RecCType_U16;
typedef uint32_t b3RecCType_U32;
typedef uint64_t b3RecCType_U64;
typedef float b3RecCType_F32;
typedef double b3RecCType_F64;
typedef b3Vec3 b3RecCType_VEC3;
typedef b3Quat b3RecCType_QUAT;
typedef b3Transform b3RecCType_TRANSFORM;
typedef b3Pos b3RecCType_POSITION;
typedef bool b3RecCType_BOOL;
typedef int32_t b3RecCType_I32;
typedef uint8_t b3RecCType_U8;
typedef uint16_t b3RecCType_U16;
typedef uint32_t b3RecCType_U32;
typedef uint64_t b3RecCType_U64;
typedef float b3RecCType_F32;
typedef double b3RecCType_F64;
typedef b3Vec3 b3RecCType_VEC3;
typedef b3Quat b3RecCType_QUAT;
typedef b3Transform b3RecCType_TRANSFORM;
typedef b3Pos b3RecCType_POSITION;
typedef b3WorldTransform b3RecCType_WORLDXF;
typedef b3Matrix3 b3RecCType_MATRIX3;
typedef b3AABB b3RecCType_AABB;
typedef b3Sphere b3RecCType_SPHERE;
typedef b3Capsule b3RecCType_CAPSULE;
typedef b3QueryFilter b3RecCType_QUERYFILTER;
typedef b3ShapeProxy b3RecCType_SHAPEPROXY;
typedef b3Matrix3 b3RecCType_MATRIX3;
typedef b3AABB b3RecCType_AABB;
typedef b3Sphere b3RecCType_SPHERE;
typedef b3Capsule b3RecCType_CAPSULE;
typedef b3QueryFilter b3RecCType_QUERYFILTER;
typedef b3ShapeProxy b3RecCType_SHAPEPROXY;
// Geometry reference: a plain u32 id into the trailing registry
typedef uint32_t b3RecCType_GEOMID;
typedef b3Filter b3RecCType_FILTER;
typedef uint32_t b3RecCType_GEOMID;
typedef b3Filter b3RecCType_FILTER;
typedef b3SurfaceMaterial b3RecCType_MATERIAL;
typedef b3MassData b3RecCType_MASSDATA;
typedef b3MotionLocks b3RecCType_LOCKS;
typedef const char* b3RecCType_STR;
typedef b3WorldId b3RecCType_WORLDID;
typedef b3BodyId b3RecCType_BODYID;
typedef b3ShapeId b3RecCType_SHAPEID;
typedef b3JointId b3RecCType_JOINTID;
typedef b3BodyDef b3RecCType_BODYDEF;
typedef b3ShapeDef b3RecCType_SHAPEDEF;
typedef b3ExplosionDef b3RecCType_EXPLOSIONDEF;
typedef b3ParallelJointDef b3RecCType_PARALLELJOINTDEF;
typedef b3DistanceJointDef b3RecCType_DISTANCEJOINTDEF;
typedef b3FilterJointDef b3RecCType_FILTERJOINTDEF;
typedef b3MotorJointDef b3RecCType_MOTORJOINTDEF;
typedef b3MassData b3RecCType_MASSDATA;
typedef b3MotionLocks b3RecCType_LOCKS;
typedef const char* b3RecCType_STR;
typedef b3WorldId b3RecCType_WORLDID;
typedef b3BodyId b3RecCType_BODYID;
typedef b3ShapeId b3RecCType_SHAPEID;
typedef b3JointId b3RecCType_JOINTID;
typedef b3BodyDef b3RecCType_BODYDEF;
typedef b3ShapeDef b3RecCType_SHAPEDEF;
typedef b3ExplosionDef b3RecCType_EXPLOSIONDEF;
typedef b3ParallelJointDef b3RecCType_PARALLELJOINTDEF;
typedef b3DistanceJointDef b3RecCType_DISTANCEJOINTDEF;
typedef b3FilterJointDef b3RecCType_FILTERJOINTDEF;
typedef b3MotorJointDef b3RecCType_MOTORJOINTDEF;
typedef b3PrismaticJointDef b3RecCType_PRISMATICJOINTDEF;
typedef b3RevoluteJointDef b3RecCType_REVOLUTEJOINTDEF;
typedef b3RevoluteJointDef b3RecCType_REVOLUTEJOINTDEF;
typedef b3SphericalJointDef b3RecCType_SPHERICALJOINTDEF;
typedef b3WeldJointDef b3RecCType_WELDJOINTDEF;
typedef b3WheelJointDef b3RecCType_WHEELJOINTDEF;
typedef b3WeldJointDef b3RecCType_WELDJOINTDEF;
typedef b3WheelJointDef b3RecCType_WHEELJOINTDEF;
// Codegen pass 1a: arg structs. Generated here so call sites (body.c, shape.c, etc.) can see them.
#define ARG( TAG, field ) b3RecCType_##TAG field;
@ -251,7 +272,7 @@ void b3RecEndRecord( b3Recording* rec );
// Create ops: declare writers that also append the returned id inside the record.
#define B3_REC_RETDECL_RET_NONE( Name )
#define B3_REC_RETDECL_RET_BODYID( Name ) void b3RecWriteRet_##Name( b3Recording* rec, const b3RecArgs_##Name* a, b3BodyId id );
#define B3_REC_RETDECL_RET_BODYID( Name ) void b3RecWriteRet_##Name( b3Recording* rec, const b3RecArgs_##Name* a, b3BodyId id );
#define B3_REC_RETDECL_RET_SHAPEID( Name ) void b3RecWriteRet_##Name( b3Recording* rec, const b3RecArgs_##Name* a, b3ShapeId id );
#define B3_REC_RETDECL_RET_JOINTID( Name ) void b3RecWriteRet_##Name( b3Recording* rec, const b3RecArgs_##Name* a, b3JointId id );
#define B3_REC_OP( op, Name, RET, ... ) B3_REC_RETDECL_##RET( Name )
@ -268,8 +289,8 @@ void b3RecEndRecord( b3Recording* rec );
{ \
if ( ( world )->recording != NULL ) \
{ \
b3RecArgs_##Name recArgs = { __VA_ARGS__ }; \
b3RecWrite_##Name( ( world )->recording, &recArgs ); \
b3RecArgs_##Name recArgs = { __VA_ARGS__ }; \
b3RecWrite_##Name( ( world )->recording, &recArgs ); \
} \
} \
while ( 0 )
@ -280,14 +301,14 @@ void b3RecEndRecord( b3Recording* rec );
{ \
if ( ( world )->recording != NULL ) \
{ \
b3RecArgs_##Name recCreateArgs = { __VA_ARGS__ }; \
b3RecWriteRet_##Name( ( world )->recording, &recCreateArgs, id ); \
b3RecArgs_##Name recCreateArgs = { __VA_ARGS__ }; \
b3RecWriteRet_##Name( ( world )->recording, &recCreateArgs, id ); \
} \
} \
while ( 0 )
// Patch helpers for the query hit-count backfill
int b3RecReserveU32( b3RecBuffer* buf );
int b3RecReserveU32( b3RecBuffer* buf );
void b3RecPatchU32( b3RecBuffer* buf, int offset, uint32_t v );
// Commit a finished query record under the lock. The payload buffer stays owned by the caller.
@ -299,31 +320,44 @@ typedef struct b3RecQueryWriter
union
{
b3OverlapResultFcn* overlapFcn;
b3CastResultFcn* castFcn;
b3PlaneResultFcn* planeFcn;
b3MoverFilterFcn* moverFilterFcn;
b3CastResultFcn* castFcn;
b3PlaneResultFcn* planeFcn;
b3MoverFilterFcn* moverFilterFcn;
} userFcn;
void* userContext;
b3RecBuffer buf; // per-call local payload, heap-backed
int countOffset; // offset of the reserved u32 hit-count slot
uint32_t hitCount;
void* userContext;
b3RecBuffer buf; // per-call local payload, heap-backed
int countOffset; // offset of the reserved u32 hit-count slot
uint32_t hitCount;
uint64_t tagId; // caller query id, 0 = untagged. Emitted as a QueryTag before the record.
const char* tagName; // caller query name, interned by id. NULL = none.
} b3RecQueryWriter;
void b3RecQueryBegin( b3RecQueryWriter* w, void* context );
void b3RecQueryBegin( b3RecQueryWriter* w, void* context, uint64_t tagId, const char* tagName );
void b3RecQueryCommit( b3Recording* rec, uint8_t opcode, b3RecQueryWriter* w );
// Recording trampolines: replace the user fcn so hits are captured before dispatch. The overlap
// trampoline doubles for the mover filter, which has the same bool(shapeId, ctx) shape.
bool b3RecOverlapTrampoline( b3ShapeId id, void* ctx );
bool b3RecOverlapTrampoline( b3ShapeId id, void* ctx );
float b3RecCastTrampoline( b3ShapeId id, b3Pos point, b3Vec3 normal, float fraction, uint64_t userMaterialId, int triangleIndex,
int childIndex, void* ctx );
bool b3RecPlaneTrampoline( b3ShapeId id, const b3PlaneResult* planes, int planeCount, void* ctx );
bool b3RecPlaneTrampoline( b3ShapeId id, const b3PlaneResult* planes, int planeCount, void* ctx );
// Geometry registry
uint32_t b3InternGeometry( b3GeometryRegistry* reg, b3GeometryKind kind, uint64_t contentHash,
uint8_t* bytes, int byteCount );
void b3FreeRegistry( b3GeometryRegistry* reg );
void b3RecWriteRegistry( b3Recording* rec );
uint32_t b3InternGeometry( b3GeometryRegistry* reg, b3GeometryKind kind, uint64_t contentHash, uint8_t* bytes, int byteCount );
// Append an entry unconditionally and return its id, which equals its array index. Unlike
// b3InternGeometry it never deduplicates, so the keyframe seed can mirror slots 1:1 even when an
// already-recorded file carries byte-identical duplicate slots (a hash collision wrote them apart).
uint32_t b3AppendGeometry( b3GeometryRegistry* reg, b3GeometryKind kind, uint64_t contentHash, uint8_t* bytes, int byteCount );
void b3FreeRegistry( b3GeometryRegistry* reg );
void b3RecWriteRegistry( b3Recording* rec );
// Hash a query (id, name) pair into the stable key the viewer tracks the query by. Never returns 0,
// so the key doubles as a tagged/untagged flag.
uint64_t b3HashQueryTag( uint64_t id, const char* name );
// Record a key->(id, name) mapping once, deduped by key (a repeated key keeps its first id/name).
// The name is clamped to B3_NAME_LENGTH.
void b3RecInternTag( b3Recording* rec, uint64_t key, uint64_t id, const char* name );
// Intern each large geometry kind and return a stable u32 id for use in create ops.
// Caller does NOT free bytes; b3InternGeometry takes ownership (frees on duplicate).

View file

@ -223,6 +223,11 @@ B3_REC_OP( 0xED, QueryCastMover, RET_NONE,
B3_REC_OP( 0xEE, QueryCollideMover, RET_NONE,
ARG( WORLDID, world ) ARG( POSITION, origin ) ARG( CAPSULE, mover ) ARG( QUERYFILTER, filter ) )
// Identity key (hash of the caller id + label) for the query that immediately follows. Emitted only
// for a tagged query. The id and label are interned in the trailing tag table, so only the 8 byte key
// rides the stream.
B3_REC_OP( 0xEF, QueryTag, RET_NONE, ARG( U64, key ) )
B3_REC_OP( 0xF1, StateHash, RET_NONE, ARG( WORLDID, world ) ARG( U64, hash ) )
// Accumulated world bounds over the whole recording, written once at stop. Informational.

File diff suppressed because it is too large Load diff

View file

@ -15,17 +15,17 @@ typedef struct b3RecPlayer b3RecPlayer;
// replicated across a shape's planes so the replay walker can re-group and compare per shape.
typedef struct b3RecRecordedHit
{
b3ShapeId id;
b3Pos point;
b3Vec3 normal;
float fraction;
uint64_t userMaterialId;
int triangleIndex;
int childIndex;
b3PlaneResult plane; // collide-mover: this plane
int planeCount; // collide-mover: planes in this hit's shape group (replicated)
float userReturnF; // cast queries
bool userReturnB; // overlap / collide-mover (per shape, replicated)
b3ShapeId id;
b3Pos point;
b3Vec3 normal;
float fraction;
uint64_t userMaterialId;
int triangleIndex;
int childIndex;
b3PlaneResult plane; // collide-mover: this plane
int planeCount; // collide-mover: planes in this hit's shape group (replicated)
float userReturnF; // cast queries
bool userReturnB; // overlap / collide-mover (per shape, replicated)
} b3RecRecordedHit;
// Recorded query kind, matching the public b3RecQueryType order.
@ -45,20 +45,21 @@ typedef enum b3RecQueryKind
// AABB, which is world space in 3D.
typedef struct b3RecDrawQuery
{
int kind;
int kind;
uint64_t key; // identity key (hash of caller id+name), 0 = untagged
b3QueryFilter filter;
b3AABB aabb; // overlap AABB, world space
b3Vec3 proxyPoints[B3_MAX_SHAPE_CAST_POINTS]; // overlap/cast shape proxy, origin relative
int proxyCount;
float proxyRadius;
b3Capsule mover; // cast/collide mover, origin relative
b3Pos origin;
b3Vec3 translation;
float castFraction; // cast-mover result fraction
b3RayResult rayResult; // cast-ray-closest result
b3ShapeId shape;
int hitStart; // first hit in the player's frameHits store
int hitCount;
b3AABB aabb; // world-space bounds of the query, swept for casts
b3Vec3 proxyPoints[B3_MAX_SHAPE_CAST_POINTS]; // overlap/cast shape proxy, origin relative
int proxyCount;
float proxyRadius;
b3Capsule mover; // cast/collide mover, origin relative
b3Pos origin;
b3Vec3 translation;
float castFraction; // cast-mover result fraction
b3RayResult rayResult; // cast-ray-closest result
b3ShapeId shape;
int hitStart; // first hit in the player's frameHits store
int hitCount;
} b3RecDrawQuery;
// One slot in the preloaded geometry registry. Loaded from the trailing block before any
@ -66,174 +67,184 @@ typedef struct b3RecDrawQuery
typedef struct b3RegistrySlot
{
b3GeometryKind kind;
int byteCount;
uint8_t* bytes; // raw bytes from the file (always freed at teardown)
void* live; // reconstructed live object, freed after b3DestroyWorld
int byteCount;
uint8_t* bytes; // raw bytes from the file (always freed at teardown)
void* live; // reconstructed live object, freed after b3DestroyWorld
} b3RegistrySlot;
// Reader state threaded through the replay loop and all dispatch functions
typedef struct b3RecReader
{
const uint8_t* data;
int size;
int cursor;
b3WorldId replayWorldId;
bool ok; // false on read overrun or id mismatch, fatal stop
bool diverged; // a StateHash failed, non-fatal
int size;
int cursor;
b3WorldId replayWorldId;
bool ok; // false on read overrun or id mismatch, fatal stop
bool diverged; // a StateHash failed, non-fatal
// Player that owns this reader, or NULL during a headless b3ValidateReplay. Body
// create/destroy and the bounds record fold back into it for the outliner and camera framing.
b3RecPlayer* owner;
b3RecPlayer* owner;
// Scratch for per-triangle materials in shape defs (grown on demand, freed at teardown)
b3SurfaceMaterial* matScratch;
int matScratchCap;
int matScratchCap;
// Scratch for string reads: rotating slots, valid until the next 4 STR reads
char strBufs[4][B3_NAME_LENGTH + 1];
int strNext;
int strNext;
// Preloaded geometry registry
b3RegistrySlot* slots;
int slotCount;
int slotCount;
// Preloaded query-tag table (key -> id, name), loaded with the registry. Resolves the caller id and
// label for the viewer. tagMap maps a key to its tag index for O(1) lookup; opaque, owned by the player.
b3RecTag* tags;
int tagCount; // tags that loaded; a truncated tail loads fewer
int tagCapacity; // tags allocated, used to free the array
void* tagMap;
// Key from the QueryTag op preceding the next query, consumed by the next stash. 0 = untagged.
uint64_t pendingQueryKey;
// Scratch for recorded query hits; grown on demand, freed with the player.
b3RecRecordedHit* hits;
int hitCap;
int hitCap;
// Scratch for a shape-proxy point cloud read from the stream. b3ShapeProxy holds the points
// behind a pointer, so a decoded proxy borrows this until the next proxy read or teardown.
b3Vec3* proxyScratch;
int proxyScratchCap;
int proxyScratchCap;
} b3RecReader;
// Stored snapshot for fast backward seek.
typedef struct b3RecKeyframe
{
uint8_t* image; // serialized world image at the end of this frame
int imageSize;
int imageCapacity; // allocation size (may exceed imageSize)
int frame; // frame index this restores to
int cursor; // op-stream cursor for the frame AFTER this one
int divergeFrame; // divergeFrame state at capture
bool diverged; // rdr.diverged state at capture
uint8_t* image; // serialized world image at the end of this frame
int imageSize;
int imageCapacity; // allocation size (may exceed imageSize)
int frame; // frame index this restores to
int cursor; // op-stream cursor for the frame AFTER this one
int divergeFrame; // divergeFrame state at capture
bool diverged; // rdr.diverged state at capture
// Outliner body list as it stood at this frame, restored verbatim so ordinals are stable.
b3BodyId* bodyIds;
int bodyIdCount;
int bodyIdCount;
} b3RecKeyframe;
struct b3RecPlayer
{
uint8_t* data; // owned copy of recording bytes
int size;
int headerEnd; // first byte of op stream (past header + snapshot blob)
int registryEnd; // end of op stream = start of registry block (or size)
float lengthScale;
float previousLengthScale;
int frame;
int frameCount;
float recordedDt;
int recordedSubStepCount;
int recordedWorkerCount; // worker count requested for the replay world
b3AABB bounds; // accumulated world bounds, decoded from the trailing record
bool atEnd;
int divergeFrame; // first frame that diverged, -1 until then
uint8_t* data; // owned copy of recording bytes
int size;
int headerEnd; // first byte of op stream (past header + snapshot blob)
int registryEnd; // end of op stream = start of registry block (or size)
float lengthScale;
float previousLengthScale;
int frame;
int frameCount;
float recordedDt;
int recordedSubStepCount;
int recordedWorkerCount; // worker count requested for the replay world
b3AABB bounds; // accumulated world bounds, decoded from the trailing record
bool atEnd;
int divergeFrame; // first frame that diverged, -1 until then
// Outliner body list, indexed by creation ordinal. Holes (null ids) mark destroyed bodies so
// later ordinals never shift. Snapshotted into each keyframe and the frame-0 copy, not rebuilt
// from the world, so a stored selection survives backward seeks.
b3BodyId* bodyIds;
int bodyIdCount;
int bodyIdCap;
int bodyIdCount;
int bodyIdCap;
b3BodyId* frame0BodyIds;
int frame0BodyIdCount;
int frame0BodyIdCount;
// Per-frame query store, reset at the top of each StepFrame and filled by the query dispatchers.
// Drawn by b3RecPlayer_DrawFrameQueries and inspected via the public GetFrameQuery API.
b3RecDrawQuery* frameQueries;
int frameQueryCount;
int frameQueryCap;
b3RecDrawQuery* frameQueries;
int frameQueryCount;
int frameQueryCap;
b3RecRecordedHit* frameHits;
int frameHitCount;
int frameHitCap;
int frameHitCount;
int frameHitCap;
// Host debug-shape callbacks applied to every world the player creates. The 3D
// sample renderer builds GPU meshes here, so a replay world without them draws
// nothing. Set once via b3RecPlayer_SetDebugShapeCallbacks; persisted so a world
// rebuilt under new callbacks keeps drawing.
b3CreateDebugShapeCallback* createDebugShape;
b3CreateDebugShapeCallback* createDebugShape;
b3DestroyDebugShapeCallback* destroyDebugShape;
void* debugShapeContext;
void* debugShapeContext;
b3RecReader rdr;
// Frame-0 restore image, points into the owned data copy. Restart and backward seek
// deserialize this in place so the replay world id stays stable.
const uint8_t* frame0Image;
int frame0Size;
int frame0Size;
// Keyframe ring
b3RecKeyframe* keyframes;
int keyframeCount;
int keyframeCapacity;
size_t keyframeBudget;
size_t keyframeBytes;
int keyframeMinInterval;
int keyframeInterval;
int lastKeyframeFrame;
int keyframeCount;
int keyframeCapacity;
size_t keyframeBudget;
size_t keyframeBytes;
int keyframeMinInterval;
int keyframeInterval;
int lastKeyframeFrame;
// Pre-populated recording used by b3SerializeWorld during keyframe capture.
// Its registry mirrors rdr.slots so geometry ids stay stable.
b3Recording* keyframeRec;
b3Recording* keyframeRec;
};
// Read primitives
uint8_t b3RecR_U8( b3RecReader* rdr );
uint16_t b3RecR_U16( b3RecReader* rdr );
uint32_t b3RecR_U24( b3RecReader* rdr );
uint32_t b3RecR_U32( b3RecReader* rdr );
uint64_t b3RecR_U64( b3RecReader* rdr );
int32_t b3RecR_I32( b3RecReader* rdr );
float b3RecR_F32( b3RecReader* rdr );
double b3RecR_F64( b3RecReader* rdr );
bool b3RecR_BOOL( b3RecReader* rdr );
b3Vec3 b3RecR_VEC3( b3RecReader* rdr );
b3Quat b3RecR_QUAT( b3RecReader* rdr );
b3Transform b3RecR_TRANSFORM( b3RecReader* rdr );
b3Pos b3RecR_POSITION( b3RecReader* rdr );
uint8_t b3RecR_U8( b3RecReader* rdr );
uint16_t b3RecR_U16( b3RecReader* rdr );
uint32_t b3RecR_U24( b3RecReader* rdr );
uint32_t b3RecR_U32( b3RecReader* rdr );
uint64_t b3RecR_U64( b3RecReader* rdr );
int32_t b3RecR_I32( b3RecReader* rdr );
float b3RecR_F32( b3RecReader* rdr );
double b3RecR_F64( b3RecReader* rdr );
bool b3RecR_BOOL( b3RecReader* rdr );
b3Vec3 b3RecR_VEC3( b3RecReader* rdr );
b3Quat b3RecR_QUAT( b3RecReader* rdr );
b3Transform b3RecR_TRANSFORM( b3RecReader* rdr );
b3Pos b3RecR_POSITION( b3RecReader* rdr );
b3WorldTransform b3RecR_WORLDXF( b3RecReader* rdr );
b3Matrix3 b3RecR_MATRIX3( b3RecReader* rdr );
b3AABB b3RecR_AABB( b3RecReader* rdr );
b3WorldId b3RecR_WORLDID( b3RecReader* rdr );
b3BodyId b3RecR_BODYID( b3RecReader* rdr );
b3ShapeId b3RecR_SHAPEID( b3RecReader* rdr );
b3JointId b3RecR_JOINTID( b3RecReader* rdr );
b3Sphere b3RecR_SPHERE( b3RecReader* rdr );
b3Capsule b3RecR_CAPSULE( b3RecReader* rdr );
uint32_t b3RecR_GEOMID( b3RecReader* rdr );
b3Filter b3RecR_FILTER( b3RecReader* rdr );
b3Matrix3 b3RecR_MATRIX3( b3RecReader* rdr );
b3AABB b3RecR_AABB( b3RecReader* rdr );
b3WorldId b3RecR_WORLDID( b3RecReader* rdr );
b3BodyId b3RecR_BODYID( b3RecReader* rdr );
b3ShapeId b3RecR_SHAPEID( b3RecReader* rdr );
b3JointId b3RecR_JOINTID( b3RecReader* rdr );
b3Sphere b3RecR_SPHERE( b3RecReader* rdr );
b3Capsule b3RecR_CAPSULE( b3RecReader* rdr );
uint32_t b3RecR_GEOMID( b3RecReader* rdr );
b3Filter b3RecR_FILTER( b3RecReader* rdr );
b3SurfaceMaterial b3RecR_MATERIAL( b3RecReader* rdr );
b3MassData b3RecR_MASSDATA( b3RecReader* rdr );
b3MotionLocks b3RecR_LOCKS( b3RecReader* rdr );
const char* b3RecR_STR( b3RecReader* rdr );
b3ExplosionDef b3RecR_EXPLOSIONDEF( b3RecReader* rdr );
b3BodyDef b3RecR_BODYDEF( b3RecReader* rdr );
b3ShapeDef b3RecR_SHAPEDEF( b3RecReader* rdr );
b3ParallelJointDef b3RecR_PARALLELJOINTDEF( b3RecReader* rdr );
b3DistanceJointDef b3RecR_DISTANCEJOINTDEF( b3RecReader* rdr );
b3FilterJointDef b3RecR_FILTERJOINTDEF( b3RecReader* rdr );
b3MotorJointDef b3RecR_MOTORJOINTDEF( b3RecReader* rdr );
b3MassData b3RecR_MASSDATA( b3RecReader* rdr );
b3MotionLocks b3RecR_LOCKS( b3RecReader* rdr );
const char* b3RecR_STR( b3RecReader* rdr );
b3ExplosionDef b3RecR_EXPLOSIONDEF( b3RecReader* rdr );
b3BodyDef b3RecR_BODYDEF( b3RecReader* rdr );
b3ShapeDef b3RecR_SHAPEDEF( b3RecReader* rdr );
b3ParallelJointDef b3RecR_PARALLELJOINTDEF( b3RecReader* rdr );
b3DistanceJointDef b3RecR_DISTANCEJOINTDEF( b3RecReader* rdr );
b3FilterJointDef b3RecR_FILTERJOINTDEF( b3RecReader* rdr );
b3MotorJointDef b3RecR_MOTORJOINTDEF( b3RecReader* rdr );
b3PrismaticJointDef b3RecR_PRISMATICJOINTDEF( b3RecReader* rdr );
b3RevoluteJointDef b3RecR_REVOLUTEJOINTDEF( b3RecReader* rdr );
b3RevoluteJointDef b3RecR_REVOLUTEJOINTDEF( b3RecReader* rdr );
b3SphericalJointDef b3RecR_SPHERICALJOINTDEF( b3RecReader* rdr );
b3WeldJointDef b3RecR_WELDJOINTDEF( b3RecReader* rdr );
b3WheelJointDef b3RecR_WHEELJOINTDEF( b3RecReader* rdr );
b3QueryFilter b3RecR_QUERYFILTER( b3RecReader* rdr );
b3ShapeProxy b3RecR_SHAPEPROXY( b3RecReader* rdr );
b3TreeStats b3RecR_TREESTATS( b3RecReader* rdr );
b3RayResult b3RecR_RAYRESULT( b3RecReader* rdr );
b3PlaneResult b3RecR_PLANERESULT( b3RecReader* rdr );
b3WeldJointDef b3RecR_WELDJOINTDEF( b3RecReader* rdr );
b3WheelJointDef b3RecR_WHEELJOINTDEF( b3RecReader* rdr );
b3QueryFilter b3RecR_QUERYFILTER( b3RecReader* rdr );
b3ShapeProxy b3RecR_SHAPEPROXY( b3RecReader* rdr );
b3TreeStats b3RecR_TREESTATS( b3RecReader* rdr );
b3RayResult b3RecR_RAYRESULT( b3RecReader* rdr );
b3PlaneResult b3RecR_PLANERESULT( b3RecReader* rdr );
// Grow the reader's hit scratch to at least n entries, preserving contents. n is bounded by the
// file size since every recorded hit consumes at least one byte.

View file

@ -191,20 +191,6 @@ static b3Shape* b3CreateShapeInternal( b3World* world, b3Body* body, b3WorldTran
shape->fatAABB = (b3AABB){ b3Vec3_zero, b3Vec3_zero };
shape->generation += 1;
if ( def->name )
{
#if defined( _MSC_VER )
strncpy_s( shape->name, B3_NAME_LENGTH + 1, def->name, B3_NAME_LENGTH );
#else
strncpy( shape->name, def->name, B3_NAME_LENGTH );
shape->name[B3_NAME_LENGTH] = 0;
#endif
}
else
{
memset( shape->name, 0, sizeof( shape->name ) );
}
if ( shape->type == b3_compoundShape )
{
// Own a copy of the compound materials so every shape frees its array the same way. Compounds
@ -381,7 +367,22 @@ b3ShapeId b3CreateTransformedHullShape( b3BodyId bodyId, const b3ShapeDef* def,
b3Vec3 scale )
{
B3_VALIDATE( b3IsValidHull( hull ) );
return b3CreateShape( bodyId, def, hull, b3_hullShape, transform, scale, true );
b3ShapeId shapeId = b3CreateShape( bodyId, def, hull, b3_hullShape, transform, scale, true );
if ( shapeId.index1 != 0 )
{
b3World* world = b3GetUnlockedWorld( bodyId.world0 );
if ( world != NULL && world->recording != NULL )
{
// The transform and scale are baked into fresh hull data at create time. Record the baked hull
// as a plain hull shape so replay rebuilds identical geometry with no rebake, and the keyframe
// registry, which interns the live baked hull, stays seeded.
b3Shape* shape = b3Array_Get( world->shapes, shapeId.index1 - 1 );
uint32_t geometryId = b3RecInternHull( world->recording, shape->hull );
b3RecArgs_CreateHullShape createArgs = { bodyId, *def, geometryId };
b3RecWriteRet_CreateHullShape( world->recording, &createArgs, shapeId );
}
}
return shapeId;
}
b3ShapeId b3CreateMeshShape( b3BodyId bodyId, const b3ShapeDef* def, const b3MeshData* mesh, b3Vec3 scale )
@ -1134,33 +1135,6 @@ bool b3Shape_IsSensor( b3ShapeId shapeId )
return shape->sensorIndex != B3_NULL_INDEX;
}
void b3Shape_SetName( b3ShapeId shapeId, const char* name )
{
b3World* world = b3GetWorld( shapeId.world0 );
b3Shape* shape = b3GetShape( world, shapeId );
if ( name )
{
#if defined( _MSC_VER )
strncpy_s( shape->name, B3_NAME_LENGTH + 1, name, B3_NAME_LENGTH );
#else
strncpy( shape->name, name, B3_NAME_LENGTH );
shape->name[B3_NAME_LENGTH] = 0;
#endif
}
else
{
memset( shape->name, 0, sizeof( shape->name ) );
}
}
const char* b3Shape_GetName( b3ShapeId shapeId )
{
b3World* world = b3GetWorld( shapeId.world0 );
b3Shape* shape = b3GetShape( world, shapeId );
return shape->name;
}
// todo no tests
b3WorldCastOutput b3Shape_RayCast( b3ShapeId shapeId, b3Pos origin, b3Vec3 translation )
{
@ -2050,13 +2024,17 @@ typedef struct b3MeshImpactContext
b3Vec3 meshLocalCentroidB1, meshLocalCentroidB2;
float fallbackRadius;
bool isSensor;
int visitCount;
} b3MeshImpactContext;
static bool b3MeshTimeOfImpactFcn( b3Vec3 a, b3Vec3 b, b3Vec3 c, int triangleIndex, void* context )
{
B3_UNUSED( triangleIndex );
b3MeshImpactContext* toiContext = (b3MeshImpactContext*)context;
b3MeshImpactContext* toiContext = context;
toiContext->visitCount += 1;
// Early out for parallel movement
b3Vec3 c1 = toiContext->meshLocalCentroidB1;
@ -2257,6 +2235,8 @@ b3TOIOutput b3ShapeTimeOfImpact( b3Shape* shapeA, b3Shape* shapeB, b3Sweep* swee
// todo implement b3MeshTimeOfImpact and b3HeightFieldTimeOfImpact
// Note: assuming mesh is static
uint64_t ticks = b3GetTicks();
b3MeshImpactContext context = { 0 };
context.toiInput.sweepA = *sweepA;
context.toiInput.proxyA.count = 3;
@ -2284,11 +2264,6 @@ b3TOIOutput b3ShapeTimeOfImpact( b3Shape* shapeA, b3Shape* shapeB, b3Sweep* swee
.q = sweepB->q2,
};
// b3Vec3 centroidB1 = b3InvRotateVector( xfA.q, b3RotateVector( sweepB->q1, localCentroidB - sweepB->localCenter ) +
// ( sweepB->c1 - xfA.p ) );
// b3Vec3 centroidB2 = b3InvRotateVector( xfA.q, b3RotateVector( sweepB->q2, localCentroidB - sweepB->localCenter ) +
// ( sweepB->c2 - xfA.p ) );
context.meshLocalCentroidB1 = b3InvTransformPoint( xfA, b3TransformPoint( xfB1, localCentroidB ) );
context.meshLocalCentroidB2 = b3InvTransformPoint( xfA, b3TransformPoint( xfB2, localCentroidB ) );
@ -2311,6 +2286,12 @@ b3TOIOutput b3ShapeTimeOfImpact( b3Shape* shapeA, b3Shape* shapeB, b3Sweep* swee
b3QueryHeightField( shapeA->heightField, localBounds, b3MeshTimeOfImpactFcn, &context );
}
float ms = b3GetMilliseconds( ticks );
if ( ms > 1000.0f * b3GetStallThreshold() )
{
b3Log( "CCD stall: visited %d triangles", context.visitCount );
}
return context.toiOutput;
}
@ -2396,11 +2377,6 @@ void b3DumpShape( b3World* world, int shapeIndex )
b3Dump( " b3ShapeDef sd = b3DefaultShapeDef();\n" );
if ( shape->name[0] != 0 )
{
b3Dump( " sd.name = \"%s\";\n", shape->name );
}
// printf("%" PRIx64 ";\n", t);
b3Dump( " sd.density = %.9g;\n", shape->density );
b3Dump( " sd.isSensor = bool(%d);\n", shape->sensorIndex != B3_NULL_INDEX );

View file

@ -36,7 +36,6 @@ typedef struct b3Shape
b3Filter filter;
void* userData;
void* userShape;
char name[B3_NAME_LENGTH + 1];
uint16_t generation;
bool enableSensorEvents;

View file

@ -326,6 +326,8 @@ typedef struct b3ContinuousContext
float sensorFractions[B2_MAX_CONTINUOUS_SENSOR_HITS];
int sensorCount;
int visitCount;
int distanceIterations;
int pushBackIterations;
int rootIterations;
@ -337,7 +339,9 @@ static bool b3ContinuousQueryCallback( int proxyId, uint64_t userData, void* con
B3_UNUSED( proxyId );
int shapeId = (int)userData;
b3ContinuousContext* continuousContext = (b3ContinuousContext*)context;
b3ContinuousContext* continuousContext = context;
continuousContext->visitCount += 1;
b3Shape* fastShape = continuousContext->fastShape;
b3BodySim* fastBodySim = continuousContext->fastBodySim;
@ -407,6 +411,8 @@ static bool b3ContinuousQueryCallback( int proxyId, uint64_t userData, void* con
}
}
uint64_t ticks = b3GetTicks();
// todo does having a sweep on shapeA help with bullets?
b3Sweep sweepA = b3MakeRelativeSweep( bodySim, continuousContext->base );
@ -452,6 +458,12 @@ static bool b3ContinuousQueryCallback( int proxyId, uint64_t userData, void* con
}
}
float ms = b3GetMilliseconds( ticks );
if ( ms > 1000.0f * b3GetStallThreshold() )
{
b3Log( "CCD stall: duration %.1f ms for %s versus %s", ms, fastBody->name, body->name );
}
// Continue query
return true;
}
@ -461,6 +473,8 @@ static void b3SolveContinuous( b3World* world, int bodySimIndex, b3TaskContext*
{
b3TracyCZoneNC( ccd, "CCD", b3_colorDarkGoldenRod, true );
uint64_t ticks = b3GetTicks();
b3SolverSet* awakeSet = b3Array_Get( world->solverSets, b3_awakeSet );
b3BodySim* fastBodySim = b3Array_Get( awakeSet->bodySims, bodySimIndex );
B3_ASSERT( fastBodySim->flags & b3_isFast );
@ -621,6 +635,16 @@ static void b3SolveContinuous( b3World* world, int bodySimIndex, b3TaskContext*
taskContext->pushBackIterations = b3MaxInt( taskContext->pushBackIterations, context.pushBackIterations );
taskContext->rootIterations = b3MaxInt( taskContext->rootIterations, context.rootIterations );
float ms = b3GetMilliseconds( ticks );
if ( ms > 1000.0f * b3GetStallThreshold() )
{
b3Vec3 c1 = sweep.c1;
b3Vec3 c2 = sweep.c2;
int vc = context.visitCount;
b3Log( "CCD stall: duration %.1f ms and visit count %d for %s: c1 = (%g, %g, %g), c2 = (%g, %g, %g)", ms, vc,
fastBody->name, c1.x, c1.y, c1.z, c2.x, c2.y, c2.z );
}
b3TracyCZoneEnd( ccd );
}

View file

@ -52,7 +52,7 @@ b3Filter b3DefaultFilter( void )
b3QueryFilter b3DefaultQueryFilter( void )
{
b3QueryFilter filter = { B3_DEFAULT_CATEGORY_BITS, B3_DEFAULT_MASK_BITS };
b3QueryFilter filter = { B3_DEFAULT_CATEGORY_BITS, B3_DEFAULT_MASK_BITS, 0, NULL };
return filter;
}
@ -105,6 +105,11 @@ static void b3EmptyDrawSphere( b3Pos p, float radius, b3HexColor color, float al
B3_UNUSED( p, radius, color, alpha, context );
}
static void b3EmptyDrawCapsule( b3Pos p1, b3Pos p2, float radius, b3HexColor color, float alpha, void* context )
{
B3_UNUSED( p1, p2, radius, color, alpha, context );
}
static void b3EmptyDrawBounds( b3AABB aabb, b3HexColor color, void* context )
{
B3_UNUSED( aabb, color, context );
@ -130,6 +135,7 @@ b3DebugDraw b3DefaultDebugDraw( void )
draw.DrawTransformFcn = b3EmptyDrawTransform;
draw.DrawPointFcn = b3EmptyDrawPoint;
draw.DrawSphereFcn = b3EmptyDrawSphere;
draw.DrawCapsuleFcn = b3EmptyDrawCapsule;
draw.DrawBoundsFcn = b3EmptyDrawBounds;
draw.DrawBoxFcn = b3EmptyDrawBox;
draw.DrawStringFcn = b3EmptyDrawString;

View file

@ -32,10 +32,10 @@
#include <string.h>
// Snapshot image magic 'BNS3' and version
#define B3_SNAP_MAGIC 0x33534E42u
#define B3_SNAP_MAGIC 0x33534E42u
#define B3_SNAP_VERSION 1u
#define B3_SNAP_FLAG_VALIDATION 0x1u
#define B3_SNAP_FLAG_VALIDATION 0x1u
#define B3_SNAP_FLAG_DOUBLE_PRECISION 0x2u
// Layout hash over all POD-copied structs + key constants.
@ -43,8 +43,8 @@
static uint32_t b3ComputeLayoutHash( void )
{
uint32_t h = 2166136261u;
#define MIX( x ) \
h ^= (uint32_t)( x ); \
#define MIX( x ) \
h ^= (uint32_t)( x ); \
h *= 16777619u;
MIX( sizeof( b3Body ) )
MIX( sizeof( b3BodySim ) )
@ -88,9 +88,9 @@ typedef struct b3SnapHeader
typedef struct b3SnapReader
{
const uint8_t* data;
int cursor;
int size;
bool ok;
int cursor;
int size;
bool ok;
} b3SnapReader;
static void b3SnapRCheck( b3SnapReader* r, int need )
@ -158,36 +158,36 @@ static bool b3SnapCheckCount( const b3SnapReader* r, int count, int memSize, int
}
// POD array: count + raw bytes
#define b3SerPodArray( buf, arr ) \
do \
{ \
b3SnapW_I32( buf, ( arr ).count ); \
if ( ( arr ).count > 0 ) \
{ \
b3SnapW_Bytes( buf, ( arr ).data, ( arr ).count * (int)sizeof( *( arr ).data ) ); \
} \
} \
#define b3SerPodArray( buf, arr ) \
do \
{ \
b3SnapW_I32( buf, ( arr ).count ); \
if ( ( arr ).count > 0 ) \
{ \
b3SnapW_Bytes( buf, ( arr ).data, ( arr ).count * (int)sizeof( *( arr ).data ) ); \
} \
} \
while ( 0 )
#define b3DesPodArray( r, arr ) \
do \
{ \
int cnt = b3SnapR_I32( r ); \
int elemSize = (int)sizeof( *( arr ).data ); \
if ( (r)->ok && b3SnapCheckCount( r, cnt, elemSize, elemSize ) == false ) \
{ \
(r)->ok = false; \
} \
if ( (r)->ok && cnt > 0 ) \
{ \
b3Array_Resize( arr, cnt ); \
b3SnapR_Bytes( r, ( arr ).data, cnt * elemSize ); \
} \
else if ( (r)->ok ) \
{ \
( arr ).count = 0; \
} \
} \
#define b3DesPodArray( r, arr ) \
do \
{ \
int cnt = b3SnapR_I32( r ); \
int elemSize = (int)sizeof( *( arr ).data ); \
if ( ( r )->ok && b3SnapCheckCount( r, cnt, elemSize, elemSize ) == false ) \
{ \
( r )->ok = false; \
} \
if ( ( r )->ok && cnt > 0 ) \
{ \
b3Array_Resize( arr, cnt ); \
b3SnapR_Bytes( r, ( arr ).data, cnt * elemSize ); \
} \
else if ( ( r )->ok ) \
{ \
( arr ).count = 0; \
} \
} \
while ( 0 )
// Id pool: nextIndex + freeArray
@ -229,7 +229,7 @@ static void b3DesBitSet( b3SnapReader* r, b3BitSet* bs )
bs->bits = (uint64_t*)b3Alloc( blockCapacity * sizeof( uint64_t ) );
memset( bs->bits, 0, blockCapacity * sizeof( uint64_t ) );
bs->blockCapacity = blockCapacity;
bs->blockCount = blockCount;
bs->blockCount = blockCount;
if ( blockCount > 0 )
{
b3SnapR_Bytes( r, bs->bits, (int)( blockCount * sizeof( uint64_t ) ) );
@ -252,7 +252,7 @@ static void b3DesHashSet( b3SnapReader* r, b3HashSet* hs )
uint32_t cap = b3SnapR_U32( r );
uint32_t cnt = b3SnapR_U32( r );
bool valid = b3SnapCheckCount( r, (int)cap, (int)sizeof( b3SetItem ), (int)sizeof( b3SetItem ) ) &&
( cap & ( cap - 1 ) ) == 0 && cnt <= cap;
( cap & ( cap - 1 ) ) == 0 && cnt <= cap;
if ( r->ok && valid == false && ( cap != 0 || cnt != 0 ) )
{
r->ok = false;
@ -264,16 +264,16 @@ static void b3DesHashSet( b3SnapReader* r, b3HashSet* hs )
}
if ( cap > 0 )
{
hs->items = (b3SetItem*)b3Alloc( cap * sizeof( b3SetItem ) );
hs->items = (b3SetItem*)b3Alloc( cap * sizeof( b3SetItem ) );
hs->capacity = cap;
hs->count = cnt;
hs->count = cnt;
b3SnapR_Bytes( r, hs->items, (int)( cap * sizeof( b3SetItem ) ) );
}
else
{
hs->items = NULL;
hs->items = NULL;
hs->capacity = 0;
hs->count = 0;
hs->count = 0;
}
}
@ -296,11 +296,11 @@ static void b3DesTree( b3SnapReader* r, b3DynamicTree* tree )
{
uint64_t version;
b3SnapR_Bytes( r, &version, sizeof( uint64_t ) );
int root = b3SnapR_I32( r );
int nodeCount = b3SnapR_I32( r );
int root = b3SnapR_I32( r );
int nodeCount = b3SnapR_I32( r );
int nodeCapacity = b3SnapR_I32( r );
int freeList = b3SnapR_I32( r );
int proxyCount = b3SnapR_I32( r );
int freeList = b3SnapR_I32( r );
int proxyCount = b3SnapR_I32( r );
if ( r->ok && b3SnapCheckCount( r, nodeCapacity, (int)sizeof( b3TreeNode ), (int)sizeof( b3TreeNode ) ) == false )
{
@ -309,16 +309,16 @@ static void b3DesTree( b3SnapReader* r, b3DynamicTree* tree )
// Free existing allocation including any rebuild scratch
b3Free( tree->nodes, tree->nodeCapacity * (int)sizeof( b3TreeNode ) );
b3Free( tree->leafIndices, tree->rebuildCapacity * (int)sizeof( int ) );
b3Free( tree->leafBoxes, tree->rebuildCapacity * (int)sizeof( b3AABB ) );
b3Free( tree->leafCenters, tree->rebuildCapacity * (int)sizeof( b3Vec3 ) );
b3Free( tree->binIndices, tree->rebuildCapacity * (int)sizeof( int ) );
tree->nodes = NULL;
tree->leafIndices = NULL;
tree->leafBoxes = NULL;
tree->leafCenters = NULL;
tree->binIndices = NULL;
tree->nodeCapacity = 0;
b3Free( tree->leafIndices, tree->rebuildCapacity * (int)sizeof( int ) );
b3Free( tree->leafBoxes, tree->rebuildCapacity * (int)sizeof( b3AABB ) );
b3Free( tree->leafCenters, tree->rebuildCapacity * (int)sizeof( b3Vec3 ) );
b3Free( tree->binIndices, tree->rebuildCapacity * (int)sizeof( int ) );
tree->nodes = NULL;
tree->leafIndices = NULL;
tree->leafBoxes = NULL;
tree->leafCenters = NULL;
tree->binIndices = NULL;
tree->nodeCapacity = 0;
tree->rebuildCapacity = 0;
if ( !r->ok )
@ -326,11 +326,11 @@ static void b3DesTree( b3SnapReader* r, b3DynamicTree* tree )
return;
}
tree->version = version;
tree->root = root;
tree->nodeCount = nodeCount;
tree->version = version;
tree->root = root;
tree->nodeCount = nodeCount;
tree->nodeCapacity = nodeCapacity;
tree->freeList = freeList;
tree->freeList = freeList;
tree->proxyCount = proxyCount;
if ( nodeCapacity > 0 )
@ -389,50 +389,50 @@ static void b3DesGraphColor( b3SnapReader* r, b3GraphColor* color, bool isOverfl
// World simulation scalars (never host/callback/worker state)
static void b3SerWorldConfig( b3RecBuffer* buf, const b3World* world )
{
b3SnapW_Bytes( buf, &world->gravity, sizeof( b3Vec3 ) );
b3SnapW_Bytes( buf, &world->hitEventThreshold, sizeof( float ) );
b3SnapW_Bytes( buf, &world->restitutionThreshold, sizeof( float ) );
b3SnapW_Bytes( buf, &world->maxLinearSpeed, sizeof( float ) );
b3SnapW_Bytes( buf, &world->contactSpeed, sizeof( float ) );
b3SnapW_Bytes( buf, &world->contactHertz, sizeof( float ) );
b3SnapW_Bytes( buf, &world->contactDampingRatio, sizeof( float ) );
b3SnapW_Bytes( buf, &world->gravity, sizeof( b3Vec3 ) );
b3SnapW_Bytes( buf, &world->hitEventThreshold, sizeof( float ) );
b3SnapW_Bytes( buf, &world->restitutionThreshold, sizeof( float ) );
b3SnapW_Bytes( buf, &world->maxLinearSpeed, sizeof( float ) );
b3SnapW_Bytes( buf, &world->contactSpeed, sizeof( float ) );
b3SnapW_Bytes( buf, &world->contactHertz, sizeof( float ) );
b3SnapW_Bytes( buf, &world->contactDampingRatio, sizeof( float ) );
b3SnapW_Bytes( buf, &world->contactRecycleDistance, sizeof( float ) );
b3SnapW_Bytes( buf, &world->stepIndex, sizeof( uint64_t ) );
b3SnapW_Bytes( buf, &world->stepIndex, sizeof( uint64_t ) );
b3SnapW_I32( buf, world->splitIslandId );
b3SnapW_Bytes( buf, &world->inv_h, sizeof( float ) );
b3SnapW_Bytes( buf, &world->inv_dt, sizeof( float ) );
b3SnapW_Bytes( buf, &world->inv_h, sizeof( float ) );
b3SnapW_Bytes( buf, &world->inv_dt, sizeof( float ) );
b3SnapW_I32( buf, world->endEventArrayIndex );
b3SnapW_Bytes( buf, &world->maxCapacity, sizeof( b3Capacity ) );
b3SnapW_Bytes( buf, &world->maxCapacity, sizeof( b3Capacity ) );
uint8_t flags = 0;
flags |= world->enableSleep ? 0x01u : 0u;
flags |= world->enableWarmStarting ? 0x02u : 0u;
flags |= world->enableContinuous ? 0x04u : 0u;
flags |= world->enableSpeculative ? 0x08u : 0u;
flags |= world->enableSleep ? 0x01u : 0u;
flags |= world->enableWarmStarting ? 0x02u : 0u;
flags |= world->enableContinuous ? 0x04u : 0u;
flags |= world->enableSpeculative ? 0x08u : 0u;
b3RecBufAppend( buf, &flags, 1 );
}
static void b3DesWorldConfig( b3SnapReader* r, b3World* world )
{
b3SnapR_Bytes( r, &world->gravity, sizeof( b3Vec3 ) );
b3SnapR_Bytes( r, &world->hitEventThreshold, sizeof( float ) );
b3SnapR_Bytes( r, &world->restitutionThreshold, sizeof( float ) );
b3SnapR_Bytes( r, &world->maxLinearSpeed, sizeof( float ) );
b3SnapR_Bytes( r, &world->contactSpeed, sizeof( float ) );
b3SnapR_Bytes( r, &world->contactHertz, sizeof( float ) );
b3SnapR_Bytes( r, &world->contactDampingRatio, sizeof( float ) );
b3SnapR_Bytes( r, &world->gravity, sizeof( b3Vec3 ) );
b3SnapR_Bytes( r, &world->hitEventThreshold, sizeof( float ) );
b3SnapR_Bytes( r, &world->restitutionThreshold, sizeof( float ) );
b3SnapR_Bytes( r, &world->maxLinearSpeed, sizeof( float ) );
b3SnapR_Bytes( r, &world->contactSpeed, sizeof( float ) );
b3SnapR_Bytes( r, &world->contactHertz, sizeof( float ) );
b3SnapR_Bytes( r, &world->contactDampingRatio, sizeof( float ) );
b3SnapR_Bytes( r, &world->contactRecycleDistance, sizeof( float ) );
b3SnapR_Bytes( r, &world->stepIndex, sizeof( uint64_t ) );
b3SnapR_Bytes( r, &world->stepIndex, sizeof( uint64_t ) );
world->splitIslandId = b3SnapR_I32( r );
b3SnapR_Bytes( r, &world->inv_h, sizeof( float ) );
b3SnapR_Bytes( r, &world->inv_dt, sizeof( float ) );
b3SnapR_Bytes( r, &world->inv_h, sizeof( float ) );
b3SnapR_Bytes( r, &world->inv_dt, sizeof( float ) );
world->endEventArrayIndex = b3SnapR_I32( r );
b3SnapR_Bytes( r, &world->maxCapacity, sizeof( b3Capacity ) );
b3SnapR_Bytes( r, &world->maxCapacity, sizeof( b3Capacity ) );
uint8_t flags = 0;
b3SnapR_Bytes( r, &flags, 1 );
world->enableSleep = ( flags & 0x01u ) != 0;
world->enableSleep = ( flags & 0x01u ) != 0;
world->enableWarmStarting = ( flags & 0x02u ) != 0;
world->enableContinuous = ( flags & 0x04u ) != 0;
world->enableSpeculative = ( flags & 0x08u ) != 0;
world->enableContinuous = ( flags & 0x04u ) != 0;
world->enableSpeculative = ( flags & 0x08u ) != 0;
}
// Shapes carry pointer fields: materials, userData, userShape, and the geometry union.
@ -447,12 +447,12 @@ static void b3SerShapes( b3RecBuffer* buf, b3World* world, b3Recording* rec )
for ( int i = 0; i < count; ++i )
{
b3Shape shape = world->shapes.data[i];
bool isLive = ( shape.id == i );
bool isLive = ( shape.id == i );
// Null out pointer fields before writing the raw struct
shape.materials = NULL;
shape.userData = NULL;
shape.userShape = NULL;
shape.materials = NULL;
shape.userData = NULL;
shape.userShape = NULL;
// Zero the geometry union so free-slot images have deterministic bytes
if ( !isLive )
{
@ -463,7 +463,7 @@ static void b3SerShapes( b3RecBuffer* buf, b3World* world, b3Recording* rec )
if ( !isLive )
{
// Free slot: no materials or geometry
b3SnapW_I32( buf, 0 ); // materialCount
b3SnapW_I32( buf, 0 ); // materialCount
b3SnapW_I32( buf, -1 ); // geometry kind sentinel
continue;
}
@ -549,18 +549,18 @@ static void b3DesShapes( b3SnapReader* r, b3World* world, b3RecReader* rdr )
// GPU mesh on each seek, which the host (a 3D renderer) would otherwise pay for. Handles that are
// not reclaimed below belong to shapes that are gone or were replaced, and get released so the host
// pool does not leak across seeks. Box2D has no such handles, so its restore skips all of this.
int oldShapeCount = world->shapes.count;
void** savedUserShape = NULL;
int oldShapeCount = world->shapes.count;
void** savedUserShape = NULL;
uint16_t* savedGeneration = NULL;
if ( oldShapeCount > 0 )
{
savedUserShape = (void**)b3Alloc( (size_t)oldShapeCount * sizeof( void* ) );
savedUserShape = (void**)b3Alloc( (size_t)oldShapeCount * sizeof( void* ) );
savedGeneration = (uint16_t*)b3Alloc( (size_t)oldShapeCount * sizeof( uint16_t ) );
for ( int i = 0; i < oldShapeCount; ++i )
{
b3Shape* old = world->shapes.data + i;
bool oldLive = ( old->id == i );
savedUserShape[i] = oldLive ? old->userShape : NULL;
b3Shape* old = world->shapes.data + i;
bool oldLive = ( old->id == i );
savedUserShape[i] = oldLive ? old->userShape : NULL;
savedGeneration[i] = old->generation;
}
}
@ -574,7 +574,7 @@ static void b3DesShapes( b3SnapReader* r, b3World* world, b3RecReader* rdr )
b3SnapR_Bytes( r, dst, sizeof( b3Shape ) );
// Pointer fields were written as NULL; set them cleanly
dst->materials = NULL;
dst->userData = NULL;
dst->userData = NULL;
dst->userShape = NULL;
memset( &dst->capsule, 0, sizeof( dst->capsule ) );
@ -583,9 +583,9 @@ static void b3DesShapes( b3SnapReader* r, b3World* world, b3RecReader* rdr )
// Carry the renderer handle over when the same shape still occupies this slot. Consumed
// handles are nulled so the teardown sweep only releases the ones that vanished.
if ( isLive && i < oldShapeCount && savedUserShape != NULL && savedUserShape[i] != NULL &&
savedGeneration[i] == dst->generation )
savedGeneration[i] == dst->generation )
{
dst->userShape = savedUserShape[i];
dst->userShape = savedUserShape[i];
savedUserShape[i] = NULL;
}
@ -615,7 +615,7 @@ static void b3DesShapes( b3SnapReader* r, b3World* world, b3RecReader* rdr )
break;
}
dst->materialCount = matCount;
dst->materials = (b3SurfaceMaterial*)b3Alloc( (size_t)matCount * sizeof( b3SurfaceMaterial ) );
dst->materials = (b3SurfaceMaterial*)b3Alloc( (size_t)matCount * sizeof( b3SurfaceMaterial ) );
b3SnapR_Bytes( r, dst->materials, matCount * (int)sizeof( b3SurfaceMaterial ) );
}
else
@ -667,7 +667,7 @@ static void b3DesShapes( b3SnapReader* r, b3World* world, b3RecReader* rdr )
}
b3RegistrySlot* slot = rdr->slots + gid;
// Mesh is a self-contained blob used by reference; point straight at the pristine bytes.
dst->mesh.data = (const b3MeshData*)slot->bytes;
dst->mesh.data = (const b3MeshData*)slot->bytes;
dst->mesh.scale = scale;
break;
}
@ -746,17 +746,17 @@ static void b3SerContacts( b3RecBuffer* buf, b3World* world )
for ( int i = 0; i < count; ++i )
{
const b3Contact* c = world->contacts.data + i;
bool isLive = ( c->contactId == i );
bool isLive = ( c->contactId == i );
// Write raw struct with pointer fields zeroed
b3Contact copy = *c;
copy.manifolds = NULL;
copy.bodySimIndexA = B3_NULL_INDEX;
copy.bodySimIndexB = B3_NULL_INDEX;
copy.manifolds = NULL;
copy.bodySimIndexA = B3_NULL_INDEX;
copy.bodySimIndexB = B3_NULL_INDEX;
if ( copy.flags & b3_simMeshContact )
{
copy.meshContact.triangleCache.data = NULL;
copy.meshContact.triangleCache.count = 0;
copy.meshContact.triangleCache.data = NULL;
copy.meshContact.triangleCache.count = 0;
copy.meshContact.triangleCache.capacity = 0;
}
b3SnapW_Bytes( buf, &copy, sizeof( b3Contact ) );
@ -783,7 +783,7 @@ static void b3SerContacts( b3RecBuffer* buf, b3World* world )
if ( c->meshContact.triangleCache.count > 0 )
{
b3SnapW_Bytes( buf, c->meshContact.triangleCache.data,
c->meshContact.triangleCache.count * (int)sizeof( b3TriangleCache ) );
c->meshContact.triangleCache.count * (int)sizeof( b3TriangleCache ) );
}
}
}
@ -808,13 +808,13 @@ static void b3DesContacts( b3SnapReader* r, b3World* world )
{
b3Contact* dst = world->contacts.data + i;
b3SnapR_Bytes( r, dst, sizeof( b3Contact ) );
dst->manifolds = NULL;
dst->manifolds = NULL;
dst->bodySimIndexA = B3_NULL_INDEX;
dst->bodySimIndexB = B3_NULL_INDEX;
if ( dst->flags & b3_simMeshContact )
{
dst->meshContact.triangleCache.data = NULL;
dst->meshContact.triangleCache.count = 0;
dst->meshContact.triangleCache.data = NULL;
dst->meshContact.triangleCache.count = 0;
dst->meshContact.triangleCache.capacity = 0;
}
@ -834,13 +834,13 @@ static void b3DesContacts( b3SnapReader* r, b3World* world )
r->ok = false;
break;
}
dst->manifolds = b3AllocateManifolds( world, manifoldCount );
dst->manifolds = b3AllocateManifolds( world, manifoldCount );
dst->manifoldCount = manifoldCount;
b3SnapR_Bytes( r, dst->manifolds, manifoldCount * (int)sizeof( b3Manifold ) );
}
else
{
dst->manifolds = NULL;
dst->manifolds = NULL;
dst->manifoldCount = 0;
}
@ -883,7 +883,7 @@ static void b3FreeLiveSimElements( b3World* world )
if ( s->materials != NULL )
{
b3Free( s->materials, (size_t)s->materialCount * sizeof( b3SurfaceMaterial ) );
s->materials = NULL;
s->materials = NULL;
s->materialCount = 0;
}
// Hull is ref-counted in the world DB; release before overwrite so re-adding is ref-neutral.
@ -904,7 +904,7 @@ static void b3FreeLiveSimElements( b3World* world )
if ( c->manifolds != NULL )
{
b3FreeManifolds( world, c->manifolds, c->manifoldCount );
c->manifolds = NULL;
c->manifolds = NULL;
c->manifoldCount = 0;
}
if ( c->flags & b3_simMeshContact )
@ -939,10 +939,10 @@ int b3SerializeWorld( b3World* world, b3RecBuffer* buf, b3Recording* rec )
// Snapshot header
b3SnapHeader hdr;
hdr.magic = B3_SNAP_MAGIC;
hdr.version = B3_SNAP_VERSION;
hdr.magic = B3_SNAP_MAGIC;
hdr.version = B3_SNAP_VERSION;
hdr.layoutHash = b3ComputeLayoutHash();
hdr.flags = B3_ENABLE_VALIDATION ? B3_SNAP_FLAG_VALIDATION : 0u;
hdr.flags = B3_ENABLE_VALIDATION ? B3_SNAP_FLAG_VALIDATION : 0u;
#if defined( BOX3D_DOUBLE_PRECISION )
hdr.flags |= B3_SNAP_FLAG_DOUBLE_PRECISION;
#endif
@ -973,7 +973,7 @@ int b3SerializeWorld( b3World* world, b3RecBuffer* buf, b3Recording* rec )
b3SnapW_I32( buf, bodyCount );
for ( int i = 0; i < bodyCount; ++i )
{
b3Body elem = world->bodies.data[i];
b3Body elem = world->bodies.data[i];
elem.userData = NULL;
b3SnapW_Bytes( buf, &elem, sizeof( b3Body ) );
}
@ -991,7 +991,7 @@ int b3SerializeWorld( b3World* world, b3RecBuffer* buf, b3Recording* rec )
b3SnapW_I32( buf, jointCount );
for ( int i = 0; i < jointCount; ++i )
{
b3Joint elem = world->joints.data[i];
b3Joint elem = world->joints.data[i];
elem.userData = NULL;
b3SnapW_Bytes( buf, &elem, sizeof( b3Joint ) );
}
@ -1085,10 +1085,10 @@ bool b3DeserializeIntoShell( const uint8_t* data, int size, b3World* world, b3Re
b3SnapReader readerStorage;
b3SnapReader* r = &readerStorage;
r->data = data;
r->data = data;
r->cursor = (int)sizeof( b3SnapHeader );
r->size = size;
r->ok = true;
r->size = size;
r->ok = true;
// Free existing per-object heap before overwriting
b3FreeLiveSimElements( world );
@ -1240,9 +1240,9 @@ bool b3DeserializeIntoShell( const uint8_t* data, int size, b3World* world, b3Re
for ( int i = 0; i < islandCount && r->ok; ++i )
{
b3Island* island = world->islands.data + i;
island->setIndex = b3SnapR_I32( r );
island->localIndex = b3SnapR_I32( r );
island->islandId = b3SnapR_I32( r );
island->setIndex = b3SnapR_I32( r );
island->localIndex = b3SnapR_I32( r );
island->islandId = b3SnapR_I32( r );
island->constraintRemoveCount = b3SnapR_I32( r );
b3Array_Create( island->bodies );
b3Array_Create( island->contacts );