Draw sleep velocity (#49)

- draw sleep velocity for debugging
- added back shape names with B3_SHAPE_NAME_LENGTH
- zup command line option
This commit is contained in:
Erin Catto 2026-07-05 00:33:00 -07:00 • committed by GitHub
commit 540ea387b0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
28 changed files with 554 additions and 132 deletions

View file

@ -508,7 +508,7 @@ B3_API b3BodyType b3Body_GetType( b3BodyId bodyId );
/// properties regardless of the automatic mass setting.
B3_API void b3Body_SetType( b3BodyId bodyId, b3BodyType type );
/// Set the body name. Up to B3_BODY_NAME_LENGTH characters including null termination.
/// Set the body name. Up to B3_BODY_NAME_LENGTH characters excluding null termination.
B3_API void b3Body_SetName( b3BodyId bodyId, const char* name );
/// Get the body name.
@ -729,7 +729,7 @@ B3_API bool b3Body_IsContactRecyclingEnabled( b3BodyId bodyId );
/// Enable/disable hit events on all shapes
/// @see b3ShapeDef::enableHitEvents
B3_API void b3Body_EnableHitEvents( b3BodyId bodyId, bool enableHitEvents );
B3_API void b3Body_EnableHitEvents( b3BodyId bodyId, bool flag );
/// Get the world that owns this body
B3_API b3WorldId b3Body_GetWorld( b3BodyId bodyId );
@ -846,6 +846,12 @@ B3_API b3WorldId b3Shape_GetWorld( b3ShapeId shapeId );
/// Returns true if the shape is a sensor
B3_API bool b3Shape_IsSensor( b3ShapeId shapeId );
/// Set the shape name. Up to B3_SHAPE_NAME_LENGTH characters excluding null termination.
B3_API void b3Shape_SetName( b3ShapeId shapeId, const char* name );
/// Get the shape name.
B3_API const char* b3Shape_GetName( b3ShapeId shapeId );
/// Set the user data for a shape
B3_API void b3Shape_SetUserData( b3ShapeId shapeId, void* userData );

View file

@ -98,16 +98,13 @@ B3_API float b3GetStallThreshold( void );
#define B3_TIME_TO_SLEEP 0.5f
/// Maximum length of the body name. Can be 0 if you don't need names.
/// Note: this gates recording capability.
#ifndef B3_BODY_NAME_LENGTH
#define B3_BODY_NAME_LENGTH 18
#endif
/// Maximum length of the shape name. Can be 0 if you don't need names.
/// Note: this gates recording capability.
/// todo waiting on this because it breaks existing recordings
#ifndef B3_SHAPE_NAME_LENGTH
#define B3_SHAPE_NAME_LENGTH 18
#define B3_SHAPE_NAME_LENGTH 0
#endif
/// The maximum number of contact points between two touching shapes.

View file

@ -432,7 +432,7 @@ typedef enum b3ShapeType
/// A capsule is an extruded sphere
b3_capsuleShape,
/// A compound shape composed of up to 64K spheres, capsules, hulls, and meshes
/// A baked compound shape composed of spheres, capsules, hulls, and meshes
b3_compoundShape,
/// A height field useful for terrain
@ -455,6 +455,9 @@ typedef enum b3ShapeType
/// @ingroup shape
typedef struct b3ShapeDef
{
/// Optional shape name for debugging
const char* name;
/// Use this to store application specific shape data.
void* userData;
@ -2406,11 +2409,13 @@ typedef struct b3CompoundDef
/// a mesh with many materials, you can use it outside of the compound.
#define B3_MAX_COMPOUND_MESH_MATERIALS 4
/// The runtime data for a compound shape. This is a potentially large yet highly optimized
/// The runtime data for a baked compound shape. This is a potentially large yet highly optimized
/// data structure. It can contain thousands of child shapes, yet at runtime it populates
/// into the world as a single shape in the runtime broad-phase.
/// This data structure has data living off the end and must be accessed using offsets.
/// Accessors are provided for user relevant data.
/// Note: you don't need to use this to create runtime compounds. For runtime compounds you can
/// add multiple shapes to a body using the regular shape creation functions.
typedef struct b3CompoundData
{
/// The compound version is always first.
@ -2998,6 +3003,9 @@ typedef struct b3DebugDraw
/// Option to draw the mass and center of mass of dynamic bodies
bool drawMass;
/// Option to draw the sleep information for dynamic and kinematic bodies
bool drawSleep;
/// Option to draw body names
bool drawBodyNames;

View file

@ -219,6 +219,7 @@ void ApplyGuiFlags( b3DebugDraw* out )
out->drawJointExtras = s_adapter.guiDraw.drawJointExtras;
out->drawBounds = s_adapter.guiDraw.drawBounds;
out->drawMass = s_adapter.guiDraw.drawMass;
out->drawSleep = s_adapter.guiDraw.drawSleep;
out->drawBodyNames = s_adapter.guiDraw.drawBodyNames;
out->drawContacts = s_adapter.guiDraw.drawContacts;
out->drawAnchorA = s_adapter.guiDraw.drawAnchorA;

View file

@ -493,6 +493,10 @@ sapp_desc sokol_main( int argc, char** argv )
s_sampleOverride = g_replayIndex;
}
}
else if ( strcmp( argv[i], "--zup" ) == 0 )
{
s_context.viewZUp = true;
}
}
sapp_desc desc{};

View file

@ -1633,6 +1633,7 @@ static void DrawMenuBar( SampleContext* context )
ImGui::MenuItem( "Joint Extras", nullptr, &gd->drawJointExtras );
ImGui::MenuItem( "Bounds", nullptr, &gd->drawBounds );
ImGui::MenuItem( "Mass", nullptr, &gd->drawMass );
ImGui::MenuItem( "Sleep", nullptr, &gd->drawSleep );
ImGui::MenuItem( "Body Names", nullptr, &gd->drawBodyNames );
ImGui::MenuItem( "Graph Colors", nullptr, &gd->drawGraphColors );
ImGui::MenuItem( "Islands", nullptr, &gd->drawIslands );

View file

