Fixes 03 (#40)

Fixes #33, #34, #35, #37, #39, #41, #42, #43

Also fixes b3Body_SetMassData inertia tensor.
This commit is contained in:
Erin Catto 2026-07-03 17:15:03 -07:00 • committed by GitHub
commit 655799893a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
25 changed files with 771 additions and 151 deletions

View file

@ -198,7 +198,8 @@ elseif (APPLE)
target_compile_options(box3d PRIVATE -Wmissing-prototypes -Wall -Wextra -pedantic)
elseif (EMSCRIPTEN)
message(STATUS "Box3D on Emscripten")
target_compile_options(box3d PRIVATE -msimd128 -msse2)
# SSE2/wasm SIMD flags are set directory-wide in the top-level CMakeLists so the
# tests, which include simd.h, get them too.
elseif (UNIX)
message(STATUS "Box3D using Unix")
target_compile_options(box3d PRIVATE -Wmissing-prototypes -Wall -Wextra -pedantic -Wno-unused-value)

View file

@ -72,7 +72,7 @@ b3BodyState* b3GetBodyState( b3World* world, b3Body* body )
return NULL;
}
static void b3SyncBodyFlags( b3World* world, b3Body* body )
void b3SyncBodyFlags( b3World* world, b3Body* body )
{
// Never sync transient flags
uint32_t flags = body->flags & ~b3_bodyTransientFlags;
@ -801,6 +801,10 @@ void b3UpdateBodyMassData( b3World* world, b3Body* body )
{
b3BodySim* bodySim = b3GetBodySim( world, body );
// Mass is no longer dirty
body->flags &= ~b3_dirtyMass;
b3SyncBodyFlags( world, body );
// Compute mass data from shapes. Each shape has its own density.
body->mass = 0.0f;
body->inertia = b3Mat3_zero;
@ -888,7 +892,7 @@ void b3UpdateBodyMassData( b3World* world, b3Body* body )
// Shift to center of mass. This is safe because it can only increase.
b3Vec3 offset = b3Sub( localCenter, massData.center );
b3Matrix3 inertia = b3AddMM( massData.inertia, b3Steiner( massData.mass, offset ) );
body->inertia = b3AddMM(body->inertia, inertia);
body->inertia = b3AddMM( body->inertia, inertia );
}
b3StackFree( &world->stack, masses );
@ -1829,6 +1833,10 @@ void b3Body_SetMassData( b3BodyId bodyId, b3MassData massData )
b3Body* body = b3GetBodyFullId( world, bodyId );
b3BodySim* bodySim = b3GetBodySim( world, body );
// Mass is no longer dirty
body->flags &= ~b3_dirtyMass;
b3SyncBodyFlags( world, body );
body->mass = massData.mass;
body->inertia = massData.inertia;
bodySim->localCenter = massData.center;
@ -1836,9 +1844,45 @@ void b3Body_SetMassData( b3BodyId bodyId, b3MassData massData )
b3Pos center = b3TransformWorldPoint( bodySim->transform, massData.center );
bodySim->center = center;
bodySim->center0 = center;
bodySim->invMass = body->mass > 0.0f ? 1.0f / body->mass : 0.0f;
bodySim->invInertiaLocal = b3Det( body->inertia ) > 0.0f ? b3InvertT( body->inertia ) : b3Mat3_zero;
float det = b3Det( body->inertia );
B3_ASSERT( det >= 0.0f );
if ( det > 0.0f )
{
// This call is faster than b3Invert
bodySim->invInertiaLocal = b3InvertT( body->inertia );
b3Matrix3 rotationMatrix = b3MakeMatrixFromQuat( bodySim->transform.q );
bodySim->invInertiaWorld = b3MulMM( b3MulMM( rotationMatrix, bodySim->invInertiaLocal ), b3Transpose( rotationMatrix ) );
}
else
{
bodySim->invInertiaLocal = b3Mat3_zero;
bodySim->invInertiaWorld = b3Mat3_zero;
}
// Apply fixed rotation
if ( ( bodySim->flags & b3_fixedRotation ) == b3_fixedRotation )
{
body->inertia = b3Mat3_zero;
bodySim->invInertiaLocal = b3Mat3_zero;
bodySim->invInertiaWorld = b3Mat3_zero;
}
// Update extents using supplied mass center.
bodySim->minExtent = B3_HUGE;
bodySim->maxExtent = b3Vec3_zero;
int shapeId = body->headShapeId;
while ( shapeId != B3_NULL_INDEX )
{
const b3Shape* s = b3Array_Get( world->shapes, shapeId );
b3ShapeExtent extent = b3ComputeShapeExtent( s, massData.center );
bodySim->minExtent = b3MinFloat( bodySim->minExtent, extent.minExtent );
bodySim->maxExtent = b3Max( bodySim->maxExtent, extent.maxExtent );
shapeId = s->nextShapeId;
}
}
b3MassData b3Body_GetMassData( b3BodyId bodyId )

