Recording and replay system for Box3D. Ported from Box2D.

b3HeightField is now b3HeightFieldData and is a blob.
This commit is contained in:
Erin Catto 2026-06-20 23:35:04 -07:00 • committed by GitHub
commit 5c9b516486
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
56 changed files with 10837 additions and 448 deletions

1
.gitignore vendored
View file

@ -12,3 +12,4 @@ CMakeUserPresets.json
.tmp/
.fetchcontent-cache/
build-dp/
*.b3rec

View file

@ -196,7 +196,7 @@ def.scale = (b3Vec3){1.0f, 1.0f, 1.0f};
def.globalMinimumHeight = -10.0f;
def.globalMaximumHeight = 50.0f;
b3HeightField* hf = b3CreateHeightField(&def);
b3HeightFieldData* hf = b3CreateHeightField(&def);
b3ShapeId id = b3CreateHeightFieldShape(bodyId, &shapeDef, hf);
```

View file

@ -1,14 +1,211 @@
# Recording and Replay
# Recording and Replay {#recording}
Deterministic recording, replay, and world snapshots are planned features for Box3D but are not yet
available. Box3D's sister engine Box2D ships a full recording and snapshot API; a 3D equivalent
will follow once the simulation format stabilizes.
Box3D can record a simulation into a memory buffer and replay it later, reproducing the original
run exactly. A recording is a snapshot of the world at the moment recording starts followed by a
log of every world-mutating API call after that. Replaying it re-runs the engine from the
snapshot over those same calls, so the bodies follow the same paths and end up in the same state.
In the meantime:
The main use is for debugging. You can record a session, save the buffer to a file, then load it
in the sample app and view the Box3D state as the simulation progresses.
- Box3D is deterministic given the same inputs and the same build. See the **Determinism** section
of the Simulation page for details on what "same inputs" means across platforms and thread counts.
- There is no API to serialize or restore a world state in the current release.
- There is no replay viewer in the current samples application.
You own the recording buffer. Box3D records into it and grows it as needed; you save it to disk
and free it. The library does no file I/O of its own for recording, beyond two optional
convenience helpers (`b3SaveRecordingToFile` / `b3LoadRecordingFromFile`).
Check the [Box3D repository](https://github.com/erincatto/box3d) for updates on this feature.
A recording can start before the first step, capturing the whole session, or mid-session for the
"a bug appeared after 30 seconds and only then did I turn recording on" case. Either way the
buffer opens with a snapshot of the world as it stands when recording starts, so there is one
code path for both.
A recording is self-contained. Shape geometry that cannot ride along as plain data, hulls,
meshes, heightfields, and compounds, is interned once into a registry stored in the recording, so
the file carries everything needed to rebuild the world. No external mesh assets are required to
replay.
## Recording
Create a recording buffer, start recording the world into it, then run the simulation as usual.
Start before the first step to capture everything.
```c
b3WorldId worldId = b3CreateWorld( &worldDef );
b3Recording* recording = b3CreateRecording( 0 ); // 0 = default capacity (64 KiB)
b3World_StartRecording( worldId, recording ); // snapshots the world, then logs calls
// ... create bodies, step the world as usual ...
b3World_StopRecording( worldId );
```
`b3CreateRecording` takes a byte capacity to pre-size the buffer. The buffer still grows on
demand, so any value is safe; pre-sizing just avoids reallocations during a long session. Pass
`0` for the default.
`b3World_StartRecording` must be called at a step boundary. It serializes a snapshot of the
current world as the seed, so it works whether you call it before any bodies exist or deep into
a running simulation. It has no effect if the world is already recording. The buffer is reset on
each call, so a single `b3Recording` can be reused for several sessions.
When you are done, save the buffer and free it. File I/O is yours to do; the convenience helper
writes the raw bytes:
```c
b3SaveRecordingToFile( recording, "session.b3rec" ); // or fwrite the bytes yourself:
// const uint8_t* data = b3Recording_GetData( recording );
// int size = b3Recording_GetSize( recording );
b3DestroyRecording( recording );
```
Stopping is optional: `b3DestroyWorld` detaches an active recording for you. The recording buffer
outlives the world, so you can still save it after the world is gone. You can also keep
simulating after `b3World_StopRecording` without recording, and reuse the same handle for a fresh
recording with another `b3World_StartRecording`.
## Replay
The simplest way to check a recording is the headless validator. It re-runs the engine over the
recorded bytes and confirms every recorded id and per-step state reproduces.
```c
const uint8_t* data = b3Recording_GetData( recording );
int size = b3Recording_GetSize( recording );
bool ok = b3ValidateReplay( data, size, 1 );
// ok == false means replay diverged from the recording.
```
`b3ValidateReplay` runs the replay on a single worker; pass `1` for the `workerCount`. To exercise
multi-worker replay, use the player and `b3RecPlayer_SetWorkerCount` (see below).
To replay a recording from disk, load it into a buffer first:
```c
b3Recording* loaded = b3LoadRecordingFromFile( "session.b3rec" );
bool ok = b3ValidateReplay( b3Recording_GetData( loaded ), b3Recording_GetSize( loaded ), 1 );
b3DestroyRecording( loaded );
```
For stepping through a recording frame by frame, for example to drive a viewer or inspect the
world between steps, use the player handle. The player copies the bytes it is given, so you can
free the source buffer immediately after creating it.
```c
b3RecPlayer* player = b3RecPlayer_Create( data, size, 1 );
b3WorldId worldId = b3RecPlayer_GetWorldId( player );
while ( b3RecPlayer_StepFrame( player ) )
{
// The replay world now holds the state after b3RecPlayer_GetFrame( player ) steps.
// Read it with the normal b3Body_Get* and b3World_* functions, or draw it.
}
b3RecPlayer_Restart( player ); // rewind to frame 0 in place; the world id stays the same
b3RecPlayer_Destroy( player );
```
`b3RecPlayer_Create` returns `NULL` if the bytes are malformed or fail the layout gate (see the
determinism contract below). `b3RecPlayer_IsAtEnd` reports when the recording is exhausted, and
`b3RecPlayer_HasDiverged` reports whether a recorded state hash failed to reproduce.
`b3RecPlayer_GetDivergeFrame` returns the first frame that diverged, or `-1`. Divergence is
non-fatal during playback so the viewer can keep playing and show where the run starts to differ.
`b3RecPlayer_GetInfo` returns a `b3RecPlayerInfo` read once at open: frame count, recorded time
step and sub-step count, the length scale in effect when recorded, and the accumulated world
bounds, enough to frame and label the recording before the first step.
### Seeking and keyframes
`b3RecPlayer_SeekFrame` jumps to any frame. A forward seek steps op by op; a backward seek
restores the nearest keyframe and re-steps the remaining gap. A keyframe is a periodic snapshot
the player keeps so backward seeking does not replay from the start. `b3RecPlayer_SetKeyframePolicy`
trades memory for seek speed: it caps the bytes spent on kept snapshots and sets the finest
spacing in frames. The spacing widens automatically as the ring evicts to stay under budget, so
the effective backward-seek granularity is reported by `b3RecPlayer_GetKeyframeInterval`.
### Worker count
`b3RecPlayer_Create` takes a worker count for the replay world; pass `1` to match a serial
recording. `b3RecPlayer_SetWorkerCount` changes it on the live player and is reused whenever the
player rebuilds its world on restart or a backward seek. Replaying at a different worker count
than was recorded re-partitions the constraint graph, so the state-hash check becomes a
cross-thread determinism test.
## The seed snapshot
A recording is seeded by a snapshot: a serialized image of the world's simulation state at a step
boundary. It captures everything the engine needs to continue the simulation: bodies, shapes,
joints, contacts with their warm-start impulses, the island and sleep partition, the broad-phase
trees, the id pools, and the interned shape geometry. It does not capture host wiring (worker
count, task callbacks, user data, the friction and restitution mixers); that is rebuilt or
reinstalled at restore.
This machinery is currently internal, used only to seed and replay recordings. Box3D does not yet
expose a standalone save-state / restore API.
## Debug shapes for replay
The player's replay world is created internally, so a renderer has no chance to build per-shape
draw resources as shapes appear. `b3RecPlayer_SetDebugShapeCallbacks` wires host callbacks into
the replay world for exactly that: one is called when a replayed shape is added (returning a user
draw handle), one when it is removed. Call it once right after `b3RecPlayer_Create` and re-read
the world id afterward, since installing the callbacks rebuilds the world and rewinds to frame 0.
The callbacks persist across restart and backward seeks. The 3D sample needs this or the replay
world draws nothing.
## Viewing a recording
The samples app has a **Replay** category with a **Viewer**. Open a recording from its file row,
choose a keyframe budget and minimum interval in the load dialog, then play, pause, single-step,
seek with the scrubber, restart, and change the replay worker count. A `****DIVERGED****` marker
appears, and the scrubber marks the diverge frame, if a recorded state hash fails to reproduce,
which is a real determinism break, not a viewer bug. The info panel lists the recorded bodies,
shapes, joints, and per-frame spatial queries for inspection.
You can also record any sample: open the **Recording** controls in the sample's panel, set a file
name, and press **Record (restart)** to capture from the start or **Record Now** to capture from
the current step. **Stop** saves the buffer to the file.
## Determinism contract
Replay reproduces the original run exactly only when the replaying build matches the recording
build in the ways that affect the math. Some of this the format enforces on load, and the rest is
your responsibility:
- **Struct layout** is enforced. A recording opens by deserializing a snapshot, which is a raw
struct image, so the reader's build must have identical struct layouts. The image carries a
layout hash and `b3RecPlayer_Create` / `b3ValidateReplay` reject a recording whose hash differs
rather than producing a silently wrong replay. A recording therefore does not replay across a
build whose internal layout changed, including a change in SIMD width.
- **Pointer width**, **endianness**, and the format version are enforced the same way.
- **Floating-point environment** must match. Box3D builds with `-ffp-contract=off` so fused
multiply-add does not change results. Building with `-ffast-math` is unsupported.
See the **Determinism** section of the Simulation page for what "same inputs" means across
platforms and thread counts.
## Spatial queries
Overlap and cast queries issued during a recorded step (ray casts, shape casts, overlap tests,
and the character mover casts) are recorded too. On replay each query is re-issued against the
replayed world and its results are compared against what was recorded, so a query that returns
different hits is flagged like any other divergence. The player exposes the recorded queries of
the most recently replayed frame through `b3RecPlayer_GetFrameQueryCount`,
`b3RecPlayer_GetFrameQuery`, and `b3RecPlayer_GetFrameQueryHit`, and
`b3RecPlayer_DrawFrameQueries` draws them layered on top of the world; call it after
`b3World_Draw`.
## Limitations
- **Recordings require a matching struct layout.** A recording is seeded by a raw struct-image
snapshot gated on an exact layout hash, so it will not load into a build whose internal layout
changed, even if the float environment and architecture match.
- **User data is not preserved.** `userData` pointers are host addresses with no meaning in the
replay process, so they are written as zero. Code that keys off user data during replay will
not see the original pointers.
- **Host callbacks are not captured.** The friction and restitution mixers, preSolve, and
custom-filter callbacks are host functions, so they are not part of the recording. The default
mixers are pure functions of their inputs and reproduce exactly. A session that installed a
custom mixer, or a preSolve or custom-filter callback that changes the simulation, will diverge
on replay because the internally created replay world runs without them.

View file

@ -252,6 +252,218 @@ B3_API void b3World_DumpAwake( b3WorldId worldId );
/// Dump world to a text file. Meshes are saved to binary b3m files.
B3_API void b3World_Dump( b3WorldId worldId );
/**
* @defgroup recording Recording
* @brief Record and replay world state for debugging.
* @{
*/
/// Opaque recording handle. Create with b3CreateRecording, destroy with b3DestroyRecording.
typedef struct b3Recording b3Recording;
/// Create a recording buffer with an optional initial byte capacity.
/// Pass 0 to use the default (64 KiB). The buffer grows on demand.
/// @return a new recording, owned by the caller
B3_API b3Recording* b3CreateRecording( int byteCapacity );
/// Destroy a recording and free its buffer.
/// @param recording may be NULL
B3_API void b3DestroyRecording( b3Recording* recording );
/// Get a pointer to the raw recording bytes.
/// Valid until the recording buffer is modified or destroyed.
/// @param recording the recording handle
/// @return pointer to the byte buffer, or NULL if no bytes have been written
B3_API const uint8_t* b3Recording_GetData( const b3Recording* recording );
/// Get the number of bytes currently in the recording buffer.
/// @param recording the recording handle
B3_API int b3Recording_GetSize( const b3Recording* recording );
/// Begin recording world mutations into the provided buffer.
/// The buffer is reset on each call so a single b3Recording can be reused for multiple sessions.
/// @param worldId the world to record
/// @param recording the recording handle to write into
B3_API void b3World_StartRecording( b3WorldId worldId, b3Recording* recording );
/// End the current recording session. Writes the trailing geometry registry and
/// backpatches the header. The buffer remains valid until the recording is destroyed.
/// @param worldId the world currently being recorded
B3_API void b3World_StopRecording( b3WorldId worldId );
/// Save the recording buffer to a file. Returns true on success.
/// @param recording the recording to save
/// @param path file path to write
B3_API bool b3SaveRecordingToFile( const b3Recording* recording, const char* path );
/// Load a recording from a file. Returns NULL on failure (file not found, wrong magic).
/// The caller owns the returned recording and must destroy it with b3DestroyRecording.
/// @param path file path to read
B3_API b3Recording* b3LoadRecordingFromFile( const char* path );
/// Replay a recording from memory and verify it reproduces the same world-state hashes.
/// Stands up a fresh world, restores the seed snapshot, replays every op, and checks each embedded
/// StateHash record. Returns true if replay completed without id mismatches or hash divergences.
/// @param data pointer to recording bytes
/// @param size byte count of the recording
/// @param workerCount reserved for future multithreaded replay; pass 1 for now
B3_API bool b3ValidateReplay( const void* data, int size, int workerCount );
/// Opaque incremental replay player with a keyframe ring for O(interval) backward seek.
typedef struct b3RecPlayer b3RecPlayer;
/// Summary of a recording, read once at open so a viewer can frame and label it.
typedef struct b3RecPlayerInfo
{
int frameCount; // total recorded steps
int workerCount; // worker count requested for the replay world
float timeStep; // dt of the recorded steps
int subStepCount; // recorded sub-steps
float lengthScale; // length units per meter in effect when recorded
b3AABB bounds; // accumulated world bounds over the recording, zero-extent if unavailable
} b3RecPlayerInfo;
/// Create a player over a recording. Owns a private copy of the bytes.
/// @param data pointer to recording bytes
/// @param size byte count of the recording
/// @param workerCount worker count for the replay world; pass 1 to match a serial recording.
/// Replaying at a different count re-partitions the constraint graph, so the StateHash check
/// becomes a cross-thread determinism test. Adjustable later with b3RecPlayer_SetWorkerCount.
/// @return a new player, or NULL on bad header or deserialization failure
B3_API b3RecPlayer* b3RecPlayer_Create( const void* data, int size, int workerCount );
/// Destroy the player and free all memory. Restores the previous global length scale.
B3_API void b3RecPlayer_Destroy( b3RecPlayer* player );
/// Advance one frame: dispatch ops until the next Step completes.
/// @return true when a frame was stepped, false at end-of-recording
B3_API bool b3RecPlayer_StepFrame( b3RecPlayer* player );
/// Rewind to frame 0 (in-place restore so the world id stays stable).
B3_API void b3RecPlayer_Restart( b3RecPlayer* player );
/// Seek to a specific frame. Forward seek steps op-by-op; backward seek restores
/// the nearest keyframe then re-steps the remaining gap.
B3_API void b3RecPlayer_SeekFrame( b3RecPlayer* player, int targetFrame );
/// @return the world currently driven by this player
B3_API b3WorldId b3RecPlayer_GetWorldId( const b3RecPlayer* player );
/// @return the last fully-stepped frame index (0 before any step)
B3_API int b3RecPlayer_GetFrame( const b3RecPlayer* player );
/// @return total number of recorded frames
B3_API int b3RecPlayer_GetFrameCount( const b3RecPlayer* player );
/// @return true when the op stream is exhausted
B3_API bool b3RecPlayer_IsAtEnd( const b3RecPlayer* player );
/// @return true when any StateHash mismatch has been detected
B3_API bool b3RecPlayer_HasDiverged( const b3RecPlayer* player );
/// @return a summary of the recording read at open: frame count, recorded tuning, and bounds
B3_API b3RecPlayerInfo b3RecPlayer_GetInfo( const b3RecPlayer* player );
/// @return the first frame at which replay diverged, or -1 if it has not diverged
B3_API int b3RecPlayer_GetDivergeFrame( const b3RecPlayer* player );
/// Set the worker count of the replay world. Clamped to [1, B3_MAX_WORKERS]. Applied to the live
/// world at once and reused whenever the player rebuilds its world on Restart or a backward seek.
/// Replaying at a different count than recorded re-partitions the constraint graph, so the StateHash
/// check becomes a cross-thread determinism test.
B3_API void b3RecPlayer_SetWorkerCount( b3RecPlayer* player, int count );
/// Tune the keyframe ring used to speed up backward seeking. A keyframe is a periodic snapshot the
/// player restores from instead of replaying from the start, trading memory for seek speed.
/// @param player the recording player
/// @param budgetBytes memory cap for the kept snapshots; the spacing widens to stay under it
/// @param minIntervalFrames finest spacing between keyframes, in frames
/// A zero budget or a non-positive interval keeps that value. Clears the existing ring, so call
/// b3RecPlayer_Restart afterward to repopulate it under the new policy.
B3_API void b3RecPlayer_SetKeyframePolicy( b3RecPlayer* player, size_t budgetBytes, int minIntervalFrames );
/// @return the keyframe memory budget in bytes
B3_API size_t b3RecPlayer_GetKeyframeBudget( const b3RecPlayer* player );
/// @return the finest keyframe spacing in frames
B3_API int b3RecPlayer_GetKeyframeMinInterval( const b3RecPlayer* player );
/// @return the current keyframe spacing in frames; starts at the min interval and doubles as the
/// ring evicts to stay under budget, so it reflects the effective backward-seek granularity now
B3_API int b3RecPlayer_GetKeyframeInterval( const b3RecPlayer* player );
/// @return the memory currently held by keyframe snapshots, in bytes
B3_API size_t b3RecPlayer_GetKeyframeBytes( const b3RecPlayer* player );
/// @return the number of bodies tracked in creation order (including holes for destroyed bodies)
B3_API int b3RecPlayer_GetBodyCount( const b3RecPlayer* player );
/// Resolve a creation ordinal to the live body id at the current frame.
/// @return the body id, or a null id if that ordinal is out of range or its body is destroyed
B3_API b3BodyId b3RecPlayer_GetBodyId( const b3RecPlayer* player, int index );
/// Wire host debug-shape callbacks into the player's replay world so a renderer can build
/// per-shape draw resources (the 3D sample needs this or the replay world draws nothing).
/// Rebuilds the current world under the new callbacks and rewinds to frame 0, so call it
/// once right after b3RecPlayer_Create and re-read the world id afterward. The callbacks
/// persist across Restart and backward seeks, which recreate the world internally.
/// @param player the player to configure
/// @param createDebugShape called when a replayed shape is added; returns a user draw handle
/// @param destroyDebugShape called when a replayed shape is removed; may be NULL
/// @param context user context passed to both callbacks
B3_API void b3RecPlayer_SetDebugShapeCallbacks( b3RecPlayer* player, b3CreateDebugShapeCallback* createDebugShape,
b3DestroyDebugShapeCallback* destroyDebugShape, void* context );
/// Draw the spatial queries recorded during the most recently replayed frame, layered on top of the
/// world. Call after b3World_Draw. NULL draw function pointers are skipped.
/// @param player a valid player handle
/// @param draw debug draw callbacks
/// @param queryIndex index of the frame query to draw, or -1 to draw all of them
B3_API void b3RecPlayer_DrawFrameQueries( b3RecPlayer* player, b3DebugDraw* draw, int queryIndex );
/// The kind of a recorded spatial query, matching the public query and cast functions.
typedef enum b3RecQueryType
{
b3_recQueryOverlapAABB,
b3_recQueryOverlapShape,
b3_recQueryCastRay,
b3_recQueryCastShape,
b3_recQueryCastRayClosest,
b3_recQueryCastMover,
b3_recQueryCollideMover,
} b3RecQueryType;
/// A spatial query recorded during a replayed frame, exposed for inspection.
typedef struct b3RecQueryInfo
{
b3RecQueryType type;
b3QueryFilter filter;
b3AABB aabb; // overlap AABB, world space
b3Pos origin; // query origin (zero for overlap AABB)
b3Vec3 translation; // ray and cast translation
int hitCount; // number of recorded results
} b3RecQueryInfo;
/// One result of a recorded spatial query.
typedef struct b3RecQueryHit
{
b3ShapeId shape;
b3Pos point;
b3Vec3 normal;
float fraction;
} b3RecQueryHit;
/// @return the number of spatial queries recorded for the most recently replayed frame
B3_API int b3RecPlayer_GetFrameQueryCount( const b3RecPlayer* player );
/// Get a recorded query from the most recently replayed frame by index.
B3_API b3RecQueryInfo b3RecPlayer_GetFrameQuery( const b3RecPlayer* player, int index );
/// Get one result of a recorded query from the most recently replayed frame.
B3_API b3RecQueryHit b3RecPlayer_GetFrameQueryHit( const b3RecPlayer* player, int queryIndex, int hitIndex );
/**@}*/ // recording
/** @} */ // world
/**
@ -597,10 +809,10 @@ B3_API b3ShapeId b3CreateMeshShape( b3BodyId bodyId, const b3ShapeDef* def, cons
/// Height field is only allowed on static bodies.
/// @warning this holds reference to the input height field which must remain valid for the lifetime of this shape
/// @return the shape id for accessing the shape
B3_API b3ShapeId b3CreateHeightFieldShape( b3BodyId bodyId, const b3ShapeDef* def, const b3HeightField* heightField );
B3_API b3ShapeId b3CreateHeightFieldShape( b3BodyId bodyId, const b3ShapeDef* def, const b3HeightFieldData* heightField );
/// Compound shapes are only allowed on static bodies.
B3_API b3ShapeId b3CreateCompoundShape( b3BodyId bodyId, b3ShapeDef* def, const b3Compound* compound );
B3_API b3ShapeId b3CreateCompoundShape( b3BodyId bodyId, b3ShapeDef* def, const b3CompoundData* compound );
/// Destroy a shape. You may defer the body mass update which can improve performance if several shapes on a
/// body are destroyed at once.
@ -726,7 +938,7 @@ B3_API const b3HullData* b3Shape_GetHull( b3ShapeId shapeId );
B3_API b3Mesh b3Shape_GetMesh( b3ShapeId shapeId );
/// Get the shape's height field. Asserts the type is correct.
B3_API const b3HeightField* b3Shape_GetHeightField( b3ShapeId shapeId );
B3_API const b3HeightFieldData* b3Shape_GetHeightField( b3ShapeId shapeId );
/// Allows you to change a shape to be a sphere or update the current sphere.
/// This does not modify the mass properties.

View file

@ -343,24 +343,57 @@ B3_API int b3GetHeight( const b3MeshData* mesh );
* @{
*/
/// Get read only compressed heights. One uint16_t per grid point.
B3_INLINE const uint16_t* b3GetHeightFieldCompressedHeights( const b3HeightFieldData* hf )
{
if ( hf->heightsOffset == 0 )
{
return NULL;
}
return (const uint16_t*)( (intptr_t)hf + hf->heightsOffset );
}
/// Get read only material indices. One uint8_t per cell.
B3_INLINE const uint8_t* b3GetHeightFieldMaterialIndices( const b3HeightFieldData* hf )
{
if ( hf->materialOffset == 0 )
{
return NULL;
}
return (const uint8_t*)( (intptr_t)hf + hf->materialOffset );
}
/// Get read only triangle flags. One uint8_t per triangle.
B3_INLINE const uint8_t* b3GetHeightFieldFlags( const b3HeightFieldData* hf )
{
if ( hf->flagsOffset == 0 )
{
return NULL;
}
return (const uint8_t*)( (intptr_t)hf + hf->flagsOffset );
}
/// Create a generic height field.
B3_API b3HeightField* b3CreateHeightField( const b3HeightFieldDef* data );
B3_API b3HeightFieldData* b3CreateHeightField( const b3HeightFieldDef* data );
/// Create a grid as a height field.
B3_API b3HeightField* b3CreateGrid( int rowCount, int columnCount, b3Vec3 scale, bool makeHoles );
B3_API b3HeightFieldData* b3CreateGrid( int rowCount, int columnCount, b3Vec3 scale, bool makeHoles );
/// Create a wave grid as a height field.
B3_API b3HeightField* b3CreateWave( int rowCount, int columnCount, b3Vec3 scale, float rowFrequency, float columnFrequency,
bool makeHoles );
B3_API b3HeightFieldData* b3CreateWave( int rowCount, int columnCount, b3Vec3 scale, float rowFrequency, float columnFrequency,
bool makeHoles );
/// Destroy a height field.
B3_API void b3DestroyHeightField( b3HeightField* heightField );
B3_API void b3DestroyHeightField( b3HeightFieldData* heightField );
/// Save input height data to a file
B3_API void b3DumpHeightData( const b3HeightFieldDef* data, const char* fileName );
/// Create a height field by loading a previously saved height data
B3_API b3HeightField* b3LoadHeightField( const char* fileName );
B3_API b3HeightFieldData* b3LoadHeightField( const char* fileName );
/**@}*/ // height_field
@ -370,41 +403,41 @@ B3_API b3HeightField* b3LoadHeightField( const char* fileName );
*/
/// Get a child shape of a compound.
B3_API b3ChildShape b3GetCompoundChild( const b3Compound* compound, int childIndex );
B3_API b3ChildShape b3GetCompoundChild( const b3CompoundData* compound, int childIndex );
/// Query a compound shape for children that overlap an AABB.
B3_API void b3QueryCompound( const b3Compound* compound, b3AABB aabb, b3CompoundQueryFcn* fcn, void* context );
B3_API void b3QueryCompound( const b3CompoundData* compound, b3AABB aabb, b3CompoundQueryFcn* fcn, void* context );
/// Access a child capsule by index.
B3_API b3CompoundCapsule b3GetCompoundCapsule( const b3Compound* compound, int index );
B3_API b3CompoundCapsule b3GetCompoundCapsule( const b3CompoundData* compound, int index );
/// Access a child hull by index.
B3_API b3CompoundHull b3GetCompoundHull( const b3Compound* compound, int index );
B3_API b3CompoundHull b3GetCompoundHull( const b3CompoundData* compound, int index );
/// Access a child mesh by index.
B3_API b3CompoundMesh b3GetCompoundMesh( const b3Compound* compound, int index );
B3_API b3CompoundMesh b3GetCompoundMesh( const b3CompoundData* compound, int index );
/// Access a child sphere by index.
B3_API b3CompoundSphere b3GetCompoundSphere( const b3Compound* compound, int index );
B3_API b3CompoundSphere b3GetCompoundSphere( const b3CompoundData* compound, int index );
/// Access the compound material array.
B3_API const b3SurfaceMaterial* b3GetCompoundMaterials( const b3Compound* compound );
B3_API const b3SurfaceMaterial* b3GetCompoundMaterials( const b3CompoundData* compound );
/// Create a compound shape. All input data in the definition is cloned into the resulting compound.
B3_API b3Compound* b3CreateCompound( const b3CompoundDef* def );
B3_API b3CompoundData* b3CreateCompound( const b3CompoundDef* def );
/// Destroy a compound shape.
B3_API void b3DestroyCompound( b3Compound* compound );
B3_API void b3DestroyCompound( b3CompoundData* compound );
/// If bytes is null then this returns the number of required bytes. This clones all the
/// data into the bytes buffer. This is expected to run offline or asynchronously.
/// This mutates the compound to nullify pointers, leaving the compound in an unusable state.
B3_API uint8_t* b3ConvertCompoundToBytes( b3Compound* compound );
B3_API uint8_t* b3ConvertCompoundToBytes( b3CompoundData* compound );
/// Convert bytes to compound. This does not clone. The bytes must remain in scope while the
/// compound is used. This is done to improve run-time performance and allow for instancing.
/// The bytes are mutated to fixup pointers.
B3_API b3Compound* b3ConvertBytesToCompound( uint8_t* bytes, int byteCount );
B3_API b3CompoundData* b3ConvertBytesToCompound( uint8_t* bytes, int byteCount );
/**@}*/ // compound
@ -435,10 +468,10 @@ B3_API b3AABB b3ComputeHullAABB( const b3HullData* shape, b3Transform transform
B3_API b3AABB b3ComputeMeshAABB( const b3MeshData* shape, b3Transform transform, b3Vec3 scale );
/// Compute the bounding box of a transformed height-field
B3_API b3AABB b3ComputeHeightFieldAABB( const b3HeightField* shape, b3Transform transform );
B3_API b3AABB b3ComputeHeightFieldAABB( const b3HeightFieldData* shape, b3Transform transform );
/// Compute the bounding box of a compound
B3_API b3AABB b3ComputeCompoundAABB( const b3Compound* shape, b3Transform transform );
B3_API b3AABB b3ComputeCompoundAABB( const b3CompoundData* shape, b3Transform transform );
/**@}*/ // geometry
@ -454,10 +487,10 @@ B3_API bool b3IsValidRay( const b3RayCastInput* input );
B3_API bool b3OverlapCapsule( const b3Capsule* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy );
/// Overlap shape versus compound
B3_API bool b3OverlapCompound( const b3Compound* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy );
B3_API bool b3OverlapCompound( const b3CompoundData* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy );
/// Overlap shape versus height field
B3_API bool b3OverlapHeightField( const b3HeightField* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy );
B3_API bool b3OverlapHeightField( const b3HeightFieldData* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy );
/// Overlap shape versus hull
B3_API bool b3OverlapHull( const b3HullData* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy );
@ -478,7 +511,7 @@ B3_API b3CastOutput b3RayCastHollowSphere( const b3Sphere* shape, const b3RayCas
B3_API b3CastOutput b3RayCastCapsule( const b3Capsule* shape, const b3RayCastInput* input );
/// Ray cast versus compound in local space. Initial overlap is treated as a miss.
B3_API b3CastOutput b3RayCastCompound( const b3Compound* shape, const b3RayCastInput* input );
B3_API b3CastOutput b3RayCastCompound( const b3CompoundData* shape, const b3RayCastInput* input );
/// Ray cast versus hull shape in local space. Initial overlap is treated as a miss.
B3_API b3CastOutput b3RayCastHull( const b3HullData* shape, const b3RayCastInput* input );
@ -487,7 +520,7 @@ B3_API b3CastOutput b3RayCastHull( const b3HullData* shape, const b3RayCastInput
B3_API b3CastOutput b3RayCastMesh( const b3Mesh* shape, const b3RayCastInput* input );
/// Ray cast versus height field in local space.
B3_API b3CastOutput b3RayCastHeightField( const b3HeightField* shape, const b3RayCastInput* input );
B3_API b3CastOutput b3RayCastHeightField( const b3HeightFieldData* shape, const b3RayCastInput* input );
/// Shape cast versus a sphere. Initial overlap is treated as a miss.
B3_API b3CastOutput b3ShapeCastSphere( const b3Sphere* shape, const b3ShapeCastInput* input );
@ -496,7 +529,7 @@ B3_API b3CastOutput b3ShapeCastSphere( const b3Sphere* shape, const b3ShapeCastI
B3_API b3CastOutput b3ShapeCastCapsule( const b3Capsule* shape, const b3ShapeCastInput* input );
/// Shape cast versus compound. Initial overlap is treated as a miss.
B3_API b3CastOutput b3ShapeCastCompound( const b3Compound* shape, const b3ShapeCastInput* input );
B3_API b3CastOutput b3ShapeCastCompound( const b3CompoundData* shape, const b3ShapeCastInput* input );
/// Shape cast versus a hull. Initial overlap is treated as a miss.
B3_API b3CastOutput b3ShapeCastHull( const b3HullData* shape, const b3ShapeCastInput* input );
@ -505,7 +538,7 @@ B3_API b3CastOutput b3ShapeCastHull( const b3HullData* shape, const b3ShapeCastI
B3_API b3CastOutput b3ShapeCastMesh( const b3Mesh* shape, const b3ShapeCastInput* input );
/// Shape cast versus a height field. Initial overlap is treated as a miss.
B3_API b3CastOutput b3ShapeCastHeightField( const b3HeightField* shape, const b3ShapeCastInput* input );
B3_API b3CastOutput b3ShapeCastHeightField( const b3HeightFieldData* shape, const b3ShapeCastInput* input );
/// Query callback.
typedef bool b3MeshQueryFcn( b3Vec3 a, b3Vec3 b, b3Vec3 c, int triangleIndex, void* context );
@ -522,7 +555,7 @@ B3_API void b3QueryMesh( const b3Mesh* mesh, const b3AABB bounds, b3MeshQueryFcn
/// @param bounds the bounding box in local space
/// @param fcn a user function to collect triangles
/// @param context the context sent to the user function.
B3_API void b3QueryHeightField( const b3HeightField* heightField, b3AABB bounds, b3MeshQueryFcn* fcn, void* context );
B3_API void b3QueryHeightField( const b3HeightFieldData* heightField, b3AABB bounds, b3MeshQueryFcn* fcn, void* context );
/// Compute the closest points between two shapes represented as point clouds.
/// b3SimplexCache cache is input/output. On the first call set b3SimplexCache.count to zero.

View file

@ -2240,26 +2240,19 @@ typedef struct b3HeightFieldDef
#define B3_HEIGHT_FIELD_HOLE 0xFF
/// 64-bit height-field version. Useful for validating serialized data.
#define B3_HEIGHT_FIELD_VERSION 0xB6E83F1D947A28C5ull
#define B3_HEIGHT_FIELD_VERSION 0x3D9A1F6C24E87B05ull
/// A height field with compressed storage.
typedef struct b3HeightField
/// @note This data structure has data hanging off the end and cannot be directly copied.
typedef struct b3HeightFieldData
{
/// Version must be first
/// Version must be first and match B3_HEIGHT_FIELD_VERSION
uint64_t version;
/// The compressed height values.
uint16_t* compressedHeights;
/// Material indices, one for each cell.
uint8_t* materialIndices;
/// Flags per cell.
uint8_t* flags;
/// The total number of bytes for this height field.
int byteCount;
/// Hash of this height field (this field is zero when the hash is computed).
/// Pointer values above are skipped; the bulk arrays they reference and the
/// scalar block below are folded in at construction time.
uint32_t hash;
/// The local axis-aligned bounding box.
@ -2283,9 +2276,25 @@ typedef struct b3HeightField
/// The number of grid rows along the local z-axis.
int rowCount;
/// Offset of the compressed height array in bytes from the struct address.
/// uint16_t, one per grid point.
int heightsOffset;
/// Offset of the material index array in bytes from the struct address.
/// uint8_t, one per cell.
int materialOffset;
/// Offset of the flag array in bytes from the struct address.
/// uint8_t, one per triangle.
int flagsOffset;
/// Triangle winding.
bool clockwise;
} b3HeightField;
/// Explicit padding. Identity is a content hash over raw bytes, so there must
/// be no unnamed padding for struct copies to scramble.
uint8_t padding[3];
} b3HeightFieldData;
/**@}*/ // height_field
@ -2389,7 +2398,7 @@ typedef struct b3CompoundDef
/// 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.
typedef struct b3Compound
typedef struct b3CompoundData
{
/// The compound version is always first.
uint64_t version;
@ -2438,7 +2447,7 @@ typedef struct b3Compound
/// The number of spheres.
int sphereCount;
} b3Compound;
} b3CompoundData;
/// A capsule that lives in a compound.
typedef struct b3CompoundCapsule
@ -2516,7 +2525,7 @@ typedef struct b3ChildShape
} b3ChildShape;
/// Callback for compound overlap queries.
typedef bool b3CompoundQueryFcn( const b3Compound* compound, int childIndex, void* context );
typedef bool b3CompoundQueryFcn( const b3CompoundData* compound, int childIndex, void* context );
/**@}*/ // compound
@ -2912,8 +2921,8 @@ typedef struct b3DebugShape
union
{
const b3Capsule* capsule; ///< Capsule shape.
const b3Compound* compound; ///< Compound shape.
const b3HeightField* heightField; ///< Height-field shape.
const b3CompoundData* compound; ///< Compound shape.
const b3HeightFieldData* heightField; ///< Height-field shape.
const b3HullData* hull; ///< Convex hull shape.
const b3Mesh* mesh; ///< Mesh shape with scale.
const b3Sphere* sphere; ///< Sphere shape.
@ -2937,6 +2946,9 @@ typedef struct b3DebugDraw
/// Draw a point.
void ( *DrawPointFcn )( b3Pos p, float size, b3HexColor color, void* context );
/// Draw a sphere.
void ( *DrawSphereFcn )( b3Pos p, float radius, b3HexColor color, float alpha, void* context );
/// Draw a bounding box.
void ( *DrawBoundsFcn )( b3AABB aabb, b3HexColor color, void* context );

View file

@ -16,6 +16,17 @@ FetchContent_Declare(implot
)
FetchContent_MakeAvailable(implot)
# nativefiledialog-extended for the Replay open dialog. Native OS file picker, target nfd.
set(NFD_BUILD_TESTS OFF CACHE BOOL "" FORCE)
set(NFD_INSTALL OFF CACHE BOOL "" FORCE)
FetchContent_Declare(nfd
GIT_REPOSITORY https://github.com/btzy/nativefiledialog-extended.git
GIT_TAG v1.3.0
GIT_SHALLOW TRUE
GIT_PROGRESS TRUE
)
FetchContent_MakeAvailable(nfd)
# The shader compiler is only needed when recompiling shaders. A fresh clone
# with BOX3D_BUILD_SHADERS=OFF builds from the committed headers and skips this.
if(BOX3D_BUILD_SHADERS)
@ -156,6 +167,7 @@ set(SAMPLE_FILES
sample_manifold.cpp
sample_mesh.cpp
sample_ragdoll.cpp
sample_replay.cpp
sample_robustness.cpp
sample_shapes.cpp
sample_stacking.cpp
@ -180,7 +192,7 @@ target_include_directories(samples PRIVATE
# gfx: the renderer + Draw*/adapter. shared: human, utils (Random*), the
# benchmark/determinism helpers the samples lean on.
target_link_libraries(samples PRIVATE gfx shared imgui implot sokol)
target_link_libraries(samples PRIVATE gfx shared imgui implot sokol nfd)
set_target_properties(samples PROPERTIES
CXX_STANDARD 20

View file

@ -3,7 +3,6 @@
#include "gfx/debug_adapter.h"
#include "box3d/box3d.h"
#include "gfx/debug_shapes.h"
#include "gfx/draw.h"
#include "gfx/geometry_registry.h"
@ -12,6 +11,8 @@
#include "gfx/renderer.h"
#include "gfx/text.h"
#include "box3d/box3d.h"
#include <assert.h>
#include <math.h>
#include <stdbool.h>
@ -226,7 +227,7 @@ void SetShapeMaterial( b3ShapeId shapeId, Vec4 color, float metallic, float roug
return;
}
}
if ( s_adapter.materialOverrideCount >= BOX3D_MATERIAL_OVERRIDE_CAPACITY )
{
return;
@ -285,12 +286,12 @@ static HighlightKind ResolveHighlightKind( b3BodyId bodyId )
{
return HIGHLIGHT_KIND_SELECT;
}
if ( B3_ID_EQUALS( bodyId, s_adapter.hoveredBodyId ) )
{
return HIGHLIGHT_KIND_HOVER;
}
return HIGHLIGHT_KIND_NONE;
}
@ -340,6 +341,15 @@ static Vec4 HexColorToVec4( b3HexColor color )
return MakeVec4( r, g, b, 1.0f );
}
static Vec4 HexColorAToVec4( b3HexColor color, float alpha )
{
const uint32_t v = (uint32_t)color;
const float r = (float)( ( v >> 16 ) & 0xFFu ) * ( 1.0f / 255.0f );
const float g = (float)( ( v >> 8 ) & 0xFFu ) * ( 1.0f / 255.0f );
const float b = (float)( v & 0xFFu ) * ( 1.0f / 255.0f );
return MakeVec4( r, g, b, alpha );
}
// sRGB EOTF, the standard piecewise curve (IEC 61966-2-1), one channel.
static float SRGBToLinear( float c )
{
@ -357,7 +367,7 @@ static Vec4 HexColorToLinear( b3HexColor color )
// Get a capsule transform to represent axial spin
static b3Transform GetCapsuleLocalFrame( b3Vec3 c1, b3Vec3 c2, float* outHalfLength )
{
b3Vec3 d = b3Sub(c2, c1);
b3Vec3 d = b3Sub( c2, c1 );
float length = b3Length( d );
*outHalfLength = 0.5f * length;
@ -557,7 +567,7 @@ static void* AdapterCreateDebugShape( const b3DebugShape* debugShape, void* cont
if ( debugShape->type == b3_heightShape )
{
const b3HeightField* hf = debugShape->heightField;
const b3HeightFieldData* hf = debugShape->heightField;
const MeshHandle handle = FindOrAddHeightField( hf );
if ( !IsMeshHandleValid( handle ) )
{
@ -591,7 +601,7 @@ static void* AdapterCreateDebugShape( const b3DebugShape* debugShape, void* cont
// Flatten the children once. The fixed pool never relocates, so the
// parent pointer stays valid while children are allocated.
const b3Compound* compound = debugShape->compound;
const b3CompoundData* compound = debugShape->compound;
const int total = compound->capsuleCount + compound->hullCount + compound->meshCount + compound->sphereCount;
int prev = -1;
for ( int i = 0; i < total; ++i )
@ -767,7 +777,7 @@ static bool DrawShape( void* userShape, b3WorldTransform shapeTransform, b3HexCo
}
#define BOX3D_LINE_THICKNESS_PX 2.5f
#define BOX3D_TRANSFORM_LENGTH (0.25f * b3GetLengthUnitsPerMeter())
#define BOX3D_TRANSFORM_LENGTH ( 0.25f * b3GetLengthUnitsPerMeter() )
static void DrawSegmentFcn( b3Pos p1, b3Pos p2, b3HexColor color, void* context )
{
@ -802,6 +812,13 @@ static void DrawPointFcn( b3Pos p, float size, b3HexColor color, void* context )
OVERLAY_OCCLUSION_HIDE );
}
static void DrawSphereFcn( b3Pos p, float radius, b3HexColor color, float alpha, void* context )
{
(void)context;
DrawSphereEx( (b3WorldTransform){ p, b3Quat_identity }, radius, HexColorAToVec4( color, alpha ), DEFAULT_METALLIC,
DEFAULT_ROUGHNESS, TRANSPARENT_SHADOW_NONE );
}
static void DrawBoundsFcn( b3AABB aabb, b3HexColor color, void* context )
{
(void)context;
@ -824,7 +841,7 @@ static void DrawBoundsFcn( b3AABB aabb, b3HexColor color, void* context )
float th = BOX3D_LINE_THICKNESS_PX;
OverlayThicknessUnit u = OVERLAY_THICKNESS_PIXELS;
OverlayOcclusionMode o = OVERLAY_OCCLUSION_HIDE;
// Bottom face
OverlayAppendLine( c000, c100, c, th, u, o );
OverlayAppendLine( c100, c101, c, th, u, o );
@ -917,6 +934,7 @@ void MakeDebugDraw( b3DebugDraw* out )
out->DrawSegmentFcn = DrawSegmentFcn;
out->DrawTransformFcn = DrawTransformFcn;
out->DrawPointFcn = DrawPointFcn;
out->DrawSphereFcn = DrawSphereFcn;
out->DrawBoundsFcn = DrawBoundsFcn;
out->DrawBoxFcn = DrawBoxFcn;
out->DrawStringFcn = DrawStringFcn;

View file

@ -543,10 +543,10 @@ static MeshHandle BuildMeshData( const b3MeshData* meshData )
return h;
}
static b3Vec3 HeightFieldSample( const b3HeightField* hf, int row, int col )
static b3Vec3 HeightFieldSample( const b3HeightFieldData* hf, int row, int col )
{
int index = row * hf->columnCount + col;
float decoded = hf->minHeight + hf->heightScale * (float)hf->compressedHeights[index];
float decoded = hf->minHeight + hf->heightScale * (float)b3GetHeightFieldCompressedHeights( hf )[index];
b3Vec3 scale = hf->scale;
b3Vec3 v;
v.x = scale.x * (float)col;
@ -555,9 +555,9 @@ static b3Vec3 HeightFieldSample( const b3HeightField* hf, int row, int col )
return v;
}
static MeshHandle BuildHeightField( const b3HeightField* hf )
static MeshHandle BuildHeightField( const b3HeightFieldData* hf )
{
if ( hf->columnCount < 2 || hf->rowCount < 2 || !hf->compressedHeights )
if ( hf->columnCount < 2 || hf->rowCount < 2 )
{
fprintf( stderr, "error: heightfield degenerate (hash=0x%08x)\n", hf->hash );
return InvalidMeshHandle();
@ -568,8 +568,8 @@ static MeshHandle BuildHeightField( const b3HeightField* hf )
const int cols = hf->columnCount;
const int rows = hf->rowCount;
const uint8_t* materials = hf->materialIndices; // may be NULL if all solid
const uint8_t* edgeFlags = hf->flags; // per-triangle concave bits
const uint8_t* materials = b3GetHeightFieldMaterialIndices( hf ); // may be NULL if all solid
const uint8_t* edgeFlags = b3GetHeightFieldFlags( hf ); // per-triangle concave bits
const bool clockwise = hf->clockwise;
// Build a (rows x cols) grid vertex array up front. Triangle emission
@ -593,7 +593,7 @@ static MeshHandle BuildHeightField( const b3HeightField* hf )
// Each cell (row, col) covers world rectangle:
// x in [scale.x * col, scale.x * (col + 1)]
// z in [scale.z * row, scale.z * (row + 1)]
// with corner heights at the four grid corners. b3HeightField holds
// with corner heights at the four grid corners. b3HeightFieldData holds
// per-cell material. B3_HEIGHT_FIELD_HOLE (0xFF) marks a hole, skip
// both triangles for that cell. Triangulation matches Box3D's collision
// triangulation (see height_field.c line 228+):
@ -823,7 +823,7 @@ MeshHandle FindOrAddMesh( const b3MeshData* meshData )
return BuildMeshData( meshData );
}
MeshHandle FindOrAddHeightField( const b3HeightField* heightField )
MeshHandle FindOrAddHeightField( const b3HeightFieldData* heightField )
{
if ( !heightField || heightField->hash == 0u )
{

View file

@ -39,11 +39,11 @@ MeshHandle FindOrAddHull( const b3HullData* hull );
// draw time. Two b3Mesh sharing the same b3MeshData share one entry.
MeshHandle FindOrAddMesh( const b3MeshData* meshData );
// Acquire for b3HeightField. The `scale` vector is part of the height
// Acquire for b3HeightFieldData. The `scale` vector is part of the height
// field's hash (folded into construction), so two heightfields with
// different scales hash to different entries, per-instance scale stays
// at (1, 1, 1) for heightfield draws.
MeshHandle FindOrAddHeightField( const b3HeightField* heightField );
MeshHandle FindOrAddHeightField( const b3HeightFieldData* heightField );
#ifdef __cplusplus
} // extern "C"

View file

@ -4,7 +4,7 @@
// Ref-counted GPU buffer store for triangle geometries (convex hulls,
// triangle meshes, heightfields). Owned by the renderer
// Keyed by uint32_t content hash for Box3D shapes we
// pass through b3HullData.hash / b3MeshData.hash / b3HeightField.hash
// pass through b3HullData.hash / b3MeshData.hash / b3HeightFieldData.hash
//
// Lifecycle:
//

View file

@ -103,18 +103,22 @@ static void OnEvent( const sapp_event* e )
return;
}
const bool imguiCaptured = HandleEvent( e );
bool uiCaptured = false;
if (s_context.camera.m_thirdPerson == false)
{
uiCaptured = HandleEvent( e );
}
// The camera must always see button releases and focus loss, even when the UI
// captures the event. Otherwise a release over an ImGui panel never clears the
// drag flag and the camera keeps orbiting.
const bool releaseOrUnfocus = e->type == SAPP_EVENTTYPE_MOUSE_UP || e->type == SAPP_EVENTTYPE_UNFOCUSED;
if ( imguiCaptured == false || releaseOrUnfocus )
if ( uiCaptured == false || releaseOrUnfocus )
{
s_context.camera.OnEvent( e );
}
if ( imguiCaptured )
if ( uiCaptured )
{
return;
}

View file

@ -24,6 +24,8 @@
#include "box3d/box3d.h"
#include <nfd.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
@ -269,6 +271,9 @@ Sample::Sample( SampleContext* context )
m_worldId = b3_nullWorldId;
m_recording = nullptr;
m_recordStartStep = 0;
m_mouseBodyId = {};
m_mouseJointId = {};
m_mouseFraction = 0.0f;
@ -302,13 +307,44 @@ Sample::~Sample()
{
ResetAdapterPool();
ResetGroundShapeId();
b3DestroyWorld( m_worldId );
if ( B3_IS_NON_NULL( m_worldId ) )
{
FinishRecording();
b3DestroyWorld( m_worldId );
}
}
void Sample::StartRecording()
{
if ( m_recording != nullptr )
{
return;
}
// Snapshot the live world as the seed, so recording can begin at any step boundary.
m_recording = b3CreateRecording( 0 );
b3World_StartRecording( m_worldId, m_recording );
m_recordStartStep = m_stepCount;
}
void Sample::FinishRecording()
{
if ( m_recording == nullptr )
{
return;
}
b3World_StopRecording( m_worldId );
b3SaveRecordingToFile( m_recording, m_context->recordingFile );
b3DestroyRecording( m_recording );
m_recording = nullptr;
}
void Sample::CreateWorld( b3Capacity* capacity )
{
if ( B3_IS_NON_NULL( m_worldId ) )
{
FinishRecording();
b3DestroyWorld( m_worldId );
}
@ -1042,6 +1078,9 @@ void Sample::DrawMetrics()
ImGui::EndTabItem();
}
// Sample-specific tabs (the Replay viewer adds Timeline here).
DrawMetricsTab();
ImGui::EndTabBar();
ImGui::End();
}
@ -1205,6 +1244,7 @@ void Sample::DrawTextLine( const char* text, ... )
SampleEntry g_sampleEntries[MAX_SAMPLES];
int g_sampleCount = 0;
int g_replayIndex = -1;
int RegisterSample( const char* category, const char* name, SampleCreateFcn* fcn )
{
@ -1219,6 +1259,17 @@ int RegisterSample( const char* category, const char* name, SampleCreateFcn* fcn
return -1;
}
// Like RegisterSample but remembers the index so the Replay menu can switch to the viewer.
int RegisterReplay( const char* category, const char* name, SampleCreateFcn* fcn )
{
int index = RegisterSample( category, name, fcn );
if ( index >= 0 )
{
g_replayIndex = index;
}
return index;
}
void SelectSample( SampleContext* context, int selection, bool restart )
{
if ( selection < 0 || selection >= g_sampleCount )
@ -1573,6 +1624,26 @@ static void DrawMenuBar( SampleContext* context )
ImGui::EndMenu();
}
// Only present once the replay viewer is registered. Open pops a native picker, then hands
// the chosen file to the viewer through replayFile.
if ( g_replayIndex >= 0 && ImGui::BeginMenu( "Replay" ) )
{
if ( ImGui::MenuItem( "Open..." ) )
{
NFD_Init();
nfdu8char_t* outPath = nullptr;
nfdu8filteritem_t filter[1] = { { "Box3D recording", "b3rec" } };
if ( NFD_OpenDialogU8( &outPath, filter, 1, nullptr ) == NFD_OKAY )
{
snprintf( context->replayFile, sizeof( context->replayFile ), "%s", outPath );
NFD_FreePathU8( outPath );
SelectSample( context, g_replayIndex, false );
}
NFD_Quit();
}
ImGui::EndMenu();
}
static bool showHelp = false;
static bool showAbout = false;
if ( ImGui::BeginMenu( "Help" ) )
@ -1808,6 +1879,37 @@ static void DrawInfoPanel( SampleContext* context )
}
}
if ( context->sample->HasSolverControls() && ImGui::CollapsingHeader( "Recording", ImGuiTreeNodeFlags_DefaultOpen ) )
{
ImGui::PushItemWidth( 9.0f * fontSize );
ImGui::InputText( "File##Recording", context->recordingFile, sizeof( context->recordingFile ) );
ImGui::PopItemWidth();
if ( context->sample->m_recording == nullptr )
{
// Restart to a clean world then snapshot it at step 0, a whole session capture.
if ( ImGui::Button( "Record (restart)##Recording" ) )
{
SelectSample( context, context->sampleIndex, true );
context->sample->StartRecording();
}
// Snapshot the running world and log from here, the mid simulation case.
if ( ImGui::Button( "Record Now##Recording" ) )
{
context->sample->StartRecording();
}
}
else
{
if ( ImGui::Button( "Stop##Recording" ) )
{
context->sample->FinishRecording();
}
ImGui::TextColored( HexColor( b3_colorSeaGreen ), "recording (from step %d)", context->sample->m_recordStartStep );
}
}
ImGui::End();
}
@ -1836,6 +1938,9 @@ void DrawUI( SampleContext* context )
DrawSamplePicker( context );
DrawInfoPanel( context );
// Extra top-level windows (the Replay viewer adds the Outline panel).
context->sample->DrawSampleWindows();
// Bottom diagnostics drawer. Sample controls live in the info panel.
context->sample->DrawMetrics();
}

View file

@ -46,6 +46,14 @@ struct SampleContext
// Used to shift the origin and test round-off problems
b3Vec3 origin = b3Vec3_zero;
// Recording output path and the path the Replay viewer opens. Edited in the UI and persisted.
char recordingFile[256] = "recording.b3rec";
char replayFile[256] = "";
// Keyframe ring policy the Replay viewer applies on open, persisted across sessions.
int replayKeyframeBudgetMB = 512;
int replayKeyframeMinInterval = 16;
float hertz = 60.0f;
float recycleDistance = 0.05f;
int subStepCount = 4;
@ -107,9 +115,24 @@ public:
return true;
}
// Arm recording on the live world, snapshotting it as the seed so capture can begin at any
// step boundary. Stop writes the file named by the context and frees the buffer.
void StartRecording();
void FinishRecording();
// Bottom diagnostics drawer (Profile / Counters / Renderer / Frame Time).
void DrawMetrics();
// Append extra tabs to the diagnostics drawer's tab bar (the Replay viewer adds Timeline).
virtual void DrawMetricsTab()
{
}
// Draw extra top-level windows when the UI is shown (the Replay viewer adds the Outline panel).
virtual void DrawSampleWindows()
{
}
virtual void Keyboard( int key, int action, int modifiers )
{
}
@ -152,6 +175,10 @@ public:
int m_triangleIndex;
uint64_t m_userMaterialId;
// Active recording, or null when not recording. The step recording began on drives the status.
struct b3Recording* m_recording;
int m_recordStartStep;
b3Profile m_profiles[m_profileCapacity];
int m_currentProfileIndex;
int m_profileReadIndex;
@ -178,8 +205,14 @@ struct SampleEntry
extern SampleEntry g_sampleEntries[MAX_SAMPLES];
extern int g_sampleCount;
// Index of the registered Replay viewer, or -1 if none. Gates the Replay menu.
extern int g_replayIndex;
int RegisterSample( const char* category, const char* name, SampleCreateFcn* fcn );
// Register the Replay viewer and record its index in g_replayIndex.
int RegisterReplay( const char* category, const char* name, SampleCreateFcn* fcn );
// Destroy the active sample and build the selected one. restart keeps the camera
// by leaving the restart flag set while the new sample constructs.
void SelectSample( SampleContext* context, int selection, bool restart );

View file

@ -654,7 +654,7 @@ public:
return new BenchmarkHeightField( context );
}
b3HeightField* m_heightField;
b3HeightFieldData* m_heightField;
int m_columnCount;
int m_rowCount;
float m_radius;

View file

@ -582,7 +582,7 @@ public:
b3MeshData* m_levelMesh;
b3MeshData* m_stairs;
b3MeshData* m_torus;
b3HeightField* m_heightField;
b3HeightFieldData* m_heightField;
b3ShapeId m_ignoreShapeId;
bool m_clipVelocity;
};
@ -1664,7 +1664,7 @@ public:
b3MeshData* m_building;
b3MeshData* m_voxel01;
b3MeshData* m_voxel02;
b3HeightField* m_heightField;
b3HeightFieldData* m_heightField;
bool m_showDebug;
};

View file

@ -349,11 +349,6 @@ public:
e_maxCount = 64
};
static Sample* Create( SampleContext* context )
{
return new CastWorld( context );
}
explicit CastWorld( SampleContext* context )
: Sample( context )
{
@ -516,11 +511,6 @@ public:
}
}
bool HasSolverControls() const override
{
return false;
}
bool DrawControls() override
{
const char* castTypes[] = { "Ray", "Sphere", "Capsule", "Box" };
@ -573,55 +563,6 @@ public:
return true;
}
void Render() override
{
DrawTextLine( "Ctrl + left mouse to cast through cursor" );
DrawTextLine( "Shapes drawn in yellow boxes are ignored by the ray" );
// Outline the bodies the cast ignores
for ( int i = 0; i < m_maxCount; ++i )
{
if ( ( i & m_ignoreBase ) == m_ignoreBase && B3_IS_NULL( m_bodies[i] ) == false )
{
b3AABB bounds = b3Body_ComputeAABB( m_bodies[i] );
DrawBounds( bounds, 0.0f, MakeColor( b3_colorYellow ) );
}
}
switch ( m_mode )
{
case e_any:
DrawTextLine( "Cast mode: any - check for obstruction - unsorted" );
break;
case e_closest:
DrawTextLine( "Cast mode: closest - find closest shape along the cast" );
break;
case e_multiple:
DrawTextLine( "Cast mode: multiple - gather multiple shapes - unsorted" );
break;
case e_sorted:
DrawTextLine( "Cast mode: sorted - gather multiple shapes sorted by closeness" );
break;
default:
assert( false );
break;
}
for ( int i = 0; i < m_castContext.count; ++i )
{
DrawTextLine( "material = %d, triangle = %d", m_castContext.materialIds[i], m_castContext.triangleIndices[i] );
}
DrawGroundGrid( 10 );
DrawAxes( b3WorldTransform_identity, 1.0f );
Sample::Render();
}
void Step() override
{
Sample::Step();
@ -717,6 +658,7 @@ public:
else if ( m_castType == e_sphereCast )
{
DrawLine( point, head, MakeColor( color1 ) );
//DrawWireSphere( transform, &sphere, 32, MakeColorAlpha( colors[i], 0.5f ) );
DrawSolidSphere( transform, sphere, MakeColorAlpha( colors[i], 0.5f ) );
}
else if ( m_castType == e_capsuleCast )
@ -752,16 +694,65 @@ public:
}
DrawPoint( m_origin, 10.0f, MakeColor( green ) );
DrawTextLine( "Ctrl + left mouse to cast through cursor" );
DrawTextLine( "Shapes drawn in yellow boxes are ignored by the ray" );
// Outline the bodies the cast ignores
for ( int i = 0; i < m_maxCount; ++i )
{
if ( ( i & m_ignoreBase ) == m_ignoreBase && B3_IS_NULL( m_bodies[i] ) == false )
{
b3AABB bounds = b3Body_ComputeAABB( m_bodies[i] );
DrawBounds( bounds, 0.0f, MakeColor( b3_colorYellow ) );
}
}
switch ( m_mode )
{
case e_any:
DrawTextLine( "Cast mode: any - check for obstruction - unsorted" );
break;
case e_closest:
DrawTextLine( "Cast mode: closest - find closest shape along the cast" );
break;
case e_multiple:
DrawTextLine( "Cast mode: multiple - gather multiple shapes - unsorted" );
break;
case e_sorted:
DrawTextLine( "Cast mode: sorted - gather multiple shapes sorted by closeness" );
break;
default:
assert( false );
break;
}
for ( int i = 0; i < m_castContext.count; ++i )
{
DrawTextLine( "material = %d, triangle = %d", m_castContext.materialIds[i], m_castContext.triangleIndices[i] );
}
DrawGroundGrid( 10 );
DrawAxes( b3WorldTransform_identity, 1.0f );
}
static Sample* Create( SampleContext* context )
{
return new CastWorld( context );
}
static constexpr int m_maxCount = 64;
static constexpr int m_ignoreBase = 0x3;
static constexpr int m_ignoreBase = 0x7;
b3Capsule m_capsule;
b3Sphere m_sphere;
b3BoxHull m_box;
b3MeshData* m_mesh;
b3HeightField* m_heightField;
b3HeightFieldData* m_heightField;
b3BodyId m_bodies[m_maxCount];
int m_bodyIndex;
@ -1335,7 +1326,7 @@ public:
b3BoxHull m_box;
b3MeshData* m_mesh;
b3HeightField* m_heightField;
b3HeightFieldData* m_heightField;
int m_baseX;
float m_castOffset;
bool m_tracking;

View file

@ -100,7 +100,7 @@ public:
return new SimpleCompound( context );
}
b3Compound* m_compound;
b3CompoundData* m_compound;
};
static int sampleSimple = RegisterSample( "Compound", "Simple", SimpleCompound::Create );
@ -161,7 +161,7 @@ public:
}
static constexpr int m_count = 20;
b3Compound* m_compound;
b3CompoundData* m_compound;
};
static int sampleCompoundSpheres = RegisterSample( "Compound", "Spheres", CompoundSpheres::Create );
@ -235,7 +235,7 @@ public:
}
static constexpr int m_count = 20;
b3Compound* m_compound;
b3CompoundData* m_compound;
};
static int sampleCompoundHulls = RegisterSample( "Compound", "Hulls", CompoundHulls::Create );
@ -353,7 +353,7 @@ public:
return new TileFloor( context );
}
b3Compound* m_compound;
b3CompoundData* m_compound;
};
static int sampleTileFloor = RegisterSample( "Compound", "Tile Floor", TileFloor::Create );
@ -469,7 +469,7 @@ public:
return new MeshTile( context );
}
b3Compound* m_compound;
b3CompoundData* m_compound;
};
static int sampleCompoundMesh = RegisterSample( "Compound", "Mesh Tile", MeshTile::Create );
@ -789,7 +789,7 @@ public:
return new Village( context );
}
b3Compound* m_compound;
b3CompoundData* m_compound;
CharacterMover m_mover;
float m_worldWidth;
b3Pos m_rayOrigin;

View file

@ -454,7 +454,7 @@ public:
}
b3MeshData* m_boxMesh;
b3HeightField* m_heightField;
b3HeightFieldData* m_heightField;
b3MeshData* m_gridMesh;
};

View file

@ -2394,8 +2394,7 @@ public:
// b3DestroyHull( hull );
m_camera->m_thirdPerson = true;
sapp_lock_mouse( true );
m_camera->m_thirdPerson = false;
m_haveMouseLast = false;
m_mouseLast = { 0.0f, 0.0f };
@ -2404,37 +2403,14 @@ public:
~Driving() override
{
m_camera->m_thirdPerson = false;
sapp_lock_mouse( false );
if (m_camera->m_thirdPerson)
{
m_camera->m_thirdPerson = false;
sapp_lock_mouse( false );
}
b3DestroyHeightField( m_heightField );
}
#if 0
void MouseMove( b3Vec2 p ) override
{
if ( m_camera->m_thirdPerson )
{
if ( m_haveMouseLast == false )
{
m_mouseLast = p;
m_haveMouseLast = true;
}
else
{
m_mouseDelta = { p.x - m_mouseLast.x, p.y - m_mouseLast.y };
m_mouseLast = p;
}
const float sensitivity = 0.05f;
m_camera->m_yaw -= 2.0f * sensitivity * m_mouseDelta.x;
m_camera->m_pitch += sensitivity * m_mouseDelta.y;
m_camera->m_pitch = b3ClampFloat( m_camera->m_pitch, -85.0f, 85.0f );
}
Sample::MouseMove( p );
}
#endif
void Keyboard( int key, int action, int mods ) override
{
if ( key == KEY_T && action == ACTION_PRESS )
@ -2620,7 +2596,7 @@ public:
return new Driving( context );
}
b3HeightField* m_heightField;
b3HeightFieldData* m_heightField;
b3BodyId m_chassisId;
b3JointId m_frontLeftId;
b3JointId m_frontRightId;

View file

@ -985,7 +985,7 @@ public:
b3Vec3 m_scale;
b3Vec3 m_rayOrigin;
b3Vec3 m_rayTranslation;
b3HeightField* m_heightField;
b3HeightFieldData* m_heightField;
float m_radius;
int m_rowCount;
int m_columnCount;

1255
samples/sample_replay.cpp Normal file

File diff suppressed because it is too large Load diff

View file

@ -55,6 +55,13 @@ set(BOX3D_SOURCE_FILES
platform.h
prismatic_joint.c
qsort.h
recording.c
recording.h
recording_ops.inl
recording_replay.c
recording_replay.h
world_snapshot.c
world_snapshot.h
revolute_joint.c
scheduler.c
scheduler.h

View file

@ -10,6 +10,7 @@
#include "island.h"
#include "joint.h"
#include "physics_world.h"
#include "recording.h"
#include "sensor.h"
#include "shape.h"
#include "solver_set.h"
@ -318,6 +319,8 @@ b3BodyId b3CreateBody( b3WorldId worldId, const b3BodyDef* def )
world->locked = false;
B3_REC_CREATE( world, CreateBody, id, worldId, *def );
return id;
}
@ -356,6 +359,8 @@ void b3DestroyBody( b3BodyId bodyId )
return;
}
B3_REC( world, DestroyBody, bodyId );
world->locked = true;
b3Body* body = b3GetBodyFullId( world, bodyId );
@ -621,7 +626,7 @@ b3BodyCastResult b3Body_CastRay( b3BodyId bodyId, b3Pos origin, b3Vec3 translati
b3ShapeId id = { shape->id + 1, bodyId.world0, shape->generation };
int materialIndex = b3ClampInt( shapeOutput.materialIndex, 0, shape->materialCount - 1 );
uint64_t userMaterialId = shape->materials[materialIndex].userMaterialId;
uint64_t userMaterialId = b3GetShapeMaterials( shape )[materialIndex].userMaterialId;
result = (b3BodyCastResult){
.shapeId = id,
@ -686,7 +691,7 @@ b3BodyCastResult b3Body_CastShape( b3BodyId bodyId, b3Pos origin, const b3ShapeP
// Careful with id, shapeId is the next shape.
b3ShapeId id = { shape->id + 1, bodyId.world0, shape->generation };
int materialIndex = b3ClampInt( shapeOutput.materialIndex, 0, shape->materialCount - 1 );
uint64_t userMaterialId = shape->materials[materialIndex].userMaterialId;
uint64_t userMaterialId = b3GetShapeMaterials( shape )[materialIndex].userMaterialId;
result = (b3BodyCastResult){
.shapeId = id,
@ -1052,6 +1057,8 @@ void b3Body_SetTransform( b3BodyId bodyId, b3Pos position, b3Quat rotation )
b3World* world = b3GetWorld( bodyId.world0 );
B3_ASSERT( world->locked == false );
B3_REC( world, BodySetTransform, bodyId, position, rotation );
b3Body* body = b3GetBodyFullId( world, bodyId );
b3BodySim* bodySim = b3GetBodySim( world, body );
@ -1129,6 +1136,9 @@ void b3Body_SetLinearVelocity( b3BodyId bodyId, b3Vec3 linearVelocity )
B3_ASSERT( b3IsValidVec3( linearVelocity ) );
b3World* world = b3GetWorld( bodyId.world0 );
B3_REC( world, BodySetLinearVelocity, bodyId, linearVelocity );
b3Body* body = b3GetBodyFullId( world, bodyId );
if ( body->type == b3_staticBody )
@ -1155,6 +1165,9 @@ void b3Body_SetAngularVelocity( b3BodyId bodyId, b3Vec3 angularVelocity )
B3_ASSERT( b3IsValidVec3( angularVelocity ) );
b3World* world = b3GetWorld( bodyId.world0 );
B3_REC( world, BodySetAngularVelocity, bodyId, angularVelocity );
b3Body* body = b3GetBodyFullId( world, bodyId );
if ( body->type == b3_staticBody )
@ -1187,6 +1200,9 @@ void b3Body_SetTargetTransform( b3BodyId bodyId, b3WorldTransform target, float
B3_ASSERT( b3IsValidWorldTransform( target ) );
b3World* world = b3GetWorld( bodyId.world0 );
B3_REC( world, BodySetTargetTransform, bodyId, target, timeStep, wake );
b3Body* body = b3GetBodyFullId( world, bodyId );
if ( body->setIndex == b3_disabledSet )
@ -1292,6 +1308,9 @@ void b3Body_ApplyForce( b3BodyId bodyId, b3Vec3 force, b3Pos point, bool wake )
B3_ASSERT( b3IsValidVec3( force ) );
b3World* world = b3GetWorld( bodyId.world0 );
B3_REC( world, BodyApplyForce, bodyId, force, point, wake );
b3Body* body = b3GetBodyFullId( world, bodyId );
if ( wake && body->setIndex >= b3_firstSleepingSet )
@ -1312,6 +1331,9 @@ void b3Body_ApplyForceToCenter( b3BodyId bodyId, b3Vec3 force, bool wake )
B3_ASSERT( b3IsValidVec3( force ) );
b3World* world = b3GetWorld( bodyId.world0 );
B3_REC( world, BodyApplyForceToCenter, bodyId, force, wake );
b3Body* body = b3GetBodyFullId( world, bodyId );
if ( wake && body->setIndex >= b3_firstSleepingSet )
@ -1331,6 +1353,9 @@ void b3Body_ApplyTorque( b3BodyId bodyId, b3Vec3 torque, bool wake )
B3_ASSERT( b3IsValidVec3( torque ) );
b3World* world = b3GetWorld( bodyId.world0 );
B3_REC( world, BodyApplyTorque, bodyId, torque, wake );
b3Body* body = b3GetBodyFullId( world, bodyId );
if ( wake && body->setIndex >= b3_firstSleepingSet )
@ -1351,6 +1376,9 @@ void b3Body_ApplyLinearImpulse( b3BodyId bodyId, b3Vec3 impulse, b3Pos point, bo
B3_ASSERT( b3IsValidPosition( point ) );
b3World* world = b3GetWorld( bodyId.world0 );
B3_REC( world, BodyApplyLinearImpulse, bodyId, impulse, point, wake );
b3Body* body = b3GetBodyFullId( world, bodyId );
if ( wake && body->setIndex >= b3_firstSleepingSet )
@ -1383,6 +1411,9 @@ void b3Body_ApplyLinearImpulseToCenter( b3BodyId bodyId, b3Vec3 impulse, bool wa
B3_ASSERT( b3IsValidVec3( impulse ) );
b3World* world = b3GetWorld( bodyId.world0 );
B3_REC( world, BodyApplyLinearImpulseToCenter, bodyId, impulse, wake );
b3Body* body = b3GetBodyFullId( world, bodyId );
if ( wake && body->setIndex >= b3_firstSleepingSet )
@ -1413,6 +1444,8 @@ void b3Body_ApplyAngularImpulse( b3BodyId bodyId, b3Vec3 impulse, bool wake )
b3World* world = b3GetWorld( bodyId.world0 );
B3_REC( world, BodyApplyAngularImpulse, bodyId, impulse, wake );
int id = bodyId.index1 - 1;
b3Body* body = b3Array_Get( world->bodies, id );
B3_ASSERT( body->generation == bodyId.generation );
@ -1479,6 +1512,8 @@ void b3Body_SetType( b3BodyId bodyId, b3BodyType type )
return;
}
B3_REC( world, BodySetType, bodyId, (int32_t)type );
world->locked = true;
b3Body* body = b3GetBodyFullId( world, bodyId );
@ -1690,6 +1725,9 @@ void b3Body_SetType( b3BodyId bodyId, b3BodyType type )
void b3Body_SetName( b3BodyId bodyId, const char* name )
{
b3World* world = b3GetWorld( bodyId.world0 );
B3_REC( world, BodySetName, bodyId, name );
b3Body* body = b3GetBodyFullId( world, bodyId );
if ( name )
@ -1786,6 +1824,8 @@ void b3Body_SetMassData( b3BodyId bodyId, b3MassData massData )
return;
}
B3_REC( world, BodySetMassData, bodyId, massData );
b3Body* body = b3GetBodyFullId( world, bodyId );
b3BodySim* bodySim = b3GetBodySim( world, body );
@ -1818,6 +1858,8 @@ void b3Body_ApplyMassFromShapes( b3BodyId bodyId )
return;
}
B3_REC( world, BodyApplyMassFromShapes, bodyId );
b3Body* body = b3GetBodyFullId( world, bodyId );
b3UpdateBodyMassData( world, body );
}
@ -1832,6 +1874,8 @@ void b3Body_SetLinearDamping( b3BodyId bodyId, float linearDamping )
return;
}
B3_REC( world, BodySetLinearDamping, bodyId, linearDamping );
b3Body* body = b3GetBodyFullId( world, bodyId );
b3BodySim* bodySim = b3GetBodySim( world, body );
bodySim->linearDamping = linearDamping;
@ -1855,6 +1899,8 @@ void b3Body_SetAngularDamping( b3BodyId bodyId, float angularDamping )
return;
}
B3_REC( world, BodySetAngularDamping, bodyId, angularDamping );
b3Body* body = b3GetBodyFullId( world, bodyId );
b3BodySim* bodySim = b3GetBodySim( world, body );
bodySim->angularDamping = angularDamping;
@ -1879,6 +1925,8 @@ void b3Body_SetGravityScale( b3BodyId bodyId, float gravityScale )
return;
}
B3_REC( world, BodySetGravityScale, bodyId, gravityScale );
b3Body* body = b3GetBodyFullId( world, bodyId );
b3BodySim* bodySim = b3GetBodySim( world, body );
bodySim->gravityScale = gravityScale;
@ -1908,6 +1956,8 @@ void b3Body_SetAwake( b3BodyId bodyId, bool awake )
return;
}
B3_REC( world, BodySetAwake, bodyId, awake );
world->locked = true;
b3Body* body = b3GetBodyFullId( world, bodyId );
@ -1948,6 +1998,9 @@ bool b3Body_IsSleepEnabled( b3BodyId bodyId )
void b3Body_SetSleepThreshold( b3BodyId bodyId, float sleepThreshold )
{
b3World* world = b3GetWorld( bodyId.world0 );
B3_REC( world, BodySetSleepThreshold, bodyId, sleepThreshold );
b3Body* body = b3GetBodyFullId( world, bodyId );
body->sleepThreshold = sleepThreshold;
}
@ -1967,6 +2020,8 @@ void b3Body_EnableSleep( b3BodyId bodyId, bool enableSleep )
return;
}
B3_REC( world, BodyEnableSleep, bodyId, enableSleep );
b3Body* body = b3GetBodyFullId( world, bodyId );
bool flag = ( body->flags & b3_enableSleep ) == b3_enableSleep;
@ -1998,6 +2053,8 @@ void b3Body_Disable( b3BodyId bodyId )
return;
}
B3_REC( world, BodyDisable, bodyId );
world->locked = true;
b3Body* body = b3GetBodyFullId( world, bodyId );
@ -2073,6 +2130,8 @@ void b3Body_Enable( b3BodyId bodyId )
return;
}
B3_REC( world, BodyEnable, bodyId );
b3Body* body = b3GetBodyFullId( world, bodyId );
if ( body->setIndex != b3_disabledSet )
{
@ -2163,6 +2222,8 @@ void b3Body_SetMotionLocks( b3BodyId bodyId, b3MotionLocks locks )
return;
}
B3_REC( world, BodySetMotionLocks, bodyId, locks );
uint32_t newLocks = 0;
newLocks |= locks.linearX ? b3_lockLinearX : 0;
newLocks |= locks.linearY ? b3_lockLinearY : 0;
@ -2249,6 +2310,8 @@ void b3Body_SetBullet( b3BodyId bodyId, bool flag )
return;
}
B3_REC( world, BodySetBullet, bodyId, flag );
uint32_t newFlag = flag ? b3_isBullet : 0;
b3Body* body = b3GetBodyFullId( world, bodyId );
@ -2278,6 +2341,8 @@ void b3Body_EnableContactRecycling( b3BodyId bodyId, bool flag )
return;
}
B3_REC( world, BodyEnableContactRecycling, bodyId, flag );
uint32_t newFlag = flag ? b3_bodyEnableContactRecycling : 0;
b3Body* body = b3GetBodyFullId( world, bodyId );
@ -2302,6 +2367,9 @@ bool b3Body_IsContactRecyclingEnabled( b3BodyId bodyId )
void b3Body_EnableHitEvents( b3BodyId bodyId, bool enableHitEvents )
{
b3World* world = b3GetWorld( bodyId.world0 );
B3_REC( world, BodyEnableHitEvents, bodyId, enableHitEvents );
b3Body* body = b3GetBodyFullId( world, bodyId );
int shapeId = body->headShapeId;
while ( shapeId != B3_NULL_INDEX )

View file

@ -42,7 +42,7 @@ typedef struct b3MeshInstance
uint32_t materialIndices[B3_MAX_COMPOUND_MESH_MATERIALS];
} b3MeshInstance;
static inline b3TreeNode* b3GetCompoundNodes( b3Compound* compound )
static inline b3TreeNode* b3GetCompoundNodes( b3CompoundData* compound )
{
if ( compound->nodeOffset == 0 )
{
@ -52,7 +52,7 @@ static inline b3TreeNode* b3GetCompoundNodes( b3Compound* compound )
return (b3TreeNode*)( (intptr_t)compound + compound->nodeOffset );
}
const b3SurfaceMaterial* b3GetCompoundMaterials( const b3Compound* compound )
const b3SurfaceMaterial* b3GetCompoundMaterials( const b3CompoundData* compound )
{
if ( compound->materialOffset == 0 )
{
@ -62,7 +62,7 @@ const b3SurfaceMaterial* b3GetCompoundMaterials( const b3Compound* compound )
return (b3SurfaceMaterial*)( (intptr_t)compound + compound->materialOffset );
}
b3CompoundCapsule b3GetCompoundCapsule( const b3Compound* compound, int index )
b3CompoundCapsule b3GetCompoundCapsule( const b3CompoundData* compound, int index )
{
B3_ASSERT( 0 <= index && index < compound->capsuleCount && compound->capsuleOffset > 0 );
@ -76,7 +76,7 @@ b3CompoundCapsule b3GetCompoundCapsule( const b3Compound* compound, int index )
return capsules[index];
}
b3CompoundHull b3GetCompoundHull( const b3Compound* compound, int index )
b3CompoundHull b3GetCompoundHull( const b3CompoundData* compound, int index )
{
B3_ASSERT( 0 <= index && index < compound->hullCount && compound->hullOffset > 0 );
@ -95,7 +95,7 @@ b3CompoundHull b3GetCompoundHull( const b3Compound* compound, int index )
return result;
}
b3CompoundMesh b3GetCompoundMesh( const b3Compound* compound, int index )
b3CompoundMesh b3GetCompoundMesh( const b3CompoundData* compound, int index )
{
B3_ASSERT( 0 <= index && index < compound->meshCount && compound->meshOffset > 0 );
@ -118,7 +118,7 @@ b3CompoundMesh b3GetCompoundMesh( const b3Compound* compound, int index )
return result;
}
b3CompoundSphere b3GetCompoundSphere( const b3Compound* compound, int index )
b3CompoundSphere b3GetCompoundSphere( const b3CompoundData* compound, int index )
{
B3_ASSERT( 0 <= index && index < compound->sphereCount && compound->sphereOffset > 0 );
@ -132,7 +132,7 @@ b3CompoundSphere b3GetCompoundSphere( const b3Compound* compound, int index )
return spheres[index];
}
b3ChildShape b3GetCompoundChild( const b3Compound* compound, int childIndex )
b3ChildShape b3GetCompoundChild( const b3CompoundData* compound, int childIndex )
{
// Capsule?
if ( 0 <= childIndex && childIndex < compound->capsuleCount )
@ -251,7 +251,7 @@ static bool b3CompareMaterials( const b3SurfaceMaterial* mat1, const b3SurfaceMa
#define FREE_FN b3Free
#include "verstable.h"
b3Compound* b3CreateCompound( const b3CompoundDef* def )
b3CompoundData* b3CreateCompound( const b3CompoundDef* def )
{
int convexCount = def->capsuleCount + def->hullCount + def->sphereCount;
int shapeCount = convexCount + def->meshCount;
@ -467,7 +467,7 @@ b3Compound* b3CreateCompound( const b3CompoundDef* def )
b3DynamicTree_Rebuild( &tree, true );
int byteCount = sizeof( b3Compound );
int byteCount = sizeof( b3CompoundData );
// Tree nodes - todo 64 byte alignment
int nodeOffset = byteCount;
@ -514,7 +514,7 @@ b3Compound* b3CreateCompound( const b3CompoundDef* def )
int sphereOffset = byteCount;
byteCount += def->sphereCount * sizeof( b3CompoundSphere );
b3Compound* compound = b3Alloc( byteCount );
b3CompoundData* compound = b3Alloc( byteCount );
memset( compound, 0, byteCount );
compound->version = B3_COMPOUND_VERSION;
@ -626,27 +626,27 @@ b3Compound* b3CreateCompound( const b3CompoundDef* def )
return compound;
}
void b3DestroyCompound( b3Compound* compound )
void b3DestroyCompound( b3CompoundData* compound )
{
b3Free( compound, compound->byteCount );
}
uint8_t* b3ConvertCompoundToBytes( b3Compound* compound )
uint8_t* b3ConvertCompoundToBytes( b3CompoundData* compound )
{
// scrub this pointer before serialization
compound->tree.nodes = NULL;
return (uint8_t*)compound;
}
b3Compound* b3ConvertBytesToCompound( uint8_t* bytes, int byteCount )
b3CompoundData* b3ConvertBytesToCompound( uint8_t* bytes, int byteCount )
{
b3Compound* compound = (b3Compound*)bytes;
b3CompoundData* compound = (b3CompoundData*)bytes;
if ( compound->version != B3_COMPOUND_VERSION )
{
return NULL;
}
if ( compound->byteCount < (int)sizeof( b3Compound ) )
if ( compound->byteCount < (int)sizeof( b3CompoundData ) )
{
return NULL;
}
@ -666,7 +666,7 @@ b3Compound* b3ConvertBytesToCompound( uint8_t* bytes, int byteCount )
return compound;
}
b3AABB b3ComputeCompoundAABB( const b3Compound* shape, b3Transform transform )
b3AABB b3ComputeCompoundAABB( const b3CompoundData* shape, b3Transform transform )
{
B3_ASSERT( shape->nodeOffset > 0 );
@ -678,7 +678,7 @@ b3AABB b3ComputeCompoundAABB( const b3Compound* shape, b3Transform transform )
struct b3CompoundOverlapContext
{
const b3Compound* compound;
const b3CompoundData* compound;
// transform of the compound
b3Transform transform;
b3ShapeProxy proxy;
@ -730,7 +730,7 @@ static bool b3CompoundOverlapCallback( int proxyId, uint64_t userData, void* con
return true;
}
bool b3OverlapCompound( const b3Compound* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy )
bool b3OverlapCompound( const b3CompoundData* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy )
{
struct b3CompoundOverlapContext context = {
.compound = shape,
@ -757,7 +757,7 @@ bool b3OverlapCompound( const b3Compound* shape, b3Transform shapeTransform, con
struct b3CompoundCastContext
{
const b3Compound* compound;
const b3CompoundData* compound;
b3CastOutput* output;
// origin of the shape cast, the box cast callback only carries the advancing fraction
const b3ShapeCastInput* shapeInput;
@ -768,7 +768,7 @@ static float b3CompoundRayCastCallback( const b3RayCastInput* input, int proxyId
B3_UNUSED( proxyId );
struct b3CompoundCastContext* castContext = context;
const b3Compound* compound = castContext->compound;
const b3CompoundData* compound = castContext->compound;
int childIndex = (int)userData;
@ -823,7 +823,7 @@ static float b3CompoundRayCastCallback( const b3RayCastInput* input, int proxyId
return input->maxFraction;
}
b3CastOutput b3RayCastCompound( const b3Compound* shape, const b3RayCastInput* input )
b3CastOutput b3RayCastCompound( const b3CompoundData* shape, const b3RayCastInput* input )
{
b3CastOutput result = { 0 };
@ -840,7 +840,7 @@ static float b3CompoundShapeCastCallback( const b3BoxCastInput* input, int proxy
B3_UNUSED( proxyId );
struct b3CompoundCastContext* castContext = context;
const b3Compound* compound = castContext->compound;
const b3CompoundData* compound = castContext->compound;
const b3ShapeCastInput* shapeInput = castContext->shapeInput;
int childIndex = (int)userData;
@ -910,7 +910,7 @@ static float b3CompoundShapeCastCallback( const b3BoxCastInput* input, int proxy
return input->maxFraction;
}
b3CastOutput b3ShapeCastCompound( const b3Compound* shape, const b3ShapeCastInput* input )
b3CastOutput b3ShapeCastCompound( const b3CompoundData* shape, const b3ShapeCastInput* input )
{
b3CastOutput result = { 0 };
@ -934,7 +934,7 @@ b3CastOutput b3ShapeCastCompound( const b3Compound* shape, const b3ShapeCastInpu
struct b3CompoundQueryContext
{
const b3Compound* compound;
const b3CompoundData* compound;
b3CompoundQueryFcn* fcn;
void* userContext;
};
@ -946,7 +946,7 @@ static bool TreeQueryCallbackFcn( int proxyId, uint64_t userData, void* treeCont
return context->fcn( context->compound, (int)userData, context->userContext );
}
void b3QueryCompound( const b3Compound* compound, b3AABB aabb, b3CompoundQueryFcn* fcn, void* context )
void b3QueryCompound( const b3CompoundData* compound, b3AABB aabb, b3CompoundQueryFcn* fcn, void* context )
{
struct b3CompoundQueryContext compoundContext = {
.compound = compound,
@ -972,7 +972,7 @@ struct b3CompoundImpactContext
float fallbackRadius;
};
static bool b3CompoundTimeOfImpactFcn( const b3Compound* compound, int childIndex, void* context )
static bool b3CompoundTimeOfImpactFcn( const b3CompoundData* compound, int childIndex, void* context )
{
b3CompoundImpactContext* toiContext = (b3CompoundImpactContext*)context;
@ -1063,7 +1063,7 @@ static bool b3CompoundTimeOfImpactFcn( const b3Compound* compound, int childInde
return true;
}
b3TOIOutput b3CompoundTimeOfImpact(const b3Compound* compound, b3Transform transform, const b3ShapeProxy* proxy,
b3TOIOutput b3CompoundTimeOfImpact(const b3CompoundData* compound, b3Transform transform, const b3ShapeProxy* proxy,
const b3Sweep* sweep, float maxFraction)
{
b3CompoundImpactContext context = {0};
@ -1110,7 +1110,7 @@ b3Sweep b3MakeCompoundChildSweep( b3Transform compoundTransform, b3Transform chi
struct b3CompoundMoverContext
{
const b3Compound* compound;
const b3CompoundData* compound;
b3PlaneResult* planes;
int planeCapacity;
int planeCount;
@ -1173,7 +1173,7 @@ static bool b3CompoundMoverCallback( int proxyId, uint64_t userData, void* conte
return moverContext->planeCount < moverContext->planeCapacity;
}
int b3CollideMoverAndCompound( b3PlaneResult* planes, int capacity, const b3Compound* shape, const b3Capsule* mover )
int b3CollideMoverAndCompound( b3PlaneResult* planes, int capacity, const b3CompoundData* shape, const b3Capsule* mover )
{
struct b3CompoundMoverContext context = {
.compound = shape,

View file

@ -5,10 +5,10 @@
#include "box3d/types.h"
b3TOIOutput b3CompoundTimeOfImpact( const b3Compound* compound, b3Transform transform, const b3ShapeProxy* proxy,
b3TOIOutput b3CompoundTimeOfImpact( const b3CompoundData* compound, b3Transform transform, const b3ShapeProxy* proxy,
const b3Sweep* sweep, float maxFraction );
// Transforms a sweep for a compound child shape
b3Sweep b3MakeCompoundChildSweep( b3Transform compoundTransform, b3Transform childTransform );
int b3CollideMoverAndCompound( b3PlaneResult* planes, int capacity, const b3Compound* shape, const b3Capsule* mover );
int b3CollideMoverAndCompound( b3PlaneResult* planes, int capacity, const b3CompoundData* shape, const b3Capsule* mover );

View file

@ -314,7 +314,8 @@ void b3CreateContact( b3World* world, b3Shape* shapeA, b3Shape* shapeB, int chil
// Assuming the rolling resistance doesn't change
contact->rollingResistance =
b3MaxFloat( shapeA->materials[0].rollingResistance, shapeB->materials[0].rollingResistance ) * maxRadius;
b3MaxFloat( b3GetShapeMaterials( shapeA )[0].rollingResistance, b3GetShapeMaterials( shapeB )[0].rollingResistance ) *
maxRadius;
if ( shapeA->enablePreSolveEvents || shapeB->enablePreSolveEvents )
{
@ -633,8 +634,8 @@ static bool b3UpdateConvexContact( b3World* world, int workerIndex, b3Contact* c
}
}
const b3SurfaceMaterial* materialA = shapeA->materials + 0;
const b3SurfaceMaterial* materialB = shapeB->materials + 0;
const b3SurfaceMaterial* materialA = b3GetShapeMaterials( shapeA );
const b3SurfaceMaterial* materialB = b3GetShapeMaterials( shapeB );
// Keep these updated in case the values on the shapes are modified
contact->friction =

View file

@ -5,6 +5,7 @@
#include "core.h"
#include "joint.h"
#include "physics_world.h"
#include "recording.h"
#include "solver.h"
#include "solver_set.h"
@ -13,6 +14,8 @@
void b3DistanceJoint_SetLength( b3JointId jointId, float length )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, DistanceJointSetLength, jointId, length );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_distanceJoint );
b3DistanceJoint* joint = &base->distanceJoint;
@ -31,6 +34,8 @@ float b3DistanceJoint_GetLength( b3JointId jointId )
void b3DistanceJoint_EnableLimit( b3JointId jointId, bool enableLimit )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, DistanceJointEnableLimit, jointId, enableLimit );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_distanceJoint );
b3DistanceJoint* joint = &base->distanceJoint;
joint->enableLimit = enableLimit;
@ -44,6 +49,8 @@ bool b3DistanceJoint_IsLimitEnabled( b3JointId jointId )
void b3DistanceJoint_SetLengthRange( b3JointId jointId, float minLength, float maxLength )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, DistanceJointSetLengthRange, jointId, minLength, maxLength );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_distanceJoint );
b3DistanceJoint* joint = &base->distanceJoint;
@ -92,6 +99,8 @@ float b3DistanceJoint_GetCurrentLength( b3JointId jointId )
void b3DistanceJoint_EnableSpring( b3JointId jointId, bool enableSpring )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, DistanceJointEnableSpring, jointId, enableSpring );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_distanceJoint );
base->distanceJoint.enableSpring = enableSpring;
}
@ -106,6 +115,8 @@ bool b3DistanceJoint_IsSpringEnabled( b3JointId jointId )
void b3DistanceJoint_SetSpringForceRange( b3JointId jointId, float lowerForce, float upperForce )
{
B3_ASSERT( lowerForce <= upperForce );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, DistanceJointSetSpringForceRange, jointId, lowerForce, upperForce );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_distanceJoint );
base->distanceJoint.lowerSpringForce = lowerForce;
base->distanceJoint.upperSpringForce = upperForce;
@ -120,12 +131,16 @@ void b3DistanceJoint_GetSpringForceRange( b3JointId jointId, float* lowerForce,
void b3DistanceJoint_SetSpringHertz( b3JointId jointId, float hertz )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, DistanceJointSetSpringHertz, jointId, hertz );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_distanceJoint );
base->distanceJoint.hertz = hertz;
}
void b3DistanceJoint_SetSpringDampingRatio( b3JointId jointId, float dampingRatio )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, DistanceJointSetSpringDampingRatio, jointId, dampingRatio );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_distanceJoint );
base->distanceJoint.dampingRatio = dampingRatio;
}
@ -146,6 +161,8 @@ float b3DistanceJoint_GetSpringDampingRatio( b3JointId jointId )
void b3DistanceJoint_EnableMotor( b3JointId jointId, bool enableMotor )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, DistanceJointEnableMotor, jointId, enableMotor );
b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_distanceJoint );
if ( enableMotor != joint->distanceJoint.enableMotor )
{
@ -162,6 +179,8 @@ bool b3DistanceJoint_IsMotorEnabled( b3JointId jointId )
void b3DistanceJoint_SetMotorSpeed( b3JointId jointId, float motorSpeed )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, DistanceJointSetMotorSpeed, jointId, motorSpeed );
b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_distanceJoint );
joint->distanceJoint.motorSpeed = motorSpeed;
}
@ -181,6 +200,8 @@ float b3DistanceJoint_GetMotorForce( b3JointId jointId )
void b3DistanceJoint_SetMaxMotorForce( b3JointId jointId, float force )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, DistanceJointSetMaxMotorForce, jointId, force );
b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_distanceJoint );
joint->distanceJoint.maxMotorForce = force;
}

View file

@ -99,23 +99,45 @@
21 3 22
*/
b3HeightField* b3CreateHeightField( const b3HeightFieldDef* data )
b3HeightFieldData* b3CreateHeightField( const b3HeightFieldDef* data )
{
// Zero-init so the trailing pad after `clockwise` is defined — the construction-time
// hash below sweeps raw struct bytes and would otherwise pick up uninitialized padding.
b3HeightField* hf = (b3HeightField*)b3AllocZeroed( sizeof( b3HeightField ) );
int columnCount = data->countX;
int rowCount = data->countZ;
hf->scale = data->scale;
hf->columnCount = columnCount;
hf->rowCount = rowCount;
int heightCount = columnCount * rowCount;
B3_ASSERT( heightCount >= 4 );
hf->compressedHeights = (uint16_t*)b3Alloc( heightCount * sizeof( uint16_t ) );
int cellCount = ( columnCount - 1 ) * ( rowCount - 1 );
int triangleCount = 2 * cellCount;
// Single blob: struct followed by the height, material, and flag arrays. Layout
// mirrors b3HullData/b3MeshData so the recording path can copy it with one memcpy.
size_t byteCount = b3AlignUp8( sizeof( b3HeightFieldData ) );
int heightsOffset = (int)byteCount;
byteCount += b3AlignUp8( heightCount * sizeof( uint16_t ) );
int materialOffset = (int)byteCount;
byteCount += b3AlignUp8( cellCount * sizeof( uint8_t ) );
int flagsOffset = (int)byteCount;
byteCount += b3AlignUp8( triangleCount * sizeof( uint8_t ) );
// Zero the whole blob so alignment padding is defined. The construction-time hash
// sweeps raw bytes and would otherwise pick up uninitialized padding.
b3HeightFieldData* hf = (b3HeightFieldData*)b3Alloc( byteCount );
memset( hf, 0, byteCount );
hf->version = B3_HEIGHT_FIELD_VERSION;
hf->byteCount = (int)byteCount;
hf->scale = data->scale;
hf->columnCount = columnCount;
hf->rowCount = rowCount;
hf->heightsOffset = heightsOffset;
hf->materialOffset = materialOffset;
hf->flagsOffset = flagsOffset;
hf->clockwise = data->clockwiseWinding;
uint16_t* compressedHeights = (uint16_t*)( (intptr_t)hf + heightsOffset );
uint8_t* materialIndices = (uint8_t*)( (intptr_t)hf + materialOffset );
uint8_t* flags = (uint8_t*)( (intptr_t)hf + flagsOffset );
const float* heights = data->heights;
@ -134,7 +156,7 @@ b3HeightField* b3CreateHeightField( const b3HeightFieldDef* data )
{
float clampedHeight = b3ClampFloat( heights[i], hf->minHeight, hf->maxHeight );
float scaledHeight = ( clampedHeight - hf->minHeight ) * invHeightScale;
hf->compressedHeights[i] = (uint16_t)( b3MinFloat( scaledHeight, (float)UINT16_MAX ) );
compressedHeights[i] = (uint16_t)( b3MinFloat( scaledHeight, (float)UINT16_MAX ) );
lowerHeightBound = b3MinFloat( lowerHeightBound, clampedHeight );
upperHeightBound = b3MaxFloat( upperHeightBound, clampedHeight );
@ -144,26 +166,22 @@ b3HeightField* b3CreateHeightField( const b3HeightFieldDef* data )
float* decompressedHeights = (float*)b3Alloc( heightCount * sizeof( float ) );
for ( int i = 0; i < heightCount; ++i )
{
decompressedHeights[i] = hf->minHeight + hf->heightScale * hf->compressedHeights[i];
decompressedHeights[i] = hf->minHeight + hf->heightScale * compressedHeights[i];
}
heights = decompressedHeights;
int cellCount = ( hf->columnCount - 1 ) * ( hf->rowCount - 1 );
hf->materialIndices = (uint8_t*)b3Alloc( cellCount * sizeof( uint8_t ) );
if ( data->materialIndices != NULL )
{
for ( int i = 0; i < cellCount; ++i )
{
hf->materialIndices[i] = data->materialIndices[i];
materialIndices[i] = data->materialIndices[i];
}
}
else
{
for ( int i = 0; i < cellCount; ++i )
{
hf->materialIndices[i] = 0;
materialIndices[i] = 0;
}
}
@ -171,15 +189,6 @@ b3HeightField* b3CreateHeightField( const b3HeightFieldDef* data )
hf->aabb.upperBound =
(b3Vec3){ hf->scale.x * ( hf->columnCount - 1 ), hf->scale.y * upperHeightBound, hf->scale.z * ( hf->rowCount - 1 ) };
hf->version = B3_HEIGHT_FIELD_VERSION;
hf->clockwise = data->clockwiseWinding;
int triangleCount = 2 * cellCount;
hf->flags = (uint8_t*)b3Alloc( triangleCount * sizeof( uint8_t ) );
memset( hf->flags, 0, triangleCount * sizeof( uint8_t ) );
float cos5Deg = 0.9962f;
b3Vec3 scale = hf->scale;
@ -200,7 +209,7 @@ b3HeightField* b3CreateHeightField( const b3HeightFieldDef* data )
int cellIndex = row * ( columnCount - 1 ) + column;
if ( hf->materialIndices[cellIndex] == B3_HEIGHT_FIELD_HOLE )
if ( materialIndices[cellIndex] == B3_HEIGHT_FIELD_HOLE )
{
continue;
}
@ -264,7 +273,7 @@ b3HeightField* b3CreateHeightField( const b3HeightFieldDef* data )
// top
int topCellIndex = ( row - 1 ) * ( columnCount - 1 ) + column;
if ( row > 0 && hf->materialIndices[topCellIndex] != B3_HEIGHT_FIELD_HOLE )
if ( row > 0 && materialIndices[topCellIndex] != B3_HEIGHT_FIELD_HOLE )
{
B3_ASSERT( 0 <= topCellIndex && topCellIndex < cellCount );
@ -310,7 +319,7 @@ b3HeightField* b3CreateHeightField( const b3HeightFieldDef* data )
}
int bottomCellIndex = ( row + 1 ) * ( columnCount - 1 ) + column;
if ( row + 1 < rowCount - 1 && hf->materialIndices[bottomCellIndex] != B3_HEIGHT_FIELD_HOLE )
if ( row + 1 < rowCount - 1 && materialIndices[bottomCellIndex] != B3_HEIGHT_FIELD_HOLE )
{
B3_ASSERT( 0 <= bottomCellIndex && bottomCellIndex < cellCount );
@ -356,7 +365,7 @@ b3HeightField* b3CreateHeightField( const b3HeightFieldDef* data )
}
int leftCellIndex = row * ( columnCount - 1 ) + column - 1;
if ( column - 1 >= 0 && hf->materialIndices[leftCellIndex] != B3_HEIGHT_FIELD_HOLE )
if ( column - 1 >= 0 && materialIndices[leftCellIndex] != B3_HEIGHT_FIELD_HOLE )
{
B3_ASSERT( 0 <= leftCellIndex && leftCellIndex < cellCount );
@ -402,7 +411,7 @@ b3HeightField* b3CreateHeightField( const b3HeightFieldDef* data )
}
int rightCellIndex = row * ( columnCount - 1 ) + column + 1;
if ( column + 1 < columnCount - 1 && hf->materialIndices[rightCellIndex] != B3_HEIGHT_FIELD_HOLE )
if ( column + 1 < columnCount - 1 && materialIndices[rightCellIndex] != B3_HEIGHT_FIELD_HOLE )
{
B3_ASSERT( 0 <= rightCellIndex && rightCellIndex < cellCount );
@ -450,8 +459,8 @@ b3HeightField* b3CreateHeightField( const b3HeightFieldDef* data )
B3_ASSERT( 0 <= flags1 && flags1 <= UINT8_MAX );
B3_ASSERT( 0 <= flags2 && flags2 <= UINT8_MAX );
hf->flags[triangleIndex1] = (uint8_t)flags1;
hf->flags[triangleIndex2] = (uint8_t)flags2;
flags[triangleIndex1] = (uint8_t)flags1;
flags[triangleIndex2] = (uint8_t)flags2;
}
}
@ -459,13 +468,9 @@ b3HeightField* b3CreateHeightField( const b3HeightFieldDef* data )
b3Free( decompressedHeights, heightCount * sizeof( float ) );
// Content hash over the whole blob with the hash field zeroed, like b3HullData/b3MeshData.
hf->hash = 0;
uint32_t h = B3_HASH_INIT;
h = b3Hash( h, (const uint8_t*)hf->compressedHeights, heightCount * (int)sizeof( uint16_t ) );
h = b3Hash( h, (const uint8_t*)hf->materialIndices, cellCount * (int)sizeof( uint8_t ) );
h = b3Hash( h, (const uint8_t*)hf->flags, triangleCount * (int)sizeof( uint8_t ) );
h = b3Hash( h, (const uint8_t*)&hf->aabb, (int)( sizeof( b3HeightField ) - offsetof( b3HeightField, aabb ) ) );
hf->hash = b3NonZeroHash( h );
hf->hash = b3NonZeroHash( b3Hash( B3_HASH_INIT, (const uint8_t*)hf, hf->byteCount ) );
return hf;
}
@ -477,7 +482,7 @@ _Static_assert( b3_inverseConcaveEdge3 == 4 * b3_inverseConcaveEdge1, "bit math"
// Output order matches the index naming used throughout this file:
// corners[0] = (column, row), corners[1] = (column + 1, row),
// corners[2] = (column, row + 1), corners[3] = (column + 1, row + 1).
static inline void b3GetHeightFieldCellCorners( const b3HeightField* hf, int row, int column, b3Vec3 corners[4] )
static inline void b3GetHeightFieldCellCorners( const b3HeightFieldData* hf, int row, int column, b3Vec3 corners[4] )
{
B3_ASSERT( 0 <= row && row < hf->rowCount - 1 && 0 <= column && column < hf->columnCount - 1 );
@ -489,7 +494,7 @@ static inline void b3GetHeightFieldCellCorners( const b3HeightField* hf, int row
float minHeight = hf->minHeight;
float heightScale = hf->heightScale;
const uint16_t* heights = hf->compressedHeights;
const uint16_t* heights = b3GetHeightFieldCompressedHeights( hf );
float height11 = minHeight + heightScale * heights[index11];
float height12 = minHeight + heightScale * heights[index12];
@ -508,13 +513,13 @@ static inline void b3GetHeightFieldCellCorners( const b3HeightField* hf, int row
corners[3] = b3Mul( scale, (b3Vec3){ x2, height22, z2 } );
}
b3Triangle b3GetHeightFieldTriangle( const b3HeightField* heightField, int triangleIndex )
b3Triangle b3GetHeightFieldTriangle( const b3HeightFieldData* heightField, int triangleIndex )
{
B3_ASSERT( 0 <= triangleIndex );
B3_ASSERT( triangleIndex < 2 * ( heightField->columnCount - 1 ) * ( heightField->rowCount - 1 ) );
b3Triangle triangle;
triangle.flags = heightField->flags[triangleIndex];
triangle.flags = b3GetHeightFieldFlags( heightField )[triangleIndex];
int columnCount = heightField->columnCount;
int quadIndex = triangleIndex >> 1;
@ -529,7 +534,7 @@ b3Triangle b3GetHeightFieldTriangle( const b3HeightField* heightField, int trian
int cellIndex = row * ( columnCount - 1 ) + column;
B3_ASSERT( quadIndex == cellIndex );
B3_ASSERT( heightField->materialIndices[cellIndex] != B3_HEIGHT_FIELD_HOLE );
B3_ASSERT( b3GetHeightFieldMaterialIndices( heightField )[cellIndex] != B3_HEIGHT_FIELD_HOLE );
B3_UNUSED( cellIndex );
b3Vec3 corners[4];
@ -572,21 +577,21 @@ b3Triangle b3GetHeightFieldTriangle( const b3HeightField* heightField, int trian
return triangle;
}
int b3GetHeightFieldMaterial( const b3HeightField* heightField, int triangleIndex )
int b3GetHeightFieldMaterial( const b3HeightFieldData* heightField, int triangleIndex )
{
B3_ASSERT( 0 <= triangleIndex );
B3_ASSERT( triangleIndex < 2 * ( heightField->columnCount - 1 ) * ( heightField->rowCount - 1 ) );
int cellIndex = triangleIndex >> 1;
return heightField->materialIndices[cellIndex];
return b3GetHeightFieldMaterialIndices( heightField )[cellIndex];
}
b3AABB b3ComputeHeightFieldAABB( const b3HeightField* shape, b3Transform transform )
b3AABB b3ComputeHeightFieldAABB( const b3HeightFieldData* shape, b3Transform transform )
{
return b3AABB_Transform( transform, shape->aabb );
}
b3CastOutput b3RayCastHeightField( const b3HeightField* heightField, const b3RayCastInput* input )
b3CastOutput b3RayCastHeightField( const b3HeightFieldData* heightField, const b3RayCastInput* input )
{
b3ShapeCastInput shapeCastInput = { 0 };
shapeCastInput.proxy = (b3ShapeProxy){ &input->origin, 1, 0.0f };
@ -598,7 +603,7 @@ b3CastOutput b3RayCastHeightField( const b3HeightField* heightField, const b3Ray
// todo advance cast to the grid border immediately if it starts outside the row/column range
// todo terminate the cast immediately if it leaves the row/column range
b3CastOutput b3ShapeCastHeightField( const b3HeightField* heightField, const b3ShapeCastInput* input )
b3CastOutput b3ShapeCastHeightField( const b3HeightFieldData* heightField, const b3ShapeCastInput* input )
{
b3AABB shapeBounds = b3MakeAABB( input->proxy.points, input->proxy.count, input->proxy.radius );
b3Vec3 shapeTranslation = input->translation;
@ -810,7 +815,7 @@ b3CastOutput b3ShapeCastHeightField( const b3HeightField* heightField, const b3S
int cellIndex = row * ( columnCount - 1 ) + column;
B3_ASSERT( cellIndex < cellCount );
uint8_t materialIndex = heightField->materialIndices[cellIndex];
uint8_t materialIndex = b3GetHeightFieldMaterialIndices( heightField )[cellIndex];
if ( materialIndex == B3_HEIGHT_FIELD_HOLE )
{
continue;
@ -1027,7 +1032,7 @@ b3CastOutput b3ShapeCastHeightField( const b3HeightField* heightField, const b3S
return result;
}
bool b3OverlapHeightField( const b3HeightField* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy )
bool b3OverlapHeightField( const b3HeightFieldData* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy )
{
b3Vec3 buffer[B3_MAX_SHAPE_CAST_POINTS];
b3ShapeProxy localProxy = b3MakeLocalProxy( proxy, shapeTransform, buffer );
@ -1069,7 +1074,7 @@ bool b3OverlapHeightField( const b3HeightField* shape, b3Transform shapeTransfor
int cellIndex = row * ( shape->columnCount - 1 ) + column;
B3_ASSERT( cellIndex < ( shape->rowCount - 1 ) * ( shape->columnCount - 1 ) );
uint8_t material = shape->materialIndices[cellIndex];
uint8_t material = b3GetHeightFieldMaterialIndices( shape )[cellIndex];
if ( material == B3_HEIGHT_FIELD_HOLE )
{
continue;
@ -1130,7 +1135,7 @@ bool b3OverlapHeightField( const b3HeightField* shape, b3Transform shapeTransfor
return false;
}
void b3QueryHeightField( const b3HeightField* heightField, b3AABB bounds, b3MeshQueryFcn* fcn, void* context )
void b3QueryHeightField( const b3HeightFieldData* heightField, b3AABB bounds, b3MeshQueryFcn* fcn, void* context )
{
b3Vec3 scale = heightField->scale;
@ -1157,7 +1162,7 @@ void b3QueryHeightField( const b3HeightField* heightField, b3AABB bounds, b3Mesh
int cellIndex = row * ( heightField->columnCount - 1 ) + column;
B3_ASSERT( cellIndex < ( heightField->rowCount - 1 ) * ( heightField->columnCount - 1 ) );
uint8_t material = heightField->materialIndices[cellIndex];
uint8_t material = b3GetHeightFieldMaterialIndices( heightField )[cellIndex];
if ( material == B3_HEIGHT_FIELD_HOLE )
{
continue;
@ -1196,7 +1201,7 @@ void b3QueryHeightField( const b3HeightField* heightField, b3AABB bounds, b3Mesh
}
}
int b3CollideMoverAndHeightField( b3PlaneResult* planes, int capacity, const b3HeightField* shape, const b3Capsule* mover )
int b3CollideMoverAndHeightField( b3PlaneResult* planes, int capacity, const b3HeightFieldData* shape, const b3Capsule* mover )
{
b3DistanceInput distanceInput = { 0 };
distanceInput.proxyB = (b3ShapeProxy){ &mover->center1, 2, 0.0f };
@ -1245,7 +1250,7 @@ int b3CollideMoverAndHeightField( b3PlaneResult* planes, int capacity, const b3H
int cellIndex = row * ( shape->columnCount - 1 ) + column;
B3_ASSERT( cellIndex < ( shape->rowCount - 1 ) * ( shape->columnCount - 1 ) );
uint8_t material = shape->materialIndices[cellIndex];
uint8_t material = b3GetHeightFieldMaterialIndices( shape )[cellIndex];
if ( material == B3_HEIGHT_FIELD_HOLE )
{
continue;
@ -1324,7 +1329,7 @@ int b3CollideMoverAndHeightField( b3PlaneResult* planes, int capacity, const b3H
return planeCount;
}
b3HeightField* b3CreateGrid( int rowCount, int columnCount, b3Vec3 scale, bool makeHoles )
b3HeightFieldData* b3CreateGrid( int rowCount, int columnCount, b3Vec3 scale, bool makeHoles )
{
int heightCount = rowCount * columnCount;
float* heights = (float*)b3Alloc( heightCount * sizeof( float ) );
@ -1368,7 +1373,7 @@ b3HeightField* b3CreateGrid( int rowCount, int columnCount, b3Vec3 scale, bool m
data.globalMaximumHeight = 256.0f;
data.clockwiseWinding = false;
b3HeightField* heightField = b3CreateHeightField( &data );
b3HeightFieldData* heightField = b3CreateHeightField( &data );
b3Free( heights, heightCount * sizeof( float ) );
b3Free( materialIndices, cellCount * sizeof( uint8_t ) );
@ -1376,7 +1381,7 @@ b3HeightField* b3CreateGrid( int rowCount, int columnCount, b3Vec3 scale, bool m
return heightField;
}
b3HeightField* b3CreateWave( int rowCount, int columnCount, b3Vec3 scale, float rowFrequency, float columnFrequency,
b3HeightFieldData* b3CreateWave( int rowCount, int columnCount, b3Vec3 scale, float rowFrequency, float columnFrequency,
bool makeHoles )
{
int heightCount = rowCount * columnCount;
@ -1427,7 +1432,7 @@ b3HeightField* b3CreateWave( int rowCount, int columnCount, b3Vec3 scale, float
data.globalMaximumHeight = 256.0f;
data.clockwiseWinding = false;
b3HeightField* heightField = b3CreateHeightField( &data );
b3HeightFieldData* heightField = b3CreateHeightField( &data );
b3Free( heights, heightCount * sizeof( float ) );
b3Free( materialIndices, cellCount * sizeof( uint8_t ) );
@ -1435,18 +1440,9 @@ b3HeightField* b3CreateWave( int rowCount, int columnCount, b3Vec3 scale, float
return heightField;
}
void b3DestroyHeightField( b3HeightField* heightField )
void b3DestroyHeightField( b3HeightFieldData* heightField )
{
int heightCount = heightField->rowCount * heightField->columnCount;
b3Free( heightField->compressedHeights, heightCount * sizeof( uint16_t ) );
int cellCount = ( heightField->rowCount - 1 ) * ( heightField->columnCount - 1 );
b3Free( heightField->materialIndices, cellCount * sizeof( uint8_t ) );
int triangleCount = 2 * cellCount;
b3Free( heightField->flags, triangleCount * sizeof( uint8_t ) );
b3Free( heightField, sizeof( b3HeightField ) );
b3Free( heightField, heightField->byteCount );
}
void b3DumpHeightData( const b3HeightFieldDef* data, const char* fileName )
@ -1493,7 +1489,7 @@ void b3DumpHeightData( const b3HeightFieldDef* data, const char* fileName )
#define B3_FILE_SCAN fscanf
#endif
b3HeightField* b3LoadHeightField( const char* fileName )
b3HeightFieldData* b3LoadHeightField( const char* fileName )
{
FILE* file = NULL;
@ -1577,7 +1573,7 @@ b3HeightField* b3LoadHeightField( const char* fileName )
fclose( file );
// Create height field from loaded data
b3HeightField* heightField = b3CreateHeightField( &data );
b3HeightFieldData* heightField = b3CreateHeightField( &data );
// Clean up temporary allocations
b3Free( data.heights, heightCount * sizeof( float ) );

View file

@ -8,6 +8,7 @@
#include "core.h"
#include "island.h"
#include "physics_world.h"
#include "recording.h"
#include "shape.h"
#include "solver.h"
#include "solver_set.h"
@ -378,6 +379,7 @@ void b3Joint_SetConstraintTuning( b3JointId jointId, float hertz, float dampingR
B3_ASSERT( b3IsValidFloat( dampingRatio ) && dampingRatio >= 0.0f );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, JointSetConstraintTuning, jointId, hertz, dampingRatio );
b3Joint* joint = b3GetJointFullId( world, jointId );
b3JointSim* base = b3GetJointSim( world, joint );
base->constraintHertz = hertz;
@ -398,6 +400,7 @@ void b3Joint_SetForceThreshold( b3JointId jointId, float threshold )
B3_ASSERT( b3IsValidFloat( threshold ) && threshold >= 0.0f );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, JointSetForceThreshold, jointId, threshold );
b3Joint* joint = b3GetJointFullId( world, jointId );
b3JointSim* base = b3GetJointSim( world, joint );
base->forceThreshold = threshold;
@ -416,6 +419,7 @@ void b3Joint_SetTorqueThreshold( b3JointId jointId, float threshold )
B3_ASSERT( b3IsValidFloat( threshold ) && threshold >= 0.0f );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, JointSetTorqueThreshold, jointId, threshold );
b3Joint* joint = b3GetJointFullId( world, jointId );
b3JointSim* base = b3GetJointSim( world, joint );
base->torqueThreshold = threshold;
@ -464,6 +468,7 @@ b3JointId b3CreateDistanceJoint( b3WorldId worldId, const b3DistanceJointDef* de
joint->distanceJoint.motorImpulse = 0.0f;
b3JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->generation };
B3_REC_CREATE( world, CreateDistanceJoint, jointId, worldId, *def );
return jointId;
}
@ -492,6 +497,7 @@ b3JointId b3CreateMotorJoint( b3WorldId worldId, const b3MotorJointDef* def )
joint->motorJoint.maxSpringTorque = def->maxSpringTorque;
b3JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->generation };
B3_REC_CREATE( world, CreateMotorJoint, jointId, worldId, *def );
return jointId;
}
@ -509,6 +515,7 @@ b3JointId b3CreateFilterJoint( b3WorldId worldId, const b3FilterJointDef* def )
b3JointSim* joint = pair.jointSim;
b3JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->generation };
B3_REC_CREATE( world, CreateFilterJoint, jointId, worldId, *def );
return jointId;
}
@ -535,6 +542,7 @@ b3JointId b3CreateParallelJoint( b3WorldId worldId, const b3ParallelJointDef* de
joint->parallelJoint.maxTorque = def->maxTorque;
b3JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->generation };
B3_REC_CREATE( world, CreateParallelJoint, jointId, worldId, *def );
return jointId;
}
@ -566,6 +574,7 @@ b3JointId b3CreatePrismaticJoint( b3WorldId worldId, const b3PrismaticJointDef*
joint->prismaticJoint.enableMotor = def->enableMotor;
b3JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->generation };
B3_REC_CREATE( world, CreatePrismaticJoint, jointId, worldId, *def );
return jointId;
}
@ -601,6 +610,7 @@ b3JointId b3CreateRevoluteJoint( b3WorldId worldId, const b3RevoluteJointDef* de
joint->revoluteJoint.enableMotor = def->enableMotor;
b3JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->generation };
B3_REC_CREATE( world, CreateRevoluteJoint, jointId, worldId, *def );
return jointId;
}
@ -640,6 +650,7 @@ b3JointId b3CreateSphericalJoint( b3WorldId worldId, const b3SphericalJointDef*
joint->sphericalJoint.enableMotor = def->enableMotor;
b3JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->generation };
B3_REC_CREATE( world, CreateSphericalJoint, jointId, worldId, *def );
return jointId;
}
@ -668,6 +679,7 @@ b3JointId b3CreateWeldJoint( b3WorldId worldId, const b3WeldJointDef* def )
joint->weldJoint.angularDampingRatio = def->angularDampingRatio;
b3JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->generation };
B3_REC_CREATE( world, CreateWeldJoint, jointId, worldId, *def );
return jointId;
}
@ -707,6 +719,7 @@ b3JointId b3CreateWheelJoint( b3WorldId worldId, const b3WheelJointDef* def )
joint->wheelJoint.upperSteeringLimit = def->upperSteeringLimit;
b3JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->generation };
B3_REC_CREATE( world, CreateWheelJoint, jointId, worldId, *def );
return jointId;
}
@ -825,6 +838,8 @@ void b3DestroyJoint( b3JointId jointId, bool wakeAttached )
return;
}
B3_REC( world, DestroyJoint, jointId, wakeAttached );
b3Joint* joint = b3GetJointFullId( world, jointId );
b3DestroyJointInternal( world, joint, wakeAttached );
@ -862,6 +877,7 @@ void b3Joint_SetLocalFrameA( b3JointId jointId, b3Transform localFrame )
B3_ASSERT( b3IsValidTransform( localFrame ) );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, JointSetLocalFrameA, jointId, localFrame );
b3Joint* joint = b3GetJointFullId( world, jointId );
b3JointSim* jointSim = b3GetJointSim( world, joint );
jointSim->localFrameA = localFrame;
@ -880,6 +896,7 @@ void b3Joint_SetLocalFrameB( b3JointId jointId, b3Transform localFrame )
B3_ASSERT( b3IsValidTransform( localFrame ) );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, JointSetLocalFrameB, jointId, localFrame );
b3Joint* joint = b3GetJointFullId( world, jointId );
b3JointSim* jointSim = b3GetJointSim( world, joint );
jointSim->localFrameB = localFrame;
@ -901,6 +918,8 @@ void b3Joint_SetCollideConnected( b3JointId jointId, bool shouldCollide )
return;
}
B3_REC( world, JointSetCollideConnected, jointId, shouldCollide );
b3Joint* joint = b3GetJointFullId( world, jointId );
if ( joint->collideConnected == shouldCollide )
{
@ -967,6 +986,8 @@ void b3Joint_WakeBodies( b3JointId jointId )
return;
}
B3_REC( world, JointWakeBodies, jointId );
world->locked = true;
b3Joint* joint = b3GetJointFullId( world, jointId );
@ -1662,6 +1683,7 @@ void b3DrawJoint( b3DebugDraw* draw, b3World* world, b3Joint* joint )
break;
case b3_motorJoint:
draw->DrawSegmentFcn( pA, pB, b3_colorPlum, draw->context );
draw->DrawPointFcn( pA, 8.0f, b3_colorYellowGreen, draw->context );
draw->DrawPointFcn( pB, 8.0f, b3_colorPlum, draw->context );
break;

View file

@ -62,7 +62,7 @@ static int b3QueryMeshTriangles( int* indices, int capacity, const b3Mesh* mesh,
return context.count;
}
static int b3QueryHeightFieldTriangles( int* indices, int capacity, const b3HeightField* heightField, b3AABB bounds )
static int b3QueryHeightFieldTriangles( int* indices, int capacity, const b3HeightFieldData* heightField, b3AABB bounds )
{
b3TriangleQueryContext context = {
.indices = indices,
@ -1084,7 +1084,8 @@ bool b3ComputeMeshManifolds( b3World* world, int workerIndex, b3Contact* contact
}
}
const b3SurfaceMaterial* materialB = shapeB->materials + 0;
const b3SurfaceMaterial* materialsA = b3GetShapeMaterials( shapeA );
const b3SurfaceMaterial* materialB = b3GetShapeMaterials( shapeB );
b3Vec3 tangentVelocityA = b3Vec3_zero;
// Update friction and restitution if the mesh has per triangle material
@ -1101,7 +1102,7 @@ bool b3ComputeMeshManifolds( b3World* world, int workerIndex, b3Contact* contact
}
else
{
materialIndices = shapeA->heightField->materialIndices;
materialIndices = b3GetHeightFieldMaterialIndices( shapeA->heightField );
}
for ( int i = 0; i < clusterCount; ++i )
@ -1127,7 +1128,7 @@ bool b3ComputeMeshManifolds( b3World* world, int workerIndex, b3Contact* contact
}
materialIndex = b3ClampInt( materialIndex, 0, shapeA->materialCount - 1 );
b3SurfaceMaterial material = shapeA->materials[materialIndex];
b3SurfaceMaterial material = materialsA[materialIndex];
friction += world->frictionCallback( material.friction, material.userMaterialId, materialB->friction,
materialB->userMaterialId );
restitution += world->restitutionCallback( material.restitution, material.userMaterialId, materialB->restitution,
@ -1153,11 +1154,11 @@ bool b3ComputeMeshManifolds( b3World* world, int workerIndex, b3Contact* contact
else
{
// Keep these updated in case the values on the shapes are modified
contact->friction = world->frictionCallback( shapeA->materials[0].friction, shapeA->materials[0].userMaterialId,
materialB->friction, materialB->userMaterialId );
contact->restitution = world->restitutionCallback( shapeA->materials[0].restitution, shapeA->materials[0].userMaterialId,
contact->friction = world->frictionCallback( materialsA[0].friction, materialsA[0].userMaterialId, materialB->friction,
materialB->userMaterialId );
contact->restitution = world->restitutionCallback( materialsA[0].restitution, materialsA[0].userMaterialId,
materialB->restitution, materialB->userMaterialId );
tangentVelocityA = shapeA->materials[0].tangentVelocity;
tangentVelocityA = materialsA[0].tangentVelocity;
}
tangentVelocityA = b3RotateVector( xfA.q, tangentVelocityA );
@ -1176,7 +1177,7 @@ bool b3ComputeMeshManifolds( b3World* world, int workerIndex, b3Contact* contact
radiusB = shapeB->hull->innerRadius;
}
contact->rollingResistance = shapeB->materials[0].rollingResistance * radiusB;
contact->rollingResistance = materialB->rollingResistance * radiusB;
b3Vec3 tangentVelocityB = b3RotateVector( xfB.q, materialB->tangentVelocity );
contact->tangentVelocity = b3Sub( tangentVelocityA, tangentVelocityB );

View file

@ -8,12 +8,15 @@
#include "physics_world.h"
#include "solver.h"
#include "solver_set.h"
#include "recording.h"
// needed for dll export
#include "box3d/box3d.h"
void b3MotorJoint_SetLinearVelocity( b3JointId jointId, b3Vec3 velocity )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, MotorJointSetLinearVelocity, jointId, velocity );
b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint );
joint->motorJoint.linearVelocity = velocity;
}
@ -26,6 +29,8 @@ b3Vec3 b3MotorJoint_GetLinearVelocity( b3JointId jointId )
void b3MotorJoint_SetAngularVelocity( b3JointId jointId, b3Vec3 velocity )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, MotorJointSetAngularVelocity, jointId, velocity );
b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint );
joint->motorJoint.angularVelocity = velocity;
}
@ -38,6 +43,8 @@ b3Vec3 b3MotorJoint_GetAngularVelocity( b3JointId jointId )
void b3MotorJoint_SetMaxVelocityTorque( b3JointId jointId, float maxTorque )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, MotorJointSetMaxVelocityTorque, jointId, maxTorque );
b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint );
joint->motorJoint.maxVelocityTorque = maxTorque;
}
@ -50,6 +57,8 @@ float b3MotorJoint_GetMaxVelocityTorque( b3JointId jointId )
void b3MotorJoint_SetMaxVelocityForce( b3JointId jointId, float maxForce )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, MotorJointSetMaxVelocityForce, jointId, maxForce );
b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint );
joint->motorJoint.maxVelocityForce = maxForce;
}
@ -62,6 +71,8 @@ float b3MotorJoint_GetMaxVelocityForce( b3JointId jointId )
void b3MotorJoint_SetLinearHertz( b3JointId jointId, float hertz )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, MotorJointSetLinearHertz, jointId, hertz );
b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint );
joint->motorJoint.linearHertz = hertz;
}
@ -74,6 +85,8 @@ float b3MotorJoint_GetLinearHertz( b3JointId jointId )
void b3MotorJoint_SetLinearDampingRatio( b3JointId jointId, float damping )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, MotorJointSetLinearDampingRatio, jointId, damping );
b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint );
joint->motorJoint.linearDampingRatio = damping;
}
@ -86,6 +99,8 @@ float b3MotorJoint_GetLinearDampingRatio( b3JointId jointId )
void b3MotorJoint_SetAngularHertz( b3JointId jointId, float hertz )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, MotorJointSetAngularHertz, jointId, hertz );
b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint );
joint->motorJoint.angularHertz = hertz;
}
@ -98,6 +113,8 @@ float b3MotorJoint_GetAngularHertz( b3JointId jointId )
void b3MotorJoint_SetAngularDampingRatio( b3JointId jointId, float damping )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, MotorJointSetAngularDampingRatio, jointId, damping );
b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint );
joint->motorJoint.angularDampingRatio = damping;
}
@ -110,6 +127,8 @@ float b3MotorJoint_GetAngularDampingRatio( b3JointId jointId )
void b3MotorJoint_SetMaxSpringForce( b3JointId jointId, float maxForce )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, MotorJointSetMaxSpringForce, jointId, maxForce );
b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint );
joint->motorJoint.maxSpringForce = b3MaxFloat( 0.0f, maxForce );
}
@ -122,6 +141,8 @@ float b3MotorJoint_GetMaxSpringForce( b3JointId jointId )
void b3MotorJoint_SetMaxSpringTorque( b3JointId jointId, float maxTorque )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, MotorJointSetMaxSpringTorque, jointId, maxTorque );
b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_motorJoint );
joint->motorJoint.maxSpringTorque = b3MaxFloat( 0.0f, maxTorque );
}
@ -416,22 +437,3 @@ void b3SolveMotorJoint( b3JointSim* base, b3StepContext* context )
stateB->angularVelocity = wB;
}
}
#if 0
void b3DumpMotorJoint()
{
int32 indexA = m_bodyA->m_islandIndex;
int32 indexB = m_bodyB->m_islandIndex;
b3Dump(" b3MotorJointDef jd;\n");
b3Dump(" jd.bodyA = sims[%d];\n", indexA);
b3Dump(" jd.bodyB = sims[%d];\n", indexB);
b3Dump(" jd.collideConnected = bool(%d);\n", m_collideConnected);
b3Dump(" jd.localAnchorA.Set(%.9g, %.9g);\n", m_localAnchorA.x, m_localAnchorA.y);
b3Dump(" jd.localAnchorB.Set(%.9g, %.9g);\n", m_localAnchorB.x, m_localAnchorB.y);
b3Dump(" jd.referenceAngle = %.9g;\n", m_referenceAngle);
b3Dump(" jd.stiffness = %.9g;\n", m_stiffness);
b3Dump(" jd.damping = %.9g;\n", m_damping);
b3Dump(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index);
}
#endif

View file

@ -8,6 +8,7 @@
#include "physics_world.h"
#include "solver.h"
#include "solver_set.h"
#include "recording.h"
// needed for dll export
#include "box3d/box3d.h"
@ -15,6 +16,8 @@
void b3ParallelJoint_SetSpringHertz( b3JointId jointId, float hertz )
{
B3_ASSERT( b3IsValidFloat( hertz ) && hertz >= 0.0f );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, ParallelJointSetSpringHertz, jointId, hertz );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_parallelJoint );
base->parallelJoint.hertz = hertz;
}
@ -28,6 +31,8 @@ float b3ParallelJoint_GetSpringHertz( b3JointId jointId )
void b3ParallelJoint_SetSpringDampingRatio( b3JointId jointId, float dampingRatio )
{
B3_ASSERT( b3IsValidFloat( dampingRatio ) && dampingRatio >= 0.0f );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, ParallelJointSetSpringDampingRatio, jointId, dampingRatio );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_parallelJoint );
base->parallelJoint.dampingRatio = dampingRatio;
}
@ -41,6 +46,8 @@ float b3ParallelJoint_GetSpringDampingRatio( b3JointId jointId )
void b3ParallelJoint_SetMaxTorque( b3JointId jointId, float maxForce )
{
B3_ASSERT( b3IsValidFloat( maxForce ) && maxForce >= 0.0f );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, ParallelJointSetMaxTorque, jointId, maxForce );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_parallelJoint );
base->parallelJoint.maxTorque = maxForce;
}

View file

@ -3,6 +3,8 @@
#include "physics_world.h"
#include "recording.h"
#include "arena_allocator.h"
#include "bitset.h"
#include "body.h"
@ -405,6 +407,9 @@ void b3DestroyWorld( b3WorldId worldId )
world->locked = true;
// Detach any recording before teardown. The user owns and frees the recording buffer.
b3StopRecordingInternal( world );
if ( world->scheduler != NULL )
{
b3DestroyScheduler( world->scheduler );
@ -1026,6 +1031,8 @@ void b3World_Step( b3WorldId worldId, float timeStep, int subStepCount )
return;
}
B3_REC( world, Step, worldId, timeStep, subStepCount );
world->locked = true;
b3TracyCZoneNC( world_step, "Step", b3_colorBox2DGreen, true );
@ -1159,6 +1166,32 @@ void b3World_Step( b3WorldId worldId, float timeStep, int subStepCount )
b3Array_Clear( world->contactEndEvents[world->endEventArrayIndex] );
world->locked = false;
if ( world->recording != NULL )
{
uint64_t hash = b3HashWorldState( world );
b3RecArgs_StateHash stateHash = { worldId, hash };
b3RecWrite_StateHash( world->recording, &stateHash );
// Fold this step's world bounds into the recording so a viewer can frame the whole motion.
b3AABB worldBounds = { 0 };
bool haveBounds = false;
for ( int i = 0; i < b3_bodyTypeCount; ++i )
{
b3DynamicTree* tree = world->broadPhase.trees + i;
if ( b3DynamicTree_GetProxyCount( tree ) == 0 )
{
continue;
}
b3AABB bounds = b3DynamicTree_GetRootBounds( tree );
worldBounds = haveBounds ? b3AABB_Union( worldBounds, bounds ) : bounds;
haveBounds = true;
}
if ( haveBounds )
{
b3RecAccumulateBounds( world->recording, worldBounds );
}
}
b3TracyCZoneEnd( world_step );
b3TracyCFrame;
}
@ -1191,10 +1224,11 @@ static bool DrawQueryCallback( int proxyId, uint64_t userData, void* context )
b3HexColor color;
if ( shape->materials[0].customColor != 0 )
const b3SurfaceMaterial* surfaceMaterial = b3GetShapeMaterials( shape );
if ( surfaceMaterial[0].customColor != 0 )
{
// May already carry a packed material preset, pass through unchanged
color = (b3HexColor)shape->materials[0].customColor;
color = (b3HexColor)surfaceMaterial[0].customColor;
}
else
{
@ -1905,6 +1939,8 @@ void b3World_EnableSleeping( b3WorldId worldId, bool flag )
return;
}
B3_REC( world, WorldEnableSleeping, worldId, flag );
world->enableSleep = flag;
if ( flag == false )
@ -1935,6 +1971,8 @@ void b3World_EnableWarmStarting( b3WorldId worldId, bool flag )
return;
}
B3_REC( world, WorldEnableWarmStarting, worldId, flag );
world->enableWarmStarting = flag;
}
@ -1963,6 +2001,8 @@ void b3World_EnableContinuous( b3WorldId worldId, bool flag )
return;
}
B3_REC( world, WorldEnableContinuous, worldId, flag );
world->enableContinuous = flag;
}
@ -1980,6 +2020,8 @@ void b3World_SetRestitutionThreshold( b3WorldId worldId, float value )
return;
}
B3_REC( world, WorldSetRestitutionThreshold, worldId, value );
world->restitutionThreshold = b3ClampFloat( value, 0.0f, FLT_MAX );
}
@ -1997,6 +2039,8 @@ void b3World_SetHitEventThreshold( b3WorldId worldId, float value )
return;
}
B3_REC( world, WorldSetHitEventThreshold, worldId, value );
world->hitEventThreshold = b3ClampFloat( value, 0.0f, FLT_MAX );
}
@ -2014,6 +2058,8 @@ void b3World_SetContactTuning( b3WorldId worldId, float hertz, float dampingRati
return;
}
B3_REC( world, WorldSetContactTuning, worldId, hertz, dampingRatio, contactSpeed );
world->contactHertz = b3ClampFloat( hertz, 0.0f, FLT_MAX );
world->contactDampingRatio = b3ClampFloat( dampingRatio, 0.0f, FLT_MAX );
world->contactSpeed = b3ClampFloat( contactSpeed, 0.0f, FLT_MAX );
@ -2028,6 +2074,8 @@ void b3World_SetContactRecycleDistance( b3WorldId worldId, float recycleDistance
return;
}
B3_REC( world, WorldSetContactRecycleDistance, worldId, recycleDistance );
world->contactRecycleDistance = b3ClampFloat( recycleDistance, 0.0f, FLT_MAX );
}
@ -2047,6 +2095,8 @@ void b3World_SetMaximumLinearSpeed( b3WorldId worldId, float maximumLinearSpeed
return;
}
B3_REC( world, WorldSetMaximumLinearSpeed, worldId, maximumLinearSpeed );
world->maxLinearSpeed = maximumLinearSpeed;
}
@ -2181,6 +2231,30 @@ int b3World_GetWorkerCount( b3WorldId worldId )
return world->workerCount;
}
void b3World_StartRecording( b3WorldId worldId, b3Recording* recording )
{
// Must be a step boundary, so refuse a locked world
b3World* world = b3GetUnlockedWorldFromId( worldId );
if ( world == NULL || recording == NULL || world->recording != NULL )
{
return;
}
b3StartRecordingIntoBuffer( world, recording );
}
void b3World_StopRecording( b3WorldId worldId )
{
b3World* world = b3GetUnlockedWorldFromId( worldId );
if ( world == NULL )
{
return;
}
b3StopRecordingInternal( world );
}
static FILE* b3OpenFile( const char* fileName )
{
FILE* file = NULL;
@ -2516,6 +2590,19 @@ b3TreeStats b3World_OverlapAABB( b3WorldId worldId, b3AABB aabb, b3QueryFilter f
B3_ASSERT( b3IsValidAABB( aabb ) );
b3RecQueryWriter recWriter = { 0 };
if ( world->recording != NULL )
{
b3RecQueryBegin( &recWriter, context );
recWriter.userFcn.overlapFcn = fcn;
b3RecW_WORLDID( &recWriter.buf, worldId );
b3RecW_AABB( &recWriter.buf, aabb );
b3RecW_QUERYFILTER( &recWriter.buf, filter );
recWriter.countOffset = b3RecReserveU32( &recWriter.buf );
fcn = b3RecOverlapTrampoline;
context = &recWriter;
}
WorldQueryContext worldContext = { world, fcn, filter, context };
for ( int i = 0; i < b3_bodyTypeCount; ++i )
@ -2527,6 +2614,13 @@ b3TreeStats b3World_OverlapAABB( b3WorldId worldId, b3AABB aabb, b3QueryFilter f
treeStats.leafVisits += treeResult.leafVisits;
}
if ( world->recording != NULL )
{
b3RecPatchU32( &recWriter.buf, recWriter.countOffset, recWriter.hitCount );
b3RecW_TREESTATS( &recWriter.buf, treeStats );
b3RecQueryCommit( world->recording, b3_recOpQueryOverlapAABB, &recWriter );
}
return treeStats;
}
@ -2586,6 +2680,20 @@ b3TreeStats b3World_OverlapShape( b3WorldId worldId, b3Pos origin, const b3Shape
B3_ASSERT( b3IsValidPosition( origin ) );
b3RecQueryWriter recWriter = { 0 };
if ( world->recording != NULL )
{
b3RecQueryBegin( &recWriter, context );
recWriter.userFcn.overlapFcn = fcn;
b3RecW_WORLDID( &recWriter.buf, worldId );
b3RecW_POSITION( &recWriter.buf, origin );
b3RecW_SHAPEPROXY( &recWriter.buf, *proxy );
b3RecW_QUERYFILTER( &recWriter.buf, filter );
recWriter.countOffset = b3RecReserveU32( &recWriter.buf );
fcn = b3RecOverlapTrampoline;
context = &recWriter;
}
// Bound the proxy in origin relative space then lift to a conservative world float box
b3AABB aabb = b3OffsetAABB( b3MakeAABB( proxy->points, proxy->count, proxy->radius ), origin );
WorldOverlapContext worldContext = {
@ -2601,6 +2709,13 @@ b3TreeStats b3World_OverlapShape( b3WorldId worldId, b3Pos origin, const b3Shape
treeStats.leafVisits += treeResult.leafVisits;
}
if ( world->recording != NULL )
{
b3RecPatchU32( &recWriter.buf, recWriter.countOffset, recWriter.hitCount );
b3RecW_TREESTATS( &recWriter.buf, treeStats );
b3RecQueryCommit( world->recording, b3_recOpQueryOverlapShape, &recWriter );
}
return treeStats;
}
@ -2662,6 +2777,20 @@ void b3World_CollideMover( b3WorldId worldId, b3Pos origin, const b3Capsule* mov
B3_ASSERT( b3IsValidPosition( origin ) );
b3RecQueryWriter recWriter = { 0 };
if ( world->recording != NULL )
{
b3RecQueryBegin( &recWriter, context );
recWriter.userFcn.planeFcn = fcn;
b3RecW_WORLDID( &recWriter.buf, worldId );
b3RecW_POSITION( &recWriter.buf, origin );
b3RecW_CAPSULE( &recWriter.buf, *mover );
b3RecW_QUERYFILTER( &recWriter.buf, filter );
recWriter.countOffset = b3RecReserveU32( &recWriter.buf );
fcn = b3RecPlaneTrampoline;
context = &recWriter;
}
b3Vec3 r = { mover->radius, mover->radius, mover->radius };
// Relative box lifted to world float with outward rounding, conservative for the tree
@ -2678,6 +2807,13 @@ void b3World_CollideMover( b3WorldId worldId, b3Pos origin, const b3Capsule* mov
{
b3DynamicTree_Query( world->broadPhase.trees + i, aabb, filter.maskBits, false, TreeCollideCallback, &worldContext );
}
if ( world->recording != NULL )
{
// CollideMover returns void: no treestats tail, just the per-shape plane batches.
b3RecPatchU32( &recWriter.buf, recWriter.countOffset, recWriter.hitCount );
b3RecQueryCommit( world->recording, b3_recOpQueryCollideMover, &recWriter );
}
}
typedef struct WorldRayCastContext
@ -2722,7 +2858,7 @@ static float RayCastCallback( const b3RayCastInput* input, int proxyId, uint64_t
b3ShapeId id = { shapeId + 1, world->worldId, shape->generation };
b3Pos point = b3OffsetPos( worldContext->origin, output.point );
int materialIndex = b3ClampInt( output.materialIndex, 0, shape->materialCount - 1 );
uint64_t userMaterialId = shape->materials[materialIndex].userMaterialId;
uint64_t userMaterialId = b3GetShapeMaterials( shape )[materialIndex].userMaterialId;
int triangleIndex = output.triangleIndex;
int childIndex = output.childIndex;
@ -2755,6 +2891,20 @@ b3TreeStats b3World_CastRay( b3WorldId worldId, b3Pos origin, b3Vec3 translation
B3_ASSERT( b3IsValidPosition( origin ) );
B3_ASSERT( b3IsValidVec3( translation ) );
b3RecQueryWriter recWriter = { 0 };
if ( world->recording != NULL )
{
b3RecQueryBegin( &recWriter, context );
recWriter.userFcn.castFcn = fcn;
b3RecW_WORLDID( &recWriter.buf, worldId );
b3RecW_POSITION( &recWriter.buf, origin );
b3RecW_VEC3( &recWriter.buf, translation );
b3RecW_QUERYFILTER( &recWriter.buf, filter );
recWriter.countOffset = b3RecReserveU32( &recWriter.buf );
fcn = b3RecCastTrampoline;
context = &recWriter;
}
// The tree traverses in float relative to the world origin. Each shape is then re-differenced at
// full precision against the origin, so a hit stays accurate far from the origin.
b3RayCastInput input = { b3ToVec3( origin ), translation, 1.0f };
@ -2770,12 +2920,19 @@ b3TreeStats b3World_CastRay( b3WorldId worldId, b3Pos origin, b3Vec3 translation
if ( worldContext.fraction == 0.0f )
{
return treeStats;
break;
}
input.maxFraction = worldContext.fraction;
}
if ( world->recording != NULL )
{
b3RecPatchU32( &recWriter.buf, recWriter.countOffset, recWriter.hitCount );
b3RecW_TREESTATS( &recWriter.buf, treeStats );
b3RecQueryCommit( world->recording, b3_recOpQueryCastRay, &recWriter );
}
return treeStats;
}
@ -2835,12 +2992,25 @@ b3RayResult b3World_CastRayClosest( b3WorldId worldId, b3Pos origin, b3Vec3 tran
if ( worldContext.fraction == 0.0f )
{
return result;
break;
}
input.maxFraction = worldContext.fraction;
}
// Closed query, no user callback: record the inputs and the single result for the replay compare.
if ( world->recording != NULL )
{
b3RecQueryWriter recWriter = { 0 };
b3RecQueryBegin( &recWriter, NULL );
b3RecW_WORLDID( &recWriter.buf, worldId );
b3RecW_POSITION( &recWriter.buf, origin );
b3RecW_VEC3( &recWriter.buf, translation );
b3RecW_QUERYFILTER( &recWriter.buf, filter );
b3RecW_RAYRESULT( &recWriter.buf, result );
b3RecQueryCommit( world->recording, b3_recOpQueryCastRayClosest, &recWriter );
}
return result;
}
@ -2888,7 +3058,7 @@ static float b3ShapeCastCallback( const b3BoxCastInput* input, int proxyId, uint
{
b3ShapeId id = { shapeId + 1, world->worldId, shape->generation };
int materialIndex = b3ClampInt( output.materialIndex, 0, shape->materialCount - 1 );
uint64_t userMaterialId = shape->materials[materialIndex].userMaterialId;
uint64_t userMaterialId = b3GetShapeMaterials( shape )[materialIndex].userMaterialId;
int triangleIndex = output.triangleIndex;
int childIndex = output.childIndex;
@ -2921,6 +3091,21 @@ b3TreeStats b3World_CastShape( b3WorldId worldId, b3Pos origin, const b3ShapePro
B3_ASSERT( b3IsValidPosition( origin ) );
B3_ASSERT( b3IsValidVec3( translation ) );
b3RecQueryWriter recWriter = { 0 };
if ( world->recording != NULL )
{
b3RecQueryBegin( &recWriter, context );
recWriter.userFcn.castFcn = fcn;
b3RecW_WORLDID( &recWriter.buf, worldId );
b3RecW_POSITION( &recWriter.buf, origin );
b3RecW_SHAPEPROXY( &recWriter.buf, *proxy );
b3RecW_VEC3( &recWriter.buf, translation );
b3RecW_QUERYFILTER( &recWriter.buf, filter );
recWriter.countOffset = b3RecReserveU32( &recWriter.buf );
fcn = b3RecCastTrampoline;
context = &recWriter;
}
WorldShapeCastContext worldContext = { 0 };
worldContext.world = world;
worldContext.fcn = fcn;
@ -2948,12 +3133,19 @@ b3TreeStats b3World_CastShape( b3WorldId worldId, b3Pos origin, const b3ShapePro
if ( worldContext.fraction == 0.0f )
{
return treeStats;
break;
}
treeInput.maxFraction = worldContext.fraction;
}
if ( world->recording != NULL )
{
b3RecPatchU32( &recWriter.buf, recWriter.countOffset, recWriter.hitCount );
b3RecW_TREESTATS( &recWriter.buf, treeStats );
b3RecQueryCommit( world->recording, b3_recOpQueryCastShape, &recWriter );
}
return treeStats;
}
@ -3027,6 +3219,24 @@ float b3World_CastMover( b3WorldId worldId, b3Pos origin, const b3Capsule* mover
return 1.0f;
}
// The mover filter is a per-shape bool(shapeId, ctx) decision, the same shape as an overlap
// callback, so the overlap trampoline captures it. Installing it even when the user passed no
// filter records an accept-all stream that replays identically.
b3RecQueryWriter recWriter = { 0 };
if ( world->recording != NULL )
{
b3RecQueryBegin( &recWriter, context );
recWriter.userFcn.moverFilterFcn = fcn;
b3RecW_WORLDID( &recWriter.buf, worldId );
b3RecW_POSITION( &recWriter.buf, origin );
b3RecW_CAPSULE( &recWriter.buf, *mover );
b3RecW_VEC3( &recWriter.buf, translation );
b3RecW_QUERYFILTER( &recWriter.buf, filter );
recWriter.countOffset = b3RecReserveU32( &recWriter.buf );
fcn = b3RecOverlapTrampoline;
context = &recWriter;
}
WorldMoverCastContext worldContext = {
.world = world,
.fcn = fcn,
@ -3051,12 +3261,21 @@ float b3World_CastMover( b3WorldId worldId, b3Pos origin, const b3Capsule* mover
if ( worldContext.fraction == 0.0f )
{
return 0.0f;
break;
}
treeInput.maxFraction = worldContext.fraction;
}
if ( world->recording != NULL )
{
// The mover filter type aliases the overlap trampoline, so the user fcn lands in the same
// union slot. Backpatch the accept count, then record the returned fraction as the tail.
b3RecPatchU32( &recWriter.buf, recWriter.countOffset, recWriter.hitCount );
b3RecW_F32( &recWriter.buf, worldContext.fraction );
b3RecQueryCommit( world->recording, b3_recOpQueryCastMover, &recWriter );
}
return worldContext.fraction;
}
@ -3085,6 +3304,9 @@ void b3World_SetPreSolveCallback( b3WorldId worldId, b3PreSolveFcn* fcn, void* c
void b3World_SetGravity( b3WorldId worldId, b3Vec3 gravity )
{
b3World* world = b3GetWorldFromId( worldId );
B3_REC( world, WorldSetGravity, worldId, gravity );
world->gravity = gravity;
}
@ -3208,6 +3430,8 @@ void b3World_Explode( b3WorldId worldId, const b3ExplosionDef* explosionDef )
return;
}
B3_REC( world, WorldExplode, worldId, *explosionDef );
// Locked due to waking
world->locked = true;
@ -3231,6 +3455,8 @@ void b3World_RebuildStaticTree( b3WorldId worldId )
return;
}
B3_REC( world, WorldRebuildStaticTree, worldId );
b3DynamicTree* staticTree = world->broadPhase.trees + b3_staticBody;
b3DynamicTree_Rebuild( staticTree, true );
}
@ -3242,6 +3468,9 @@ void b3World_EnableSpeculative( b3WorldId worldId, bool flag )
{
return;
}
B3_REC( world, WorldEnableSpeculative, worldId, flag );
world->enableSpeculative = flag;
}

View file

@ -16,6 +16,7 @@
#define B3_DEBUG_LINE_CAPACITY 64
typedef struct b3Body b3Body;
typedef struct b3Recording b3Recording;
typedef struct b3Contact b3Contact;
typedef struct b3Island b3Island;
typedef struct b3Joint b3Joint;
@ -274,6 +275,10 @@ typedef struct b3World
// not a real mutex. This should have minimal performance impact.
bool locked;
// Non-NULL while a recording session is active. Set by b3World_StartRecording,
// cleared by b3World_StopRecording. Hooks in mutators check this before writing.
struct b3Recording* recording;
bool enableWarmStarting;
bool enableContinuous;
bool enableSpeculative;

View file

@ -8,6 +8,7 @@
#include "physics_world.h"
#include "solver.h"
#include "solver_set.h"
#include "recording.h"
// needed for dll export
#include "box3d/box3d.h"
@ -52,6 +53,8 @@
void b3PrismaticJoint_EnableLimit( b3JointId jointId, bool enableLimit )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, PrismaticJointEnableLimit, jointId, enableLimit );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint );
if ( enableLimit != base->prismaticJoint.enableLimit )
{
@ -82,6 +85,8 @@ float b3PrismaticJoint_GetUpperLimit( b3JointId jointId )
void b3PrismaticJoint_SetLimits( b3JointId jointId, float lower, float upper )
{
B3_ASSERT( b3IsValidFloat( lower ) && b3IsValidFloat( upper ) );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, PrismaticJointSetLimits, jointId, lower, upper );
float lowerAngle = b3MinFloat( lower, upper );
float upperAngle = b3MaxFloat( lower, upper );
@ -109,6 +114,8 @@ float b3PrismaticJoint_GetTranslation( b3JointId jointId )
void b3PrismaticJoint_EnableSpring( b3JointId jointId, bool enableSpring )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, PrismaticJointEnableSpring, jointId, enableSpring );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint );
if ( enableSpring != base->prismaticJoint.enableSpring )
{
@ -126,6 +133,8 @@ bool b3PrismaticJoint_IsSpringEnabled( b3JointId jointId )
void b3PrismaticJoint_SetTargetTranslation( b3JointId jointId, float targetTranslation )
{
B3_ASSERT( b3IsValidFloat( targetTranslation ) );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, PrismaticJointSetTargetTranslation, jointId, targetTranslation );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint );
base->prismaticJoint.targetTranslation = targetTranslation;
}
@ -139,6 +148,8 @@ float b3PrismaticJoint_GetTargetTranslation( b3JointId jointId )
void b3PrismaticJoint_SetSpringHertz( b3JointId jointId, float hertz )
{
B3_ASSERT( b3IsValidFloat( hertz ) && hertz >= 0.0f );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, PrismaticJointSetSpringHertz, jointId, hertz );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint );
base->prismaticJoint.hertz = hertz;
}
@ -152,6 +163,8 @@ float b3PrismaticJoint_GetSpringHertz( b3JointId jointId )
void b3PrismaticJoint_SetSpringDampingRatio( b3JointId jointId, float dampingRatio )
{
B3_ASSERT( b3IsValidFloat( dampingRatio ) && dampingRatio >= 0.0f );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, PrismaticJointSetSpringDampingRatio, jointId, dampingRatio );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint );
base->prismaticJoint.dampingRatio = dampingRatio;
}
@ -164,6 +177,8 @@ float b3PrismaticJoint_GetSpringDampingRatio( b3JointId jointId )
void b3PrismaticJoint_EnableMotor( b3JointId jointId, bool enableMotor )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, PrismaticJointEnableMotor, jointId, enableMotor );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint );
if ( enableMotor != base->prismaticJoint.enableMotor )
{
@ -181,6 +196,8 @@ bool b3PrismaticJoint_IsMotorEnabled( b3JointId jointId )
void b3PrismaticJoint_SetMotorSpeed( b3JointId jointId, float motorSpeed )
{
B3_ASSERT( b3IsValidFloat( motorSpeed ) );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, PrismaticJointSetMotorSpeed, jointId, motorSpeed );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint );
base->prismaticJoint.motorSpeed = motorSpeed;
}
@ -194,6 +211,8 @@ float b3PrismaticJoint_GetMotorSpeed( b3JointId jointId )
void b3PrismaticJoint_SetMaxMotorForce( b3JointId jointId, float maxForce )
{
B3_ASSERT( b3IsValidFloat( maxForce ) && maxForce >= 0.0f );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, PrismaticJointSetMaxMotorForce, jointId, maxForce );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint );
base->prismaticJoint.maxMotorForce = maxForce;
}

1094
src/recording.c Normal file

File diff suppressed because it is too large Load diff

346
src/recording.h Normal file
View file

@ -0,0 +1,346 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
#pragma once
#include "core.h"
#include "box3d/id.h"
#include "box3d/math_functions.h"
#include "box3d/types.h"
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
// FNV-1a 64-bit constants
#define B3_SNAP_FNV_INIT 14695981039346656037ull
#define B3_SNAP_FNV_PRIME 1099511628211ull
// Mix a world position at full width so the determinism gate validates past float precision
// when the body is far from the origin.
static inline uint64_t b3FnvMixPosition( uint64_t hash, b3Pos p )
{
#if defined( BOX3D_DOUBLE_PRECISION )
uint64_t bx, by, bz;
memcpy( &bx, &p.x, 8 );
memcpy( &by, &p.y, 8 );
memcpy( &bz, &p.z, 8 );
#else
uint32_t fx, fy, fz;
memcpy( &fx, &p.x, 4 );
memcpy( &fy, &p.y, 4 );
memcpy( &fz, &p.z, 4 );
uint64_t bx = fx, by = fy, bz = fz;
#endif
hash = ( hash ^ bx ) * B3_SNAP_FNV_PRIME;
hash = ( hash ^ by ) * B3_SNAP_FNV_PRIME;
hash = ( hash ^ bz ) * B3_SNAP_FNV_PRIME;
return hash;
}
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).
#define B3_REC_VERSION_MAJOR 1
#define B3_REC_VERSION_MINOR 1
// File header, fixed 48 bytes, little-endian. Contains the registry locator so the player
// can load geometry before replaying any ops.
typedef struct b3RecHeader
{
uint32_t magic; // 'B3RC' = 0x43523342
uint16_t versionMajor; // B3_REC_VERSION_MAJOR
uint16_t versionMinor; // B3_REC_VERSION_MINOR
uint8_t pointerWidth; // sizeof(void*), gates POD-def struct layout
uint8_t bigEndian; // 0 on all supported targets
uint8_t validationEnabled; // 1 if built with BOX3D_VALIDATE, diagnostic only
uint8_t reserved;
float lengthScale; // b3GetLengthUnitsPerMeter()
uint32_t reserved2;
uint32_t reserved3; // explicit pad so the 64-bit fields align with no implicit gap
uint64_t snapshotSize; // bytes of snapshot blob after the header (0 in Phase 1)
uint64_t registryOffset; // absolute offset to trailing registry block, backpatched at stop
uint64_t registryByteCount; // size of the registry block
} b3RecHeader;
_Static_assert( sizeof( b3RecHeader ) == 48, "recording header must be 48 bytes" );
// Growable append-only byte buffer. Doubles on demand. countOnly mode tallies size without
// allocating, used to size a buffer cheaply before a second filling pass.
typedef struct b3RecBuffer
{
uint8_t* data;
int capacity;
int size;
bool countOnly;
} b3RecBuffer;
// Geometry kinds for the trailing registry section
typedef enum b3GeometryKind
{
b3_geometryHull,
b3_geometryMesh,
b3_geometryHeightField,
b3_geometryCompound,
} b3GeometryKind;
// One entry per unique geometry blob. id == index in the entries array.
typedef struct b3GeometryEntry
{
uint64_t contentHash;
uint32_t id;
b3GeometryKind kind;
int byteCount;
uint8_t* bytes;
} b3GeometryEntry;
// Growable array of geometry entries. Ids are array indices, so the array is serialized in order.
// dedupMap maps content hash to entry id for O(1) dedup; it is opaque here and owned by recording.c.
typedef struct b3GeometryRegistry
{
b3GeometryEntry* entries;
int count;
int capacity;
void* dedupMap;
} b3GeometryRegistry;
// User-owned recording buffer. The world appends into it while active; the host saves and
// destroys it. Opaque across the public API.
typedef struct b3Recording
{
b3RecBuffer buffer;
int recordStart; // offset of the 3-byte size field for u24 backpatch
b3Mutex* lock; // serializes query commits from concurrent threads
b3GeometryRegistry registry;
// Union of world bounds over every recorded step, written at stop.
b3AABB accumulatedBounds;
bool haveBounds;
} b3Recording;
// C type aliases per TAG, used in the X-macro codegen arg structs
typedef bool b3RecCType_BOOL;
typedef int32_t b3RecCType_I32;
typedef uint8_t b3RecCType_U8;
typedef uint16_t b3RecCType_U16;
typedef uint32_t b3RecCType_U32;
typedef uint64_t b3RecCType_U64;
typedef float b3RecCType_F32;
typedef double b3RecCType_F64;
typedef b3Vec3 b3RecCType_VEC3;
typedef b3Quat b3RecCType_QUAT;
typedef b3Transform b3RecCType_TRANSFORM;
typedef b3Pos b3RecCType_POSITION;
typedef b3WorldTransform b3RecCType_WORLDXF;
typedef b3Matrix3 b3RecCType_MATRIX3;
typedef b3AABB b3RecCType_AABB;
typedef b3Sphere b3RecCType_SPHERE;
typedef b3Capsule b3RecCType_CAPSULE;
typedef b3QueryFilter b3RecCType_QUERYFILTER;
typedef b3ShapeProxy b3RecCType_SHAPEPROXY;
// Geometry reference: a plain u32 id into the trailing registry
typedef uint32_t b3RecCType_GEOMID;
typedef b3Filter b3RecCType_FILTER;
typedef b3SurfaceMaterial b3RecCType_MATERIAL;
typedef b3MassData b3RecCType_MASSDATA;
typedef b3MotionLocks b3RecCType_LOCKS;
typedef const char* b3RecCType_STR;
typedef b3WorldId b3RecCType_WORLDID;
typedef b3BodyId b3RecCType_BODYID;
typedef b3ShapeId b3RecCType_SHAPEID;
typedef b3JointId b3RecCType_JOINTID;
typedef b3BodyDef b3RecCType_BODYDEF;
typedef b3ShapeDef b3RecCType_SHAPEDEF;
typedef b3ExplosionDef b3RecCType_EXPLOSIONDEF;
typedef b3ParallelJointDef b3RecCType_PARALLELJOINTDEF;
typedef b3DistanceJointDef b3RecCType_DISTANCEJOINTDEF;
typedef b3FilterJointDef b3RecCType_FILTERJOINTDEF;
typedef b3MotorJointDef b3RecCType_MOTORJOINTDEF;
typedef b3PrismaticJointDef b3RecCType_PRISMATICJOINTDEF;
typedef b3RevoluteJointDef b3RecCType_REVOLUTEJOINTDEF;
typedef b3SphericalJointDef b3RecCType_SPHERICALJOINTDEF;
typedef b3WeldJointDef b3RecCType_WELDJOINTDEF;
typedef b3WheelJointDef b3RecCType_WHEELJOINTDEF;
// Codegen pass 1a: arg structs. Generated here so call sites (body.c, shape.c, etc.) can see them.
#define ARG( TAG, field ) b3RecCType_##TAG field;
#define B3_REC_OP( op, Name, RET, ... ) \
typedef struct \
{ \
__VA_ARGS__ \
} b3RecArgs_##Name;
#include "recording_ops.inl"
#undef B3_REC_OP
#undef ARG
// Opcode constants generated from the manifest, so call sites name an op instead of a raw byte and
// can't drift from the manifest if an op is renumbered.
enum
{
#define B3_REC_OP( op, Name, RET, ... ) b3_recOp##Name = ( op ),
#include "recording_ops.inl"
#undef B3_REC_OP
};
// Low-level buffer helpers
void b3RecBufAppend( b3RecBuffer* buf, const void* data, int size );
void b3RecBufFree( b3RecBuffer* buf );
// Write primitives
void b3RecW_U8( b3RecBuffer* buf, uint8_t v );
void b3RecW_U16( b3RecBuffer* buf, uint16_t v );
void b3RecW_U32( b3RecBuffer* buf, uint32_t v );
void b3RecW_U64( b3RecBuffer* buf, uint64_t v );
void b3RecW_I32( b3RecBuffer* buf, int32_t v );
void b3RecW_F32( b3RecBuffer* buf, float v );
void b3RecW_F64( b3RecBuffer* buf, double v );
void b3RecW_BOOL( b3RecBuffer* buf, bool v );
void b3RecW_VEC3( b3RecBuffer* buf, b3Vec3 v );
void b3RecW_QUAT( b3RecBuffer* buf, b3Quat v );
void b3RecW_TRANSFORM( b3RecBuffer* buf, b3Transform v );
// World position: doubles in large-world mode, floats otherwise (wire-identical to VEC3 in float build)
void b3RecW_POSITION( b3RecBuffer* buf, b3Pos v );
void b3RecW_WORLDXF( b3RecBuffer* buf, b3WorldTransform v );
void b3RecW_MATRIX3( b3RecBuffer* buf, b3Matrix3 v );
void b3RecW_AABB( b3RecBuffer* buf, b3AABB v );
void b3RecW_QUERYFILTER( b3RecBuffer* buf, b3QueryFilter v );
void b3RecW_SHAPEPROXY( b3RecBuffer* buf, b3ShapeProxy v );
void b3RecW_TREESTATS( b3RecBuffer* buf, b3TreeStats v );
void b3RecW_RAYRESULT( b3RecBuffer* buf, b3RayResult v );
void b3RecW_PLANERESULT( b3RecBuffer* buf, b3PlaneResult v );
void b3RecW_WORLDID( b3RecBuffer* buf, b3WorldId v );
void b3RecW_BODYID( b3RecBuffer* buf, b3BodyId v );
void b3RecW_SHAPEID( b3RecBuffer* buf, b3ShapeId v );
void b3RecW_JOINTID( b3RecBuffer* buf, b3JointId v );
void b3RecW_SPHERE( b3RecBuffer* buf, b3Sphere v );
void b3RecW_CAPSULE( b3RecBuffer* buf, b3Capsule v );
void b3RecW_GEOMID( b3RecBuffer* buf, uint32_t v );
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_EXPLOSIONDEF( b3RecBuffer* buf, b3ExplosionDef v );
void b3RecW_BODYDEF( b3RecBuffer* buf, b3BodyDef v );
void b3RecW_SHAPEDEF( b3RecBuffer* buf, b3ShapeDef v );
void b3RecW_PARALLELJOINTDEF( b3RecBuffer* buf, b3ParallelJointDef v );
void b3RecW_DISTANCEJOINTDEF( b3RecBuffer* buf, b3DistanceJointDef v );
void b3RecW_FILTERJOINTDEF( b3RecBuffer* buf, b3FilterJointDef v );
void b3RecW_MOTORJOINTDEF( b3RecBuffer* buf, b3MotorJointDef v );
void b3RecW_PRISMATICJOINTDEF( b3RecBuffer* buf, b3PrismaticJointDef v );
void b3RecW_REVOLUTEJOINTDEF( b3RecBuffer* buf, b3RevoluteJointDef v );
void b3RecW_SPHERICALJOINTDEF( b3RecBuffer* buf, b3SphericalJointDef v );
void b3RecW_WELDJOINTDEF( b3RecBuffer* buf, b3WeldJointDef v );
void b3RecW_WHEELJOINTDEF( b3RecBuffer* buf, b3WheelJointDef v );
// Record framing
void b3RecBeginRecord( b3Recording* rec, uint8_t opcode );
void b3RecEndRecord( b3Recording* rec );
// Per-op arg writers (no framing) and full writers (framing + args), generated from the manifest.
#define B3_REC_OP( op, Name, RET, ... ) \
void b3RecWriteArgs_##Name( b3Recording* rec, const b3RecArgs_##Name* a ); \
void b3RecWrite_##Name( b3Recording* rec, const b3RecArgs_##Name* a );
#include "recording_ops.inl"
#undef B3_REC_OP
// Create ops: declare writers that also append the returned id inside the record.
#define B3_REC_RETDECL_RET_NONE( Name )
#define B3_REC_RETDECL_RET_BODYID( Name ) void b3RecWriteRet_##Name( b3Recording* rec, const b3RecArgs_##Name* a, b3BodyId id );
#define B3_REC_RETDECL_RET_SHAPEID( Name ) void b3RecWriteRet_##Name( b3Recording* rec, const b3RecArgs_##Name* a, b3ShapeId id );
#define B3_REC_RETDECL_RET_JOINTID( Name ) void b3RecWriteRet_##Name( b3Recording* rec, const b3RecArgs_##Name* a, b3JointId id );
#define B3_REC_OP( op, Name, RET, ... ) B3_REC_RETDECL_##RET( Name )
#include "recording_ops.inl"
#undef B3_REC_OP
#undef B3_REC_RETDECL_RET_NONE
#undef B3_REC_RETDECL_RET_BODYID
#undef B3_REC_RETDECL_RET_SHAPEID
#undef B3_REC_RETDECL_RET_JOINTID
// Record a void op. The branch is free when recording is off.
#define B3_REC( world, Name, ... ) \
do \
{ \
if ( ( world )->recording != NULL ) \
{ \
b3RecArgs_##Name recArgs = { __VA_ARGS__ }; \
b3RecWrite_##Name( ( world )->recording, &recArgs ); \
} \
} \
while ( 0 )
// Record a create op and its returned id in one framed record. Place after the real create call.
#define B3_REC_CREATE( world, Name, id, ... ) \
do \
{ \
if ( ( world )->recording != NULL ) \
{ \
b3RecArgs_##Name recCreateArgs = { __VA_ARGS__ }; \
b3RecWriteRet_##Name( ( world )->recording, &recCreateArgs, id ); \
} \
} \
while ( 0 )
// Patch helpers for the query hit-count backfill
int b3RecReserveU32( b3RecBuffer* buf );
void b3RecPatchU32( b3RecBuffer* buf, int offset, uint32_t v );
// Commit a finished query record under the lock. The payload buffer stays owned by the caller.
void b3RecCommitRecord( b3Recording* rec, uint8_t opcode, const uint8_t* payload, int payloadSize );
// Per-query writer context: holds the user fcn+ctx, the local payload buffer, and the hit counter
typedef struct b3RecQueryWriter
{
union
{
b3OverlapResultFcn* overlapFcn;
b3CastResultFcn* castFcn;
b3PlaneResultFcn* planeFcn;
b3MoverFilterFcn* moverFilterFcn;
} userFcn;
void* userContext;
b3RecBuffer buf; // per-call local payload, heap-backed
int countOffset; // offset of the reserved u32 hit-count slot
uint32_t hitCount;
} b3RecQueryWriter;
void b3RecQueryBegin( b3RecQueryWriter* w, void* context );
void b3RecQueryCommit( b3Recording* rec, uint8_t opcode, b3RecQueryWriter* w );
// Recording trampolines: replace the user fcn so hits are captured before dispatch. The overlap
// trampoline doubles for the mover filter, which has the same bool(shapeId, ctx) shape.
bool b3RecOverlapTrampoline( b3ShapeId id, void* ctx );
float b3RecCastTrampoline( b3ShapeId id, b3Pos point, b3Vec3 normal, float fraction, uint64_t userMaterialId, int triangleIndex,
int childIndex, void* ctx );
bool b3RecPlaneTrampoline( b3ShapeId id, const b3PlaneResult* planes, int planeCount, void* ctx );
// Geometry registry
uint32_t b3InternGeometry( b3GeometryRegistry* reg, b3GeometryKind kind, uint64_t contentHash,
uint8_t* bytes, int byteCount );
void b3FreeRegistry( b3GeometryRegistry* reg );
void b3RecWriteRegistry( b3Recording* rec );
// Intern each large geometry kind and return a stable u32 id for use in create ops.
// Caller does NOT free bytes; b3InternGeometry takes ownership (frees on duplicate).
uint32_t b3RecInternHull( b3Recording* rec, const b3HullData* hull );
uint32_t b3RecInternMesh( b3Recording* rec, const b3MeshData* mesh );
uint32_t b3RecInternHeightField( b3Recording* rec, const b3HeightFieldData* hf );
uint32_t b3RecInternCompound( b3Recording* rec, const b3CompoundData* compound );
uint64_t b3Hash64Blob( const uint8_t* bytes, int n );
// Lifecycle engine-side hooks
void b3StartRecordingIntoBuffer( b3World* world, b3Recording* recording );
void b3StopRecordingInternal( b3World* world );
// Fold one step's world bounds into the running union.
void b3RecAccumulateBounds( b3Recording* rec, b3AABB bounds );
// Deterministic hash over all body transforms and velocities.
// Called by both recorder and replayer to verify simulation reproduces exactly.
uint64_t b3HashWorldState( b3World* world );

229
src/recording_ops.inl Normal file
View file

@ -0,0 +1,229 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
// X-macro manifest for the recording system.
// Include with B3_REC_OP and ARG defined. No commas between ARG tokens.
//
// B3_REC_OP( opcode, Name, RET, ARGS )
// RET in { RET_NONE, RET_BODYID, RET_SHAPEID, RET_JOINTID }
// ARGS = zero or more ARG( TAG, fieldName ) tokens, NO commas between them
//
// Opcode ranges:
// 0x00-0x0F world lifecycle and config
// 0x10-0x1F body create/destroy
// 0x20-0x3F body mutators
// 0x40-0x4F shape create/destroy
// 0x50-0x6F shape mutators
// 0x80 step
// 0x90-0xE7 joints (create, generic, per-type)
// 0xE8-0xEF spatial queries
// 0xF0-0xFF markers
// Recordings are seeded with a world snapshot, not a CreateWorld op. DestroyWorld stays as the
// end-of-session marker the viewer reads.
B3_REC_OP( 0x01, DestroyWorld, RET_NONE, ARG( WORLDID, world ) )
B3_REC_OP( 0x80, Step, RET_NONE, ARG( WORLDID, world ) ARG( F32, dt ) ARG( I32, subStepCount ) )
// World config. The world arg is informational; replay always targets its own world.
B3_REC_OP( 0x02, WorldEnableSleeping, RET_NONE, ARG( WORLDID, world ) ARG( BOOL, flag ) )
B3_REC_OP( 0x03, WorldEnableContinuous, RET_NONE, ARG( WORLDID, world ) ARG( BOOL, flag ) )
B3_REC_OP( 0x04, WorldSetRestitutionThreshold, RET_NONE, ARG( WORLDID, world ) ARG( F32, value ) )
B3_REC_OP( 0x05, WorldSetHitEventThreshold, RET_NONE, ARG( WORLDID, world ) ARG( F32, value ) )
B3_REC_OP( 0x06, WorldSetGravity, RET_NONE, ARG( WORLDID, world ) ARG( VEC3, gravity ) )
B3_REC_OP( 0x07, WorldExplode, RET_NONE, ARG( WORLDID, world ) ARG( EXPLOSIONDEF, def ) )
B3_REC_OP( 0x08, WorldSetContactTuning, RET_NONE,
ARG( WORLDID, world ) ARG( F32, hertz ) ARG( F32, dampingRatio ) ARG( F32, contactSpeed ) )
B3_REC_OP( 0x09, WorldSetContactRecycleDistance, RET_NONE, ARG( WORLDID, world ) ARG( F32, recycleDistance ) )
B3_REC_OP( 0x0A, WorldSetMaximumLinearSpeed, RET_NONE, ARG( WORLDID, world ) ARG( F32, maximumLinearSpeed ) )
B3_REC_OP( 0x0B, WorldEnableWarmStarting, RET_NONE, ARG( WORLDID, world ) ARG( BOOL, flag ) )
B3_REC_OP( 0x0C, WorldRebuildStaticTree, RET_NONE, ARG( WORLDID, world ) )
B3_REC_OP( 0x0D, WorldEnableSpeculative, RET_NONE, ARG( WORLDID, world ) ARG( BOOL, flag ) )
// Body
B3_REC_OP( 0x10, CreateBody, RET_BODYID, ARG( WORLDID, world ) ARG( BODYDEF, def ) )
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( 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 ) )
B3_REC_OP( 0x27, BodyApplyForceToCenter, RET_NONE, ARG( BODYID, body ) ARG( VEC3, force ) ARG( BOOL, wake ) )
B3_REC_OP( 0x28, BodyApplyTorque, RET_NONE, ARG( BODYID, body ) ARG( VEC3, torque ) ARG( BOOL, wake ) )
B3_REC_OP( 0x29, BodyApplyLinearImpulse, RET_NONE, ARG( BODYID, body ) ARG( VEC3, impulse ) ARG( POSITION, point ) ARG( BOOL, wake ) )
B3_REC_OP( 0x2A, BodyApplyLinearImpulseToCenter, RET_NONE, ARG( BODYID, body ) ARG( VEC3, impulse ) ARG( BOOL, wake ) )
B3_REC_OP( 0x2B, BodyApplyAngularImpulse, RET_NONE, ARG( BODYID, body ) ARG( VEC3, impulse ) ARG( BOOL, wake ) )
B3_REC_OP( 0x2C, BodySetMassData, RET_NONE, ARG( BODYID, body ) ARG( MASSDATA, massData ) )
B3_REC_OP( 0x2D, BodyApplyMassFromShapes, RET_NONE, ARG( BODYID, body ) )
B3_REC_OP( 0x2E, BodySetLinearDamping, RET_NONE, ARG( BODYID, body ) ARG( F32, damping ) )
B3_REC_OP( 0x2F, BodySetAngularDamping, RET_NONE, ARG( BODYID, body ) ARG( F32, damping ) )
B3_REC_OP( 0x30, BodySetGravityScale, RET_NONE, ARG( BODYID, body ) ARG( F32, scale ) )
B3_REC_OP( 0x31, BodySetAwake, RET_NONE, ARG( BODYID, body ) ARG( BOOL, awake ) )
B3_REC_OP( 0x32, BodyEnableSleep, RET_NONE, ARG( BODYID, body ) ARG( BOOL, flag ) )
B3_REC_OP( 0x33, BodySetSleepThreshold, RET_NONE, ARG( BODYID, body ) ARG( F32, threshold ) )
B3_REC_OP( 0x34, BodyDisable, RET_NONE, ARG( BODYID, body ) )
B3_REC_OP( 0x35, BodyEnable, RET_NONE, ARG( BODYID, body ) )
B3_REC_OP( 0x36, BodySetMotionLocks, RET_NONE, ARG( BODYID, body ) ARG( LOCKS, locks ) )
B3_REC_OP( 0x37, BodySetBullet, RET_NONE, ARG( BODYID, body ) ARG( BOOL, flag ) )
B3_REC_OP( 0x38, BodyEnableContactRecycling, RET_NONE, ARG( BODYID, body ) ARG( BOOL, flag ) )
B3_REC_OP( 0x39, BodyEnableHitEvents, RET_NONE, ARG( BODYID, body ) ARG( BOOL, flag ) )
// Shape create/destroy
B3_REC_OP( 0x40, CreateSphereShape, RET_SHAPEID, ARG( BODYID, body ) ARG( SHAPEDEF, def ) ARG( SPHERE, sphere ) )
B3_REC_OP( 0x41, CreateCapsuleShape, RET_SHAPEID, ARG( BODYID, body ) ARG( SHAPEDEF, def ) ARG( CAPSULE, capsule ) )
B3_REC_OP( 0x42, CreateHullShape, RET_SHAPEID, ARG( BODYID, body ) ARG( SHAPEDEF, def ) ARG( GEOMID, geometryId ) )
B3_REC_OP( 0x43, CreateMeshShape, RET_SHAPEID, ARG( BODYID, body ) ARG( SHAPEDEF, def ) ARG( GEOMID, geometryId ) ARG( VEC3, scale ) )
B3_REC_OP( 0x44, CreateHeightFieldShape, RET_SHAPEID, ARG( BODYID, body ) ARG( SHAPEDEF, def ) ARG( GEOMID, geometryId ) )
B3_REC_OP( 0x45, CreateCompoundShape, RET_SHAPEID, ARG( BODYID, body ) ARG( SHAPEDEF, def ) ARG( GEOMID, geometryId ) )
B3_REC_OP( 0x46, DestroyShape, RET_NONE, ARG( SHAPEID, shape ) ARG( BOOL, updateBodyMass ) )
// Shape mutators
B3_REC_OP( 0x50, ShapeSetDensity, RET_NONE, ARG( SHAPEID, shape ) ARG( F32, density ) ARG( BOOL, updateBodyMass ) )
B3_REC_OP( 0x51, ShapeSetFriction, RET_NONE, ARG( SHAPEID, shape ) ARG( F32, friction ) )
B3_REC_OP( 0x52, ShapeSetRestitution, RET_NONE, ARG( SHAPEID, shape ) ARG( F32, restitution ) )
B3_REC_OP( 0x53, ShapeSetSurfaceMaterial, RET_NONE, ARG( SHAPEID, shape ) ARG( MATERIAL, material ) )
B3_REC_OP( 0x54, ShapeSetFilter, RET_NONE, ARG( SHAPEID, shape ) ARG( FILTER, filter ) ARG( BOOL, invokeContacts ) )
B3_REC_OP( 0x55, ShapeEnableSensorEvents, RET_NONE, ARG( SHAPEID, shape ) ARG( BOOL, flag ) )
B3_REC_OP( 0x56, ShapeEnableContactEvents, RET_NONE, ARG( SHAPEID, shape ) ARG( BOOL, flag ) )
B3_REC_OP( 0x57, ShapeEnablePreSolveEvents, RET_NONE, ARG( SHAPEID, shape ) ARG( BOOL, flag ) )
B3_REC_OP( 0x58, ShapeEnableHitEvents, RET_NONE, ARG( SHAPEID, shape ) ARG( BOOL, flag ) )
B3_REC_OP( 0x59, ShapeSetSphere, RET_NONE, ARG( SHAPEID, shape ) ARG( SPHERE, sphere ) )
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 ) )
// Joint create and destroy
B3_REC_OP( 0x90, CreateParallelJoint, RET_JOINTID, ARG( WORLDID, world ) ARG( PARALLELJOINTDEF, def ) )
B3_REC_OP( 0x91, CreateDistanceJoint, RET_JOINTID, ARG( WORLDID, world ) ARG( DISTANCEJOINTDEF, def ) )
B3_REC_OP( 0x92, CreateFilterJoint, RET_JOINTID, ARG( WORLDID, world ) ARG( FILTERJOINTDEF, def ) )
B3_REC_OP( 0x93, CreateMotorJoint, RET_JOINTID, ARG( WORLDID, world ) ARG( MOTORJOINTDEF, def ) )
B3_REC_OP( 0x94, CreatePrismaticJoint, RET_JOINTID, ARG( WORLDID, world ) ARG( PRISMATICJOINTDEF, def ) )
B3_REC_OP( 0x95, CreateRevoluteJoint, RET_JOINTID, ARG( WORLDID, world ) ARG( REVOLUTEJOINTDEF, def ) )
B3_REC_OP( 0x96, CreateSphericalJoint, RET_JOINTID, ARG( WORLDID, world ) ARG( SPHERICALJOINTDEF, def ) )
B3_REC_OP( 0x97, CreateWeldJoint, RET_JOINTID, ARG( WORLDID, world ) ARG( WELDJOINTDEF, def ) )
B3_REC_OP( 0x98, CreateWheelJoint, RET_JOINTID, ARG( WORLDID, world ) ARG( WHEELJOINTDEF, def ) )
B3_REC_OP( 0x99, DestroyJoint, RET_NONE, ARG( JOINTID, joint ) ARG( BOOL, wakeAttached ) )
// Generic joint mutators
B3_REC_OP( 0x9A, JointSetLocalFrameA, RET_NONE, ARG( JOINTID, joint ) ARG( TRANSFORM, localFrame ) )
B3_REC_OP( 0x9B, JointSetLocalFrameB, RET_NONE, ARG( JOINTID, joint ) ARG( TRANSFORM, localFrame ) )
B3_REC_OP( 0x9C, JointSetCollideConnected, RET_NONE, ARG( JOINTID, joint ) ARG( BOOL, shouldCollide ) )
B3_REC_OP( 0x9D, JointWakeBodies, RET_NONE, ARG( JOINTID, joint ) )
B3_REC_OP( 0x9E, JointSetConstraintTuning, RET_NONE, ARG( JOINTID, joint ) ARG( F32, hertz ) ARG( F32, dampingRatio ) )
B3_REC_OP( 0x9F, JointSetForceThreshold, RET_NONE, ARG( JOINTID, joint ) ARG( F32, threshold ) )
B3_REC_OP( 0xA0, JointSetTorqueThreshold, RET_NONE, ARG( JOINTID, joint ) ARG( F32, threshold ) )
// Parallel joint
B3_REC_OP( 0xA1, ParallelJointSetSpringHertz, RET_NONE, ARG( JOINTID, joint ) ARG( F32, hertz ) )
B3_REC_OP( 0xA2, ParallelJointSetSpringDampingRatio, RET_NONE, ARG( JOINTID, joint ) ARG( F32, dampingRatio ) )
B3_REC_OP( 0xA3, ParallelJointSetMaxTorque, RET_NONE, ARG( JOINTID, joint ) ARG( F32, maxTorque ) )
// Distance joint
B3_REC_OP( 0xA4, DistanceJointSetLength, RET_NONE, ARG( JOINTID, joint ) ARG( F32, length ) )
B3_REC_OP( 0xA5, DistanceJointEnableSpring, RET_NONE, ARG( JOINTID, joint ) ARG( BOOL, enableSpring ) )
B3_REC_OP( 0xA6, DistanceJointSetSpringForceRange, RET_NONE, ARG( JOINTID, joint ) ARG( F32, lowerForce ) ARG( F32, upperForce ) )
B3_REC_OP( 0xA7, DistanceJointSetSpringHertz, RET_NONE, ARG( JOINTID, joint ) ARG( F32, hertz ) )
B3_REC_OP( 0xA8, DistanceJointSetSpringDampingRatio, RET_NONE, ARG( JOINTID, joint ) ARG( F32, dampingRatio ) )
B3_REC_OP( 0xA9, DistanceJointEnableLimit, RET_NONE, ARG( JOINTID, joint ) ARG( BOOL, enableLimit ) )
B3_REC_OP( 0xAA, DistanceJointSetLengthRange, RET_NONE, ARG( JOINTID, joint ) ARG( F32, minLength ) ARG( F32, maxLength ) )
B3_REC_OP( 0xAB, DistanceJointEnableMotor, RET_NONE, ARG( JOINTID, joint ) ARG( BOOL, enableMotor ) )
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)
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 ) )
B3_REC_OP( 0xB1, MotorJointSetMaxVelocityTorque, RET_NONE, ARG( JOINTID, joint ) ARG( F32, maxTorque ) )
B3_REC_OP( 0xB2, MotorJointSetLinearHertz, RET_NONE, ARG( JOINTID, joint ) ARG( F32, hertz ) )
B3_REC_OP( 0xB3, MotorJointSetLinearDampingRatio, RET_NONE, ARG( JOINTID, joint ) ARG( F32, damping ) )
B3_REC_OP( 0xB4, MotorJointSetAngularHertz, RET_NONE, ARG( JOINTID, joint ) ARG( F32, hertz ) )
B3_REC_OP( 0xB5, MotorJointSetAngularDampingRatio, RET_NONE, ARG( JOINTID, joint ) ARG( F32, damping ) )
B3_REC_OP( 0xB6, MotorJointSetMaxSpringForce, RET_NONE, ARG( JOINTID, joint ) ARG( F32, maxForce ) )
B3_REC_OP( 0xB7, MotorJointSetMaxSpringTorque, RET_NONE, ARG( JOINTID, joint ) ARG( F32, maxTorque ) )
// Prismatic joint
B3_REC_OP( 0xB8, PrismaticJointEnableSpring, RET_NONE, ARG( JOINTID, joint ) ARG( BOOL, enableSpring ) )
B3_REC_OP( 0xB9, PrismaticJointSetSpringHertz, RET_NONE, ARG( JOINTID, joint ) ARG( F32, hertz ) )
B3_REC_OP( 0xBA, PrismaticJointSetSpringDampingRatio, RET_NONE, ARG( JOINTID, joint ) ARG( F32, dampingRatio ) )
B3_REC_OP( 0xBB, PrismaticJointSetTargetTranslation, RET_NONE, ARG( JOINTID, joint ) ARG( F32, translation ) )
B3_REC_OP( 0xBC, PrismaticJointEnableLimit, RET_NONE, ARG( JOINTID, joint ) ARG( BOOL, enableLimit ) )
B3_REC_OP( 0xBD, PrismaticJointSetLimits, RET_NONE, ARG( JOINTID, joint ) ARG( F32, lower ) ARG( F32, upper ) )
B3_REC_OP( 0xBE, PrismaticJointEnableMotor, RET_NONE, ARG( JOINTID, joint ) ARG( BOOL, enableMotor ) )
B3_REC_OP( 0xBF, PrismaticJointSetMotorSpeed, RET_NONE, ARG( JOINTID, joint ) ARG( F32, motorSpeed ) )
B3_REC_OP( 0xC0, PrismaticJointSetMaxMotorForce, RET_NONE, ARG( JOINTID, joint ) ARG( F32, force ) )
// Revolute joint
B3_REC_OP( 0xC1, RevoluteJointEnableSpring, RET_NONE, ARG( JOINTID, joint ) ARG( BOOL, enableSpring ) )
B3_REC_OP( 0xC2, RevoluteJointSetSpringHertz, RET_NONE, ARG( JOINTID, joint ) ARG( F32, hertz ) )
B3_REC_OP( 0xC3, RevoluteJointSetSpringDampingRatio, RET_NONE, ARG( JOINTID, joint ) ARG( F32, dampingRatio ) )
B3_REC_OP( 0xC4, RevoluteJointSetTargetAngle, RET_NONE, ARG( JOINTID, joint ) ARG( F32, angle ) )
B3_REC_OP( 0xC5, RevoluteJointEnableLimit, RET_NONE, ARG( JOINTID, joint ) ARG( BOOL, enableLimit ) )
B3_REC_OP( 0xC6, RevoluteJointSetLimits, RET_NONE, ARG( JOINTID, joint ) ARG( F32, lower ) ARG( F32, upper ) )
B3_REC_OP( 0xC7, RevoluteJointEnableMotor, RET_NONE, ARG( JOINTID, joint ) ARG( BOOL, enableMotor ) )
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)
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 ) )
B3_REC_OP( 0xCD, SphericalJointSetTwistLimits, RET_NONE, ARG( JOINTID, joint ) ARG( F32, lower ) ARG( F32, upper ) )
B3_REC_OP( 0xCE, SphericalJointEnableSpring, RET_NONE, ARG( JOINTID, joint ) ARG( BOOL, enableSpring ) )
B3_REC_OP( 0xCF, SphericalJointSetSpringHertz, RET_NONE, ARG( JOINTID, joint ) ARG( F32, hertz ) )
B3_REC_OP( 0xD0, SphericalJointSetSpringDampingRatio, RET_NONE, ARG( JOINTID, joint ) ARG( F32, dampingRatio ) )
B3_REC_OP( 0xD1, SphericalJointSetTargetRotation, RET_NONE, ARG( JOINTID, joint ) ARG( QUAT, targetRotation ) )
B3_REC_OP( 0xD2, SphericalJointEnableMotor, RET_NONE, ARG( JOINTID, joint ) ARG( BOOL, enableMotor ) )
B3_REC_OP( 0xD3, SphericalJointSetMotorVelocity, RET_NONE, ARG( JOINTID, joint ) ARG( VEC3, motorVelocity ) )
B3_REC_OP( 0xD4, SphericalJointSetMaxMotorTorque, RET_NONE, ARG( JOINTID, joint ) ARG( F32, torque ) )
// Weld joint
B3_REC_OP( 0xD5, WeldJointSetLinearHertz, RET_NONE, ARG( JOINTID, joint ) ARG( F32, hertz ) )
B3_REC_OP( 0xD6, WeldJointSetLinearDampingRatio, RET_NONE, ARG( JOINTID, joint ) ARG( F32, dampingRatio ) )
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)
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 ) )
B3_REC_OP( 0xDC, WheelJointEnableSuspensionLimit, RET_NONE, ARG( JOINTID, joint ) ARG( BOOL, flag ) )
B3_REC_OP( 0xDD, WheelJointSetSuspensionLimits, RET_NONE, ARG( JOINTID, joint ) ARG( F32, lower ) ARG( F32, upper ) )
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.
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 ) )
B3_REC_OP( 0xE3, WheelJointSetSteeringDampingRatio, RET_NONE, ARG( JOINTID, joint ) ARG( F32, dampingRatio ) )
B3_REC_OP( 0xE4, WheelJointSetMaxSteeringTorque, RET_NONE, ARG( JOINTID, joint ) ARG( F32, torque ) )
B3_REC_OP( 0xE5, WheelJointEnableSteeringLimit, RET_NONE, ARG( JOINTID, joint ) ARG( BOOL, flag ) )
B3_REC_OP( 0xE6, WheelJointSetSteeringLimits, RET_NONE, ARG( JOINTID, joint ) ARG( F32, lower ) ARG( F32, upper ) )
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.
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 ) )
B3_REC_OP( 0xEA, QueryCastRay, RET_NONE,
ARG( WORLDID, world ) ARG( POSITION, origin ) ARG( VEC3, translation ) ARG( QUERYFILTER, filter ) )
B3_REC_OP( 0xEB, QueryCastShape, RET_NONE,
ARG( WORLDID, world ) ARG( POSITION, origin ) ARG( SHAPEPROXY, proxy ) ARG( VEC3, translation )
ARG( QUERYFILTER, filter ) )
B3_REC_OP( 0xEC, QueryCastRayClosest, RET_NONE,
ARG( WORLDID, world ) ARG( POSITION, origin ) ARG( VEC3, translation ) ARG( QUERYFILTER, filter ) )
B3_REC_OP( 0xED, QueryCastMover, RET_NONE,
ARG( WORLDID, world ) ARG( POSITION, origin ) ARG( CAPSULE, mover ) ARG( VEC3, translation ) ARG( QUERYFILTER, filter ) )
B3_REC_OP( 0xEE, QueryCollideMover, RET_NONE,
ARG( WORLDID, world ) ARG( POSITION, origin ) ARG( CAPSULE, mover ) ARG( QUERYFILTER, filter ) )
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.
B3_REC_OP( 0xF2, RecordingBounds, RET_NONE, ARG( AABB, bounds ) )

3250
src/recording_replay.c Normal file

File diff suppressed because it is too large Load diff

240
src/recording_replay.h Normal file
View file

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

View file

@ -7,6 +7,7 @@
#include "physics_world.h"
#include "solver.h"
#include "solver_set.h"
#include "recording.h"
// needed for dll export
#include "box3d/box3d.h"
@ -41,6 +42,8 @@
void b3RevoluteJoint_EnableLimit( b3JointId jointId, bool enableLimit )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, RevoluteJointEnableLimit, jointId, enableLimit );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint );
if ( enableLimit != base->revoluteJoint.enableLimit )
{
@ -72,6 +75,8 @@ void b3RevoluteJoint_SetLimits( b3JointId jointId, float lowerLimitRadians, floa
{
B3_ASSERT( lowerLimitRadians <= upperLimitRadians );
B3_ASSERT( b3IsValidFloat( lowerLimitRadians ) && b3IsValidFloat( upperLimitRadians ) );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, RevoluteJointSetLimits, jointId, lowerLimitRadians, upperLimitRadians );
float lowerAngle = b3ClampFloat( lowerLimitRadians, -B3_PI, B3_PI );
float upperAngle = b3ClampFloat( upperLimitRadians, -B3_PI, B3_PI );
@ -105,6 +110,8 @@ float b3RevoluteJoint_GetAngle( b3JointId jointId )
void b3RevoluteJoint_EnableSpring( b3JointId jointId, bool enableSpring )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, RevoluteJointEnableSpring, jointId, enableSpring );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint );
if ( enableSpring != base->revoluteJoint.enableSpring )
{
@ -122,6 +129,8 @@ bool b3RevoluteJoint_IsSpringEnabled( b3JointId jointId )
void b3RevoluteJoint_SetTargetAngle( b3JointId jointId, float targetRadians )
{
B3_ASSERT( b3IsValidFloat( targetRadians ) && -B3_PI <= targetRadians && targetRadians <= B3_PI );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, RevoluteJointSetTargetAngle, jointId, targetRadians );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint );
base->revoluteJoint.targetAngle = targetRadians;
}
@ -135,6 +144,8 @@ float b3RevoluteJoint_GetTargetAngle( b3JointId jointId )
void b3RevoluteJoint_SetSpringHertz( b3JointId jointId, float hertz )
{
B3_ASSERT( b3IsValidFloat( hertz ) && hertz >= 0.0f );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, RevoluteJointSetSpringHertz, jointId, hertz );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint );
base->revoluteJoint.hertz = hertz;
}
@ -148,6 +159,8 @@ float b3RevoluteJoint_GetSpringHertz( b3JointId jointId )
void b3RevoluteJoint_SetSpringDampingRatio( b3JointId jointId, float dampingRatio )
{
B3_ASSERT( b3IsValidFloat( dampingRatio ) && dampingRatio >= 0.0f );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, RevoluteJointSetSpringDampingRatio, jointId, dampingRatio );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint );
base->revoluteJoint.dampingRatio = dampingRatio;
}
@ -160,6 +173,8 @@ float b3RevoluteJoint_GetSpringDampingRatio( b3JointId jointId )
void b3RevoluteJoint_EnableMotor( b3JointId jointId, bool enableMotor )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, RevoluteJointEnableMotor, jointId, enableMotor );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint );
if ( enableMotor != base->revoluteJoint.enableMotor )
{
@ -177,6 +192,8 @@ bool b3RevoluteJoint_IsMotorEnabled( b3JointId jointId )
void b3RevoluteJoint_SetMotorSpeed( b3JointId jointId, float motorSpeed )
{
B3_ASSERT( b3IsValidFloat( motorSpeed ) );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, RevoluteJointSetMotorSpeed, jointId, motorSpeed );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint );
base->revoluteJoint.motorSpeed = motorSpeed;
}
@ -190,6 +207,8 @@ float b3RevoluteJoint_GetMotorSpeed( b3JointId jointId )
void b3RevoluteJoint_SetMaxMotorTorque( b3JointId jointId, float maxForce )
{
B3_ASSERT( b3IsValidFloat( maxForce ) && maxForce >= 0.0f );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, RevoluteJointSetMaxMotorTorque, jointId, maxForce );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint );
base->revoluteJoint.maxMotorTorque = maxForce;
}

View file

@ -7,6 +7,7 @@
#include "broad_phase.h"
#include "contact.h"
#include "physics_world.h"
#include "recording.h"
#include "sensor.h"
// needed for dll export
@ -125,7 +126,7 @@ static b3Shape* b3CreateShapeInternal( b3World* world, b3Body* body, b3WorldTran
// Compounds must be a static and not a sensor
B3_ASSERT( body->type == b3_staticBody );
B3_ASSERT( def->isSensor == false );
shape->compound = (b3Compound*)geometry;
shape->compound = (b3CompoundData*)geometry;
break;
case b3_sphereShape:
@ -161,7 +162,7 @@ static b3Shape* b3CreateShapeInternal( b3World* world, b3Body* body, b3WorldTran
break;
case b3_heightShape:
shape->heightField = (b3HeightField*)geometry;
shape->heightField = (b3HeightFieldData*)geometry;
break;
default:
@ -192,34 +193,40 @@ static b3Shape* b3CreateShapeInternal( b3World* world, b3Body* body, b3WorldTran
if ( def->name )
{
size_t length = strlen( def->name ) + 1;
shape->name = (char*)b3Alloc( length * sizeof( char ) );
memcpy( shape->name, def->name, length );
#if defined( _MSC_VER )
strncpy_s( shape->name, B3_NAME_LENGTH + 1, def->name, B3_NAME_LENGTH );
#else
strncpy( shape->name, def->name, B3_NAME_LENGTH );
shape->name[B3_NAME_LENGTH] = 0;
#endif
}
else
{
shape->name = NULL;
memset( shape->name, 0, sizeof( shape->name ) );
}
if ( shape->type == b3_compoundShape )
{
// Unfortunate const removal
shape->materials = (b3SurfaceMaterial*)b3GetCompoundMaterials( shape->compound );
shape->materialCount = shape->compound->materialCount;
// 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;
shape->materialCount = materialCount;
shape->materials = b3Alloc( materialCount * sizeof( b3SurfaceMaterial ) );
memcpy( shape->materials, b3GetCompoundMaterials( shape->compound ), materialCount * sizeof( b3SurfaceMaterial ) );
}
else if ( def->materialCount > 0 && def->materials != NULL )
else if ( def->materialCount > 1 && def->materials != NULL )
{
b3SurfaceMaterial* materials = (b3SurfaceMaterial*)b3Alloc( def->materialCount * sizeof( b3SurfaceMaterial ) );
memcpy( materials, def->materials, def->materialCount * sizeof( b3SurfaceMaterial ) );
shape->materials = materials;
// Per triangle materials need a heap array.
shape->materialCount = def->materialCount;
shape->materials = b3Alloc( def->materialCount * sizeof( b3SurfaceMaterial ) );
memcpy( shape->materials, def->materials, def->materialCount * sizeof( b3SurfaceMaterial ) );
}
else
{
b3SurfaceMaterial* materials = (b3SurfaceMaterial*)b3Alloc( sizeof( b3SurfaceMaterial ) );
memcpy( materials, &def->baseMaterial, sizeof( b3SurfaceMaterial ) );
shape->materials = materials;
// The common case is one material, stored inline with no allocation.
shape->material = ( def->materialCount == 1 && def->materials != NULL ) ? def->materials[0] : def->baseMaterial;
shape->materialCount = 1;
shape->materials = NULL;
}
if ( body->setIndex != b3_disabledSet )
@ -316,26 +323,58 @@ static b3ShapeId b3CreateShape( b3BodyId bodyId, const b3ShapeDef* def, const vo
b3ShapeId b3CreateSphereShape( b3BodyId bodyId, const b3ShapeDef* def, const b3Sphere* sphere )
{
return b3CreateShape( bodyId, def, sphere, b3_sphereShape, b3Transform_identity, b3Vec3_one, false );
b3ShapeId shapeId = b3CreateShape( bodyId, def, sphere, b3_sphereShape, b3Transform_identity, b3Vec3_one, false );
if ( shapeId.index1 != 0 )
{
b3World* world = b3GetUnlockedWorld( bodyId.world0 );
if ( world != NULL )
{
B3_REC_CREATE( world, CreateSphereShape, shapeId, bodyId, *def, *sphere );
}
}
return shapeId;
}
b3ShapeId b3CreateCapsuleShape( b3BodyId bodyId, const b3ShapeDef* def, const b3Capsule* capsule )
{
float lengthSqr = b3DistanceSquared( capsule->center1, capsule->center2 );
b3ShapeId shapeId;
if ( lengthSqr <= B3_LINEAR_SLOP * B3_LINEAR_SLOP )
{
b3Sphere sphere = { b3Lerp( capsule->center1, capsule->center2, 0.5f ), capsule->radius };
return b3CreateShape( bodyId, def, &sphere, b3_sphereShape, b3Transform_identity, b3Vec3_one, false );
shapeId = b3CreateShape( bodyId, def, &sphere, b3_sphereShape, b3Transform_identity, b3Vec3_one, false );
}
return b3CreateShape( bodyId, def, capsule, b3_capsuleShape, b3Transform_identity, b3Vec3_one, false );
else
{
shapeId = b3CreateShape( bodyId, def, capsule, b3_capsuleShape, b3Transform_identity, b3Vec3_one, false );
}
if ( shapeId.index1 != 0 )
{
b3World* world = b3GetUnlockedWorld( bodyId.world0 );
if ( world != NULL )
{
B3_REC_CREATE( world, CreateCapsuleShape, shapeId, bodyId, *def, *capsule );
}
}
return shapeId;
}
b3ShapeId b3CreateHullShape( b3BodyId bodyId, const b3ShapeDef* def, const b3HullData* hull )
{
B3_VALIDATE( b3IsValidHull( hull ) );
B3_VALIDATE( hull->hash != 0 );
return b3CreateShape( bodyId, def, hull, b3_hullShape, b3Transform_identity, b3Vec3_one, false );
b3ShapeId shapeId = b3CreateShape( bodyId, def, hull, b3_hullShape, b3Transform_identity, b3Vec3_one, false );
if ( shapeId.index1 != 0 )
{
b3World* world = b3GetUnlockedWorld( bodyId.world0 );
if ( world != NULL && world->recording != NULL )
{
uint32_t geometryId = b3RecInternHull( world->recording, hull );
b3RecArgs_CreateHullShape createArgs = { bodyId, *def, geometryId };
b3RecWriteRet_CreateHullShape( world->recording, &createArgs, shapeId );
}
}
return shapeId;
}
b3ShapeId b3CreateTransformedHullShape( b3BodyId bodyId, const b3ShapeDef* def, const b3HullData* hull, b3Transform transform,
@ -349,18 +388,51 @@ b3ShapeId b3CreateMeshShape( b3BodyId bodyId, const b3ShapeDef* def, const b3Mes
{
B3_VALIDATE( b3IsValidMesh( mesh ) );
B3_VALIDATE( mesh->hash != 0 );
return b3CreateShape( bodyId, def, mesh, b3_meshShape, b3Transform_identity, scale, true );
b3ShapeId shapeId = b3CreateShape( bodyId, def, mesh, b3_meshShape, b3Transform_identity, scale, true );
if ( shapeId.index1 != 0 )
{
b3World* world = b3GetUnlockedWorld( bodyId.world0 );
if ( world != NULL && world->recording != NULL )
{
uint32_t geometryId = b3RecInternMesh( world->recording, mesh );
b3RecArgs_CreateMeshShape createArgs = { bodyId, *def, geometryId, scale };
b3RecWriteRet_CreateMeshShape( world->recording, &createArgs, shapeId );
}
}
return shapeId;
}
b3ShapeId b3CreateHeightFieldShape( b3BodyId bodyId, const b3ShapeDef* def, const b3HeightField* heightField )
b3ShapeId b3CreateHeightFieldShape( b3BodyId bodyId, const b3ShapeDef* def, const b3HeightFieldData* heightField )
{
B3_VALIDATE( heightField->hash != 0 );
return b3CreateShape( bodyId, def, heightField, b3_heightShape, b3Transform_identity, b3Vec3_one, false );
b3ShapeId shapeId = b3CreateShape( bodyId, def, heightField, b3_heightShape, b3Transform_identity, b3Vec3_one, false );
if ( shapeId.index1 != 0 )
{
b3World* world = b3GetUnlockedWorld( bodyId.world0 );
if ( world != NULL && world->recording != NULL )
{
uint32_t geometryId = b3RecInternHeightField( world->recording, heightField );
b3RecArgs_CreateHeightFieldShape createArgs = { bodyId, *def, geometryId };
b3RecWriteRet_CreateHeightFieldShape( world->recording, &createArgs, shapeId );
}
}
return shapeId;
}
b3ShapeId b3CreateCompoundShape( b3BodyId bodyId, b3ShapeDef* def, const b3Compound* compound )
b3ShapeId b3CreateCompoundShape( b3BodyId bodyId, b3ShapeDef* def, const b3CompoundData* compound )
{
return b3CreateShape( bodyId, def, compound, b3_compoundShape, b3Transform_identity, b3Vec3_one, false );
b3ShapeId shapeId = b3CreateShape( bodyId, def, compound, b3_compoundShape, b3Transform_identity, b3Vec3_one, false );
if ( shapeId.index1 != 0 )
{
b3World* world = b3GetUnlockedWorld( bodyId.world0 );
if ( world != NULL && world->recording != NULL )
{
uint32_t geometryId = b3RecInternCompound( world->recording, compound );
b3RecArgs_CreateCompoundShape createArgs = { bodyId, *def, geometryId };
b3RecWriteRet_CreateCompoundShape( world->recording, &createArgs, shapeId );
}
}
return shapeId;
}
// Destroy a shape on a body. This doesn't need to be called when destroying a body.
@ -464,6 +536,8 @@ void b3DestroyShape( b3ShapeId shapeId, bool updateBodyMass )
return;
}
B3_REC( world, DestroyShape, shapeId, updateBodyMass );
world->locked = true;
b3Shape* shape = b3GetShape( world, shapeId );
@ -952,7 +1026,7 @@ void b3DestroyShapeAllocations( b3World* world, b3Shape* shape )
{
b3DestroyShapeAllocationForShapeChange( world, shape );
if ( shape->materials != NULL && shape->type != b3_compoundShape )
if ( shape->materials != NULL )
{
B3_ASSERT( shape->materialCount > 0 );
b3Free( shape->materials, shape->materialCount * sizeof( b3SurfaceMaterial ) );
@ -960,13 +1034,7 @@ void b3DestroyShapeAllocations( b3World* world, b3Shape* shape )
shape->materialCount = 0;
}
if ( shape->name != NULL )
{
b3Free( shape->name, ( strlen( shape->name ) + 1 ) * sizeof( char ) );
shape->name = NULL;
}
// Sensor data is destroyed elsewhere
// Name is stored inline. Sensor data is destroyed elsewhere
}
b3ShapeProxy b3MakeShapeProxy( const b3Shape* shape )
@ -1071,17 +1139,18 @@ void b3Shape_SetName( b3ShapeId shapeId, const char* name )
b3World* world = b3GetWorld( shapeId.world0 );
b3Shape* shape = b3GetShape( world, shapeId );
if ( shape->name != NULL )
if ( name )
{
b3Free( shape->name, ( strlen( shape->name ) + 1 ) * sizeof( char ) );
shape->name = NULL;
#if defined( _MSC_VER )
strncpy_s( shape->name, B3_NAME_LENGTH + 1, name, B3_NAME_LENGTH );
#else
strncpy( shape->name, name, B3_NAME_LENGTH );
shape->name[B3_NAME_LENGTH] = 0;
#endif
}
if ( name != NULL )
else
{
size_t length = strlen( name ) + 1;
shape->name = (char*)b3Alloc( length * sizeof( char ) );
memcpy( shape->name, name, length );
memset( shape->name, 0, sizeof( shape->name ) );
}
}
@ -1132,6 +1201,8 @@ void b3Shape_SetDensity( b3ShapeId shapeId, float density, bool updateBodyMass )
return;
}
B3_REC( world, ShapeSetDensity, shapeId, density, updateBodyMass );
b3Shape* shape = b3GetShape( world, shapeId );
if ( density == shape->density )
{
@ -1159,32 +1230,34 @@ void b3Shape_SetFriction( b3ShapeId shapeId, float friction )
{
B3_ASSERT( b3IsValidFloat( friction ) && friction >= 0.0f );
b3World* world = b3GetWorld( shapeId.world0 );
B3_REC( world, ShapeSetFriction, shapeId, friction );
b3Shape* shape = b3GetShape( world, shapeId );
B3_ASSERT( shape->type != b3_compoundShape );
shape->materials[0].friction = friction;
b3GetShapeMaterials( shape )[0].friction = friction;
}
float b3Shape_GetFriction( b3ShapeId shapeId )
{
b3World* world = b3GetWorld( shapeId.world0 );
b3Shape* shape = b3GetShape( world, shapeId );
return shape->materials[0].friction;
return b3GetShapeMaterials( shape )[0].friction;
}
void b3Shape_SetRestitution( b3ShapeId shapeId, float restitution )
{
B3_ASSERT( b3IsValidFloat( restitution ) && restitution >= 0.0f );
b3World* world = b3GetWorld( shapeId.world0 );
B3_REC( world, ShapeSetRestitution, shapeId, restitution );
b3Shape* shape = b3GetShape( world, shapeId );
B3_ASSERT( shape->type != b3_compoundShape );
shape->materials[0].restitution = restitution;
b3GetShapeMaterials( shape )[0].restitution = restitution;
}
float b3Shape_GetRestitution( b3ShapeId shapeId )
{
b3World* world = b3GetWorld( shapeId.world0 );
b3Shape* shape = b3GetShape( world, shapeId );
return shape->materials[0].restitution;
return b3GetShapeMaterials( shape )[0].restitution;
}
void b3Shape_SetSurfaceMaterial( b3ShapeId shapeId, b3SurfaceMaterial surfaceMaterial )
@ -1195,16 +1268,17 @@ void b3Shape_SetSurfaceMaterial( b3ShapeId shapeId, b3SurfaceMaterial surfaceMat
B3_ASSERT( b3IsValidVec3( surfaceMaterial.tangentVelocity ) );
b3World* world = b3GetWorld( shapeId.world0 );
B3_REC( world, ShapeSetSurfaceMaterial, shapeId, surfaceMaterial );
b3Shape* shape = b3GetShape( world, shapeId );
B3_ASSERT( shape->type != b3_compoundShape );
shape->materials[0] = surfaceMaterial;
b3GetShapeMaterials( shape )[0] = surfaceMaterial;
}
b3SurfaceMaterial b3Shape_GetSurfaceMaterial( b3ShapeId shapeId )
{
b3World* world = b3GetWorld( shapeId.world0 );
b3Shape* shape = b3GetShape( world, shapeId );
return shape->materials[0];
return b3GetShapeMaterials( shape )[0];
}
int b3Shape_GetMeshMaterialCount( b3ShapeId shapeId )
@ -1226,7 +1300,7 @@ void b3Shape_SetMeshMaterial( b3ShapeId shapeId, b3SurfaceMaterial surfaceMateri
B3_ASSERT( 0 <= index && index < shape->materialCount );
B3_ASSERT( shape->type != b3_compoundShape );
shape->materials[index] = surfaceMaterial;
b3GetShapeMaterials( shape )[index] = surfaceMaterial;
}
b3SurfaceMaterial b3Shape_GetMeshSurfaceMaterial( b3ShapeId shapeId, int index )
@ -1234,7 +1308,7 @@ b3SurfaceMaterial b3Shape_GetMeshSurfaceMaterial( b3ShapeId shapeId, int index )
b3World* world = b3GetWorld( shapeId.world0 );
b3Shape* shape = b3GetShape( world, shapeId );
B3_ASSERT( 0 <= index && index < shape->materialCount );
return shape->materials[index];
return b3GetShapeMaterials( shape )[index];
}
b3Filter b3Shape_GetFilter( b3ShapeId shapeId )
@ -1302,6 +1376,8 @@ void b3Shape_SetFilter( b3ShapeId shapeId, b3Filter filter, bool invokeContacts
return;
}
B3_REC( world, ShapeSetFilter, shapeId, filter, invokeContacts );
b3Shape* shape = b3GetShape( world, shapeId );
if ( filter.maskBits == shape->filter.maskBits && filter.categoryBits == shape->filter.categoryBits &&
filter.groupIndex == shape->filter.groupIndex )
@ -1336,6 +1412,8 @@ void b3Shape_EnableSensorEvents( b3ShapeId shapeId, bool flag )
return;
}
B3_REC( world, ShapeEnableSensorEvents, shapeId, flag );
b3Shape* shape = b3GetShape( world, shapeId );
shape->enableSensorEvents = flag;
}
@ -1355,6 +1433,8 @@ void b3Shape_EnableContactEvents( b3ShapeId shapeId, bool flag )
return;
}
B3_REC( world, ShapeEnableContactEvents, shapeId, flag );
b3Shape* shape = b3GetShape( world, shapeId );
shape->enableContactEvents = flag;
}
@ -1374,6 +1454,8 @@ void b3Shape_EnablePreSolveEvents( b3ShapeId shapeId, bool flag )
return;
}
B3_REC( world, ShapeEnablePreSolveEvents, shapeId, flag );
b3Shape* shape = b3GetShape( world, shapeId );
shape->enablePreSolveEvents = flag;
}
@ -1393,6 +1475,8 @@ void b3Shape_EnableHitEvents( b3ShapeId shapeId, bool flag )
return;
}
B3_REC( world, ShapeEnableHitEvents, shapeId, flag );
b3Shape* shape = b3GetShape( world, shapeId );
shape->enableHitEvents = flag;
}
@ -1443,7 +1527,7 @@ b3Mesh b3Shape_GetMesh( b3ShapeId shapeId )
return shape->mesh;
}
const b3HeightField* b3Shape_GetHeightField( b3ShapeId shapeId )
const b3HeightFieldData* b3Shape_GetHeightField( b3ShapeId shapeId )
{
b3World* world = b3GetWorld( shapeId.world0 );
b3Shape* shape = b3GetShape( world, shapeId );
@ -1459,6 +1543,8 @@ void b3Shape_SetSphere( b3ShapeId shapeId, const b3Sphere* sphere )
return;
}
B3_REC( world, ShapeSetSphere, shapeId, *sphere );
world->locked = true;
b3Shape* shape = b3GetShape( world, shapeId );
@ -1485,6 +1571,8 @@ void b3Shape_SetCapsule( b3ShapeId shapeId, const b3Capsule* capsule )
return;
}
B3_REC( world, ShapeSetCapsule, shapeId, *capsule );
world->locked = true;
b3Shape* shape = b3GetShape( world, shapeId );
@ -1755,6 +1843,8 @@ void b3Shape_ApplyWind( b3ShapeId shapeId, b3Vec3 wind, float drag, float lift,
return;
}
B3_REC( world, ShapeApplyWind, shapeId, wind, drag, lift, maxSpeed, wake );
b3Shape* shape = b3GetShape( world, shapeId );
b3ShapeType shapeType = shape->type;
@ -2035,7 +2125,7 @@ typedef struct b3CompoundImpactContext
} b3CompoundImpactContext;
// Implements b3CompoundQueryFcn
static bool b3CompoundTimeOfImpactFcn( const b3Compound* compound, int childIndex, void* context )
static bool b3CompoundTimeOfImpactFcn( const b3CompoundData* compound, int childIndex, void* context )
{
b3CompoundImpactContext* toiContext = (b3CompoundImpactContext*)context;
@ -2297,7 +2387,7 @@ uint64_t b3GetShapeUserMaterialId( const b3Shape* shape, int childIndex, int tri
}
materialIndex = b3ClampInt( materialIndex, 0, shape->materialCount - 1 );
return shape->materials[materialIndex].userMaterialId;
return b3GetShapeMaterials( shape )[materialIndex].userMaterialId;
}
void b3DumpShape( b3World* world, int shapeIndex )
@ -2306,7 +2396,7 @@ void b3DumpShape( b3World* world, int shapeIndex )
b3Dump( " b3ShapeDef sd = b3DefaultShapeDef();\n" );
if ( shape->name != NULL )
if ( shape->name[0] != 0 )
{
b3Dump( " sd.name = \"%s\";\n", shape->name );
}
@ -2319,7 +2409,7 @@ void b3DumpShape( b3World* world, int shapeIndex )
b3Dump( " sd.filter.groupIndex = %d;\n", shape->filter.groupIndex );
B3_ASSERT( shape->materialCount >= 1 );
b3SurfaceMaterial* m = shape->materials + 0;
const b3SurfaceMaterial* m = b3GetShapeMaterials( shape );
b3Dump( " sd.baseMaterial.friction = %.9g;\n", m->friction );
b3Dump( " sd.baseMaterial.restitution = %.9g;\n", m->restitution );
b3Dump( " sd.baseMaterial.rollingResistance = %.9g;\n", m->rollingResistance );

View file

@ -29,13 +29,14 @@ typedef struct b3Shape
b3AABB fatAABB;
b3Vec3 localCentroid;
b3SurfaceMaterial material;
int materialCount;
b3SurfaceMaterial* materials;
b3Filter filter;
char* name;
void* userData;
void* userShape;
char name[B3_NAME_LENGTH + 1];
uint16_t generation;
bool enableSensorEvents;
@ -51,12 +52,20 @@ typedef struct b3Shape
b3Sphere sphere;
const b3HullData* hull;
b3Mesh mesh;
const b3HeightField* heightField;
const b3Compound* compound;
const b3HeightFieldData* heightField;
const b3CompoundData* compound;
};
} b3Shape;
// A single material shape keeps its material inline. Multi material meshes and compounds own a heap
// array. Reach the materials the same way for both: a single material shape presents its inline
// material as a one element array. Do not cache the pointer, the shapes array can move.
static inline b3SurfaceMaterial* b3GetShapeMaterials( const b3Shape* shape )
{
return shape->materials != NULL ? shape->materials : (b3SurfaceMaterial*)&shape->material;
}
void b3CreateShapeProxy( b3Shape* shape, b3BroadPhase* bp, b3BodyType type, b3WorldTransform transform, bool forcePairCreation );
void b3DestroyShapeProxy( b3Shape* shape, b3BroadPhase* bp );
@ -95,7 +104,7 @@ int b3CollideMoverAndSphere( b3PlaneResult* result, const b3Sphere* shape, const
int b3CollideMoverAndCapsule( b3PlaneResult* result, const b3Capsule* shape, const b3Capsule* mover );
int b3CollideMoverAndHull( b3PlaneResult* result, const b3HullData* shape, const b3Capsule* mover );
int b3CollideMoverAndMesh( b3PlaneResult* planes, int capacity, const b3Mesh* shape, const b3Capsule* mover );
int b3CollideMoverAndHeightField( b3PlaneResult* results, int capacity, const b3HeightField* shape, const b3Capsule* mover );
int b3CollideMoverAndHeightField( b3PlaneResult* results, int capacity, const b3HeightFieldData* shape, const b3Capsule* mover );
int b3CollideMover( b3PlaneResult* planes, int planeCapacity, const b3Shape* shape, b3Transform transform,
const b3Capsule* mover );
@ -108,10 +117,10 @@ b3ShapeExtent b3ComputeHullExtent( const b3HullData* hull, b3Vec3 origin );
float b3ComputeHullProjectedArea( const b3HullData* hull, b3Vec3 direction );
// Height field
b3Triangle b3GetHeightFieldTriangle( const b3HeightField* heightField, int triangleIndex );
int b3GetHeightFieldMaterial( const b3HeightField* heightField, int triangleIndex );
b3Triangle b3GetHeightFieldTriangle( const b3HeightFieldData* heightField, int triangleIndex );
int b3GetHeightFieldMaterial( const b3HeightFieldData* heightField, int triangleIndex );
static inline int b3GetHeightFieldTriangleCount( const b3HeightField* heightField )
static inline int b3GetHeightFieldTriangleCount( const b3HeightFieldData* heightField )
{
int cellCount = ( heightField->rowCount - 1 ) * ( heightField->columnCount - 1 );
return 2 * cellCount;

View file

@ -8,12 +8,15 @@
#include "physics_world.h"
#include "solver.h"
#include "solver_set.h"
#include "recording.h"
// needed for dll export
#include "box3d/box3d.h"
void b3SphericalJoint_EnableConeLimit( b3JointId jointId, bool enableLimit )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, SphericalJointEnableConeLimit, jointId, enableLimit );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint );
if ( enableLimit != base->sphericalJoint.enableConeLimit )
{
@ -37,7 +40,8 @@ float b3SphericalJoint_GetConeLimit( b3JointId jointId )
void b3SphericalJoint_SetConeLimit( b3JointId jointId, float angleRadians )
{
B3_ASSERT( b3IsValidFloat( angleRadians ) && 0 <= angleRadians && angleRadians <= 0.5f * B3_PI );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, SphericalJointSetConeLimit, jointId, angleRadians );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint );
base->sphericalJoint.coneAngle = angleRadians;
}
@ -65,6 +69,8 @@ float b3SphericalJoint_GetConeAngle( b3JointId jointId )
void b3SphericalJoint_EnableTwistLimit( b3JointId jointId, bool enableLimit )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, SphericalJointEnableTwistLimit, jointId, enableLimit );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint );
if ( enableLimit != base->sphericalJoint.enableTwistLimit )
{
@ -95,6 +101,8 @@ float b3SphericalJoint_GetUpperTwistLimit( b3JointId jointId )
void b3SphericalJoint_SetTwistLimits( b3JointId jointId, float lowerLimitRadians, float upperLimitRadians )
{
B3_ASSERT( b3IsValidFloat( lowerLimitRadians ) && b3IsValidFloat( upperLimitRadians ) );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, SphericalJointSetTwistLimits, jointId, lowerLimitRadians, upperLimitRadians );
float lowerTwistAngle = b3MinFloat( lowerLimitRadians, upperLimitRadians );
float upperTwistAngle = b3MaxFloat( lowerLimitRadians, upperLimitRadians );
lowerTwistAngle = b3ClampFloat( lowerTwistAngle, -B3_PI, B3_PI );
@ -128,6 +136,8 @@ float b3SphericalJoint_GetTwistAngle( b3JointId jointId )
void b3SphericalJoint_EnableSpring( b3JointId jointId, bool enableSpring )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, SphericalJointEnableSpring, jointId, enableSpring );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint );
if ( enableSpring != base->sphericalJoint.enableSpring )
{
@ -145,6 +155,8 @@ bool b3SphericalJoint_IsSpringEnabled( b3JointId jointId )
void b3SphericalJoint_SetTargetRotation( b3JointId jointId, b3Quat targetRotation )
{
B3_ASSERT( b3IsValidQuat( targetRotation ) );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, SphericalJointSetTargetRotation, jointId, targetRotation );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint );
base->sphericalJoint.targetRotation = targetRotation;
}
@ -158,6 +170,8 @@ b3Quat b3SphericalJoint_GetTargetRotation( b3JointId jointId )
void b3SphericalJoint_SetSpringHertz( b3JointId jointId, float hertz )
{
B3_ASSERT( b3IsValidFloat( hertz ) && hertz >= 0.0f );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, SphericalJointSetSpringHertz, jointId, hertz );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint );
base->sphericalJoint.hertz = hertz;
}
@ -171,6 +185,8 @@ float b3SphericalJoint_GetSpringHertz( b3JointId jointId )
void b3SphericalJoint_SetSpringDampingRatio( b3JointId jointId, float dampingRatio )
{
B3_ASSERT( b3IsValidFloat( dampingRatio ) && dampingRatio >= 0.0f );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, SphericalJointSetSpringDampingRatio, jointId, dampingRatio );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint );
base->sphericalJoint.dampingRatio = dampingRatio;
}
@ -183,6 +199,8 @@ float b3SphericalJoint_GetSpringDampingRatio( b3JointId jointId )
void b3SphericalJoint_EnableMotor( b3JointId jointId, bool enableMotor )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, SphericalJointEnableMotor, jointId, enableMotor );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint );
if ( enableMotor != base->sphericalJoint.enableMotor )
{
@ -200,6 +218,8 @@ bool b3SphericalJoint_IsMotorEnabled( b3JointId jointId )
void b3SphericalJoint_SetMotorVelocity( b3JointId jointId, b3Vec3 motorVelocity )
{
B3_ASSERT( b3IsValidVec3( motorVelocity ) );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, SphericalJointSetMotorVelocity, jointId, motorVelocity );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint );
base->sphericalJoint.motorVelocity = motorVelocity;
}
@ -213,6 +233,8 @@ b3Vec3 b3SphericalJoint_GetMotorVelocity( b3JointId jointId )
void b3SphericalJoint_SetMaxMotorTorque( b3JointId jointId, float maxForce )
{
B3_ASSERT( b3IsValidFloat( maxForce ) && maxForce >= 0.0f );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, SphericalJointSetMaxMotorTorque, jointId, maxForce );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint );
base->sphericalJoint.maxMotorTorque = maxForce;
}

View file

@ -100,6 +100,11 @@ static void b3EmptyDrawPoint( b3Pos p, float size, b3HexColor color, void* conte
B3_UNUSED( p, size, color, context );
}
static void b3EmptyDrawSphere( b3Pos p, float radius, b3HexColor color, float alpha, void* context )
{
B3_UNUSED( p, radius, color, alpha, context );
}
static void b3EmptyDrawBounds( b3AABB aabb, b3HexColor color, void* context )
{
B3_UNUSED( aabb, color, context );
@ -124,6 +129,7 @@ b3DebugDraw b3DefaultDebugDraw( void )
draw.DrawSegmentFcn = b3EmptyDrawSegment;
draw.DrawTransformFcn = b3EmptyDrawTransform;
draw.DrawPointFcn = b3EmptyDrawPoint;
draw.DrawSphereFcn = b3EmptyDrawSphere;
draw.DrawBoundsFcn = b3EmptyDrawBounds;
draw.DrawBoxFcn = b3EmptyDrawBox;
draw.DrawStringFcn = b3EmptyDrawString;

View file

@ -6,6 +6,7 @@
#include "physics_world.h"
#include "solver.h"
#include "solver_set.h"
#include "recording.h"
// needed for dll export
#include "box3d/box3d.h"
@ -13,6 +14,8 @@
void b3WeldJoint_SetLinearHertz( b3JointId jointId, float hertz )
{
B3_ASSERT( b3IsValidFloat( hertz ) && hertz >= 0.0f );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, WeldJointSetLinearHertz, jointId, hertz );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_weldJoint );
base->weldJoint.linearHertz = hertz;
}
@ -26,6 +29,8 @@ float b3WeldJoint_GetLinearHertz( b3JointId jointId )
void b3WeldJoint_SetLinearDampingRatio( b3JointId jointId, float dampingRatio )
{
B3_ASSERT( b3IsValidFloat( dampingRatio ) && dampingRatio >= 0.0f );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, WeldJointSetLinearDampingRatio, jointId, dampingRatio );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_weldJoint );
base->weldJoint.linearDampingRatio = dampingRatio;
}
@ -39,6 +44,8 @@ float b3WeldJoint_GetLinearDampingRatio( b3JointId jointId )
void b3WeldJoint_SetAngularHertz( b3JointId jointId, float hertz )
{
B3_ASSERT( b3IsValidFloat( hertz ) && hertz >= 0.0f );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, WeldJointSetAngularHertz, jointId, hertz );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_weldJoint );
base->weldJoint.angularHertz = hertz;
}
@ -52,6 +59,8 @@ float b3WeldJoint_GetAngularHertz( b3JointId jointId )
void b3WeldJoint_SetAngularDampingRatio( b3JointId jointId, float dampingRatio )
{
B3_ASSERT( b3IsValidFloat( dampingRatio ) && dampingRatio >= 0.0f );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, WeldJointSetAngularDampingRatio, jointId, dampingRatio );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_weldJoint );
base->weldJoint.angularDampingRatio = dampingRatio;
}

View file

@ -8,12 +8,15 @@
#include "physics_world.h"
#include "solver.h"
#include "solver_set.h"
#include "recording.h"
// needed for dll export
#include "box3d/box3d.h"
void b3WheelJoint_EnableSuspension( b3JointId jointId, bool enableSpring )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, WheelJointEnableSuspension, jointId, enableSpring );
b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint );
if ( enableSpring != joint->wheelJoint.enableSuspensionSpring )
@ -31,6 +34,8 @@ bool b3WheelJoint_IsSuspensionEnabled( b3JointId jointId )
void b3WheelJoint_SetSuspensionHertz( b3JointId jointId, float hertz )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, WheelJointSetSuspensionHertz, jointId, hertz );
b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint );
joint->wheelJoint.suspensionHertz = hertz;
}
@ -43,6 +48,8 @@ float b3WheelJoint_GetSuspensionHertz( b3JointId jointId )
void b3WheelJoint_SetSuspensionDampingRatio( b3JointId jointId, float dampingRatio )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, WheelJointSetSuspensionDampingRatio, jointId, dampingRatio );
b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint );
joint->wheelJoint.suspensionDampingRatio = dampingRatio;
}
@ -55,6 +62,8 @@ float b3WheelJoint_GetSuspensionDampingRatio( b3JointId jointId )
void b3WheelJoint_EnableSuspensionLimit( b3JointId jointId, bool enableLimit )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, WheelJointEnableSuspensionLimit, jointId, enableLimit );
b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint );
if ( joint->wheelJoint.enableSuspensionLimit != enableLimit )
{
@ -85,7 +94,8 @@ float b3WheelJoint_GetUpperSuspensionLimit( b3JointId jointId )
void b3WheelJoint_SetSuspensionLimits( b3JointId jointId, float lower, float upper )
{
B3_ASSERT( lower <= upper );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, WheelJointSetSuspensionLimits, jointId, lower, upper );
b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint );
if ( lower != joint->wheelJoint.lowerSuspensionLimit || upper != joint->wheelJoint.upperSuspensionLimit )
{
@ -98,6 +108,8 @@ void b3WheelJoint_SetSuspensionLimits( b3JointId jointId, float lower, float upp
void b3WheelJoint_EnableSpinMotor( b3JointId jointId, bool enableMotor )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, WheelJointEnableSpinMotor, jointId, enableMotor );
b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint );
if ( joint->wheelJoint.enableSpinMotor != enableMotor )
{
@ -114,6 +126,8 @@ bool b3WheelJoint_IsSpinMotorEnabled( b3JointId jointId )
void b3WheelJoint_SetSpinMotorSpeed( b3JointId jointId, float motorSpeed )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, WheelJointSetSpinMotorSpeed, jointId, motorSpeed );
b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint );
joint->wheelJoint.spinSpeed = motorSpeed;
}
@ -126,6 +140,8 @@ float b3WheelJoint_GetSpinMotorSpeed( b3JointId jointId )
void b3WheelJoint_SetMaxSpinTorque( b3JointId jointId, float torque )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, WheelJointSetMaxSpinTorque, jointId, torque );
b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint );
joint->wheelJoint.maxSpinTorque = torque;
}
@ -138,6 +154,8 @@ float b3WheelJoint_GetMaxSpinTorque( b3JointId jointId )
void b3WheelJoint_EnableSteering( b3JointId jointId, bool flag )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, WheelJointEnableSteering, jointId, flag );
b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint );
if ( joint->wheelJoint.enableSteering != flag )
{
@ -154,6 +172,8 @@ bool b3WheelJoint_IsSteeringEnabled( b3JointId jointId )
void b3WheelJoint_SetSteeringHertz( b3JointId jointId, float hertz )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, WheelJointSetSteeringHertz, jointId, hertz );
b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint );
joint->wheelJoint.steeringHertz = hertz;
}
@ -166,6 +186,8 @@ float b3WheelJoint_GetSteeringHertz( b3JointId jointId )
void b3WheelJoint_SetSteeringDampingRatio( b3JointId jointId, float dampingRatio )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, WheelJointSetSteeringDampingRatio, jointId, dampingRatio );
b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint );
joint->wheelJoint.steeringDampingRatio = dampingRatio;
}
@ -178,6 +200,8 @@ float b3WheelJoint_GetSteeringDampingRatio( b3JointId jointId )
void b3WheelJoint_SetMaxSteeringTorque( b3JointId jointId, float maxTorque )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, WheelJointSetMaxSteeringTorque, jointId, maxTorque );
b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint );
joint->wheelJoint.maxSteeringTorque = maxTorque;
}
@ -190,6 +214,8 @@ float b3WheelJoint_GetMaxSteeringTorque( b3JointId jointId )
void b3WheelJoint_EnableSteeringLimit( b3JointId jointId, bool flag )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, WheelJointEnableSteeringLimit, jointId, flag );
b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint );
if ( joint->wheelJoint.enableSteeringLimit != flag )
{
@ -220,7 +246,8 @@ float b3WheelJoint_GetUpperSteeringLimit( b3JointId jointId )
void b3WheelJoint_SetSteeringLimits( b3JointId jointId, float lowerRadians, float upperRadians )
{
B3_ASSERT( lowerRadians <= upperRadians );
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, WheelJointSetSteeringLimits, jointId, lowerRadians, upperRadians );
b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint );
joint->wheelJoint.lowerSteeringLimit = lowerRadians;
joint->wheelJoint.upperSteeringLimit = upperRadians;
@ -228,6 +255,8 @@ void b3WheelJoint_SetSteeringLimits( b3JointId jointId, float lowerRadians, floa
void b3WheelJoint_SetTargetSteeringAngle( b3JointId jointId, float radians )
{
b3World* world = b3GetWorld( jointId.world0 );
B3_REC( world, WheelJointSetTargetSteeringAngle, jointId, radians );
b3JointSim* joint = b3GetJointSimCheckType( jointId, b3_wheelJoint );
joint->wheelJoint.targetSteeringAngle = radians;
}

1287
src/world_snapshot.c Normal file

File diff suppressed because it is too large Load diff

21
src/world_snapshot.h Normal file
View file

@ -0,0 +1,21 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
#pragma once
#include "recording.h"
#include "recording_replay.h"
#include <stdbool.h>
#include <stdint.h>
typedef struct b3World b3World;
// Serialize the live world into buf, interning shape geometry into rec->registry.
// On success buf holds a self-contained snapshot image. Returns the byte count.
int b3SerializeWorld( b3World* world, b3RecBuffer* buf, b3Recording* rec );
// Overwrite a freshly-created (shell) world with the simulation state held in the
// snapshot image [data, size). Geometry references are resolved via the shared
// registry slots in rdr. Returns false on a corrupt or incompatible image.
bool b3DeserializeIntoShell( const uint8_t* data, int size, b3World* world, b3RecReader* rdr );

View file

@ -18,6 +18,7 @@ set(BOX3D_TEST_FILES
test_macros.h
test_math.c
test_mover.c
test_recording.c
test_shape.c
test_table.c
test_world.c

View file

@ -40,6 +40,7 @@ extern int IdTest( void );
extern int LargeWorldTest( void );
extern int MathTest( void );
extern int MoverTest( void );
extern int RecordingTest( void );
extern int ShapeTest( void );
extern int TableTest( void );
extern int WorldTest( void );
@ -64,6 +65,12 @@ int main( int argc, char** argv )
//_CrtSetBreakAlloc(196);
_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDERR );
// Route CRT errors and assertions to stderr instead of a modal dialog so a headless run
// (CI, redirected stdout) fails fast rather than blocking on Abort/Retry/Ignore.
_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDERR );
_CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDERR );
//_CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF | _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG));
//_CrtSetAllocHook(MyAllocHook);
#endif
@ -102,6 +109,7 @@ int main( int argc, char** argv )
MAYBE_RUN_TEST( LargeWorldTest );
MAYBE_RUN_TEST( MathTest );
MAYBE_RUN_TEST( MoverTest );
MAYBE_RUN_TEST( RecordingTest );
MAYBE_RUN_TEST( ShapeTest );
MAYBE_RUN_TEST( TableTest );
MAYBE_RUN_TEST( WorldTest );

View file

@ -62,10 +62,10 @@ static int CompoundCreateMixed( void )
.sphereCount = 2,
};
b3Compound* compound = b3CreateCompound( &def );
b3CompoundData* compound = b3CreateCompound( &def );
ENSURE( compound != NULL );
ENSURE( compound->version == B3_COMPOUND_VERSION );
ENSURE( compound->byteCount > (int)sizeof( b3Compound ) );
ENSURE( compound->byteCount > (int)sizeof( b3CompoundData ) );
ENSURE( compound->capsuleCount == 1 );
ENSURE( compound->hullCount == 1 );
@ -92,7 +92,7 @@ static int CompoundCreateSingleType( void )
{
b3CompoundCapsuleDef cap = { .capsule = { { 0, 0, 0 }, { 1, 0, 0 }, 0.5f }, .material = mat };
b3CompoundDef def = { .capsules = &cap, .capsuleCount = 1 };
b3Compound* c = b3CreateCompound( &def );
b3CompoundData* c = b3CreateCompound( &def );
ENSURE( c != NULL && c->capsuleCount == 1 && c->hullCount == 0 && c->meshCount == 0 && c->sphereCount == 0 );
b3DestroyCompound( c );
}
@ -102,7 +102,7 @@ static int CompoundCreateSingleType( void )
b3BoxHull box = b3MakeBoxHull( 1, 1, 1 );
b3CompoundHullDef h = { .hull = &box.base, .transform = b3Transform_identity, .material = mat };
b3CompoundDef def = { .hulls = &h, .hullCount = 1 };
b3Compound* c = b3CreateCompound( &def );
b3CompoundData* c = b3CreateCompound( &def );
ENSURE( c != NULL && c->hullCount == 1 && c->sharedHullCount == 1 && c->capsuleCount == 0 );
b3DestroyCompound( c );
}
@ -118,7 +118,7 @@ static int CompoundCreateSingleType( void )
.materialCount = 1,
};
b3CompoundDef def = { .meshes = &m, .meshCount = 1 };
b3Compound* c = b3CreateCompound( &def );
b3CompoundData* c = b3CreateCompound( &def );
ENSURE( c != NULL && c->meshCount == 1 && c->sharedMeshCount == 1 );
b3DestroyCompound( c );
b3DestroyMesh( md );
@ -128,7 +128,7 @@ static int CompoundCreateSingleType( void )
{
b3CompoundSphereDef s = { .sphere = { { 0, 0, 0 }, 1.0f }, .material = mat };
b3CompoundDef def = { .spheres = &s, .sphereCount = 1 };
b3Compound* c = b3CreateCompound( &def );
b3CompoundData* c = b3CreateCompound( &def );
ENSURE( c != NULL && c->sphereCount == 1 );
b3DestroyCompound( c );
}
@ -148,7 +148,7 @@ static int CompoundMaterialDedup( void )
}
b3CompoundDef def = { .capsules = caps, .capsuleCount = 3 };
b3Compound* c = b3CreateCompound( &def );
b3CompoundData* c = b3CreateCompound( &def );
ENSURE( c->materialCount == 1 );
for ( int i = 0; i < 3; ++i )
{
@ -169,7 +169,7 @@ static int CompoundMaterialDistinct( void )
}
b3CompoundDef def = { .capsules = caps, .capsuleCount = 3 };
b3Compound* c = b3CreateCompound( &def );
b3CompoundData* c = b3CreateCompound( &def );
ENSURE( c->materialCount == 3 );
const b3SurfaceMaterial* mats = b3GetCompoundMaterials( c );
@ -204,7 +204,7 @@ static int CompoundMaterialCrossShape( void )
.spheres = &sph,
.sphereCount = 1,
};
b3Compound* c = b3CreateCompound( &def );
b3CompoundData* c = b3CreateCompound( &def );
ENSURE( c->materialCount == 1 );
ENSURE( b3GetCompoundCapsule( c, 0 ).materialIndex == 0 );
@ -241,7 +241,7 @@ static int CompoundMaterialMeshShared( void )
.spheres = &sph,
.sphereCount = 1,
};
b3Compound* c = b3CreateCompound( &def );
b3CompoundData* c = b3CreateCompound( &def );
ENSURE( c->materialCount == 1 );
b3DestroyCompound( c );
@ -268,7 +268,7 @@ static int CompoundHullSharingPointer( void )
}
b3CompoundDef def = { .hulls = hulls, .hullCount = 3 };
b3Compound* c = b3CreateCompound( &def );
b3CompoundData* c = b3CreateCompound( &def );
ENSURE( c->hullCount == 3 );
ENSURE( c->sharedHullCount == 1 );
b3DestroyCompound( c );
@ -292,7 +292,7 @@ static int CompoundHullSharingContent( void )
hulls[1].transform.p.x = 5.0f;
b3CompoundDef def = { .hulls = hulls, .hullCount = 2 };
b3Compound* c = b3CreateCompound( &def );
b3CompoundData* c = b3CreateCompound( &def );
ENSURE( c->sharedHullCount == 1 );
b3DestroyCompound( c );
return 0;
@ -311,7 +311,7 @@ static int CompoundHullDistinct( void )
hulls[1].transform.p.x = 5.0f;
b3CompoundDef def = { .hulls = hulls, .hullCount = 2 };
b3Compound* c = b3CreateCompound( &def );
b3CompoundData* c = b3CreateCompound( &def );
ENSURE( c->sharedHullCount == 2 );
b3DestroyCompound( c );
return 0;
@ -334,7 +334,7 @@ static int CompoundMeshSharingPointer( void )
}
b3CompoundDef def = { .meshes = meshes, .meshCount = 3 };
b3Compound* c = b3CreateCompound( &def );
b3CompoundData* c = b3CreateCompound( &def );
ENSURE( c->meshCount == 3 );
ENSURE( c->sharedMeshCount == 1 );
@ -357,7 +357,7 @@ static int CompoundMeshSharingContent( void )
meshes[1].transform.p.x = 5.0f;
b3CompoundDef def = { .meshes = meshes, .meshCount = 2 };
b3Compound* c = b3CreateCompound( &def );
b3CompoundData* c = b3CreateCompound( &def );
ENSURE( c->sharedMeshCount == 1 );
b3DestroyCompound( c );
@ -379,7 +379,7 @@ static int CompoundMeshDistinct( void )
meshes[1].transform.p.x = 5.0f;
b3CompoundDef def = { .meshes = meshes, .meshCount = 2 };
b3Compound* c = b3CreateCompound( &def );
b3CompoundData* c = b3CreateCompound( &def );
ENSURE( c->sharedMeshCount == 2 );
b3DestroyCompound( c );
@ -420,7 +420,7 @@ static int CompoundChildDispatch( void )
.spheres = spheres,
.sphereCount = 1,
};
b3Compound* c = b3CreateCompound( &def );
b3CompoundData* c = b3CreateCompound( &def );
// Index ordering is capsules → hulls → meshes → spheres.
ENSURE( b3GetCompoundChild( c, 0 ).type == b3_capsuleShape );
@ -462,7 +462,7 @@ static int CompoundAABBContainsChildren( void )
{ .sphere = { { 4, 0, 0 }, 0.5f }, .material = mat },
};
b3CompoundDef def = { .spheres = spheres, .sphereCount = 2 };
b3Compound* c = b3CreateCompound( &def );
b3CompoundData* c = b3CreateCompound( &def );
b3AABB local = b3ComputeCompoundAABB( c, b3Transform_identity );
ENSURE( local.lowerBound.x <= -4.0f + 1e-5f );
@ -486,7 +486,7 @@ static int CompoundRayCastMiss( void )
b3SurfaceMaterial mat = b3DefaultSurfaceMaterial();
b3CompoundSphereDef sph = { .sphere = { { 0, 0, 0 }, 0.5f }, .material = mat };
b3CompoundDef def = { .spheres = &sph, .sphereCount = 1 };
b3Compound* c = b3CreateCompound( &def );
b3CompoundData* c = b3CreateCompound( &def );
// Ray well above the sphere on a parallel path.
b3RayCastInput input = { .origin = { -5, 5, 0 }, .translation = { 10, 0, 0 }, .maxFraction = 1.0f };
@ -508,7 +508,7 @@ static int CompoundRayCastClosest( void )
{ .sphere = { { 10, 0, 0 }, 1.0f }, .material = matB },
};
b3CompoundDef def = { .spheres = spheres, .sphereCount = 2 };
b3Compound* c = b3CreateCompound( &def );
b3CompoundData* c = b3CreateCompound( &def );
b3RayCastInput input = { .origin = { 0, 0, 0 }, .translation = { 20, 0, 0 }, .maxFraction = 1.0f };
b3CastOutput out = b3RayCastCompound( c, &input );
@ -541,7 +541,7 @@ static int CompoundRayCastHullNormalRotation( void )
.material = mat,
};
b3CompoundDef def = { .hulls = &hull, .hullCount = 1 };
b3Compound* c = b3CreateCompound( &def );
b3CompoundData* c = b3CreateCompound( &def );
b3RayCastInput input = { .origin = { 0, 0, 0 }, .translation = { 20, 0, 0 }, .maxFraction = 1.0f };
b3CastOutput out = b3RayCastCompound( c, &input );
@ -564,7 +564,7 @@ static int CompoundShapeCastClosest( void )
{ .sphere = { { 10, 0, 0 }, 1.0f }, .material = mat },
};
b3CompoundDef def = { .spheres = spheres, .sphereCount = 2 };
b3Compound* c = b3CreateCompound( &def );
b3CompoundData* c = b3CreateCompound( &def );
b3Vec3 point = { 0, 0, 0 };
b3ShapeCastInput input = {
@ -591,7 +591,7 @@ static int CompoundOverlap( void )
{ .sphere = { { 3, 0, 0 }, 0.5f }, .material = mat },
};
b3CompoundDef def = { .spheres = spheres, .sphereCount = 2 };
b3Compound* c = b3CreateCompound( &def );
b3CompoundData* c = b3CreateCompound( &def );
// Proxy at the origin lies in the gap between the two spheres.
b3Vec3 origin = { 0, 0, 0 };
@ -614,7 +614,7 @@ struct QueryAccumulator
int stopAfter; // -1 = never stop early
};
static bool QueryCallback( const b3Compound* compound, int childIndex, void* context )
static bool QueryCallback( const b3CompoundData* compound, int childIndex, void* context )
{
(void)compound;
struct QueryAccumulator* acc = context;
@ -638,7 +638,7 @@ static int CompoundQuery( void )
{ .sphere = { { 10, 0, 0 }, 0.5f }, .material = mat },
};
b3CompoundDef def = { .spheres = spheres, .sphereCount = 3 };
b3Compound* c = b3CreateCompound( &def );
b3CompoundData* c = b3CreateCompound( &def );
// Tight box around the middle sphere — only it should be reported.
b3AABB middle = { { -1, -1, -1 }, { 1, 1, 1 } };
@ -673,7 +673,7 @@ static int CompoundMover( void )
{ .hull = &box.base, .transform = { .p = { 1.0f, 0, 0 }, .q = b3Quat_identity }, .material = mat },
};
b3CompoundDef def = { .hulls = hulls, .hullCount = 2 };
b3Compound* c = b3CreateCompound( &def );
b3CompoundData* c = b3CreateCompound( &def );
// Small capsule mover sitting on top of the boxes, low enough to penetrate both.
b3Capsule mover = { { -1.0f, 0.6f, 0 }, { 1.0f, 0.6f, 0 }, 0.2f };
@ -704,7 +704,7 @@ static int CompoundMover( void )
return 0;
}
static b3Compound* BuildSerializableCompound( b3MeshData* md )
static b3CompoundData* BuildSerializableCompound( b3MeshData* md )
{
b3SurfaceMaterial mat = b3DefaultSurfaceMaterial();
b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f );
@ -736,7 +736,7 @@ static b3Compound* BuildSerializableCompound( b3MeshData* md )
static int CompoundSerializeRoundtrip( void )
{
b3MeshData* md = b3CreateBoxMesh( b3Vec3_zero, (b3Vec3){ 0.5f, 0.5f, 0.5f }, false );
b3Compound* a = BuildSerializableCompound( md );
b3CompoundData* a = BuildSerializableCompound( md );
// Snapshot a few queries on the original.
b3AABB aabbA = b3ComputeCompoundAABB( a, b3Transform_identity );
@ -752,7 +752,7 @@ static int CompoundSerializeRoundtrip( void )
memcpy( buffer, serialized, (size_t)byteCount );
b3DestroyCompound( a );
b3Compound* b = b3ConvertBytesToCompound( buffer, byteCount );
b3CompoundData* b = b3ConvertBytesToCompound( buffer, byteCount );
ENSURE( b != NULL );
ENSURE( b->byteCount == byteCount );
ENSURE( b->capsuleCount == 1 );
@ -779,7 +779,7 @@ static int CompoundSerializeRoundtrip( void )
static int CompoundSerializeBadVersion( void )
{
b3MeshData* md = b3CreateBoxMesh( b3Vec3_zero, (b3Vec3){ 0.5f, 0.5f, 0.5f }, false );
b3Compound* a = BuildSerializableCompound( md );
b3CompoundData* a = BuildSerializableCompound( md );
int byteCount = a->byteCount;
uint8_t* buffer = (uint8_t*)malloc( (size_t)byteCount );
@ -787,9 +787,9 @@ static int CompoundSerializeBadVersion( void )
b3DestroyCompound( a );
// Corrupt the version word (first 8 bytes of b3Compound).
( (b3Compound*)buffer )->version ^= 0x1ull;
( (b3CompoundData*)buffer )->version ^= 0x1ull;
b3Compound* b = b3ConvertBytesToCompound( buffer, byteCount );
b3CompoundData* b = b3ConvertBytesToCompound( buffer, byteCount );
ENSURE( b == NULL );
free( buffer );
@ -800,7 +800,7 @@ static int CompoundSerializeBadVersion( void )
static int CompoundSerializeWrongByteCount( void )
{
b3MeshData* md = b3CreateBoxMesh( b3Vec3_zero, (b3Vec3){ 0.5f, 0.5f, 0.5f }, false );
b3Compound* a = BuildSerializableCompound( md );
b3CompoundData* a = BuildSerializableCompound( md );
int byteCount = a->byteCount;
uint8_t* buffer = (uint8_t*)malloc( (size_t)byteCount );
@ -808,7 +808,7 @@ static int CompoundSerializeWrongByteCount( void )
b3DestroyCompound( a );
// Off-by-one in the declared length is rejected.
b3Compound* b = b3ConvertBytesToCompound( buffer, byteCount + 1 );
b3CompoundData* b = b3ConvertBytesToCompound( buffer, byteCount + 1 );
ENSURE( b == NULL );
free( buffer );

View file

@ -16,7 +16,7 @@
static int HeightFieldCreate( void )
{
b3Vec3 scale = { 1.0f, 1.0f, 1.0f };
b3HeightField* hf = b3CreateGrid( 4, 4, scale, false );
b3HeightFieldData* hf = b3CreateGrid( 4, 4, scale, false );
ENSURE( hf->rowCount == 4 );
ENSURE( hf->columnCount == 4 );
@ -42,7 +42,7 @@ static int HeightFieldTriangleIndex( void )
int rowCount = 4;
int columnCount = 5;
b3Vec3 scale = { 1.0f, 1.0f, 1.0f };
b3HeightField* hf = b3CreateGrid( rowCount, columnCount, scale, false );
b3HeightFieldData* hf = b3CreateGrid( rowCount, columnCount, scale, false );
int triangleCount = 2 * ( rowCount - 1 ) * ( columnCount - 1 );
@ -97,10 +97,10 @@ static int HeightFieldWinding( void )
def.globalMaximumHeight = 1.0f;
def.clockwiseWinding = false;
b3HeightField* ccw = b3CreateHeightField( &def );
b3HeightFieldData* ccw = b3CreateHeightField( &def );
def.clockwiseWinding = true;
b3HeightField* cw = b3CreateHeightField( &def );
b3HeightFieldData* cw = b3CreateHeightField( &def );
b3Triangle ta = b3GetHeightFieldTriangle( ccw, 0 );
b3Triangle tb = b3GetHeightFieldTriangle( cw, 0 );
@ -141,7 +141,7 @@ static int RayCastFlatField( void )
def.globalMaximumHeight = 1.0f;
def.clockwiseWinding = false;
b3HeightField* hf = b3CreateHeightField( &def );
b3HeightFieldData* hf = b3CreateHeightField( &def );
// Origin sits clearly inside triangle 0 of cell (1, 1) — off the cell
// diagonal x+z = 3. The translation overshoots the surface so the hit
@ -166,7 +166,7 @@ static int RayCastFlatField( void )
static int OverlapAtSurface( void )
{
b3Vec3 scale = { 1.0f, 1.0f, 1.0f };
b3HeightField* hf = b3CreateGrid( 4, 4, scale, false );
b3HeightFieldData* hf = b3CreateGrid( 4, 4, scale, false );
// Sphere center 1.0 above the surface, radius 0.5 — clear gap.
b3Vec3 above = { 1.5f, 1.0f, 1.5f };
@ -202,7 +202,7 @@ static int FileRoundtrip( void )
const char* path = "test_height_field_roundtrip.dat";
b3DumpHeightData( &def, path );
b3HeightField* loaded = b3LoadHeightField( path );
b3HeightFieldData* loaded = b3LoadHeightField( path );
remove( path );
ENSURE( loaded != NULL );
@ -219,14 +219,14 @@ static int FileRoundtrip( void )
int cellCount = ( def.countX - 1 ) * ( def.countZ - 1 );
for ( int i = 0; i < cellCount; ++i )
{
ENSURE( loaded->materialIndices[i] == materials[i] );
ENSURE( b3GetHeightFieldMaterialIndices( loaded )[i] == materials[i] );
}
// Recovered heights round-trip within the quantization tolerance.
float quantum = ( def.globalMaximumHeight - def.globalMinimumHeight ) / (float)UINT16_MAX;
for ( int i = 0; i < def.countX * def.countZ; ++i )
{
float recovered = loaded->minHeight + loaded->heightScale * loaded->compressedHeights[i];
float recovered = loaded->minHeight + loaded->heightScale * b3GetHeightFieldCompressedHeights( loaded )[i];
ENSURE_SMALL( recovered - heights[i], 2.0f * quantum );
}
@ -256,7 +256,7 @@ static int ShapeCastVerticalStraddle( void )
def.globalMaximumHeight = 1.0f;
def.clockwiseWinding = false;
b3HeightField* hf = b3CreateHeightField( &def );
b3HeightFieldData* hf = b3CreateHeightField( &def );
// Solid cell (0,0) spans x,z in [0,1]. Radius 0.3 with the center 0.05 past a
// boundary still reaches back into the solid cell.
@ -311,7 +311,7 @@ static int ShapeCastVerticalStraddle( void )
// Brute-force shape cast: cast the proxy against every (non-hole) triangle and
// keep the closest hit. This is the ground truth for b3ShapeCastHeightField.
static b3CastOutput BruteForceShapeCast( const b3HeightField* hf, const b3ShapeCastInput* input )
static b3CastOutput BruteForceShapeCast( const b3HeightFieldData* hf, const b3ShapeCastInput* input )
{
b3CastOutput best = { 0 };
float bestFraction = input->maxFraction;
@ -320,7 +320,7 @@ static b3CastOutput BruteForceShapeCast( const b3HeightField* hf, const b3ShapeC
for ( int t = 0; t < triangleCount; ++t )
{
int cellIndex = t >> 1;
if ( hf->materialIndices[cellIndex] == B3_HEIGHT_FIELD_HOLE )
if ( b3GetHeightFieldMaterialIndices( hf )[cellIndex] == B3_HEIGHT_FIELD_HOLE )
{
continue;
}
@ -353,7 +353,7 @@ static int ShapeCastBruteForce( void )
// against every triangle is the ground truth. The grid walk must never miss a
// closer hit, regardless of cast direction, origin or radius.
b3Vec3 scale = { 2.0f, 1.5f, 2.0f };
b3HeightField* hf = b3CreateWave( 10, 10, scale, 0.1f, 0.03333f, false );
b3HeightFieldData* hf = b3CreateWave( 10, 10, scale, 0.1f, 0.03333f, false );
// Documented repro from sample/sample_mesh.cpp "Height Field": a sphere cast
// that moves only in z (and y). Body at (-9,0,-9), world origin (5.5,4,2.913)
@ -432,7 +432,7 @@ static int ShapeCastBruteForce( void )
// the closest hit. b3GetHeightFieldTriangle returns vertices in the same winding
// order that b3ShapeCastHeightField feeds to b3IntersectRayTriangle, so this is a
// pure traversal/culling check — the per-triangle math is identical.
static b3CastOutput BruteForceRayCast( const b3HeightField* hf, const b3RayCastInput* input )
static b3CastOutput BruteForceRayCast( const b3HeightFieldData* hf, const b3RayCastInput* input )
{
b3CastOutput best = { 0 };
float bestFraction = input->maxFraction;
@ -444,7 +444,7 @@ static b3CastOutput BruteForceRayCast( const b3HeightField* hf, const b3RayCastI
for ( int t = 0; t < triangleCount; ++t )
{
int cellIndex = t >> 1;
if ( hf->materialIndices[cellIndex] == B3_HEIGHT_FIELD_HOLE )
if ( b3GetHeightFieldMaterialIndices( hf )[cellIndex] == B3_HEIGHT_FIELD_HOLE )
{
continue;
}
@ -474,7 +474,7 @@ static int RayCastBruteForce( void )
// (radius-zero point proxy), so it is subject to the same early-termination
// bug. The brute-force cast against every triangle is the ground truth.
b3Vec3 scale = { 2.0f, 1.5f, 2.0f };
b3HeightField* hf = b3CreateWave( 10, 10, scale, 0.1f, 0.03333f, false );
b3HeightFieldData* hf = b3CreateWave( 10, 10, scale, 0.1f, 0.03333f, false );
const b3Vec3 deltas[] = {
{ 0.0f, -8.0f, 0.0f }, // straight down

1502
test/test_recording.c Normal file

File diff suppressed because it is too large Load diff

View file

@ -562,7 +562,7 @@ static int TestCompoundHitEvents( void )
b3CompoundDef compoundDef = { 0 };
compoundDef.hulls = hulls;
compoundDef.hullCount = 2;
b3Compound* compound = b3CreateCompound( &compoundDef );
b3CompoundData* compound = b3CreateCompound( &compoundDef );
ENSURE( compound != NULL );
// Static body holds the compound