@ -369,6 +369,76 @@ public:
static int sampleGyroscopicTorque = RegisterSample( "Bodies", "Gyroscopic Torque", GyroscopicTorque::Create );
// todo this doesn't behave correctly because the friction center is influenced by speculative points
#if 0
// Spinning tops.
// Ported from PEEL (GyroscopicPrecession).
class GyroscopicPrecession : public Sample
{
public:
explicit GyroscopicPrecession( SampleContext* context )
: Sample( context )
{
if ( context->restart == false )
{
m_camera->SetView( 0.0f, 25.0f, 55.0f, { 0.0f, 2.0f, 0.0f } );
}
AddGroundBox( 30.0f );
// Top shape: a wide n-gon rim up top and a point at the origin, so it balances on its tip.
constexpr int numSegs = 7;
constexpr float r = 2.0f;
constexpr float h = 2.0f;
b3Vec3 hullPoints[numSegs + 1];
const float dphi = 2.0f * B3_PI / numSegs;
for ( int i = 0; i < numSegs; ++i )
{
hullPoints[i] = { r * cosf( i * dphi ), h, r * sinf( i * dphi ) };
}
hullPoints[numSegs] = b3Vec3_zero;
b3HullData* hull = b3CreateHull( hullPoints, numSegs + 1, numSegs + 1 );
b3ShapeDef shapeDef = b3DefaultShapeDef();
// Tilt the symmetry axis, then spin about that tilted axis so gravity induces precession.
b3Quat rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, 15.0f * B3_PI / 180.0f );
b3Vec3 angularVelocity = b3RotateVector( rotation, { 0.0f, 75.0f, 0.0f } );
constexpr int count = 1;
constexpr float separation = 6.0f;
for ( int x = 0; x < count; ++x )
{
for ( int z = 0; z < count; ++z )
{
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.position = { ( x - count / 2 ) * separation, h, ( z - count / 2 ) * separation };
bodyDef.rotation = rotation;
bodyDef.gravityScale = 0.0f;
// The spin rate exceeds the default cap, so bypass it as the test intends.
bodyDef.allowFastRotation = true;
b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef );
b3CreateHullShape( bodyId, &shapeDef, hull );
b3Body_SetAngularVelocity( bodyId, angularVelocity );
}
}
b3DestroyHull( hull );
}
static Sample* Create( SampleContext* context )
{
return new GyroscopicPrecession( context );
}
};
static int sampleGyroscopicPrecession = RegisterSample( "Bodies", "Gyroscopic Precession", GyroscopicPrecession::Create );
#endif
class Weeble : public Sample
{
public:

View file

@ -778,9 +778,9 @@ public:
ImGui::TextColored( PanelColor( b3_colorRed ), "****DIVERGED****" );
}
const char* phaseTag = b3RecPlayer_IsAtEnd( m_player ) ? " (end)"
const char* phaseTag = b3RecPlayer_IsAtEnd( m_player ) ? " (end)"
: b3RecPlayer_IsAtPreStep( m_player ) ? " (pre-step)"
: "";
: "";
ImGui::TextDisabled( "Frame %d / %d%s", b3RecPlayer_GetFrame( m_player ), m_info.frameCount, phaseTag );
// Selection detail lives here in the info panel, not the Outline window, so the scene tree gets
@ -1197,8 +1197,8 @@ public:
int count = b3RecPlayer_GetBodyCount( m_player );
for ( int ord = 0; ord < count; ++ord )
{
b3BodyId body = b3RecPlayer_GetBodyId( m_player, ord );
if ( B3_IS_NULL( body ) || b3Body_IsValid( body ) == false )
b3BodyId bodyId = b3RecPlayer_GetBodyId( m_player, ord );
if ( B3_IS_NULL( bodyId ) || b3Body_IsValid( bodyId ) == false )
{
continue;
}
@ -1206,10 +1206,15 @@ public:
bool ownsSelection =
m_selBodyOrdinal == ord && ( m_selKind == SelBody || m_selKind == SelShape || m_selKind == SelJoint );
const char* name = b3Body_GetName( body );
const char* bodyName = b3Body_GetName( bodyId );
if ( bodyName == nullptr || bodyName[0] == 0 )
{
b3BodyType bodyType = b3Body_GetType( bodyId );
bodyName = ReplayBodyTypeName( bodyType );
}
char label[64];
snprintf( label, sizeof( label ), "Body %d %s###b%d", ord,
( name != nullptr && name[0] != '\0' ) ? name : ReplayBodyTypeName( b3Body_GetType( body ) ), ord );
snprintf( label, sizeof( label ), "Body %d %s###b%d", ord, bodyName, ord );
ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_SpanAvailWidth;
if ( m_selKind == SelBody && m_selBodyOrdinal == ord )
@ -1237,12 +1242,17 @@ public:
continue;
}
BodyShapes( m_shapeBuffer, body );
BodyShapes( m_shapeBuffer, bodyId );
for ( int s = 0; s < (int)m_shapeBuffer.size(); ++s )
{
b3ShapeType shapeType = b3Shape_GetType( m_shapeBuffer[s] );
const char* shapeName = b3Shape_GetName( m_shapeBuffer[s] );
if ( shapeName == nullptr || shapeName[0] == 0 )
{
b3ShapeType shapeType = b3Shape_GetType( m_shapeBuffer[s] );
shapeName = ReplayShapeTypeName( shapeType );
}
char sl[64];
snprintf( sl, sizeof( sl ), "Shape %d %s###b%ds%d", s, ReplayShapeTypeName( shapeType ), ord, s );
snprintf( sl, sizeof( sl ), "Shape %d %s###b%ds%d", s, shapeName, ord, s );
ImGuiTreeNodeFlags lf =
ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_NoTreePushOnOpen;
if ( m_selKind == SelShape && m_selBodyOrdinal == ord && m_selSlot == s )
@ -1263,7 +1273,7 @@ public:
}
b3JointId joints[16];
int jn = b3Body_GetJoints( body, joints, 16 );
int jn = b3Body_GetJoints( bodyId, joints, 16 );
for ( int j = 0; j < jn; ++j )
{
char jl[64];

View file

@ -2,11 +2,11 @@
// SPDX-License-Identifier: MIT
#include "gfx/debug_adapter.h"
#include "gfx/draw.h"
#include "gfx/keycodes.h"
#include "imgui.h"
#include "mesh_loader.h"
#include "sample.h"
#include "gfx/draw.h"
#include "box3d/box3d.h"
@ -452,6 +452,12 @@ public:
b3ShapeDef shapeDef = b3DefaultShapeDef();
shapeDef.baseMaterial.rollingResistance = 0.1f;
#if B3_SHAPE_NAME_LENGTH > 0
char buffer[B3_SHAPE_NAME_LENGTH + 1];
snprintf( buffer, sizeof( buffer ), "box_%d", i );
shapeDef.name = buffer;
#endif
b3CreateHullShape( bodyId, &shapeDef, &cube.base );
}
@ -573,7 +579,7 @@ public:
{
if ( m_context->restart == false )
{
if (m_isDebug)
if ( m_isDebug )
{
m_camera->SetView( 0.0f, 15.0f, 25.0f, b3Pos_zero );
}

View file

@ -271,19 +271,7 @@ b3BodyId b3CreateBody( b3WorldId worldId, const b3BodyDef* def )
b3Body* body = b3Array_Get( world->bodies, bodyId );
if ( def->name )
{
#if defined( _MSC_VER )
strncpy_s( body->name, B3_BODY_NAME_LENGTH + 1, def->name, B3_BODY_NAME_LENGTH );
#else
strncpy( body->name, def->name, B3_BODY_NAME_LENGTH );
body->name[B3_BODY_NAME_LENGTH] = 0;
#endif
}
else
{
memset( body->name, 0, sizeof( body->name ) );
}
b3StrCpy( body->name, B3_BODY_NAME_LENGTH + 1, def->name );
body->userData = def->userData;
body->setIndex = setId;
@ -302,6 +290,7 @@ b3BodyId b3CreateBody( b3WorldId worldId, const b3BodyDef* def )
body->id = bodyId;
body->sleepThreshold = def->sleepThreshold;
body->sleepTime = 0.0f;
body->sleepVelocity = 0.0f;
body->mass = 0.0f;
body->inertia = b3Mat3_zero;
body->type = def->type;
@ -1733,20 +1722,7 @@ void b3Body_SetName( b3BodyId bodyId, const char* name )
B3_REC( world, BodySetName, bodyId, name );
b3Body* body = b3GetBodyFullId( world, bodyId );
if ( name )
{
#if defined( _MSC_VER )
strncpy_s( body->name, B3_BODY_NAME_LENGTH + 1, name, B3_BODY_NAME_LENGTH );
#else
strncpy( body->name, name, B3_BODY_NAME_LENGTH );
body->name[B3_BODY_NAME_LENGTH] = 0;
#endif
}
else
{
memset( body->name, 0, sizeof( body->name ) );
}
b3StrCpy( body->name, B3_BODY_NAME_LENGTH + 1, name );
}
const char* b3Body_GetName( b3BodyId bodyId )
@ -2417,18 +2393,18 @@ bool b3Body_IsContactRecyclingEnabled( b3BodyId bodyId )
return ( body->flags & b3_bodyEnableContactRecycling ) != 0;
}
void b3Body_EnableHitEvents( b3BodyId bodyId, bool enableHitEvents )
void b3Body_EnableHitEvents( b3BodyId bodyId, bool flag )
{
b3World* world = b3GetWorld( bodyId.world0 );
B3_REC( world, BodyEnableHitEvents, bodyId, enableHitEvents );
B3_REC( world, BodyEnableHitEvents, bodyId, flag );
b3Body* body = b3GetBodyFullId( world, bodyId );
int shapeId = body->headShapeId;
while ( shapeId != B3_NULL_INDEX )
{
b3Shape* shape = b3Array_Get( world->shapes, shapeId );
shape->enableHitEvents = enableHitEvents;
shape->flags = flag ? shape->flags | b3_enableHitEvents : shape->flags & ~b3_enableHitEvents;
shapeId = shape->nextShapeId;
}
}

View file

@ -107,7 +107,7 @@ typedef struct b3Body
float sleepThreshold;
float sleepTime;
float sleepVelocity;
float mass;
// local space inertia

View file