View file

@ -57,6 +57,10 @@ enum b3BodyFlags
b3_bodyEnableContactRecycling = 0x00004000,
// The user deferred mass computation via the updateBodyMass shape option and mass
// data still hasn't been set.
b3_dirtyMass = 0x00008000,
// All lock flags
b3_allLocks = b3_lockLinearX | b3_lockLinearY | b3_lockLinearZ | b3_lockAngularX | b3_lockAngularY | b3_lockAngularZ,
@ -237,6 +241,7 @@ bool b3WakeBody( b3World* world, b3Body* body );
bool b3WakeBodyWithLock( b3World* world, b3Body* body );
void b3UpdateBodyMassData( b3World* world, b3Body* body );
void b3SyncBodyFlags( b3World* world, b3Body* body );
void b3DumpBody( b3World* world, b3Body* body );
// Make a sweep relative to a base position to keep TOI in float precision far from the origin.

View file

@ -2088,6 +2088,7 @@ static int b3RecDispatchOne( b3RecReader* rdr )
{
return -1;
}
int payloadStart = rdr->cursor;
switch ( opcode )
@ -2651,6 +2652,7 @@ static void b3RecPlayerRestoreKeyframe( b3RecPlayer* player, const b3RecKeyframe
player->frame = kf->frame;
player->divergeFrame = kf->divergeFrame;
player->atEnd = false;
player->atPreStep = false;
// Restore the outliner list verbatim so ordinals match this frame.
b3RecGrow( (void**)&player->bodyIds, &player->bodyIdCap, kf->bodyIdCount, 0, (int)sizeof( b3BodyId ) );
@ -2750,6 +2752,7 @@ b3RecPlayer* b3RecPlayer_Create( const void* data, int size, int workerCount )
player->recordedSubStepCount = 0;
player->recordedWorkerCount = workerCount;
player->atEnd = false;
player->atPreStep = false;
player->divergeFrame = -1;
player->keyframeMinInterval = B3_REC_KEYFRAME_INTERVAL_DEFAULT;
player->keyframeInterval = B3_REC_KEYFRAME_INTERVAL_DEFAULT;
@ -2914,6 +2917,9 @@ void b3RecPlayer_Destroy( b3RecPlayer* player )
bool b3RecPlayer_StepFrame( b3RecPlayer* player )
{
// This is never true when full stepping
player->atPreStep = false;
if ( player->atEnd )
{
return false;
@ -2975,6 +2981,91 @@ bool b3RecPlayer_StepFrame( b3RecPlayer* player )
}
}
void b3RecPlayer_SubStepFrame( b3RecPlayer* player )
{
if ( player->atEnd )
{
return;
}
// Reset the per-frame query store before this frame's records are dispatched.
if ( player->atPreStep == false )
{
player->frameQueryCount = 0;
player->frameHitCount = 0;
}
// A frame is its leading inputs (queries and between-step mutators), one Step, and the Step's
// trailing StateHash. Queries are recorded before the Step they belong to, so they stash here
// against the world state they were computed for.
bool stepped = false;
bool haveCreateBodyOp = false;
for ( ;; )
{
if ( player->rdr.cursor >= player->registryEnd || !player->rdr.ok )
{
player->atEnd = true;
player->atPreStep = false;
return;
}
// Once stepped, the StateHash is the only record still belonging to this frame. Anything else
// begins the next frame, so stop and let the next StepFrame consume it. Capture a keyframe at
// the boundary.
uint8_t currentOpCode = player->rdr.data[player->rdr.cursor];
if ( stepped && currentOpCode != b3_recOpStateHash )
{
if ( player->frame > player->lastKeyframeFrame && player->frame % player->keyframeInterval == 0 )
{
b3RecCaptureKeyframe( player );
}
return;
}
if ( player->atPreStep == false && haveCreateBodyOp == true && currentOpCode == b3_recOpStep )
{
player->atPreStep = true;
return;
}
int op = b3RecDispatchOne( &player->rdr );
if ( op < 0 )
{
player->atEnd = true;
player->atPreStep = false;
return;
}
if ( op == b3_recOpDestroyWorld ) // end of recording
{
player->atEnd = true;
player->atPreStep = false;
return;
}
if ( op == b3_recOpCreateBody )
{
B3_ASSERT( player->atPreStep == false );
haveCreateBodyOp = true;
}
if ( op == b3_recOpStep )
{
player->atPreStep = false;
player->frame += 1;
stepped = true;
}
else if ( op == b3_recOpStateHash ) // trailing record of the frame just stepped
{
// Latch the first frame whose state hash diverged. The hash belongs to the frame Step just
// advanced, so latch against the current frame, not the next Step which would be one late.
if ( player->divergeFrame < 0 && player->rdr.diverged )
{
player->divergeFrame = player->frame;
}
}
}
}
void b3RecPlayer_Restart( b3RecPlayer* player )
{
// Restore the frame-0 image in place so the replay world id stays stable across a restart or
@ -2991,6 +3082,7 @@ void b3RecPlayer_Restart( b3RecPlayer* player )
player->frame = 0;
player->divergeFrame = -1;
player->atEnd = false;
player->atPreStep = false;
// Frame 0 is the pre-step snapshot with no recorded queries, so clear the per-frame store. This
// keeps the last stepped frame's queries from lingering on a restart or a backward scrub to 0.
@ -3008,6 +3100,8 @@ void b3RecPlayer_Restart( b3RecPlayer* player )
void b3RecPlayer_SeekFrame( b3RecPlayer* player, int targetFrame )
{
player->atPreStep = false;
if ( player == NULL )
{
return;
@ -3071,6 +3165,11 @@ bool b3RecPlayer_IsAtEnd( const b3RecPlayer* player )
return player != NULL ? player->atEnd : true;
}
bool b3RecPlayer_IsAtPreStep( const b3RecPlayer* player )
{
return player != NULL ? player->atPreStep : false;
}
bool b3RecPlayer_HasDiverged( const b3RecPlayer* player )
{
return player != NULL ? player->rdr.diverged : false;

View file

@ -149,6 +149,9 @@ struct b3RecPlayer
int recordedWorkerCount; // worker count requested for the replay world
b3AABB bounds; // accumulated world bounds, decoded from the trailing record
bool atEnd;
// Indicates all ops for the step have been consumed up to the world step op. The next sub-step
// will clear this and perform the world step.
bool atPreStep;
int divergeFrame; // first frame that diverged, -1 until then
// Outliner body list, indexed by creation ordinal. Holes (null ids) mark destroyed bodies so

View file

@ -297,6 +297,11 @@ static b3ShapeId b3CreateShape( b3BodyId bodyId, const b3ShapeDef* def, const vo
{
b3UpdateBodyMassData( world, body );
}
else if ( ( body->flags & b3_dirtyMass ) == 0 )
{
body->flags |= b3_dirtyMass;
b3SyncBodyFlags( world, body );
}
b3ValidateSolverSets( world );

View file

@ -733,6 +733,10 @@ static void b3FinalizeBodiesTask( int startIndex, int endIndex, int workerIndex,
sim->force = b3Vec3_zero;
sim->torque = b3Vec3_zero;
// If you hit this then it means you deferred mass computation but never called b3Body_ApplyMassFromShapes
// or b3Body_SetMassData.
B3_ASSERT( ( body->flags & b3_dirtyMass ) == 0 );
body->flags &= ~b3_bodyTransientFlags;
body->flags |= ( sim->flags & ( b3_isSpeedCapped | b3_hadTimeOfImpact ) );
body->flags |= ( state->flags & ( b3_isSpeedCapped | b3_hadTimeOfImpact ) );