Optimize Broad-Phase (#159)

Broad-phase optimization ported from Box2D.
This commit is contained in:
Erin Catto 2026-09-16 22:28:39 -07:00 • committed by GitHub
commit f555ee4208
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
51 changed files with 3802 additions and 1830 deletions

View file

@ -31,6 +31,7 @@ set(BOX3D_SOURCE_FILES
distance.c
distance_joint.c
dynamic_tree.c
dynamic_tree.h
height_field.c
hull.c
hull.h

View file

@ -375,6 +375,12 @@ void b3DestroyBody( b3BodyId bodyId )
{
b3Shape* shape = b3Array_Get( world->shapes, shapeId );
if ( shape->type == b3_compoundShape )
{
B3_ASSERT( world->compoundShapeCount > 0 );
world->compoundShapeCount -= 1;
}
if ( shape->sensorIndex != B3_NULL_INDEX )
{
b3DestroySensor( world, shape );

File diff suppressed because it is too large Load diff

View file

@ -3,16 +3,13 @@
#pragma once
#include "bitset.h"
#include "container.h"
#include "dynamic_tree.h"
#include "table.h"
#include "box3d/collision.h"
#include "box3d/types.h"
typedef struct b3Shape b3Shape;
typedef struct b3MovePair b3MovePair;
typedef struct b3MoveResult b3MoveResult;
typedef struct b3Stack b3Stack;
typedef struct b3World b3World;
@ -26,20 +23,11 @@ typedef struct b3World b3World;
/// It is up to the client to consume the new pairs and to track subsequent overlap.
typedef struct b3BroadPhase
{
// One tree for each body type.
b3DynamicTree trees[b3_bodyTypeCount];
// Per body-type bit sets indexed by proxyId, marking proxies moved this step.
// Paired with moveArray which preserves deterministic insertion order for pair queries.
b3BitSet movedProxies[b3_bodyTypeCount];
b3Array( int ) moveArray;
// These are the results from the pair query and are used to create new contacts
// in deterministic order.
// todo these could be in the step context
b3MoveResult* moveResults;
b3MovePair* movePairs;
int movePairCapacity;
b3AtomicInt movePairIndex;
// The moved siblings gathered from the dynamic body tree.
int* movedSiblings;
// Tracks shape pairs that have a b3Contact
// todo pairSet can grow quite large on the first time step and remain large
@ -54,7 +42,6 @@ int b3BroadPhase_CreateProxy( b3BroadPhase* bp, b3BodyType proxyType, b3AABB aab
void b3BroadPhase_DestroyProxy( b3BroadPhase* bp, int proxyKey );
void b3BroadPhase_MoveProxy( b3BroadPhase* bp, int proxyKey, b3AABB aabb );
void b3BroadPhase_EnlargeProxy( b3BroadPhase* bp, int proxyKey, b3AABB aabb );
int b3BroadPhase_GetShapeIndex( b3BroadPhase* bp, int proxyKey );
@ -62,18 +49,18 @@ void b3UpdateBroadPhasePairs( b3World* world );
bool b3BroadPhase_TestOverlap( const b3BroadPhase* bp, int proxyKeyA, int proxyKeyB );
void b3ValidateBroadPhase( const b3BroadPhase* bp );
void b3ValidateNoEnlarged( const b3BroadPhase* bp );
void b3ValidateNoMoved( const b3BroadPhase* bp );
// This is what triggers new contact pairs to be created
// Warning: this must be called in deterministic order
static inline void b3BufferMove( b3BroadPhase* bp, int queryProxy )
static inline void b3BroadPhase_MarkProxyMovedSerial( b3BroadPhase* bp, int proxyKey )
{
b3BodyType proxyType = B3_PROXY_TYPE( queryProxy );
int proxyId = B3_PROXY_ID( queryProxy );
b3BitSet* set = &bp->movedProxies[proxyType];
if ( b3GetBit( set, proxyId ) == false )
{
b3SetBitGrow( set, proxyId );
b3Array_Push( bp->moveArray, queryProxy );
}
b3BodyType proxyType = B3_PROXY_TYPE( proxyKey );
int proxyId = B3_PROXY_ID( proxyKey );
b3DynamicTree_MarkProxyMovedSerial( bp->trees + proxyType, proxyId );
}
static inline void b3BroadPhase_MarkProxyMoved( b3BroadPhase* bp, int proxyKey, b3AABB aabb )
{
b3BodyType proxyType = B3_PROXY_TYPE( proxyKey );
int proxyId = B3_PROXY_ID( proxyKey );
b3DynamicTree_MarkProxyMoved( bp->trees + proxyType, proxyId, aabb );
}

View file

@ -3,6 +3,7 @@
#include "compound.h"
#include "dynamic_tree.h"
#include "hull.h"
#include "math_internal.h"
#include "shape.h"
@ -52,6 +53,16 @@ static inline b3TreeNode* b3GetCompoundNodes( b3CompoundData* compound )
return (b3TreeNode*)( (intptr_t)compound + compound->nodeOffset );
}
static inline b3TreeProxy* b3GetCompoundProxies( b3CompoundData* compound )
{
if ( compound->proxyOffset == 0 )
{
return NULL;
}
return (b3TreeProxy*)( (intptr_t)compound + compound->proxyOffset );
}
const b3SurfaceMaterial* b3GetCompoundMaterials( const b3CompoundData* compound )
{
if ( compound->materialOffset == 0 )
@ -274,13 +285,13 @@ b3CompoundData* b3CreateCompound( const b3CompoundDef* def )
// Instances
int capsuleCount = def->capsuleCount;
b3CompoundCapsule* capsuleInstances = b3AllocZeroed( capsuleCount * sizeof( b3CompoundCapsule ) );
b3CompoundCapsule* capsuleInstances = b3AllocZero( capsuleCount * sizeof( b3CompoundCapsule ) );
int hullCount = def->hullCount;
b3HullInstance* hullInstances = b3AllocZeroed( hullCount * sizeof( b3HullInstance ) );
b3HullInstance* hullInstances = b3AllocZero( hullCount * sizeof( b3HullInstance ) );
int meshCount = def->meshCount;
b3MeshInstance* meshInstances = b3AllocZeroed( meshCount * sizeof( b3MeshInstance ) );
b3MeshInstance* meshInstances = b3AllocZero( meshCount * sizeof( b3MeshInstance ) );
int sphereCount = def->sphereCount;
b3CompoundSphere* sphereInstances = b3AllocZeroed( sphereCount * sizeof( b3CompoundSphere ) );
b3CompoundSphere* sphereInstances = b3AllocZero( sphereCount * sizeof( b3CompoundSphere ) );
// Determine material capacity.
int materialCapacity = convexCount;
@ -294,7 +305,7 @@ b3CompoundData* b3CreateCompound( const b3CompoundDef* def )
b3MaterialMap materialMap;
b3MaterialMap_init( &materialMap );
b3MaterialMap_reserve( &materialMap, materialCapacity );
b3SurfaceMaterial* materials = b3AllocZeroed( materialCapacity * sizeof( b3SurfaceMaterial ) );
b3SurfaceMaterial* materials = b3AllocZero( materialCapacity * sizeof( b3SurfaceMaterial ) );
int materialCount = 0;
for ( int i = 0; i < def->capsuleCount; ++i )
@ -322,7 +333,7 @@ b3CompoundData* b3CreateCompound( const b3CompoundDef* def )
}
// Hulls
b3SharedHull* sharedHulls = b3AllocZeroed( hullCount * sizeof( b3SharedHull ) );
b3SharedHull* sharedHulls = b3AllocZero( hullCount * sizeof( b3SharedHull ) );
int sharedHullCount = 0;
if ( hullCount > 0 )
@ -378,7 +389,7 @@ b3CompoundData* b3CreateCompound( const b3CompoundDef* def )
}
// Meshes
b3SharedMesh* sharedMeshes = b3AllocZeroed( meshCount * sizeof( b3SharedMesh ) );
b3SharedMesh* sharedMeshes = b3AllocZero( meshCount * sizeof( b3SharedMesh ) );
int sharedMeshCount = 0;
if ( meshCount > 0 )
@ -471,14 +482,16 @@ b3CompoundData* b3CreateCompound( const b3CompoundDef* def )
}
B3_ASSERT( materialCount <= materialCapacity );
B3_ASSERT( tree.nodeCount > 0 );
B3_ASSERT( tree.proxyCount > 0 );
b3DynamicTree_Rebuild( &tree, true );
// Tree nodes
// Tree nodes and proxies. The rebuild is dense, so only the live nodes travel.
size_t byteCount = b3AlignUp8( sizeof( b3CompoundData ) );
int nodeOffset = (int)byteCount;
byteCount += b3AlignUp8( tree.nodeCapacity * sizeof( b3TreeNode ) );
byteCount += b3AlignUp8( tree.nodeEnd * sizeof( b3TreeNode ) );
int proxyOffset = (int)byteCount;
byteCount += b3AlignUp8( tree.proxyCount * sizeof( b3TreeProxy ) );
int materialOffset = (int)byteCount;
byteCount += b3AlignUp8( materialCount * sizeof( b3SurfaceMaterial ) );
int capsuleOffset = (int)byteCount;
@ -525,17 +538,25 @@ b3CompoundData* b3CreateCompound( const b3CompoundDef* def )
compound->version = B3_COMPOUND_VERSION;
compound->byteCount = (int)byteCount;
compound->nodeOffset = nodeOffset;
compound->proxyOffset = proxyOffset;
memcpy( &compound->tree, &tree, sizeof( b3DynamicTree ) );
// todo clean up this mess
compound->tree.freeList = 0;
compound->tree.nodeCapacity = tree.nodeEnd;
compound->tree.pairFreeList = B3_NULL_INDEX;
compound->tree.proxyCapacity = tree.proxyCount;
compound->tree.proxyFreeList = B3_NULL_INDEX;
compound->tree.swapNodes = NULL;
compound->tree.leafIndices = NULL;
compound->tree.leafNodes = NULL;
compound->tree.leafBoxes = NULL;
compound->tree.leafCenters = NULL;
compound->tree.binIndices = NULL;
compound->tree.rebuildCapacity = 0;
compound->tree.nodes = NULL;
compound->tree.parents = NULL;
compound->tree.proxies = NULL;
compound->materialOffset = materialOffset;
compound->materialCount = materialCount;
compound->capsuleOffset = capsuleOffset;
@ -547,11 +568,15 @@ b3CompoundData* b3CreateCompound( const b3CompoundDef* def )
compound->sphereOffset = sphereOffset;
compound->sphereCount = sphereCount;
// Tree nodes
// Tree nodes and proxies
b3TreeNode* nodes = b3GetCompoundNodes( compound );
memcpy( nodes, tree.nodes, tree.nodeCapacity * sizeof( b3TreeNode ) );
memcpy( nodes, tree.nodes, tree.nodeEnd * sizeof( b3TreeNode ) );
compound->tree.nodes = nodes;
b3TreeProxy* proxies = b3GetCompoundProxies( compound );
memcpy( proxies, tree.proxies, tree.proxyCount * sizeof( b3TreeProxy ) );
compound->tree.proxies = proxies;
// Materials
B3_ASSERT( materialCount > 0 );
b3SurfaceMaterial* destinationMaterials = (b3SurfaceMaterial*)( (intptr_t)compound + compound->materialOffset );
@ -638,8 +663,9 @@ void b3DestroyCompound( b3CompoundData* compound )
uint8_t* b3ConvertCompoundToBytes( b3CompoundData* compound )
{
// scrub this pointer before serialization
// scrub these pointers before serialization
compound->tree.nodes = NULL;
compound->tree.proxies = NULL;
return (uint8_t*)compound;
}
@ -661,13 +687,14 @@ b3CompoundData* b3ConvertBytesToCompound( uint8_t* bytes, int byteCount )
return NULL;
}
if ( compound->nodeOffset <= 0 )
if ( compound->nodeOffset <= 0 || compound->proxyOffset <= 0 )
{
return NULL;
}
// this mutates the input bytes
compound->tree.nodes = (b3TreeNode*)( (intptr_t)compound + compound->nodeOffset );
compound->tree.proxies = (b3TreeProxy*)( (intptr_t)compound + compound->proxyOffset );
return compound;
}
@ -676,8 +703,7 @@ b3AABB b3ComputeCompoundAABB( const b3CompoundData* shape, b3Transform transform
B3_ASSERT( shape->nodeOffset > 0 );
const b3TreeNode* nodes = (const b3TreeNode*)( (intptr_t)shape + shape->nodeOffset );
int root = shape->tree.root;
b3AABB aabb = nodes[root].aabb;
b3AABB aabb = nodes[B3_ROOT_NODE].aabb;
return b3AABB_Transform( transform, aabb );
}

View file

@ -182,3 +182,4 @@ B3_INLINE int b3RemoveHelper( void* data, int* count, int index, int elementSize
#define b3Array_ByteCount( a ) ( ( a ).capacity * (int)sizeof( *( a ).data ) )
b3DeclareArrayNative( int );
b3DeclareArrayNative( uint64_t );

View file

@ -230,12 +230,19 @@ void* b3GrowAlloc( void* oldMem, int oldSize, int newSize )
return newMem;
}
void* b3GrowAllocZeroed( void* oldMem, int oldSize, int newSize )
{
void* newMem = b3GrowAlloc( oldMem, oldSize, newSize );
memset( (char*)newMem + oldSize, 0, (size_t)( newSize - oldSize ) );
return newMem;
}
int b3GetByteCount( void )
{
return b3AtomicLoadInt( &b3_byteCount );
}
void* b3AllocZeroed( size_t size )
void* b3AllocZero( size_t size )
{
void* mem = b3Alloc( size );
memset( mem, 0, size );

View file

@ -133,9 +133,13 @@ typedef struct b3AtomicU32
#define B3_FREE( M, T, N ) b3Free( M, N * sizeof( T ) );
void* b3Alloc( size_t size );
void* b3AllocZeroed( size_t size );
void* b3AllocZero( size_t size );
void b3Free( void* mem, size_t size );
void* b3GrowAlloc( void* oldMem, int oldSize, int newSize );
void* b3GrowAllocZeroed( void* oldMem, int oldSize, int newSize );
#define B3_GROW( A, N, M ) b3GrowAlloc( ( A ), (int)( ( N ) * sizeof( *( A ) ) ), (int)( ( M ) * sizeof( *( A ) ) ) )
#define B3_GROW_ZERO( A, N, M ) b3GrowAllocZeroed( ( A ), (int)( ( N ) * sizeof( *( A ) ) ), (int)( ( M ) * sizeof( *( A ) ) ) )
B3_PRINTF_FORMAT( 1, 2 )
void b3Log( const char* format, ... );

File diff suppressed because it is too large Load diff

89
src/dynamic_tree.h Normal file
View file

@ -0,0 +1,89 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
#pragma once
#include "box3d/collision.h"
#include "box3d/math_functions.h"
#define B3_TREE_STACK_SIZE 512
// Used to mark a node as being moved such that pairs need to be generated and the tree
// may need to be rebuilt. This mark comes from a few sources:
// - updating the transform and AABB in the solver from movement
// - a joint disabling collision
// - creating a proxy
// - setting the transform on a body
#define B3_MOVED_NODE ( 1u << 30 )
#define B3_LEAF_NODE ( 1u << 31 )
#define B3_NODE_INDEX_MASK ( 0xFFFFFFFFu & ~( B3_MOVED_NODE | B3_LEAF_NODE ) )
// Used to indicate empty nodes. It also passes as a leaf so that internal node
// processing will naturally skip it.
#define B3_EMPTY_NODE ( B3_NODE_INDEX_MASK | B3_LEAF_NODE )
#define B3_ROOT_NODE 0
B3_FORCE_INLINE bool b3IsLeaf( const b3TreeNode* node )
{
return ( node->flagIndex & B3_LEAF_NODE ) == B3_LEAF_NODE;
}
B3_FORCE_INLINE bool b3IsNodeMoved( const b3TreeNode* node )
{
return ( node->flagIndex & B3_MOVED_NODE ) == B3_MOVED_NODE;
}
B3_FORCE_INLINE bool b3IsEmptyNode( const b3TreeNode* node )
{
return node->flagIndex == B3_EMPTY_NODE;
}
B3_FORCE_INLINE int b3GetLeftChild( const b3TreeNode* node )
{
return (int)( node->flagIndex & B3_NODE_INDEX_MASK );
}
B3_FORCE_INLINE int b3GetProxyId( const b3TreeNode* node )
{
return (int)( node->flagIndex & B3_NODE_INDEX_MASK );
}
B3_FORCE_INLINE int b3GetRootPair( const b3TreeNode* nodes )
{
const b3TreeNode* root = nodes + B3_ROOT_NODE;
return b3IsLeaf( root ) ? B3_ROOT_NODE : b3GetLeftChild( root );
}
B3_FORCE_INLINE b3TreeNode b3MakeEmptyNode( void )
{
return B3_LITERAL( b3TreeNode ){
.aabb =
{
.lowerBound = { INFINITY, INFINITY, INFINITY },
.upperBound = { -INFINITY, -INFINITY, -INFINITY },
},
.flagIndex = B3_EMPTY_NODE,
.height = 0,
};
}
static inline bool b3HasTreeMoved( const b3DynamicTree* tree )
{
return b3IsNodeMoved( tree->nodes + B3_ROOT_NODE );
}
static inline bool b3NeedsRebuild( const b3DynamicTree* tree )
{
return b3IsNodeMoved( tree->nodes + B3_ROOT_NODE ) || tree->dfsOrdered == false;
}
int b3CreateTreeProxyInternal( b3DynamicTree* tree, b3AABB aabb, uint64_t categoryBits, uint64_t userData, bool markMoved );
void b3DynamicTree_MoveProxyInternal( b3DynamicTree* tree, int proxyId, b3AABB aabb, bool markMoved );
void b3DynamicTree_MarkProxyMovedSerial( b3DynamicTree* tree, int proxyId );
void b3DynamicTree_MarkProxyMoved( b3DynamicTree* tree, int proxyId, b3AABB aabb );
void b3DynamicTree_ClearMoved( b3DynamicTree* tree );
int b3DynamicTree_GatherMovedProxies( const b3DynamicTree* tree, int* proxyIds );
void b3DynamicTree_Refit( b3DynamicTree* tree );

View file

@ -953,7 +953,7 @@ void b3Joint_SetCollideConnected( b3JointId jointId, bool shouldCollide )
if ( shape->proxyKey != B3_NULL_INDEX )
{
b3BufferMove( &world->broadPhase, shape->proxyKey );
b3BroadPhase_MarkProxyMovedSerial( &world->broadPhase, shape->proxyKey );
}
shapeId = shape->nextShapeId;

View file

@ -78,6 +78,8 @@ void b3ParallelFor( b3World* world, b3ParallelForCallback* callback, int itemCou
// block size grows once items exceed maxBlockCount * minRange
// so the block count stays bounded and per-block sync overhead stays low.
// Benchmarking shows 32 is optimal for the convex pile benchmark and others.
// This is a lot different than Box2D because the 3D narrow phase cost
// varies a lot.
int blocksPerWorker = 32;
int maxBlockCount = blocksPerWorker * workerCount;

View file

@ -175,11 +175,11 @@ static void b3CreateWorkerContexts( b3World* world )
{
world->taskContexts.data[i].arena = b3CreateArena( 128 * 1024 );
b3Array_Reserve( world->taskContexts.data[i].sensorHits, 8 );
b3Array_Reserve( world->taskContexts.data[i].pairKeys, 64 );
world->taskContexts.data[i].contactStateBitSet = b3CreateBitSet( 1024 );
world->taskContexts.data[i].hitEventBitSet = b3CreateBitSet( 1024 );
world->taskContexts.data[i].hasHitEvents = false;
world->taskContexts.data[i].jointStateBitSet = b3CreateBitSet( 1024 );
world->taskContexts.data[i].enlargedSimBitSet = b3CreateBitSet( 256 );
world->taskContexts.data[i].awakeIslandBitSet = b3CreateBitSet( 256 );
world->taskContexts.data[i].splitIslandId = B3_NULL_INDEX;
@ -193,10 +193,10 @@ static void b3DestroyWorkerContexts( b3World* world )
{
b3DestroyArena( &world->taskContexts.data[i].arena );
b3Array_Destroy( world->taskContexts.data[i].sensorHits );
b3Array_Destroy( world->taskContexts.data[i].pairKeys );
b3DestroyBitSet( &world->taskContexts.data[i].contactStateBitSet );
b3DestroyBitSet( &world->taskContexts.data[i].hitEventBitSet );
b3DestroyBitSet( &world->taskContexts.data[i].jointStateBitSet );
b3DestroyBitSet( &world->taskContexts.data[i].enlargedSimBitSet );
b3DestroyBitSet( &world->taskContexts.data[i].awakeIslandBitSet );
b3DestroyBitSet( &world->sensorTaskContexts.data[i].eventBits );
@ -1148,7 +1148,7 @@ void b3World_Step( b3WorldId worldId, float timeStep, int subStepCount )
world->finishTaskFcn( world->userTreeTask, world->userTaskContext );
world->userTreeTask = NULL;
world->activeTaskCount -= 1;
b3ValidateNoEnlarged( &world->broadPhase );
b3ValidateNoMoved( &world->broadPhase );
}
// Update sensors
@ -2419,22 +2419,14 @@ void b3World_DumpMemoryStats( b3WorldId worldId )
int staticTreeBytes = b3DynamicTree_GetByteCount( world->broadPhase.trees + b3_staticBody );
int kinematicTreeBytes = b3DynamicTree_GetByteCount( world->broadPhase.trees + b3_kinematicBody );
int dynamicTreeBytes = b3DynamicTree_GetByteCount( world->broadPhase.trees + b3_dynamicBody );
int movedBytes = 0;
for ( int i = 0; i < b3_bodyTypeCount; ++i )
{
movedBytes += b3GetBitSetBytes( &world->broadPhase.movedProxies[i] );
}
int moveArrayBytes = b3Array_ByteCount( world->broadPhase.moveArray );
b3HashSet* pairSet = &world->broadPhase.pairSet;
int pairSetBytes = b3GetHashSetBytes( pairSet );
total += (uint64_t)staticTreeBytes + kinematicTreeBytes + dynamicTreeBytes + movedBytes + moveArrayBytes + pairSetBytes;
total += (uint64_t)staticTreeBytes + kinematicTreeBytes + dynamicTreeBytes + pairSetBytes;
b3Log( "broad-phase" );
b3Log( "static tree: %d", staticTreeBytes );
b3Log( "kinematic tree: %d", kinematicTreeBytes );
b3Log( "dynamic tree: %d", dynamicTreeBytes );
b3Log( "movedProxies: %d", movedBytes );
b3Log( "moveArray: %d", moveArrayBytes );
b3Log( "pairSet: %d (%d, %d)", pairSetBytes, pairSet->count, pairSet->capacity );
// Manifold block allocators, one per manifold point count
@ -2512,10 +2504,10 @@ void b3World_DumpMemoryStats( b3WorldId worldId )
{
b3TaskContext* taskContext = world->taskContexts.data + i;
taskContextBytes += b3Array_ByteCount( taskContext->sensorHits );
taskContextBytes += b3Array_ByteCount( taskContext->pairKeys );
taskContextBytes += b3GetBitSetBytes( &taskContext->contactStateBitSet );
taskContextBytes += b3GetBitSetBytes( &taskContext->jointStateBitSet );
taskContextBytes += b3GetBitSetBytes( &taskContext->hitEventBitSet );
taskContextBytes += b3GetBitSetBytes( &taskContext->enlargedSimBitSet );
taskContextBytes += b3GetBitSetBytes( &taskContext->awakeIslandBitSet );
}

View file

@ -76,6 +76,9 @@ typedef struct b3TaskContext
// Collect per thread sensor continuous hit events.
b3Array( b3SensorHit ) sensorHits;
// Broad-phase pairs.
b3Array( uint64_t ) pairKeys;
// These bits align with the b3ConstraintGraph::contactBlocks and signal a change in contact status
b3BitSet contactStateBitSet;
@ -88,10 +91,6 @@ typedef struct b3TaskContext
// Fast-path flag: true when this worker set at least one bit in hitEventBitSet this step.
bool hasHitEvents;
// Used to track bodies with shapes that have enlarged AABBs. This avoids having a bit array
// that is very large when there are many static shapes.
b3BitSet enlargedSimBitSet;
// Used to put islands to sleep
b3BitSet awakeIslandBitSet;
@ -177,6 +176,10 @@ typedef struct b3World
// These are sparse arrays that point into the pools above
b3Array( b3Shape ) shapes;
// Compound shapes are static only, so only the broad-phase static pass can meet one. This
// lets a world without compounds skip the shape type read in the pair batch.
int compoundShapeCount;
// Reference counted store of shared hull data keyed by content. Shapes hold a
// pointer to the hull stored in the db. Type erased to avoid leaking the verstable map
// type into this header.

View file

@ -12,6 +12,11 @@
#include <intrin.h>
#elif defined( _MSC_VER )
#include <intrin0.h>
// _MM_HINT_T0 lives here. Prefetch is a platform intrinsic, not part of the SIMD kernel
// selection, so it has to survive a BOX3D_DISABLE_SIMD build.
#if defined( _M_X64 ) || defined( _M_IX86 )
#include <xmmintrin.h>
#endif
#endif
#if defined( _MSC_VER )
@ -104,3 +109,26 @@ static inline uint32_t b3AtomicLoadU32( b3AtomicU32* a )
#error "Unsupported platform"
#endif
}
// Relaxed load on a plain word. Lets a racing reader peek before paying for a read modify write.
static inline uint32_t b3AtomicLoadU32Raw( uint32_t* a )
{
#if defined( _MSC_VER ) && !defined( __clang__ )
return (uint32_t)__iso_volatile_load32( (volatile __int32*)a );
#elif defined( __GNUC__ ) || defined( __clang__ )
return __atomic_load_n( a, __ATOMIC_RELAXED );
#else
#error "Unsupported platform"
#endif
}
static inline uint32_t b3AtomicFetchOrU32( uint32_t* a, uint32_t mask )
{
#if defined( _MSC_VER )
return (uint32_t)_InterlockedOr( (long*)a, (long)mask );
#elif defined( __GNUC__ ) || defined( __clang__ )
return __atomic_fetch_or( a, mask, __ATOMIC_SEQ_CST );
#else
#error "Unsupported platform"
#endif
}

View file

@ -51,8 +51,8 @@ typedef struct b3World b3World;
#define B3_REC_VERSION_MAJOR 6
// Minor tracks op-stream additions that keep the 48 byte header shape.
// Minor version 4 added b3Shape_SetMeshMaterial, b3Shape_SetHull, b3Shape_SetMesh
#define B3_REC_VERSION_MINOR 4
// Minor version 6 moved the broad phase to the tree against tree pair traversal
#define B3_REC_VERSION_MINOR 6
// File header, fixed 48 bytes. Contains the registry locator so the player
// can load geometry before replaying any ops.

View file

@ -192,6 +192,8 @@ static b3Shape* b3CreateShapeInternal( b3World* world, b3Body* body, b3WorldTran
if ( shape->type == b3_compoundShape )
{
world->compoundShapeCount += 1;
// Own a copy of the compound materials so every shape frees its array the same way. Compounds
// are few, so the copy is cheap and avoids aliasing the geometry blob.
int materialCount = shape->compound->materialCount;
@ -481,6 +483,12 @@ static void b3DestroyShapeInternal( b3World* world, b3Shape* shape, b3Body* body
{
int shapeId = shape->id;
if ( shape->type == b3_compoundShape )
{
B3_ASSERT( world->compoundShapeCount > 0 );
world->compoundShapeCount -= 1;
}
// Remove the shape from the body's doubly linked list.
if ( shape->prevShapeId != B3_NULL_INDEX )
{

View file

@ -19,7 +19,7 @@ typedef enum b3ShapeFlags
b3_enableCustomFiltering = 0x04,
b3_enableHitEvents = 0x08,
b3_enablePreSolveEvents = 0x10,
b3_enlargedAABB = 0x20,
// 0x20 is free, it was the enlarged AABB flag before the broad-phase marked the tree
b3_enableSpeculative = 0x40,
} b3ShapeFlags;

View file

@ -5,6 +5,9 @@
#include "core.h"
#include "box3d/math_functions.h"
#include "box3d/types.h"
#include <stdbool.h>
#if defined( B3_SIMD_NEON )
@ -921,3 +924,184 @@ static inline int b3MinIndexW( b3FloatW a, int bitCount )
}
#endif
#if defined( B3_SIMD_NEON )
typedef struct b3AABBV
{
float32x4_t lower;
float32x4_t upper;
} b3AABBV;
B3_FORCE_INLINE b3AABBV b3LoadAABBV( const b3AABB* aabb )
{
const float* base = &aabb->lowerBound.x;
// Offset to avoid reading off the end (avoid UB).
// [lz ux uy uz]
float32x4_t v1 = vld1q_f32( base + 2 );
b3AABBV result;
// [lx ly lz -]
result.lower = vld1q_f32( base );
// [ux uy uz -]
result.upper = vextq_f32( v1, v1, 1 );
return result;
}
B3_FORCE_INLINE bool b3OverlapAABBV( b3AABBV a, b3AABBV b )
{
static const uint32_t laneMask[4] = { 0, 0, 0, 0xFFFFFFFFu };
uint32x4_t test = vandq_u32( vcleq_f32( a.lower, b.upper ), vcleq_f32( b.lower, a.upper ) );
return vminvq_u32( vorrq_u32( test, vld1q_u32( laneMask ) ) ) != 0;
}
B3_FORCE_INLINE bool b3OverlapNode( b3AABBV av, const b3TreeNode* node )
{
return b3OverlapAABBV( av, b3LoadAABBV( &node->aabb ) );
}
B3_FORCE_INLINE bool b3OverlapV( const b3AABB* a, const b3AABB* b )
{
return b3OverlapAABBV( b3LoadAABBV( a ), b3LoadAABBV( b ) );
}
B3_FORCE_INLINE b3AABBV b3UnionAABBV( b3AABBV a, b3AABBV b )
{
b3AABBV result;
result.lower = vminq_f32( a.lower, b.lower );
result.upper = vmaxq_f32( a.upper, b.upper );
return result;
}
B3_FORCE_INLINE b3AABBV b3UnionPairV( const b3TreeNode* pair )
{
return b3UnionAABBV( b3LoadAABBV( &pair[0].aabb ), b3LoadAABBV( &pair[1].aabb ) );
}
B3_FORCE_INLINE void b3StoreAABBV( b3AABB* aabb, b3AABBV value, bool condition )
{
float32x4_t raw0 = vsetq_lane_f32( vgetq_lane_f32( value.upper, 0 ), value.lower, 3 );
float32x4_t rotated = vextq_f32( value.upper, value.upper, 1 );
float32x4_t raw1 = vcombine_f32( vget_high_f32( raw0 ), vget_low_f32( rotated ) );
float* base = &aabb->lowerBound.x;
uint32x4_t mask = vdupq_n_u32( condition ? 0xFFFFFFFFu : 0u );
vst1q_f32( base, vbslq_f32( mask, raw0, vld1q_f32( base ) ) );
vst1q_f32( base + 2, vbslq_f32( mask, raw1, vld1q_f32( base + 2 ) ) );
}
#elif defined( B3_SIMD_SSE2 )
typedef struct b3AABBV
{
__m128 lower;
__m128 upper;
} b3AABBV;
B3_FORCE_INLINE b3AABBV b3LoadAABBV( const b3AABB* aabb )
{
const float* base = &aabb->lowerBound.x;
// Same offset as Neon to avoid UB.
__m128 v1 = _mm_loadu_ps( base + 2 );
b3AABBV result;
result.lower = _mm_loadu_ps( base );
result.upper = _mm_shuffle_ps( v1, v1, _MM_SHUFFLE( 3, 3, 2, 1 ) );
return result;
}
B3_FORCE_INLINE bool b3OverlapAABBV( b3AABBV a, b3AABBV b )
{
__m128 test = _mm_and_ps( _mm_cmple_ps( a.lower, b.upper ), _mm_cmple_ps( b.lower, a.upper ) );
return ( _mm_movemask_ps( test ) & 0x7 ) == 0x7;
}
B3_FORCE_INLINE bool b3OverlapNode( b3AABBV av, const b3TreeNode* node )
{
return b3OverlapAABBV( av, b3LoadAABBV( &node->aabb ) );
}
B3_FORCE_INLINE bool b3OverlapV( const b3AABB* a, const b3AABB* b )
{
return b3OverlapAABBV( b3LoadAABBV( a ), b3LoadAABBV( b ) );
}
B3_FORCE_INLINE b3AABBV b3UnionAABBV( b3AABBV a, b3AABBV b )
{
b3AABBV result;
result.lower = _mm_min_ps( a.lower, b.lower );
result.upper = _mm_max_ps( a.upper, b.upper );
return result;
}
B3_FORCE_INLINE b3AABBV b3UnionPairV( const b3TreeNode* pair )
{
return b3UnionAABBV( b3LoadAABBV( &pair[0].aabb ), b3LoadAABBV( &pair[1].aabb ) );
}
// Conditionally store an AABB. Avoids a branch.
B3_FORCE_INLINE void b3StoreAABBV( b3AABB* aabb, b3AABBV value, bool condition )
{
__m128 lane3 = _mm_castsi128_ps( _mm_set_epi32( -1, 0, 0, 0 ) );
__m128 uxSplat = _mm_shuffle_ps( value.upper, value.upper, _MM_SHUFFLE( 0, 0, 0, 0 ) );
__m128 raw0 = _mm_or_ps( _mm_andnot_ps( lane3, value.lower ), _mm_and_ps( lane3, uxSplat ) );
__m128 raw1 = _mm_shuffle_ps( raw0, value.upper, _MM_SHUFFLE( 2, 1, 3, 2 ) );
float* base = &aabb->lowerBound.x;
__m128 mask = _mm_castsi128_ps( _mm_set1_epi32( condition ? -1 : 0 ) );
__m128 old0 = _mm_loadu_ps( base );
__m128 old1 = _mm_loadu_ps( base + 2 );
_mm_storeu_ps( base, _mm_or_ps( _mm_and_ps( mask, raw0 ), _mm_andnot_ps( mask, old0 ) ) );
_mm_storeu_ps( base + 2, _mm_or_ps( _mm_and_ps( mask, raw1 ), _mm_andnot_ps( mask, old1 ) ) );
}
#else
typedef b3AABB b3AABBV;
B3_FORCE_INLINE b3AABBV b3LoadAABBV( const b3AABB* aabb )
{
return *aabb;
}
B3_FORCE_INLINE bool b3OverlapAABBV( b3AABBV a, b3AABBV b )
{
return a.lowerBound.x <= b.upperBound.x && a.lowerBound.y <= b.upperBound.y && a.lowerBound.z <= b.upperBound.z &&
b.lowerBound.x <= a.upperBound.x && b.lowerBound.y <= a.upperBound.y && b.lowerBound.z <= a.upperBound.z;
}
B3_FORCE_INLINE bool b3OverlapNode( b3AABBV av, const b3TreeNode* node )
{
return b3OverlapAABBV( av, node->aabb );
}
B3_FORCE_INLINE bool b3OverlapV( const b3AABB* a, const b3AABB* b )
{
return b3OverlapAABBV( *a, *b );
}
B3_FORCE_INLINE b3AABBV b3UnionAABBV( b3AABBV a, b3AABBV b )
{
return b3AABB_Union( a, b );
}
B3_FORCE_INLINE b3AABBV b3UnionPairV( const b3TreeNode* pair )
{
return b3AABB_Union( pair[0].aabb, pair[1].aabb );
}
B3_FORCE_INLINE void b3StoreAABBV( b3AABB* aabb, b3AABBV value, bool condition )
{
if ( condition )
{
*aabb = value;
}
}
#endif
B3_FORCE_INLINE b3AABB b3UnionV( b3AABB a, b3AABB b )
{
b3AABB result;
b3StoreAABBV( &result, b3UnionAABBV( b3LoadAABBV( &a ), b3LoadAABBV( &b ) ), true );
return result;
}

View file

@ -589,8 +589,14 @@ static void b3SolveContinuous( b3World* world, int bodySimIndex, b3TaskContext*
b3Vec3 aabbMargin = { marginScalar, marginScalar, marginScalar };
shape->fatAABB = (b3AABB){ b3Sub( aabb.lowerBound, aabbMargin ), b3Add( aabb.upperBound, aabbMargin ) };
shape->flags |= b3_enlargedAABB;
fastBodySim->flags |= b3_enlargeBounds;
// Regular bodies mark the hierarchy as moved using atomic operations.
// Bullets are handled separately at a later stage.
if ( isBullet == false )
{
b3BroadPhase_MarkProxyMoved( &world->broadPhase, shape->proxyKey, shape->fatAABB );
}
}
shapeId = shape->nextShapeId;
@ -621,8 +627,12 @@ static void b3SolveContinuous( b3World* world, int bodySimIndex, b3TaskContext*
.upperBound = b3Add( shape->aabb.upperBound, aabbMargin ),
};
shape->flags |= b3_enlargedAABB;
fastBodySim->flags |= b3_enlargeBounds;
if ( isBullet == false )
{
b3BroadPhase_MarkProxyMoved( &world->broadPhase, shape->proxyKey, shape->fatAABB );
}
}
shapeId = shape->nextShapeId;
@ -680,7 +690,6 @@ static void b3FinalizeBodiesTask( int startIndex, int endIndex, int workerIndex,
b3BodyMoveEvent* moveEvents = world->bodyMoveEvents.data;
b3TaskContext* taskContext = world->taskContexts.data + workerIndex;
b3BitSet* enlargedSimBitSet = &taskContext->enlargedSimBitSet;
b3BitSet* awakeIslandBitSet = &taskContext->awakeIslandBitSet;
const float speculativeScalar = B3_SPECULATIVE_DISTANCE;
@ -817,42 +826,31 @@ static void b3FinalizeBodiesTask( int startIndex, int endIndex, int workerIndex,
}
// Update shapes AABBs
b3WorldTransform transform = sim->transform;
bool isFast = ( sim->flags & b3_isFast ) != 0;
int shapeId = body->headShapeId;
while ( shapeId != B3_NULL_INDEX )
// For fast non-bullet bodies the AABB has already been updated in b3SolveContinuous
// For fast bullet bodies the AABB will be updated at a later stage
if ( ( sim->flags & b3_isFast ) == 0 )
{
b3Shape* shape = b3Array_Get( world->shapes, shapeId );
if ( isFast )
b3WorldTransform transform = sim->transform;
int shapeId = body->headShapeId;
while ( shapeId != B3_NULL_INDEX )
{
// For fast non-bullet bodies the AABB has already been updated in b3SolveContinuous
// For fast bullet bodies the AABB will be updated at a later stage
b3Shape* shape = b3Array_Get( world->shapes, shapeId );
// Add to enlarged shapes regardless of AABB changes.
// Bit-set to keep the move array sorted
b3SetBit( enlargedSimBitSet, simIndex );
}
else
{
b3AABB aabb = b3ComputeFatShapeAABB( shape, transform, speculativeScalar );
shape->aabb = aabb;
B3_ASSERT( ( shape->flags & b3_enlargedAABB ) == 0 );
if ( b3AABB_Contains( shape->fatAABB, aabb ) == false )
{
float marginScalar = shape->aabbMargin;
b3Vec3 aabbMargin = { marginScalar, marginScalar, marginScalar };
shape->fatAABB = (b3AABB){ b3Sub( aabb.lowerBound, aabbMargin ), b3Add( aabb.upperBound, aabbMargin ) };
shape->flags |= b3_enlargedAABB;
// Bit-set to keep the move array sorted
b3SetBit( enlargedSimBitSet, simIndex );
// Mark the hierarchy as moved using atomic operations.
b3BroadPhase_MarkProxyMoved( &world->broadPhase, shape->proxyKey, shape->fatAABB );
}
}
shapeId = shape->nextShapeId;
shapeId = shape->nextShapeId;
}
}
}
@ -1870,18 +1868,28 @@ void b3Solve( b3World* world, b3StepContext* stepContext )
b3TracyCZoneNC( update_transforms, "Update Transforms", b3_colorMediumSeaGreen, true );
uint64_t transformTicks = b3GetTicks();
// Prepare contact, enlarged body, and island bit sets used in body finalization.
// Prepare the island bit set used in body finalization.
int awakeIslandCount = awakeSet->islandSims.count;
for ( int i = 0; i < world->workerCount; ++i )
{
b3TaskContext* taskContext = world->taskContexts.data + i;
b3Array_Clear( taskContext->sensorHits );
b3SetBitCountAndClear( &taskContext->enlargedSimBitSet, awakeBodyCount );
b3SetBitCountAndClear( &taskContext->awakeIslandBitSet, awakeIslandCount );
taskContext->splitIslandId = B3_NULL_INDEX;
taskContext->splitSleepTime = 0.0f;
}
// Finish the user tree task that was queued earlier in the time step. This must be complete before touching the
// broad-phase.
if ( world->userTreeTask != NULL )
{
world->finishTaskFcn( world->userTreeTask, world->userTaskContext );
world->userTreeTask = NULL;
world->activeTaskCount -= 1;
}
b3ValidateNoMoved( &world->broadPhase );
// Finalize bodies. Must happen after the constraint solver and after island splitting.
b3ParallelFor( world, &b3FinalizeBodiesTask, awakeBodyCount, 16, stepContext, "ccd" );
@ -2073,90 +2081,8 @@ void b3Solve( b3World* world, b3StepContext* stepContext )
b3TracyCZoneNC( refit_bvh, "Refit BVH", b3_colorFireBrick, true );
uint64_t refitTicks = b3GetTicks();
// Finish the user tree task that was queued earlier in the time step. This must be complete before touching the
// broad-phase.
if ( world->userTreeTask != NULL )
{
world->finishTaskFcn( world->userTreeTask, world->userTaskContext );
world->userTreeTask = NULL;
world->activeTaskCount -= 1;
}
b3ValidateNoEnlarged( &world->broadPhase );
// Gather bits for all sim bodies that have enlarged AABBs
b3BitSet* enlargedBodyBitSet = &world->taskContexts.data[0].enlargedSimBitSet;
for ( int i = 1; i < world->workerCount; ++i )
{
b3InPlaceUnion( enlargedBodyBitSet, &world->taskContexts.data[i].enlargedSimBitSet );
}
// Enlarge broad-phase proxies and build move array
// Apply shape AABB changes to broad-phase. This also create the move array which must be
// in deterministic order. I'm tracking sim bodies because the number of shape ids can be huge.
// This has to happen before bullets are processed.
{
b3BroadPhase* broadPhase = &world->broadPhase;
uint32_t wordCount = enlargedBodyBitSet->blockCount;
uint64_t* bits = enlargedBodyBitSet->bits;
// Fast array access is important here
b3Body* bodyArray = world->bodies.data;
b3BodySim* bodySimArray = awakeSet->bodySims.data;
b3Shape* shapeArray = world->shapes.data;
for ( uint32_t k = 0; k < wordCount; ++k )
{
uint64_t word = bits[k];
while ( word != 0 )
{
uint32_t ctz = b3CTZ64( word );
uint32_t bodySimIndex = 64 * k + ctz;
b3BodySim* bodySim = bodySimArray + bodySimIndex;
b3Body* body = bodyArray + bodySim->bodyId;
int shapeId = body->headShapeId;
if ( ( bodySim->flags & ( b3_isBullet | b3_isFast ) ) == ( b3_isBullet | b3_isFast ) )
{
// Fast bullet bodies don't have their final AABB yet
while ( shapeId != B3_NULL_INDEX )
{
b3Shape* shape = shapeArray + shapeId;
// Shape is fast. It's aabb will be enlarged in continuous collision.
// Update the move array here for determinism because bullets are processed
// below in non-deterministic order.
b3BufferMove( broadPhase, shape->proxyKey );
shapeId = shape->nextShapeId;
}
}
else
{
while ( shapeId != B3_NULL_INDEX )
{
b3Shape* shape = shapeArray + shapeId;
// The AABB may not have been enlarged, despite the body being flagged as enlarged.
// For example, a body with multiple shapes may have not have all shapes enlarged.
// A fast body may have been flagged as enlarged despite having no shapes enlarged.
if ( shape->flags & b3_enlargedAABB )
{
b3BroadPhase_EnlargeProxy( broadPhase, shape->proxyKey, shape->fatAABB );
shape->flags &= ~b3_enlargedAABB;
}
shapeId = shape->nextShapeId;
}
}
// Clear the smallest set bit
word = word & ( word - 1 );
}
}
}
b3DynamicTree_Refit( world->broadPhase.trees + b3_kinematicBody );
b3DynamicTree_Refit( world->broadPhase.trees + b3_dynamicBody );
b3ValidateBroadPhase( &world->broadPhase );
@ -2207,23 +2133,17 @@ void b3Solve( b3World* world, b3StepContext* stepContext )
while ( shapeId != B3_NULL_INDEX )
{
b3Shape* shape = shapeArray + shapeId;
if ( ( shape->flags & b3_enlargedAABB ) == 0 )
{
shapeId = shape->nextShapeId;
continue;
}
// clear flag
shape->flags &= ~b3_enlargedAABB;
int proxyKey = shape->proxyKey;
int proxyId = B3_PROXY_ID( proxyKey );
B3_ASSERT( B3_PROXY_TYPE( proxyKey ) == b3_dynamicBody );
B3_VALIDATE( B3_PROXY_TYPE( proxyKey ) == b3_dynamicBody );
// all fast bullet shapes should already be in the move buffer
B3_ASSERT( b3GetBit( &broadPhase->movedProxies[b3_dynamicBody], proxyId ) );
b3AABB treeAABB = b3DynamicTree_GetAABB( dynamicTree, proxyId );
b3DynamicTree_EnlargeProxy( dynamicTree, proxyId, shape->fatAABB );
if ( b3AABB_Contains( treeAABB, shape->fatAABB ) == false )
{
b3DynamicTree_EnlargeProxy( dynamicTree, proxyId, shape->fatAABB );
}
shapeId = shape->nextShapeId;
}

View file

@ -52,25 +52,6 @@ void b3ClearSet( b3HashSet* set )
memset( set->items, 0, set->capacity * sizeof( b3SetItem ) );
}
// I need a good hash because the keys are built from pairs of increasing integers.
// A simple hash like hash = (integer1 XOR integer2) has many collisions.
// https://lemire.me/blog/2018/08/15/fast-strongly-universal-64-bit-hashing-everywhere/
// https://preshing.com/20130107/this-hash-set-is-faster-than-a-judy-array/
// todo try: https://www.jandrewrogers.com/2019/02/12/fast-perfect-hashing/
// todo try:
// https://probablydance.com/2018/06/16/fibonacci-hashing-the-optimization-that-the-world-forgot-or-a-better-alternative-to-integer-modulo/
static inline uint32_t b3KeyHash( uint64_t key )
{
uint64_t h = key;
h ^= h >> 33;
h *= 0xff51afd7ed558ccdL;
h ^= h >> 33;
h *= 0xc4ceb9fe1a85ec53L;
h ^= h >> 33;
return (uint32_t)h;
}
static int32_t b3FindSlot( const b3HashSet* set, uint64_t key, uint32_t hash )
{
uint32_t capacity = set->capacity;
@ -139,6 +120,15 @@ bool b3ContainsKey( const b3HashSet* set, uint64_t key )
return set->items[index].key == key;
}
// The caller already has the hash, which lets a batch prefetch the slots before probing them.
bool b3ContainsHashedKey( const b3HashSet* set, uint64_t key, uint32_t hash )
{
B3_ASSERT( key != 0 );
B3_ASSERT( hash == b3KeyHash( key ) );
int32_t index = b3FindSlot( set, key, hash );
return set->items[index].key == key;
}
int b3GetHashSetBytes( b3HashSet* set )
{
return set->capacity * (int)sizeof( b3SetItem );

View file

@ -3,11 +3,31 @@
#pragma once
#include "box3d/base.h"
#include "box3d/constants.h"
#include <stdbool.h>
#include <stdint.h>
// I need a good hash because the keys are built from pairs of increasing integers.
// A simple hash like hash = (integer1 XOR integer2) has many collisions.
// https://lemire.me/blog/2018/08/15/fast-strongly-universal-64-bit-hashing-everywhere/
// https://preshing.com/20130107/this-hash-set-is-faster-than-a-judy-array/
// todo try: https://www.jandrewrogers.com/2019/02/12/fast-perfect-hashing/
// todo try:
// https://probablydance.com/2018/06/16/fibonacci-hashing-the-optimization-that-the-world-forgot-or-a-better-alternative-to-integer-modulo/
B3_FORCE_INLINE uint32_t b3KeyHash( uint64_t key )
{
uint64_t h = key;
h ^= h >> 33;
h *= 0xff51afd7ed558ccdL;
h ^= h >> 33;
h *= 0xc4ceb9fe1a85ec53L;
h ^= h >> 33;
return (uint32_t)h;
}
typedef struct b3SetItem
{
uint64_t key;
@ -49,5 +69,6 @@ bool b3AddKey( b3HashSet* set, uint64_t key );
bool b3RemoveKey( b3HashSet* set, uint64_t key );
bool b3ContainsKey( const b3HashSet* set, uint64_t key );
bool b3ContainsHashedKey( const b3HashSet* set, uint64_t key, uint32_t hash );
int b3GetHashSetBytes( b3HashSet* set );

View file

@ -33,7 +33,7 @@
// Snapshot image magic 'BNS3' and version
#define B3_SNAP_MAGIC 0x33534E42u
#define B3_SNAP_VERSION 3u // added b3Body::safetyFactor
#define B3_SNAP_VERSION 5u // broad-phase pair traversal, move buffer removed
#define B3_SNAP_FLAG_VALIDATION 0x1u
#define B3_SNAP_FLAG_DOUBLE_PRECISION 0x2u
@ -64,6 +64,7 @@ static uint32_t b3ComputeLayoutHash( void )
MIX( sizeof( b3GraphColor ) )
MIX( sizeof( b3DynamicTree ) )
MIX( sizeof( b3TreeNode ) )
MIX( sizeof( b3TreeProxy ) )
MIX( sizeof( b3SetItem ) )
MIX( sizeof( b3IdPool ) )
MIX( sizeof( b3SurfaceMaterial ) )
@ -277,18 +278,26 @@ static void b3DesHashSet( b3SnapReader* r, b3HashSet* hs )
}
}
// DynamicTree: version, scalars, full nodeCapacity nodes (rebuild scratch excluded)
// DynamicTree: version, scalars, then nodes and parents to nodeEnd and proxies at capacity.
// The empty node and the free pairs are sentinels below the end and travel as they are. Only the
// stale tail above the end, the spare array and the rebuild scratch are skipped.
static void b3SerTree( b3RecBuffer* buf, const b3DynamicTree* tree )
{
b3SnapW_Bytes( buf, &tree->version, sizeof( uint64_t ) );
b3SnapW_I32( buf, tree->root );
b3SnapW_I32( buf, tree->nodeCount );
b3SnapW_I32( buf, tree->nodeCapacity );
b3SnapW_I32( buf, tree->freeList );
b3SnapW_I32( buf, tree->nodeEnd );
b3SnapW_I32( buf, tree->pairFreeList );
b3SnapW_I32( buf, tree->proxyCount );
if ( tree->nodeCapacity > 0 )
b3SnapW_I32( buf, tree->proxyCapacity );
b3SnapW_I32( buf, tree->proxyFreeList );
b3SnapW_I32( buf, tree->dfsOrdered ? 1 : 0 );
if ( tree->nodeEnd > 0 )
{
b3SnapW_Bytes( buf, tree->nodes, tree->nodeCapacity * (int)sizeof( b3TreeNode ) );
b3SnapW_Bytes( buf, tree->nodes, tree->nodeEnd * (int)sizeof( b3TreeNode ) );
b3SnapW_Bytes( buf, tree->parents, tree->nodeEnd * (int)sizeof( int32_t ) );
}
if ( tree->proxyCapacity > 0 )
{
b3SnapW_Bytes( buf, tree->proxies, tree->proxyCapacity * (int)sizeof( b3TreeProxy ) );
}
}
@ -296,29 +305,50 @@ 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 nodeCapacity = b3SnapR_I32( r );
int freeList = b3SnapR_I32( r );
int nodeEnd = b3SnapR_I32( r );
int pairFreeList = b3SnapR_I32( r );
int proxyCount = b3SnapR_I32( r );
int proxyCapacity = b3SnapR_I32( r );
int proxyFreeList = b3SnapR_I32( r );
bool dfsOrdered = b3SnapR_I32( r ) != 0;
if ( r->ok && b3SnapCheckCount( r, nodeCapacity, (int)sizeof( b3TreeNode ), (int)sizeof( b3TreeNode ) ) == false )
if ( r->ok && b3SnapCheckCount( r, nodeEnd, (int)sizeof( b3TreeNode ), (int)sizeof( b3TreeNode ) ) == false )
{
r->ok = false;
}
// Free existing allocation including any rebuild scratch
if ( r->ok && b3SnapCheckCount( r, proxyCapacity, (int)sizeof( b3TreeProxy ), (int)sizeof( b3TreeProxy ) ) == false )
{
r->ok = false;
}
if ( r->ok && ( nodeEnd < 2 || ( nodeEnd & 1 ) != 0 || proxyCapacity < 1 ) )
{
r->ok = false;
}
// Free existing allocation including the spare array and any rebuild scratch
b3Free( tree->nodes, tree->nodeCapacity * (int)sizeof( b3TreeNode ) );
b3Free( tree->parents, tree->nodeCapacity * (int)sizeof( int32_t ) );
b3Free( tree->proxies, tree->proxyCapacity * (int)sizeof( b3TreeProxy ) );
b3Free( tree->swapNodes, tree->nodeCapacity * (int)sizeof( b3TreeNode ) );
b3Free( tree->leafIndices, tree->rebuildCapacity * (int)sizeof( int ) );
b3Free( tree->leafNodes, tree->rebuildCapacity * (int)sizeof( b3TreeNode ) );
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->parents = NULL;
tree->proxies = NULL;
tree->swapNodes = NULL;
tree->leafIndices = NULL;
tree->leafNodes = NULL;
tree->leafBoxes = NULL;
tree->leafCenters = NULL;
tree->binIndices = NULL;
tree->nodeEnd = 0;
tree->nodeCapacity = 0;
tree->proxyCapacity = 0;
tree->rebuildCapacity = 0;
if ( !r->ok )
@ -327,17 +357,21 @@ static void b3DesTree( b3SnapReader* r, b3DynamicTree* tree )
}
tree->version = version;
tree->root = root;
tree->nodeCount = nodeCount;
tree->nodeCapacity = nodeCapacity;
tree->freeList = freeList;
tree->nodeEnd = nodeEnd;
tree->nodeCapacity = nodeEnd;
tree->pairFreeList = pairFreeList;
tree->proxyCount = proxyCount;
tree->proxyCapacity = proxyCapacity;
tree->proxyFreeList = proxyFreeList;
tree->dfsOrdered = dfsOrdered;
if ( nodeCapacity > 0 )
{
tree->nodes = (b3TreeNode*)b3Alloc( nodeCapacity * (int)sizeof( b3TreeNode ) );
b3SnapR_Bytes( r, tree->nodes, nodeCapacity * (int)sizeof( b3TreeNode ) );
}
tree->nodes = (b3TreeNode*)b3Alloc( nodeEnd * (int)sizeof( b3TreeNode ) );
tree->parents = (int32_t*)b3Alloc( nodeEnd * (int)sizeof( int32_t ) );
b3SnapR_Bytes( r, tree->nodes, nodeEnd * (int)sizeof( b3TreeNode ) );
b3SnapR_Bytes( r, tree->parents, nodeEnd * (int)sizeof( int32_t ) );
tree->proxies = (b3TreeProxy*)b3Alloc( proxyCapacity * (int)sizeof( b3TreeProxy ) );
b3SnapR_Bytes( r, tree->proxies, proxyCapacity * (int)sizeof( b3TreeProxy ) );
}
// Solver set: setIndex + 4 arrays (note: contactIndices is int array, not contactSims)
@ -446,6 +480,7 @@ static void b3SerWorldConfig( b3RecBuffer* buf, const b3World* world )
b3SnapW_Bytes( buf, &world->inv_h, sizeof( float ) );
b3SnapW_Bytes( buf, &world->inv_dt, sizeof( float ) );
b3SnapW_I32( buf, world->endEventArrayIndex );
b3SnapW_I32( buf, world->compoundShapeCount );
b3SnapW_Bytes( buf, &world->maxCapacity, sizeof( b3Capacity ) );
uint8_t flags = 0;
flags |= world->enableSleep ? 0x01u : 0u;
@ -470,6 +505,7 @@ static void b3DesWorldConfig( b3SnapReader* r, b3World* world )
b3SnapR_Bytes( r, &world->inv_h, sizeof( float ) );
b3SnapR_Bytes( r, &world->inv_dt, sizeof( float ) );
world->endEventArrayIndex = b3SnapR_I32( r );
world->compoundShapeCount = b3SnapR_I32( r );
b3SnapR_Bytes( r, &world->maxCapacity, sizeof( b3Capacity ) );
uint8_t flags = 0;
b3SnapR_Bytes( r, &flags, 1 );
@ -1078,11 +1114,6 @@ int b3SerializeWorld( b3World* world, b3RecBuffer* buf, b3Recording* rec )
{
b3SerTree( buf, &bp->trees[t] );
}
for ( int t = 0; t < b3_bodyTypeCount; ++t )
{
b3SerBitSet( buf, &bp->movedProxies[t] );
}
b3SerPodArray( buf, bp->moveArray );
b3SerHashSet( buf, &bp->pairSet );
// Constraint graph
@ -1307,17 +1338,8 @@ bool b3DeserializeIntoShell( const uint8_t* data, int size, b3World* world, b3Re
{
b3DesTree( r, &bp->trees[t] );
}
for ( int t = 0; t < b3_bodyTypeCount; ++t )
{
b3DesBitSet( r, &bp->movedProxies[t] );
}
b3Array_Destroy( bp->moveArray );
b3Array_Create( bp->moveArray );
b3DesPodArray( r, bp->moveArray );
b3DesHashSet( r, &bp->pairSet );
// Transient moveResults/movePairs stay at shell's NULL/0
// The gathered moved siblings are per step scratch and stay at the shell's NULL
}
// 11. Constraint graph