@ -281,7 +281,7 @@ static bool b3PairQueryCallback( int proxyId, uint64_t userData, void* context )
}
// Custom user filter
if ( shapeA->enableCustomFiltering || shapeB->enableCustomFiltering )
if ( ( shapeA->flags & b3_enableCustomFiltering ) || ( shapeB->flags & b3_enableCustomFiltering ) )
{
b3CustomFilterFcn* customFilterFcn = queryContext->world->customFilterFcn;
if ( customFilterFcn != NULL )

View file

@ -243,7 +243,7 @@ void b3CreateContact( b3World* world, b3Shape* shapeA, b3Shape* shapeB, int chil
B3_ASSERT( shapeA->sensorIndex == B3_NULL_INDEX && shapeB->sensorIndex == B3_NULL_INDEX );
if ( shapeA->enableContactEvents || shapeB->enableContactEvents )
if ( ( shapeA->flags & b3_enableContactEvents ) || ( shapeB->flags & b3_enableContactEvents ) )
{
contact->flags |= b3_contactEnableContactEvents;
}
@ -317,7 +317,7 @@ void b3CreateContact( b3World* world, b3Shape* shapeA, b3Shape* shapeB, int chil
b3MaxFloat( b3GetShapeMaterials( shapeA )[0].rollingResistance, b3GetShapeMaterials( shapeB )[0].rollingResistance ) *
maxRadius;
if ( shapeA->enablePreSolveEvents || shapeB->enablePreSolveEvents )
if ( ( shapeA->flags & b3_enablePreSolveEvents ) || ( shapeB->flags & b3_enablePreSolveEvents ) )
{
contact->flags |= b3_simEnablePreSolveEvents;
}
@ -707,7 +707,7 @@ static bool b3UpdateConvexContact( b3World* world, int workerIndex, b3Contact* c
}
}
if ( shapeA->enableHitEvents || shapeB->enableHitEvents )
if ( ( shapeA->flags & b3_enableHitEvents ) || ( shapeB->flags & b3_enableHitEvents ) )
{
contact->flags |= b3_simEnableHitEvent;
}
@ -721,8 +721,9 @@ static bool b3UpdateConvexContact( b3World* world, int workerIndex, b3Contact* c
// Update the contact manifold and touching status.
// Note: do not assume the shape AABBs are overlapping or are valid.
bool b3UpdateContact( b3World* world, int workerIndex, b3Contact* contact, b3Shape* shapeA, b3Vec3 localCenterA, b3WorldTransform xfA,
b3Shape* shapeB, b3Vec3 localCenterB, b3WorldTransform xfB, bool isFast, b3Arena arena )
bool b3UpdateContact( b3World* world, int workerIndex, b3Contact* contact, b3Shape* shapeA, b3Vec3 localCenterA,
b3WorldTransform xfA, b3Shape* shapeB, b3Vec3 localCenterB, b3WorldTransform xfB, bool isFast,
b3Arena arena )
{
bool touching;
@ -769,7 +770,7 @@ bool b3UpdateContact( b3World* world, int workerIndex, b3Contact* contact, b3Sha
touching = b3ComputeMeshManifolds( world, workerIndex, contact, &childShapeA, child.materialIndices, xfChild, shapeB,
xfB, isFast, arena );
if ( touching && ( shapeA->enableHitEvents || shapeB->enableHitEvents ) )
if ( touching && ( ( shapeA->flags & b3_enableHitEvents ) || ( shapeB->flags & b3_enableHitEvents ) ) )
{
contact->flags |= b3_simEnableHitEvent;
}
@ -821,7 +822,7 @@ bool b3UpdateContact( b3World* world, int workerIndex, b3Contact* contact, b3Sha
// Compute mesh manifolds
touching = b3ComputeMeshManifolds( world, workerIndex, contact, shapeA, NULL, xfA, shapeB, xfB, isFast, arena );
if ( touching && ( shapeA->enableHitEvents || shapeB->enableHitEvents ) )
if ( touching && ( ( shapeA->flags & b3_enableHitEvents ) || ( shapeB->flags & b3_enableHitEvents ) ) )
{
contact->flags |= b3_simEnableHitEvent;
}

View file

@ -295,6 +295,25 @@ int b3FetchAddMeshDumpIndex( void )
return result;
}
void b3StrCpy(char* dst, int size, const char* src)
{
B3_ASSERT( size > 0 );
if ( src != NULL )
{
#if defined( _MSC_VER )
strncpy_s( dst, size, src, size - 1 );
#else
strncpy( dst, src, size - 1 );
dst[size - 1] = 0;
#endif
}
else
{
memset( dst, 0, size );
}
}
void b3WriteBinaryFile( void* data, int size, const char* fileName )
{
if ( data == NULL || size <= 0 || fileName == NULL )

View file

@ -160,3 +160,5 @@ void b3OpenDump( const char* fileName );
void b3Dump( const char* string, ... );
void b3CloseDump( void );
int b3FetchAddMeshDumpIndex( void );
void b3StrCpy( char* dst, int size, const char* src );

View file

@ -203,14 +203,16 @@ static inline b3Quat b3QuatFromExponentialMap( b3Vec3 v )
/// q2 = q1 + 0.5 * omega * q1
static inline b3Quat b3IntegrateRotation( b3Quat q1, b3Vec3 deltaRotation )
{
#if 1
// https://fgiesen.wordpress.com/2012/08/24/quaternion-differentiation/
b3Quat qd = { b3MulSV( 0.5f, deltaRotation ), 0.0f };
qd = b3MulQuat( qd, q1 );
b3Quat q2 = { b3Add( q1.v, qd.v ), qd.s + q1.s };
q2 = b3NormalizeQuat( q2 );
return q2;
// return b3NormalizeQuat( b3MulQuat(b3QuatFromExponentialMap( deltaRotation ), q1) );
#else
return b3NormalizeQuat( b3MulQuat(b3QuatFromExponentialMap( deltaRotation ), q1) );
#endif
}
// Pseudo angular velocity from a quaternion target

View file

@ -3,8 +3,6 @@
#include "physics_world.h"
#include "recording.h"
#include "arena_allocator.h"
#include "bitset.h"
#include "body.h"
@ -18,6 +16,7 @@
#include "joint.h"
#include "parallel_for.h"
#include "platform.h"
#include "recording.h"
#include "scheduler.h"
#include "sensor.h"
#include "shape.h"
@ -1173,7 +1172,7 @@ void b3World_Step( b3WorldId worldId, float timeStep, int subStepCount )
// Fold this step's world bounds into the recording so a viewer can frame the whole motion.
b3AABB worldBounds = { 0 };
bool haveBounds = false;
bool haveBounds = false;
for ( int i = 0; i < b3_bodyTypeCount; ++i )
{
b3DynamicTree* tree = world->broadPhase.trees + i;
@ -1182,8 +1181,8 @@ void b3World_Step( b3WorldId worldId, float timeStep, int subStepCount )
continue;
}
b3AABB bounds = b3DynamicTree_GetRootBounds( tree );
worldBounds = haveBounds ? b3AABB_Union( worldBounds, bounds ) : bounds;
haveBounds = true;
worldBounds = haveBounds ? b3AABB_Union( worldBounds, bounds ) : bounds;
haveBounds = true;
}
if ( haveBounds )
{
@ -1435,6 +1434,34 @@ void b3World_Draw( b3WorldId worldId, b3DebugDraw* draw, uint64_t maskBits )
draw->DrawStringFcn( p, buffer, b3_colorWhite, draw->context );
}
if ( draw->drawSleep )
{
b3BodyState* bodyState = b3GetBodyState( world, body );
if ( bodyState != NULL )
{
b3HexColor colors[4] = { b3_colorBlue, b3_colorSkyBlue, b3_colorOrange, b3_colorRed };
b3HexColor color = b3_colorBlack;
if ( body->sleepThreshold > 0.0f )
{
float ratio = body->sleepVelocity / body->sleepThreshold;
int index = b3ClampInt( (int)ratio, 0, 3 );
color = colors[index];
}
b3Pos center = bodySim->center;
draw->DrawPointFcn( center, 10.0f, color, draw->context );
b3Vec3 offset = { 0.1f, 0.1f, 0.1f };
b3Pos p = b3OffsetPos( center, offset );
char buffer[32];
snprintf( buffer, 32, " %.3f", body->sleepVelocity );
draw->DrawStringFcn( p, buffer, color, draw->context );
}
}
if ( draw->drawJoints )
{
int jointKey = body->headJointKey;
@ -1571,7 +1598,7 @@ 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) );
p1 = b3OffsetPos( p1, b3MulSV( 0.05f * lengthScale, normal ) );
char buffer[32];
snprintf( buffer, B3_ARRAY_COUNT( buffer ), "%.2f", b3Length( frictionForce ) );
draw->DrawStringFcn( p1, buffer, b3_colorWhite, draw->context );

View file

@ -289,7 +289,7 @@ void b3RecW_LOCKS( b3RecBuffer* buf, b3MotionLocks v )
b3RecW_BOOL( buf, v.angularZ );
}
void b3RecW_STR( b3RecBuffer* buf, const char* s )
static void b3RecW_STR( b3RecBuffer* buf, const char* s )
{
if ( s == NULL )
{
@ -308,6 +308,16 @@ void b3RecW_STR( b3RecBuffer* buf, const char* s )
}
}
void b3RecW_BODYSTR( b3RecBuffer* buf, const char* s )
{
b3RecW_STR( buf, s );
}
void b3RecW_SHAPESTR( b3RecBuffer* buf, const char* s )
{
b3RecW_STR( buf, s );
}
// Hand-written def helpers. Zero pointer and cookie fields before serializing.
// Readers call b3Default*Def() first to get the cookie, then overwrite fields.
@ -319,7 +329,7 @@ _Static_assert( sizeof( void* ) != 8 || sizeof( b3ExplosionDef ) == 32 || sizeof
"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 ) == 112,
_Static_assert( sizeof( void* ) != 8 || sizeof( b3ShapeDef ) == 120,
"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" );
@ -375,6 +385,8 @@ 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.

View file

@ -45,9 +45,12 @@ typedef struct b3World b3World;
// Magic 'B3RC' in little-endian: bytes B(0x42) 3(0x33) R(0x52) C(0x43)
#define B3_REC_MAGIC 0x43523342u
// Minor tracks op-stream additions that keep the 48 byte header shape (e.g. the spatial query ops).
// 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
// Major recording version is bumped when writers change.
// Major version 3 added shape names
#define B3_REC_VERSION_MAJOR 3
// Minor tracks op-stream additions that keep the 48 byte header shape.
// Minor version 2 added the QueryTag op and the interned query-tag table at the tail of the registry block.
#define B3_REC_VERSION_MINOR 2
// File header, fixed 48 bytes, little-endian. Contains the registry locator so the player
@ -170,7 +173,8 @@ typedef b3Filter b3RecCType_FILTER;
typedef b3SurfaceMaterial b3RecCType_MATERIAL;
typedef b3MassData b3RecCType_MASSDATA;
typedef b3MotionLocks b3RecCType_LOCKS;
typedef const char* b3RecCType_STR;
typedef const char* b3RecCType_BODYSTR;
typedef const char* b3RecCType_SHAPESTR;
typedef b3WorldId b3RecCType_WORLDID;
typedef b3BodyId b3RecCType_BODYID;
typedef b3ShapeId b3RecCType_SHAPEID;
@ -245,7 +249,8 @@ void b3RecW_FILTER( b3RecBuffer* buf, b3Filter v );
void b3RecW_MATERIAL( b3RecBuffer* buf, b3SurfaceMaterial v );
void b3RecW_MASSDATA( b3RecBuffer* buf, b3MassData v );
void b3RecW_LOCKS( b3RecBuffer* buf, b3MotionLocks v );
void b3RecW_STR( b3RecBuffer* buf, const char* s );
void b3RecW_BODYSTR( b3RecBuffer* buf, const char* s );
void b3RecW_SHAPESTR( b3RecBuffer* buf, const char* s );
void b3RecW_EXPLOSIONDEF( b3RecBuffer* buf, b3ExplosionDef v );
void b3RecW_BODYDEF( b3RecBuffer* buf, b3BodyDef v );
void b3RecW_SHAPEDEF( b3RecBuffer* buf, b3ShapeDef v );

View file

@ -45,7 +45,7 @@ B3_REC_OP( 0x11, DestroyBody, RET_NONE, ARG( BODYID, body ) )
B3_REC_OP( 0x20, BodySetTransform, RET_NONE, ARG( BODYID, body ) ARG( POSITION, position ) ARG( QUAT, rotation ) )
B3_REC_OP( 0x21, BodySetLinearVelocity, RET_NONE, ARG( BODYID, body ) ARG( VEC3, v ) )
B3_REC_OP( 0x22, BodySetType, RET_NONE, ARG( BODYID, body ) ARG( I32, type ) )
B3_REC_OP( 0x23, BodySetName, RET_NONE, ARG( BODYID, body ) ARG( STR, name ) )
B3_REC_OP( 0x23, BodySetName, RET_NONE, ARG( BODYID, body ) ARG( BODYSTR, name ) )
B3_REC_OP( 0x24, BodySetAngularVelocity, RET_NONE, ARG( BODYID, body ) ARG( VEC3, w ) )
B3_REC_OP( 0x25, BodySetTargetTransform, RET_NONE, ARG( BODYID, body ) ARG( WORLDXF, target ) ARG( F32, timeStep ) ARG( BOOL, wake ) )
B3_REC_OP( 0x26, BodyApplyForce, RET_NONE, ARG( BODYID, body ) ARG( VEC3, force ) ARG( POSITION, point ) ARG( BOOL, wake ) )
@ -92,6 +92,7 @@ B3_REC_OP( 0x59, ShapeSetSphere, RET_NONE, ARG( SHAPEID, shape ) ARG( SPHERE, sp
B3_REC_OP( 0x5A, ShapeSetCapsule, RET_NONE, ARG( SHAPEID, shape ) ARG( CAPSULE, capsule ) )
B3_REC_OP( 0x5B, ShapeApplyWind, RET_NONE,
ARG( SHAPEID, shape ) ARG( VEC3, wind ) ARG( F32, drag ) ARG( F32, lift ) ARG( F32, maxSpeed ) ARG( BOOL, wake ) )
B3_REC_OP( 0x5C, ShapeSetName, RET_NONE, ARG( SHAPEID, shape ) ARG( SHAPESTR, name ) )
// Joint create and destroy
B3_REC_OP( 0x90, CreateParallelJoint, RET_JOINTID, ARG( WORLDID, world ) ARG( PARALLELJOINTDEF, def ) )
@ -131,7 +132,7 @@ B3_REC_OP( 0xAB, DistanceJointEnableMotor, RET_NONE, ARG( JOINTID, joint ) ARG(
B3_REC_OP( 0xAC, DistanceJointSetMotorSpeed, RET_NONE, ARG( JOINTID, joint ) ARG( F32, motorSpeed ) )
B3_REC_OP( 0xAD, DistanceJointSetMaxMotorForce, RET_NONE, ARG( JOINTID, joint ) ARG( F32, force ) )
// Motor joint (3D: linear/angular velocities are vec3)
// Motor joint
B3_REC_OP( 0xAE, MotorJointSetLinearVelocity, RET_NONE, ARG( JOINTID, joint ) ARG( VEC3, velocity ) )
B3_REC_OP( 0xAF, MotorJointSetAngularVelocity, RET_NONE, ARG( JOINTID, joint ) ARG( VEC3, velocity ) )
B3_REC_OP( 0xB0, MotorJointSetMaxVelocityForce, RET_NONE, ARG( JOINTID, joint ) ARG( F32, maxForce ) )
@ -165,7 +166,7 @@ B3_REC_OP( 0xC7, RevoluteJointEnableMotor, RET_NONE, ARG( JOINTID, joint ) ARG(
B3_REC_OP( 0xC8, RevoluteJointSetMotorSpeed, RET_NONE, ARG( JOINTID, joint ) ARG( F32, motorSpeed ) )
B3_REC_OP( 0xC9, RevoluteJointSetMaxMotorTorque, RET_NONE, ARG( JOINTID, joint ) ARG( F32, torque ) )
// Spherical joint (3D-only)
// Spherical joint
B3_REC_OP( 0xCA, SphericalJointEnableConeLimit, RET_NONE, ARG( JOINTID, joint ) ARG( BOOL, enableLimit ) )
B3_REC_OP( 0xCB, SphericalJointSetConeLimit, RET_NONE, ARG( JOINTID, joint ) ARG( F32, angleRadians ) )
B3_REC_OP( 0xCC, SphericalJointEnableTwistLimit, RET_NONE, ARG( JOINTID, joint ) ARG( BOOL, enableLimit ) )
@ -184,7 +185,7 @@ B3_REC_OP( 0xD6, WeldJointSetLinearDampingRatio, RET_NONE, ARG( JOINTID, joint )
B3_REC_OP( 0xD7, WeldJointSetAngularHertz, RET_NONE, ARG( JOINTID, joint ) ARG( F32, hertz ) )
B3_REC_OP( 0xD8, WeldJointSetAngularDampingRatio, RET_NONE, ARG( JOINTID, joint ) ARG( F32, dampingRatio ) )
// Wheel joint (Box3D uses Suspension/Spin/Steering naming)
// Wheel joint
B3_REC_OP( 0xD9, WheelJointEnableSuspension, RET_NONE, ARG( JOINTID, joint ) ARG( BOOL, flag ) )
B3_REC_OP( 0xDA, WheelJointSetSuspensionHertz, RET_NONE, ARG( JOINTID, joint ) ARG( F32, hertz ) )
B3_REC_OP( 0xDB, WheelJointSetSuspensionDampingRatio, RET_NONE, ARG( JOINTID, joint ) ARG( F32, dampingRatio ) )
@ -193,8 +194,7 @@ B3_REC_OP( 0xDD, WheelJointSetSuspensionLimits, RET_NONE, ARG( JOINTID, joint )
B3_REC_OP( 0xDE, WheelJointEnableSpinMotor, RET_NONE, ARG( JOINTID, joint ) ARG( BOOL, flag ) )
B3_REC_OP( 0xDF, WheelJointSetSpinMotorSpeed, RET_NONE, ARG( JOINTID, joint ) ARG( F32, speed ) )
// Wheel joint continued, overflow past the 0xDF range. Opcodes are arbitrary and need not match
// Box2D, so the wheel ops keep 0xE0-0xE7 and queries follow at 0xE8.
// Wheel joint continued, overflow past the 0xDF range.
B3_REC_OP( 0xE0, WheelJointSetMaxSpinTorque, RET_NONE, ARG( JOINTID, joint ) ARG( F32, torque ) )
B3_REC_OP( 0xE1, WheelJointEnableSteering, RET_NONE, ARG( JOINTID, joint ) ARG( BOOL, flag ) )
B3_REC_OP( 0xE2, WheelJointSetSteeringHertz, RET_NONE, ARG( JOINTID, joint ) ARG( F32, hertz ) )
@ -205,9 +205,7 @@ B3_REC_OP( 0xE6, WheelJointSetSteeringLimits, RET_NONE, ARG( JOINTID, joint ) AR
B3_REC_OP( 0xE7, WheelJointSetTargetSteeringAngle, RET_NONE, ARG( JOINTID, joint ) ARG( F32, radians ) )
// Spatial queries. Inputs flow through the manifest (reader side). The hit tail and result are
// hand-written in recording.c / recording_replay.c since they are variable length. Query geometry is
// relative to the origin so a recording reproduces queries far from the world origin. OverlapAABB has
// no origin in 3D: the box is already world space.
// hand-written in recording.c / recording_replay.c since they are variable length.
B3_REC_OP( 0xE8, QueryOverlapAABB, RET_NONE, ARG( WORLDID, world ) ARG( AABB, aabb ) ARG( QUERYFILTER, filter ) )
B3_REC_OP( 0xE9, QueryOverlapShape, RET_NONE,
ARG( WORLDID, world ) ARG( POSITION, origin ) ARG( SHAPEPROXY, proxy ) ARG( QUERYFILTER, filter ) )
@ -230,5 +228,5 @@ 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.
// Accumulated world bounds over the whole recording, written once at stop.
B3_REC_OP( 0xF2, RecordingBounds, RET_NONE, ARG( AABB, bounds ) )

View file

@ -373,10 +373,10 @@ b3MotionLocks b3RecR_LOCKS( b3RecReader* rdr )
}
// Rotating set of static string buffers, valid until the next 4 STR reads.
const char* b3RecR_STR( b3RecReader* rdr )
const char* b3RecR_BODYSTR( b3RecReader* rdr )
{
char* buf = rdr->strBufs[rdr->strNext];
rdr->strNext = ( rdr->strNext + 1 ) & 3;
char* buf = rdr->bodyStrBufs[rdr->bodyStrNext];
rdr->bodyStrNext = ( rdr->bodyStrNext + 1 ) & 3;
uint16_t len = b3RecR_U16( rdr );
if ( len == 0xFFFFu )
@ -399,6 +399,32 @@ const char* b3RecR_STR( b3RecReader* rdr )
return buf;
}
const char* b3RecR_SHAPESTR( b3RecReader* rdr )
{
char* buf = rdr->shapeStrBufs[rdr->shapeStrNext];
rdr->shapeStrNext = ( rdr->shapeStrNext + 1 ) & 3;
uint16_t len = b3RecR_U16( rdr );
if ( len == 0xFFFFu )
{
return NULL;
}
int n = (int)len;
if ( n > B3_SHAPE_NAME_LENGTH )
{
n = B3_SHAPE_NAME_LENGTH;
}
b3RecRdrCheck( rdr, (int)len );
if ( rdr->ok && n > 0 )
{
memcpy( buf, rdr->data + rdr->cursor, (size_t)n );
}
rdr->cursor += (int)len;
buf[n] = '\0';
return buf;
}
// Def readers: start from b3Default*Def() then overlay each serialized field
// in the exact order the writer produced them.
@ -425,7 +451,7 @@ b3BodyDef b3RecR_BODYDEF( b3RecReader* rdr )
def.angularDamping = b3RecR_F32( rdr );
def.gravityScale = b3RecR_F32( rdr );
def.sleepThreshold = b3RecR_F32( rdr );
def.name = b3RecR_STR( rdr );
def.name = b3RecR_BODYSTR( rdr );
(void)b3RecR_U64( rdr ); // userData placeholder
def.motionLocks = b3RecR_LOCKS( rdr );
def.enableSleep = b3RecR_BOOL( rdr );
@ -441,6 +467,8 @@ b3BodyDef b3RecR_BODYDEF( b3RecReader* rdr )
b3ShapeDef b3RecR_SHAPEDEF( b3RecReader* rdr )
{
b3ShapeDef def = b3DefaultShapeDef();
def.name = b3RecR_SHAPESTR( rdr );
(void)b3RecR_U64( rdr ); // userData placeholder
int matCount = b3RecR_I32( rdr );
@ -1076,6 +1104,11 @@ static void b3RecDispatch_DestroyShape( const b3RecArgs_DestroyShape* a, b3RecRe
b3DestroyShape( b3RecMakeShapeId( rdr, a->shape ), a->updateBodyMass );
}
static void b3RecDispatch_ShapeSetName( const b3RecArgs_ShapeSetName* a, b3RecReader* rdr )
{
b3Shape_SetName( b3RecMakeShapeId( rdr, a->shape ), a->name );
}
static void b3RecDispatch_ShapeSetDensity( const b3RecArgs_ShapeSetDensity* a, b3RecReader* rdr )
{
b3Shape_SetDensity( b3RecMakeShapeId( rdr, a->shape ), a->density, a->updateBodyMass );

View file

@ -91,8 +91,11 @@ typedef struct b3RecReader
int matScratchCap;
// Scratch for string reads: rotating slots, valid until the next 4 STR reads
char strBufs[4][B3_BODY_NAME_LENGTH + 1];
int strNext;
char bodyStrBufs[4][B3_BODY_NAME_LENGTH + 1];
int bodyStrNext;
char shapeStrBufs[4][B3_SHAPE_NAME_LENGTH + 1];
int shapeStrNext;
// Preloaded geometry registry
b3RegistrySlot* slots;
@ -230,7 +233,8 @@ 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 );
const char* b3RecR_BODYSTR( b3RecReader* rdr );
const char* b3RecR_SHAPESTR( b3RecReader* rdr );
b3ExplosionDef b3RecR_EXPLOSIONDEF( b3RecReader* rdr );
b3BodyDef b3RecR_BODYDEF( b3RecReader* rdr );
b3ShapeDef b3RecR_SHAPEDEF( b3RecReader* rdr );

View file

@ -53,7 +53,7 @@ static bool b3OverlapSensor( b3Shape* sensorShape, b3Transform sensorTransform,
return b3OverlapCapsule( &sensorShape->capsule, b3Transform_identity, &localProxy );
case b3_compoundShape:
return b3OverlapCompound( sensorShape->compound , b3Transform_identity, &localProxy );
return b3OverlapCompound( sensorShape->compound, b3Transform_identity, &localProxy );
case b3_heightShape:
return b3OverlapHeightField( sensorShape->heightField, b3Transform_identity, &localProxy );
@ -115,7 +115,7 @@ static bool b3SensorQueryCallback( int proxyId, uint64_t userData, void* context
}
// Are sensor events enabled on the other shape?
if ( otherShape->enableSensorEvents == false )
if ( ( otherShape->flags & b3_enableSensorEvents ) == 0 )
{
return true;
}
@ -133,7 +133,7 @@ static bool b3SensorQueryCallback( int proxyId, uint64_t userData, void* context
}
// Custom user filter
if ( sensorShape->enableCustomFiltering || otherShape->enableCustomFiltering )
if ( ( sensorShape->flags & b3_enableCustomFiltering ) || ( otherShape->flags & b3_enableCustomFiltering ) )
{
b3CustomFilterFcn* customFilterFcn = queryContext->world->customFilterFcn;
if ( customFilterFcn != NULL )
@ -207,7 +207,7 @@ static void b3SensorTask( int startIndex, int endIndex, int workerIndex, void* c
b3Array_Clear( sensor->hits );
b3Body* body = b3Array_Get( world->bodies, sensorShape->bodyId );
if ( body->setIndex == b3_disabledSet || sensorShape->enableSensorEvents == false )
if ( body->setIndex == b3_disabledSet || ( sensorShape->flags & b3_enableSensorEvents ) == 0 )
{
if ( sensor->overlaps1.count != 0 )
{

View file

@ -19,6 +19,8 @@
#include <inttypes.h>
#include <stdio.h>
_Static_assert( B3_SHAPE_NAME_LENGTH >= 0, "minimum name length" );
static b3Shape* b3GetShape( b3World* world, b3ShapeId shapeId )
{
int id = shapeId.index1 - 1;
@ -178,12 +180,12 @@ static b3Shape* b3CreateShapeInternal( b3World* world, b3Body* body, b3WorldTran
shape->filter = def->filter;
shape->userData = def->userData;
shape->userShape = NULL;
shape->enlargedAABB = false;
shape->enableSensorEvents = def->enableSensorEvents;
shape->enableContactEvents = def->enableContactEvents;
shape->enableCustomFiltering = def->enableCustomFiltering;
shape->enableHitEvents = def->enableHitEvents;
shape->enablePreSolveEvents = def->enablePreSolveEvents;
shape->flags = 0;
shape->flags |= def->enableSensorEvents ? b3_enableSensorEvents : 0;
shape->flags |= def->enableContactEvents ? b3_enableContactEvents : 0;
shape->flags |= def->enableCustomFiltering ? b3_enableCustomFiltering : 0;
shape->flags |= def->enableHitEvents ? b3_enableHitEvents : 0;
shape->flags |= def->enablePreSolveEvents ? b3_enablePreSolveEvents : 0;
shape->proxyKey = B3_NULL_INDEX;
shape->localCentroid = b3GetShapeCentroid( shape );
shape->aabbMargin = b3ComputeShapeMargin( shape );
@ -191,6 +193,8 @@ static b3Shape* b3CreateShapeInternal( b3World* world, b3Body* body, b3WorldTran
shape->fatAABB = (b3AABB){ b3Vec3_zero, b3Vec3_zero };
shape->generation += 1;
b3StrCpy( shape->name, B3_SHAPE_NAME_LENGTH + 1, def->name );
if ( shape->type == b3_compoundShape )
{
// Own a copy of the compound materials so every shape frees its array the same way. Compounds
@ -1133,6 +1137,23 @@ void* b3Shape_GetUserData( b3ShapeId shapeId )
return shape->userData;
}
void b3Shape_SetName( b3ShapeId shapeId, const char* name )
{
b3World* world = b3GetWorld( shapeId.world0 );
B3_REC( world, ShapeSetName, shapeId, name );
b3Shape* shape = b3GetShape( world, shapeId );
b3StrCpy( shape->name, B3_SHAPE_NAME_LENGTH + 1, name );
}
const char* b3Shape_GetName( b3ShapeId shapeId )
{
b3World* world = b3GetWorld( shapeId.world0 );
b3Shape* shape = b3GetShape( world, shapeId );
return shape->name;
}
bool b3Shape_IsSensor( b3ShapeId shapeId )
{
b3World* world = b3GetWorld( shapeId.world0 );
@ -1394,14 +1415,14 @@ void b3Shape_EnableSensorEvents( b3ShapeId shapeId, bool flag )
B3_REC( world, ShapeEnableSensorEvents, shapeId, flag );
b3Shape* shape = b3GetShape( world, shapeId );
shape->enableSensorEvents = flag;
shape->flags = flag ? shape->flags | b3_enableSensorEvents : shape->flags & ~b3_enableSensorEvents;
}
bool b3Shape_AreSensorEventsEnabled( b3ShapeId shapeId )
{
b3World* world = b3GetWorld( shapeId.world0 );
b3Shape* shape = b3GetShape( world, shapeId );
return shape->enableSensorEvents;
return shape->flags & b3_enableSensorEvents;
}
void b3Shape_EnableContactEvents( b3ShapeId shapeId, bool flag )
@ -1415,14 +1436,14 @@ void b3Shape_EnableContactEvents( b3ShapeId shapeId, bool flag )
B3_REC( world, ShapeEnableContactEvents, shapeId, flag );
b3Shape* shape = b3GetShape( world, shapeId );
shape->enableContactEvents = flag;
shape->flags = flag ? shape->flags | b3_enableContactEvents : shape->flags & ~b3_enableContactEvents;
}
bool b3Shape_AreContactEventsEnabled( b3ShapeId shapeId )
{
b3World* world = b3GetWorld( shapeId.world0 );
b3Shape* shape = b3GetShape( world, shapeId );
return shape->enableContactEvents;
return shape->flags & b3_enableContactEvents;
}
void b3Shape_EnablePreSolveEvents( b3ShapeId shapeId, bool flag )
@ -1436,14 +1457,14 @@ void b3Shape_EnablePreSolveEvents( b3ShapeId shapeId, bool flag )
B3_REC( world, ShapeEnablePreSolveEvents, shapeId, flag );
b3Shape* shape = b3GetShape( world, shapeId );
shape->enablePreSolveEvents = flag;
shape->flags = flag ? shape->flags | b3_enablePreSolveEvents : shape->flags & ~b3_enablePreSolveEvents;
}
bool b3Shape_ArePreSolveEventsEnabled( b3ShapeId shapeId )
{
b3World* world = b3GetWorld( shapeId.world0 );
b3Shape* shape = b3GetShape( world, shapeId );
return shape->enablePreSolveEvents;
return shape->flags & b3_enablePreSolveEvents;
}
void b3Shape_EnableHitEvents( b3ShapeId shapeId, bool flag )
@ -1457,14 +1478,14 @@ void b3Shape_EnableHitEvents( b3ShapeId shapeId, bool flag )
B3_REC( world, ShapeEnableHitEvents, shapeId, flag );
b3Shape* shape = b3GetShape( world, shapeId );
shape->enableHitEvents = flag;
shape->flags = flag ? shape->flags | b3_enableHitEvents : shape->flags & ~b3_enableHitEvents;
}
bool b3Shape_AreHitEventsEnabled( b3ShapeId shapeId )
{
b3World* world = b3GetWorld( shapeId.world0 );
b3Shape* shape = b3GetShape( world, shapeId );
return shape->enableHitEvents;
return shape->flags & b3_enableHitEvents;
}
b3ShapeType b3Shape_GetType( b3ShapeId shapeId )

View file

@ -12,6 +12,16 @@
typedef struct b3BroadPhase b3BroadPhase;
typedef struct b3World b3World;
typedef enum b3ShapeFlags
{
b3_enableSensorEvents = 0x01,
b3_enableContactEvents = 0x02,
b3_enableCustomFiltering = 0x04,
b3_enableHitEvents = 0x08,
b3_enablePreSolveEvents = 0x10,
b3_enlargedAABB = 0x20,
} b3ShapeFlags;
typedef struct b3Shape
{
int id;
@ -29,22 +39,14 @@ typedef struct b3Shape
b3AABB fatAABB;
b3Vec3 localCentroid;
b3SurfaceMaterial material;
int materialCount;
b3SurfaceMaterial material;
b3SurfaceMaterial* materials;
b3Filter filter;
void* userData;
void* userShape;
uint16_t generation;
bool enableSensorEvents;
bool enableContactEvents;
bool enableCustomFiltering;
bool enableHitEvents;
bool enablePreSolveEvents;
bool enlargedAABB;
union
{
b3Capsule capsule;
@ -55,6 +57,10 @@ typedef struct b3Shape
const b3CompoundData* compound;
};
uint16_t generation;
// b3ShapeFlags
uint8_t flags;
char name[B3_SHAPE_NAME_LENGTH + 1];
} b3Shape;
// A single material shape keeps its material inline. Multi material meshes and compounds own a heap

View file

@ -362,9 +362,9 @@ static bool b3ContinuousQueryCallback( int proxyId, uint64_t userData, void* con
return true;
}
// Skip sensors unless the shapes want sensor events
// Skip sensors unless both shapes want sensor events
bool isSensor = shape->sensorIndex != B3_NULL_INDEX;
if ( isSensor && ( shape->enableSensorEvents == false || fastShape->enableSensorEvents == false ) )
if ( isSensor && ( ( shape->flags & b3_enableSensorEvents ) == 0 || ( fastShape->flags & b3_enableSensorEvents ) == 0 ) )
{
return true;
}
@ -396,7 +396,7 @@ static bool b3ContinuousQueryCallback( int proxyId, uint64_t userData, void* con
}
// Custom user filtering
if ( shape->enableCustomFiltering || fastShape->enableCustomFiltering )
if ( ( shape->flags & b3_enableCustomFiltering ) != 0 || ( fastShape->flags & b3_enableCustomFiltering ) != 0 )
{
b3CustomFilterFcn* customFilterFcn = world->customFilterFcn;
if ( customFilterFcn != NULL )
@ -440,7 +440,7 @@ static bool b3ContinuousQueryCallback( int proxyId, uint64_t userData, void* con
{
bool didHit = true;
if ( didHit && ( shape->enablePreSolveEvents || fastShape->enablePreSolveEvents ) )
if ( didHit && ( ( shape->flags & b3_enablePreSolveEvents ) || ( fastShape->flags & b3_enablePreSolveEvents ) ) )
{
b3ShapeId shapeIdA = { shape->id + 1, world->worldId, shape->generation };
b3ShapeId shapeIdB = { fastShape->id + 1, world->worldId, fastShape->generation };
@ -585,7 +585,7 @@ 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->enlargedAABB = true;
shape->flags |= b3_enlargedAABB;
fastBodySim->flags |= b3_enlargeBounds;
}
@ -617,7 +617,7 @@ static void b3SolveContinuous( b3World* world, int bodySimIndex, b3TaskContext*
.upperBound = b3Add( shape->aabb.upperBound, aabbMargin ),
};
shape->enlargedAABB = true;
shape->flags |= b3_enlargedAABB;
fastBodySim->flags |= b3_enlargeBounds;
}
@ -724,6 +724,8 @@ static void b3FinalizeBodiesTask( int startIndex, int endIndex, int workerIndex,
// cache miss here, however I need the shape list below
b3Body* body = bodies + sim->bodyId;
body->bodyMoveIndex = simIndex;
body->sleepVelocity = sleepVelocity;
moveEvents[simIndex].userData = body->userData;
moveEvents[simIndex].transform = sim->transform;
moveEvents[simIndex].bodyId = (b3BodyId){ sim->bodyId + 1, worldId, body->generation };
@ -830,14 +832,14 @@ static void b3FinalizeBodiesTask( int startIndex, int endIndex, int workerIndex,
b3AABB aabb = b3ComputeFatShapeAABB( shape, transform, speculativeScalar );
shape->aabb = aabb;
B3_ASSERT( shape->enlargedAABB == false );
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->enlargedAABB = true;
shape->flags |= b3_enlargedAABB;
// Bit-set to keep the move array sorted
b3SetBit( enlargedSimBitSet, simIndex );
@ -2134,10 +2136,10 @@ void b3Solve( b3World* world, b3StepContext* stepContext )
// 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->enlargedAABB )
if ( shape->flags & b3_enlargedAABB )
{
b3BroadPhase_EnlargeProxy( broadPhase, shape->proxyKey, shape->fatAABB );
shape->enlargedAABB = false;
shape->flags &= ~b3_enlargedAABB;
}
shapeId = shape->nextShapeId;
@ -2199,14 +2201,14 @@ void b3Solve( b3World* world, b3StepContext* stepContext )
while ( shapeId != B3_NULL_INDEX )
{
b3Shape* shape = shapeArray + shapeId;
if ( shape->enlargedAABB == false )
if ( (shape->flags & b3_enlargedAABB) == 0 )
{
shapeId = shape->nextShapeId;
continue;
}
// clear flag
shape->enlargedAABB = false;
shape->flags &= ~b3_enlargedAABB;
int proxyKey = shape->proxyKey;
int proxyId = B3_PROXY_ID( proxyKey );

View file

@ -1053,6 +1053,8 @@ static int AllOps( void )
b3ShapeDef sphereShapeDef = b3DefaultShapeDef();
sphereShapeDef.density = 1.0f;
// Over-length shape name so replay exercises the clamp in the shape def reader, like the body above.
sphereShapeDef.name = "sphereNameThatExceedsTheLimit";
b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, 0.5f };
b3ShapeId sphereShapeId = b3CreateSphereShape( bodyId, &sphereShapeDef, &sphere );
ENSURE( b3Shape_IsValid( sphereShapeId ) );
@ -1159,7 +1161,7 @@ static int AllOps( void )
// Shape mutators: SetFriction, SetRestitution, SetDensity, SetSurfaceMaterial, SetFilter,
// EnableSensorEvents, EnableContactEvents, EnableHitEvents, EnablePreSolveEvents, ApplyWind,
// SetSphere, SetCapsule
// SetSphere, SetCapsule, SetName
b3Shape_SetFriction( boxShapeId, 0.3f );
b3Shape_SetRestitution( capsuleShapeId, 0.5f );
b3Shape_SetDensity( boxShapeId, 3.0f, true );
@ -1179,6 +1181,7 @@ static int AllOps( void )
b3Shape_SetSphere( sphereShapeId, &newSphere );
b3Capsule newCapsule = { { 0.0f, -0.3f, 0.0f }, { 0.0f, 0.3f, 0.0f }, 0.3f };
b3Shape_SetCapsule( capsuleShapeId, &newCapsule );
b3Shape_SetName( boxShapeId, "box" );
// Body mutators: SetTransform, SetLinearVelocity/AngularVelocity (Vec3), SetName,
// damping, gravity scale, sleep threshold, SetAwake, EnableSleep, SetBullet, SetMotionLocks,
@ -1849,9 +1852,97 @@ static int StagedStepCreationPose( void )
return 0;
}
// Shape names are debug only and do not feed the determinism hash, so b3ValidateReplay cannot catch a
// broken name round-trip. Replay through the player and read the names back to prove the def field and
// the ShapeSetName op survive serialization. Holds for any B3_SHAPE_NAME_LENGTH, including 0.
static int ShapeNameReplay( void )
{
// Replay must reproduce exactly what the shape stores: its source truncated to B3_SHAPE_NAME_LENGTH.
// Asserting the shape cap rather than the body cap also traps the shared string reader, which clamps
// to the body length, from silently shortening shape names if the two caps ever cross.
const char* names[3] = {
"def", // carried on the shape def, survives whole
"set", // applied after create through the setter op
"abcdefghijklmnopqrstuvwxyz", // over-length, forces the clamp
};
b3Recording* rec = b3CreateRecording( 0 );
ENSURE( rec != NULL );
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
b3World_StartRecording( worldId, rec );
b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, 0.5f };
// One shape per body so read-back never depends on per-body shape ordering.
for ( int i = 0; i < 3; ++i )
{
b3BodyDef bd = b3DefaultBodyDef();
bd.type = b3_dynamicBody;
bd.position = (b3Pos){ 3.0f * (float)i, 5.0f, 0.0f };
b3BodyId body = b3CreateBody( worldId, &bd );
b3ShapeDef sd = b3DefaultShapeDef();
sd.density = 1.0f;
if ( i != 1 )
{
sd.name = names[i];
}
b3ShapeId shape = b3CreateSphereShape( body, &sd, &sphere );
if ( i == 1 )
{
b3Shape_SetName( shape, names[i] );
}
}
for ( int i = 0; i < 4; ++i )
{
b3World_Step( worldId, 1.0f / 60.0f, 4 );
}
b3World_StopRecording( worldId );
b3DestroyWorld( worldId );
const uint8_t* data = b3Recording_GetData( rec );
int sz = b3Recording_GetSize( rec );
b3RecPlayer* player = b3RecPlayer_Create( data, sz, 1 );
ENSURE( player != NULL );
while ( b3RecPlayer_StepFrame( player ) )
{
}
ENSURE( b3RecPlayer_HasDiverged( player ) == false );
// Body ordinals follow creation order in the replayed world.
for ( int i = 0; i < 3; ++i )
{
b3BodyId body = b3RecPlayer_GetBodyId( player, i );
ENSURE( b3Body_IsValid( body ) );
b3ShapeId shape;
ENSURE( b3Body_GetShapes( body, &shape, 1 ) == 1 );
const char* got = b3Shape_GetName( shape );
ENSURE( got != NULL );
int srcLen = (int)strlen( names[i] );
int expectLen = srcLen < B3_SHAPE_NAME_LENGTH ? srcLen : B3_SHAPE_NAME_LENGTH;
ENSURE( (int)strlen( got ) == expectLen );
if ( expectLen > 0 )
{
ENSURE( strncmp( got, names[i], (size_t)expectLen ) == 0 );
}
}
b3RecPlayer_Destroy( player );
b3DestroyRecording( rec );
return 0;
}
int RecordingTest( void )
{
RUN_SUBTEST( GeometryHashCollision );
RUN_SUBTEST( ShapeNameReplay );
RUN_SUBTEST( SphereRoundTrip );
RUN_SUBTEST( EmptyWorldRoundTrip );
RUN_SUBTEST( HullDedup );

View file

@ -3,11 +3,13 @@
#include "test_macros.h"
#include "box3d/box3d.h"
#include "box3d/collision.h"
#include "box3d/math_functions.h"
#include <float.h>
#include <math.h>
#include <string.h>
static b3Capsule capsule = { { -1.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f }, 1.0f };
static b3Sphere sphere = { { 1.0f, 0.0f, 0.0f }, 1.0f };
@ -852,12 +854,130 @@ static int RayCastShapeTest( void )
return 0;
}
// The shape stores its name inline, capped at B3_SHAPE_NAME_LENGTH with a reserved null. The stored value
// is the source truncated to the cap, so derive the expectation from the cap and stay valid at any length.
static int CheckShapeName( b3ShapeId shapeId, const char* expected )
{
const char* got = b3Shape_GetName( shapeId );
ENSURE( got != NULL );
int srcLen = expected != NULL ? (int)strlen( expected ) : 0;
int expectLen = srcLen < B3_SHAPE_NAME_LENGTH ? srcLen : B3_SHAPE_NAME_LENGTH;
ENSURE( (int)strlen( got ) == expectLen );
if ( expectLen > 0 )
{
ENSURE( strncmp( got, expected, (size_t)expectLen ) == 0 );
}
return 0;
}
// Cover the def path, the setter, over-length truncation, and the NULL clear. A zero cap collapses every
// case to the empty string, which the length-derived check handles without a special branch.
static int ShapeNameTest( void )
{
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
b3Sphere s = { { 0.0f, 0.0f, 0.0f }, 0.5f };
// Default def leaves the name empty.
b3ShapeDef shapeDef = b3DefaultShapeDef();
shapeDef.density = 1.0f;
b3ShapeId shapeId = b3CreateSphereShape( bodyId, &shapeDef, &s );
if ( CheckShapeName( shapeId, "" ) )
return 1;
// Name carried on the def.
shapeDef.name = "box";
b3ShapeId namedId = b3CreateSphereShape( bodyId, &shapeDef, &s );
if ( CheckShapeName( namedId, "box" ) )
return 1;
// Setter overwrites.
b3Shape_SetName( shapeId, "wheel" );
if ( CheckShapeName( shapeId, "wheel" ) )
return 1;
// Over-length name truncates to the cap.
b3Shape_SetName( shapeId, "abcdefghijklmnopqrstuvwxyz" );
if ( CheckShapeName( shapeId, "abcdefghijklmnopqrstuvwxyz" ) )
return 1;
// NULL clears the name.
b3Shape_SetName( shapeId, NULL );
if ( CheckShapeName( shapeId, "" ) )
return 1;
b3DestroyWorld( worldId );
return 0;
}
// The event enables moved from separate bools to a shared bit field. Each accessor must touch only its own
// bit, so start with all set and flip them one at a time, checking the rest hold.
static int ShapeFlagsTest( void )
{
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
b3Sphere s = { { 0.0f, 0.0f, 0.0f }, 0.5f };
b3ShapeDef shapeDef = b3DefaultShapeDef();
shapeDef.density = 1.0f;
shapeDef.enableSensorEvents = true;
shapeDef.enableContactEvents = true;
shapeDef.enableHitEvents = true;
shapeDef.enablePreSolveEvents = true;
b3ShapeId shapeId = b3CreateSphereShape( bodyId, &shapeDef, &s );
// The def carries every enable through to the shape.
ENSURE( b3Shape_AreSensorEventsEnabled( shapeId ) );
ENSURE( b3Shape_AreContactEventsEnabled( shapeId ) );
ENSURE( b3Shape_AreHitEventsEnabled( shapeId ) );
ENSURE( b3Shape_ArePreSolveEventsEnabled( shapeId ) );
// Clearing one leaves the rest set.
b3Shape_EnableSensorEvents( shapeId, false );
ENSURE( b3Shape_AreSensorEventsEnabled( shapeId ) == false );
ENSURE( b3Shape_AreContactEventsEnabled( shapeId ) );
ENSURE( b3Shape_AreHitEventsEnabled( shapeId ) );
ENSURE( b3Shape_ArePreSolveEventsEnabled( shapeId ) );
// Setting it back does not disturb the others.
b3Shape_EnableSensorEvents( shapeId, true );
b3Shape_EnableHitEvents( shapeId, false );
ENSURE( b3Shape_AreSensorEventsEnabled( shapeId ) );
ENSURE( b3Shape_AreContactEventsEnabled( shapeId ) );
ENSURE( b3Shape_AreHitEventsEnabled( shapeId ) == false );
ENSURE( b3Shape_ArePreSolveEventsEnabled( shapeId ) );
// Clear two more and confirm only the remaining bit stays set.
b3Shape_EnableContactEvents( shapeId, false );
b3Shape_EnablePreSolveEvents( shapeId, false );
ENSURE( b3Shape_AreSensorEventsEnabled( shapeId ) );
ENSURE( b3Shape_AreContactEventsEnabled( shapeId ) == false );
ENSURE( b3Shape_AreHitEventsEnabled( shapeId ) == false );
ENSURE( b3Shape_ArePreSolveEventsEnabled( shapeId ) == false );
b3DestroyWorld( worldId );
return 0;
}
int ShapeTest( void )
{
box = b3MakeBoxHull( 1.0f, 1.0f, 1.0f );
RUN_SUBTEST( ShapeMassTest );
RUN_SUBTEST( ShapeAABBTest );
RUN_SUBTEST( ShapeNameTest );
RUN_SUBTEST( ShapeFlagsTest );
// RUN_SUBTEST( PointInShapeTest );
RUN_SUBTEST( RayCastShapeTest );