diff --git a/.gitignore b/.gitignore index d71466e..5e7c248 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,4 @@ CMakeUserPresets.json .tmp/ .fetchcontent-cache/ build-dp/ +*.b3rec diff --git a/docs/collision.md b/docs/collision.md index b3bc3d1..91ee199 100644 --- a/docs/collision.md +++ b/docs/collision.md @@ -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); ``` diff --git a/docs/recording.md b/docs/recording.md index 3476187..0119142 100644 --- a/docs/recording.md +++ b/docs/recording.md @@ -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. diff --git a/include/box3d/box3d.h b/include/box3d/box3d.h index 9565f94..c307d75 100644 --- a/include/box3d/box3d.h +++ b/include/box3d/box3d.h @@ -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. diff --git a/include/box3d/collision.h b/include/box3d/collision.h index d213092..ae59ad4 100644 --- a/include/box3d/collision.h +++ b/include/box3d/collision.h @@ -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. diff --git a/include/box3d/types.h b/include/box3d/types.h index 2190f49..17253c7 100644 --- a/include/box3d/types.h +++ b/include/box3d/types.h @@ -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 ); diff --git a/samples/CMakeLists.txt b/samples/CMakeLists.txt index 2995799..64a31f2 100644 --- a/samples/CMakeLists.txt +++ b/samples/CMakeLists.txt @@ -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 diff --git a/samples/gfx/debug_adapter.c b/samples/gfx/debug_adapter.c index 4423822..21ad663 100644 --- a/samples/gfx/debug_adapter.c +++ b/samples/gfx/debug_adapter.c @@ -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 #include #include @@ -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; diff --git a/samples/gfx/debug_shapes.c b/samples/gfx/debug_shapes.c index 3685cb2..dc74a55 100644 --- a/samples/gfx/debug_shapes.c +++ b/samples/gfx/debug_shapes.c @@ -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 ) { diff --git a/samples/gfx/debug_shapes.h b/samples/gfx/debug_shapes.h index 71efc0b..ecf024b 100644 --- a/samples/gfx/debug_shapes.h +++ b/samples/gfx/debug_shapes.h @@ -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" diff --git a/samples/gfx/geometry_registry.h b/samples/gfx/geometry_registry.h index 465b458..5bbedbd 100644 --- a/samples/gfx/geometry_registry.h +++ b/samples/gfx/geometry_registry.h @@ -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: // diff --git a/samples/main.cpp b/samples/main.cpp index dbee802..ad09791 100644 --- a/samples/main.cpp +++ b/samples/main.cpp @@ -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; } diff --git a/samples/sample.cpp b/samples/sample.cpp index 4fdf7b9..e4a4f9b 100644 --- a/samples/sample.cpp +++ b/samples/sample.cpp @@ -24,6 +24,8 @@ #include "box3d/box3d.h" +#include + #include #include #include @@ -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(); } diff --git a/samples/sample.h b/samples/sample.h index 0899a65..47fd9c1 100644 --- a/samples/sample.h +++ b/samples/sample.h @@ -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 ); diff --git a/samples/sample_benchmark.cpp b/samples/sample_benchmark.cpp index 976d8ab..558c3cc 100644 --- a/samples/sample_benchmark.cpp +++ b/samples/sample_benchmark.cpp @@ -654,7 +654,7 @@ public: return new BenchmarkHeightField( context ); } - b3HeightField* m_heightField; + b3HeightFieldData* m_heightField; int m_columnCount; int m_rowCount; float m_radius; diff --git a/samples/sample_character.cpp b/samples/sample_character.cpp index 12724b2..e115350 100644 --- a/samples/sample_character.cpp +++ b/samples/sample_character.cpp @@ -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; }; diff --git a/samples/sample_collision.cpp b/samples/sample_collision.cpp index 485120c..078efc0 100644 --- a/samples/sample_collision.cpp +++ b/samples/sample_collision.cpp @@ -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; diff --git a/samples/sample_compound.cpp b/samples/sample_compound.cpp index 6273b95..0f7adc6 100644 --- a/samples/sample_compound.cpp +++ b/samples/sample_compound.cpp @@ -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; diff --git a/samples/sample_issues.cpp b/samples/sample_issues.cpp index c90f71f..d05b353 100644 --- a/samples/sample_issues.cpp +++ b/samples/sample_issues.cpp @@ -454,7 +454,7 @@ public: } b3MeshData* m_boxMesh; - b3HeightField* m_heightField; + b3HeightFieldData* m_heightField; b3MeshData* m_gridMesh; }; diff --git a/samples/sample_joint.cpp b/samples/sample_joint.cpp index 107ceac..ac5d2fd 100644 --- a/samples/sample_joint.cpp +++ b/samples/sample_joint.cpp @@ -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; diff --git a/samples/sample_mesh.cpp b/samples/sample_mesh.cpp index fef585b..f00f718 100644 --- a/samples/sample_mesh.cpp +++ b/samples/sample_mesh.cpp @@ -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; diff --git a/samples/sample_replay.cpp b/samples/sample_replay.cpp new file mode 100644 index 0000000..e171cc1 --- /dev/null +++ b/samples/sample_replay.cpp @@ -0,0 +1,1255 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +#include "gfx/debug_adapter.h" +#include "gfx/draw.h" +#include "gfx/text.h" +#include "imgui.h" +#include "sample.h" + +#include "box3d/box3d.h" + +#include +#include +#include +#include + +// Inspector readout names +static const char* ReplayBodyTypeName( b3BodyType type ) +{ + switch ( type ) + { + case b3_staticBody: + return "static"; + case b3_kinematicBody: + return "kinematic"; + case b3_dynamicBody: + return "dynamic"; + default: + return "?"; + } +} + +static const char* ReplayShapeTypeName( b3ShapeType type ) +{ + switch ( type ) + { + case b3_sphereShape: + return "sphere"; + case b3_capsuleShape: + return "capsule"; + case b3_hullShape: + return "hull"; + case b3_meshShape: + return "mesh"; + case b3_heightShape: + return "height field"; + case b3_compoundShape: + return "compound"; + default: + return "?"; + } +} + +static const char* ReplayJointTypeName( b3JointType type ) +{ + switch ( type ) + { + case b3_parallelJoint: + return "parallel"; + case b3_distanceJoint: + return "distance"; + case b3_filterJoint: + return "filter"; + case b3_motorJoint: + return "motor"; + case b3_prismaticJoint: + return "prismatic"; + case b3_revoluteJoint: + return "revolute"; + case b3_sphericalJoint: + return "spherical"; + case b3_weldJoint: + return "weld"; + case b3_wheelJoint: + return "wheel"; + default: + return "?"; + } +} + +static const char* ReplayQueryTypeName( b3RecQueryType type ) +{ + switch ( type ) + { + case b3_recQueryOverlapAABB: + return "overlap AABB"; + case b3_recQueryOverlapShape: + return "overlap shape"; + case b3_recQueryCastRay: + return "cast ray"; + case b3_recQueryCastShape: + return "cast shape"; + case b3_recQueryCastRayClosest: + return "cast ray closest"; + case b3_recQueryCastMover: + return "cast mover"; + case b3_recQueryCollideMover: + return "collide mover"; + default: + return "?"; + } +} + +// b3HexColor to an opaque ImVec4 for panel text +static ImVec4 PanelColor( b3HexColor hexColor ) +{ + uint32_t h = (uint32_t)hexColor; + return ImGui::ColorConvertU32ToFloat4( IM_COL32( ( h >> 16 ) & 0xFF, ( h >> 8 ) & 0xFF, h & 0xFF, 255 ) ); +} + +// Plays back a .b3rec recording by driving the keyframe player one recorded step at a time and +// drawing the replayed world. The player owns the world, so the base sample world is left empty and +// unused. Mouse picking only reads the world (no drag joint), since mutating it would diverge the +// replay from the recording. +// +// The UI is spread across three surfaces, matching Box2D's viewer: +// - right info panel (DrawControls): Show Timeline button, divergence flag, frame counter +// - left Outline / Detail window (DrawSampleWindows): the recorded scene tree and selection detail +// - Timeline tab in the diagnostics drawer (DrawMetricsTab): transport, scrubber, keyframe readout +class ReplayViewer : public Sample +{ +public: + enum SelKind + { + SelNone, + SelBody, + SelShape, + SelJoint, + SelQuery, + }; + + explicit ReplayViewer( SampleContext* context ) + : Sample( context ) + { + m_player = nullptr; + m_replayWorldId = b3_nullWorldId; + m_info = { 0 }; + m_speed = 1.0f; + m_frameAccumulator = 0.0f; + m_loop = false; + m_selKind = SelNone; + m_selBodyOrdinal = -1; + m_selSlot = -1; + m_selQuery = -1; + m_revealSelection = false; + m_requestLoadPopup = false; + m_generating = false; + m_popupBudgetMB = m_context->replayKeyframeBudgetMB; + m_popupMinInterval = m_context->replayKeyframeMinInterval; + m_status[0] = '\0'; + + if ( context->restart == false ) + { + m_camera->SetView( 30.0f, 22.0f, 14.0f, { 0.0f, 2.0f, 0.0f } ); + } + + // The timeline scrubber lives in the diagnostics drawer, so open it and start paused. + m_prevShowMetrics = m_context->showMetrics; + m_context->showMetrics = true; + m_context->pause = true; + m_selectTimelineTab = true; + + snprintf( m_path, sizeof( m_path ), "%s", m_context->replayFile ); + + // A fresh open gathers the keyframe policy through the Load popup, then pre-generates every + // keyframe behind a progress bar. A restart reuses the persisted policy and fills the ring + // lazily so R stays quick. + if ( context->restart == false ) + { + if ( strlen( m_path ) > 0 ) + { + m_requestLoadPopup = true; + } + else + { + snprintf( m_status, sizeof( m_status ), "Open recording from Replay menu" ); + } + } + else + { + CreatePlayer(); + } + } + + ~ReplayViewer() override + { + // Runs before the base destructor, which destroys the (empty) base world and resets the + // debug-shape pool. Destroying the player here releases the replay world's pool entries first. + ClosePlayer(); + m_context->showMetrics = m_prevShowMetrics; + } + + void ClosePlayer() + { + if ( m_player != nullptr ) + { + b3RecPlayer_Destroy( m_player ); + m_player = nullptr; + } + m_replayWorldId = b3_nullWorldId; + SetHoveredBody( b3_nullBodyId ); + SetSelectedBody( b3_nullBodyId ); + m_selKind = SelNone; + m_selBodyOrdinal = -1; + m_selSlot = -1; + m_selQuery = -1; + } + + // Load m_path into a fresh player and adopt its world. Sets m_status on any failure: missing + // file, bad header, or deserialization error. Pre-generation of the keyframe ring is done by the + // Load popup, not here, so the open stays responsive. + void CreatePlayer() + { + ClosePlayer(); + + if ( strlen( m_path ) == 0 ) + { + snprintf( m_status, sizeof( m_status ), "Open recording from Replay menu" ); + return; + } + + // The player copies the bytes, so the recording can be freed right away. Replaying at the host + // worker count makes the per-step StateHash check double as a cross-thread determinism test. + b3Recording* recording = b3LoadRecordingFromFile( m_path ); + if ( recording != nullptr ) + { + m_player = b3RecPlayer_Create( b3Recording_GetData( recording ), b3Recording_GetSize( recording ), + m_context->workerCount ); + b3DestroyRecording( recording ); + } + else + { + m_player = nullptr; + } + + m_frameAccumulator = 0.0f; + + if ( m_player == nullptr ) + { + m_info = b3RecPlayerInfo{}; + snprintf( m_status, sizeof( m_status ), "failed to open file" ); + return; + } + + // Honor the persisted keyframe policy before any stepping captures keyframes. + size_t bytes = (size_t)m_context->replayKeyframeBudgetMB * 1024u * 1024u; + b3RecPlayer_SetKeyframePolicy( m_player, bytes, m_context->replayKeyframeMinInterval ); + + // Wire the renderer's debug-shape callbacks into the player's world. Without them the replay + // world has no GPU mesh handles and draws nothing. This rebuilds the world and rewinds to + // frame 0, so adopt the world id afterward. + b3WorldDef defTemplate = b3DefaultWorldDef(); + AttachToWorldDef( &defTemplate ); + b3RecPlayer_SetDebugShapeCallbacks( m_player, defTemplate.createDebugShape, defTemplate.destroyDebugShape, + defTemplate.userDebugShapeContext ); + + m_replayWorldId = b3RecPlayer_GetWorldId( m_player ); + m_info = b3RecPlayer_GetInfo( m_player ); + snprintf( m_status, sizeof( m_status ), "loaded" ); + + // Frame the recorded motion. Bounds come from the trailing RecordingBounds record; an empty + // extent means an older recording, so leave the default view. + if ( m_context->restart == false ) + { + b3Vec3 extent = b3Sub( m_info.bounds.upperBound, m_info.bounds.lowerBound ); + if ( extent.x > 0.0f || extent.y > 0.0f || extent.z > 0.0f ) + { + float aspect = m_camera->m_height > 0 ? (float)m_camera->m_width / (float)m_camera->m_height : 1.0f; + m_camera->Frame( m_info.bounds, aspect, 1.4f ); + } + } + } + + // Modal shown after the Replay menu picks a file: choose the keyframe budget and min interval, + // then Load creates the player and pre-generates the whole ring behind a progress bar. Drawn from + // DrawSampleWindows, which runs inside the imgui frame (Step does not in Box3D). + void DrawLoadPopup() + { + const char* popupId = "Load Replay"; + + if ( m_requestLoadPopup ) + { + m_requestLoadPopup = false; + m_popupBudgetMB = m_context->replayKeyframeBudgetMB; + m_popupMinInterval = m_context->replayKeyframeMinInterval; + ImGui::OpenPopup( popupId ); + } + + float fontSize = ImGui::GetFontSize(); + ImGui::SetNextWindowPos( { m_camera->m_width * 0.5f, m_camera->m_height * 0.35f }, ImGuiCond_Appearing, + { 0.5f, 0.5f } ); + ImGui::SetNextWindowSize( { 26.0f * fontSize, 0.0f }, ImGuiCond_Appearing ); + + if ( ImGui::BeginPopupModal( popupId, nullptr, ImGuiWindowFlags_AlwaysAutoResize ) == false ) + { + return; + } + + // Show just the file name, paths run long. + const char* slash = strrchr( m_path, '\\' ); + ImGui::TextDisabled( "File:" ); + ImGui::SameLine(); + ImGui::TextUnformatted( slash != nullptr ? slash + 1 : m_path ); + ImGui::Separator(); + + if ( m_generating ) + { + // Step forward in wall-clock slices so the bar animates. Forward stepping captures + // keyframes at the interval; a restart then returns to frame 0 with the ring kept. + uint64_t ticks = b3GetTicks(); + while ( b3RecPlayer_IsAtEnd( m_player ) == false && b3GetMilliseconds( ticks ) < 12.0f ) + { + b3RecPlayer_StepFrame( m_player ); + } + + int frame = b3RecPlayer_GetFrame( m_player ); + int total = m_info.frameCount > 0 ? m_info.frameCount : 1; + float frac = frame >= total ? 1.0f : (float)frame / (float)total; + char overlay[32]; + snprintf( overlay, sizeof( overlay ), "%d / %d", frame, m_info.frameCount ); + ImGui::TextUnformatted( "Generating keyframes" ); + ImGui::ProgressBar( frac, ImVec2( -FLT_MIN, 0.0f ), overlay ); + + if ( b3RecPlayer_IsAtEnd( m_player ) ) + { + b3RecPlayer_Restart( m_player ); + m_replayWorldId = b3RecPlayer_GetWorldId( m_player ); + m_generating = false; + m_context->pause = true; + ImGui::CloseCurrentPopup(); + } + + ImGui::EndPopup(); + return; + } + + ImGui::PushItemWidth( 10.0f * fontSize ); + ImGui::SliderInt( "Memory budget (MB)", &m_popupBudgetMB, 128, 4096 ); + ImGui::SliderInt( "Min sample interval", &m_popupMinInterval, 8, 60 ); + ImGui::PopItemWidth(); + + // Surface a failed open inline so Load can be retried. + if ( m_status[0] != '\0' && strcmp( m_status, "loaded" ) != 0 ) + { + ImGui::TextColored( PanelColor( b3_colorRed ), "%s", m_status ); + } + + ImGui::Separator(); + if ( ImGui::Button( "Load" ) ) + { + // Commit the choices so they persist, build the player under that policy, then start + // pre-generation. An empty recording has nothing to generate. + m_context->replayKeyframeBudgetMB = m_popupBudgetMB; + m_context->replayKeyframeMinInterval = m_popupMinInterval; + CreatePlayer(); + if ( m_player != nullptr ) + { + m_generating = m_info.frameCount > 0; + if ( m_generating == false ) + { + ImGui::CloseCurrentPopup(); + } + } + } + ImGui::SameLine(); + if ( ImGui::Button( "Cancel" ) ) + { + ImGui::CloseCurrentPopup(); + } + + ImGui::EndPopup(); + } + + // Advance one recorded step and keep the world pointer current (stable forward, refreshed cheaply). + void AdvanceOne() + { + b3RecPlayer_StepFrame( m_player ); + m_replayWorldId = b3RecPlayer_GetWorldId( m_player ); + } + + void Step() override + { + // Generation runs inside the imgui frame (DrawLoadPopup). While it fast-forwards, the world is + // mid-replay, so hold off drawing it. + if ( m_generating ) + { + m_stepCount = m_player != nullptr ? b3RecPlayer_GetFrame( m_player ) : 0; + SetDrawOrigin( m_camera->m_worldEye ); + return; + } + + if ( m_player != nullptr ) + { + if ( m_context->pause && m_context->singleStep > 0 ) + { + m_context->singleStep = b3MaxInt( 0, m_context->singleStep - 1 ); + if ( b3RecPlayer_IsAtEnd( m_player ) == false ) + { + AdvanceOne(); + } + m_frameAccumulator = 0.0f; + } + else if ( m_context->pause == false ) + { + // Speed scales recorded steps per display frame. + m_frameAccumulator += m_speed; + while ( m_frameAccumulator >= 1.0f ) + { + m_frameAccumulator -= 1.0f; + if ( b3RecPlayer_IsAtEnd( m_player ) ) + { + if ( m_loop ) + { + b3RecPlayer_Restart( m_player ); + m_replayWorldId = b3RecPlayer_GetWorldId( m_player ); + } + else + { + m_frameAccumulator = 0.0f; + break; + } + } + AdvanceOne(); + } + } + + // Keep the info panel "step N" line on the replay frame. + m_stepCount = b3RecPlayer_GetFrame( m_player ); + } + + SetDrawOrigin( m_camera->m_worldEye ); + + if ( B3_IS_NULL( m_replayWorldId ) ) + { + DrawScreenStringFormat( 5, m_textLine, MakeColor( b3_colorLightGray ), "%s", m_status ); + return; + } + + // Highlight the dynamic body under the cursor, matching the live samples. + PickRay pickRay = m_camera->BuildPickRay( m_context->mouseX, m_context->mouseY ); + b3RayResult hover = b3World_CastRayClosest( m_replayWorldId, pickRay.origin, pickRay.translation, b3DefaultQueryFilter() ); + b3BodyId hovered = b3_nullBodyId; + if ( hover.hit && b3Body_GetType( b3Shape_GetBody( hover.shapeId ) ) == b3_dynamicBody ) + { + hovered = b3Shape_GetBody( hover.shapeId ); + } + SetHoveredBody( hovered ); + + // Mirror the ordinal selection into the renderer highlight each frame. + SetSelectedBody( SelectedBody() ); + + // Draw the replay world through the same adapter path the live samples use. + b3DebugDraw debugDraw; + MakeDebugDraw( &debugDraw ); + ApplyGuiFlags( &debugDraw ); + b3Vec3 r = { 1000.0f, 1000.0f, 1000.0f }; + debugDraw.drawingBounds = b3OffsetAABB( { b3Neg( r ), r }, m_camera->m_worldEye ); + b3World_Draw( m_replayWorldId, &debugDraw, B3_DEFAULT_MASK_BITS ); + + DrawSelectionHighlight(); + + // Overlay the selected query's geometry and recorded hits on top of the world. + if ( m_selKind == SelQuery ) + { + b3RecPlayer_DrawFrameQueries( m_player, &debugDraw, m_selQuery ); + } + } + + // A replay re-runs recorded inputs, so the live solver sliders would do nothing. This also hides + // the Solver and Recording sections in the right info panel. + bool HasSolverControls() const override + { + return false; + } + + // Transport row shared by the right panel and the Timeline tab. Play is green, Pause red. + void DrawTransport() + { + int frame = b3RecPlayer_GetFrame( m_player ); + + if ( ImGui::Button( "|<" ) ) + { + b3RecPlayer_SeekFrame( m_player, 0 ); + m_replayWorldId = b3RecPlayer_GetWorldId( m_player ); + m_frameAccumulator = 0.0f; + } + ImGui::SameLine(); + if ( ImGui::Button( "<" ) ) + { + b3RecPlayer_SeekFrame( m_player, frame - 1 ); + m_replayWorldId = b3RecPlayer_GetWorldId( m_player ); + m_frameAccumulator = 0.0f; + m_context->pause = true; + } + ImGui::SameLine(); + if ( m_context->pause ) + { + ImGui::PushStyleColor( ImGuiCol_Button, (ImVec4)ImColor::HSV( 2.0f / 7.0f, 0.6f, 0.6f ) ); + ImGui::PushStyleColor( ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV( 2.0f / 7.0f, 0.7f, 0.7f ) ); + ImGui::PushStyleColor( ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV( 2.0f / 7.0f, 0.8f, 0.8f ) ); + if ( ImGui::Button( "Play " ) ) + { + m_context->pause = false; + } + ImGui::PopStyleColor( 3 ); + } + else + { + ImGui::PushStyleColor( ImGuiCol_Button, (ImVec4)ImColor::HSV( 1.0f / 7.0f, 0.6f, 0.6f ) ); + ImGui::PushStyleColor( ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV( 1.0f / 7.0f, 0.7f, 0.7f ) ); + ImGui::PushStyleColor( ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV( 1.0f / 7.0f, 0.8f, 0.8f ) ); + if ( ImGui::Button( "Pause" ) ) + { + m_context->pause = true; + } + ImGui::PopStyleColor( 3 ); + } + ImGui::SameLine(); + if ( ImGui::Button( ">" ) ) + { + b3RecPlayer_SeekFrame( m_player, frame + 1 ); + m_replayWorldId = b3RecPlayer_GetWorldId( m_player ); + m_frameAccumulator = 0.0f; + m_context->pause = true; + } + ImGui::SameLine(); + if ( ImGui::Button( ">|" ) ) + { + b3RecPlayer_SeekFrame( m_player, m_info.frameCount ); + m_replayWorldId = b3RecPlayer_GetWorldId( m_player ); + m_frameAccumulator = 0.0f; + } + } + + // Right info panel: a compact summary. The scene tree lives in the Outline window and the + // transport in the Timeline tab. + bool DrawControls() override + { + if ( m_player == nullptr ) + { + ImGui::TextWrapped( "%s", m_status ); + return true; + } + + if ( ImGui::Button( "Show Timeline" ) ) + { + m_context->showMetrics = true; + m_selectTimelineTab = true; + } + + if ( b3RecPlayer_HasDiverged( m_player ) ) + { + ImGui::TextColored( PanelColor( b3_colorRed ), "****DIVERGED****" ); + } + + ImGui::TextDisabled( "Frame %d / %d%s", b3RecPlayer_GetFrame( m_player ), m_info.frameCount, + b3RecPlayer_IsAtEnd( m_player ) ? " (end)" : "" ); + return true; + } + + // Selection resolution. The selection is stored as creation ordinals so it survives a backward + // seek that rebuilds the world. Each frame the ordinal maps back to a live id, or to null when + // that object does not exist at the current frame. + b3BodyId SelectedBody() const + { + if ( m_player == nullptr || m_selBodyOrdinal < 0 ) + { + return b3_nullBodyId; + } + return b3RecPlayer_GetBodyId( m_player, m_selBodyOrdinal ); + } + + b3ShapeId SelectedShape() const + { + b3BodyId body = SelectedBody(); + if ( m_selKind != SelShape || b3Body_IsValid( body ) == false ) + { + return b3_nullShapeId; + } + b3ShapeId shapes[32]; + int n = b3Body_GetShapes( body, shapes, 32 ); + return ( m_selSlot >= 0 && m_selSlot < n ) ? shapes[m_selSlot] : b3_nullShapeId; + } + + b3JointId SelectedJoint() const + { + b3BodyId body = SelectedBody(); + if ( m_selKind != SelJoint || b3Body_IsValid( body ) == false ) + { + return b3_nullJointId; + } + b3JointId joints[16]; + int n = b3Body_GetJoints( body, joints, 16 ); + return ( m_selSlot >= 0 && m_selSlot < n ) ? joints[m_selSlot] : b3_nullJointId; + } + + int FindBodyOrdinal( b3BodyId body ) const + { + int count = b3RecPlayer_GetBodyCount( m_player ); + for ( int i = 0; i < count; ++i ) + { + if ( B3_ID_EQUALS( b3RecPlayer_GetBodyId( m_player, i ), body ) ) + { + return i; + } + } + return -1; + } + + // Map a picked shape back to its body ordinal and shape slot. A null shape clears the selection. + void SelectShape( b3ShapeId shape ) + { + if ( B3_IS_NULL( shape ) ) + { + m_selKind = SelNone; + return; + } + b3BodyId body = b3Shape_GetBody( shape ); + int ordinal = FindBodyOrdinal( body ); + if ( ordinal < 0 ) + { + m_selKind = SelNone; + return; + } + b3ShapeId shapes[32]; + int n = b3Body_GetShapes( body, shapes, 32 ); + int slot = -1; + for ( int i = 0; i < n; ++i ) + { + if ( B3_ID_EQUALS( shapes[i], shape ) ) + { + slot = i; + break; + } + } + m_selKind = SelShape; + m_selBodyOrdinal = ordinal; + m_selSlot = slot; + m_revealSelection = true; // expand and scroll the tree to the picked shape next draw + } + + // World-space overlay: a body's live contact points and normals, the most useful solver readout. + void DrawBodyContacts( b3BodyId body ) + { + b3ContactData contacts[32]; + int capacity = b3Body_GetContactCapacity( body ); + if ( capacity > 32 ) + { + capacity = 32; + } + int count = b3Body_GetContactData( body, contacts, capacity ); + for ( int i = 0; i < count; ++i ) + { + b3Pos originA = b3Body_GetWorldCenterOfMass( b3Shape_GetBody( contacts[i].shapeIdA ) ); + for ( int m = 0; m < contacts[i].manifoldCount; ++m ) + { + const b3Manifold* manifold = &contacts[i].manifolds[m]; + for ( int p = 0; p < manifold->pointCount; ++p ) + { + b3Pos point = b3OffsetPos( originA, manifold->points[p].anchorA ); + DrawPoint( point, 6.0f, MakeColor( b3_colorOrange ) ); + DrawLine( point, b3OffsetPos( point, b3MulSV( 0.3f, manifold->normal ) ), MakeColor( b3_colorOrange ) ); + } + } + } + } + + // Highlight the current selection without touching the world: AABB box, body axes, center of + // mass, and contacts. Joints mark both connected body centers. + void DrawSelectionHighlight() + { + if ( m_selKind == SelShape ) + { + b3ShapeId shape = SelectedShape(); + if ( b3Shape_IsValid( shape ) == false ) + { + return; + } + b3BodyId body = b3Shape_GetBody( shape ); + DrawBounds( b3Shape_GetAABB( shape ), 0.0f, MakeColor( b3_colorYellow ) ); + DrawAxes( b3Body_GetTransform( body ), 0.5f ); + DrawPoint( b3Body_GetWorldCenterOfMass( body ), 8.0f, MakeColor( b3_colorYellow ) ); + DrawBodyContacts( body ); + } + else if ( m_selKind == SelBody ) + { + b3BodyId body = SelectedBody(); + if ( b3Body_IsValid( body ) == false ) + { + return; + } + DrawBounds( b3Body_ComputeAABB( body ), 0.0f, MakeColor( b3_colorYellow ) ); + DrawAxes( b3Body_GetTransform( body ), 0.5f ); + DrawPoint( b3Body_GetWorldCenterOfMass( body ), 8.0f, MakeColor( b3_colorYellow ) ); + DrawBodyContacts( body ); + } + else if ( m_selKind == SelJoint ) + { + b3JointId joint = SelectedJoint(); + if ( b3Joint_IsValid( joint ) == false ) + { + return; + } + b3BodyId a = b3Joint_GetBodyA( joint ); + b3BodyId b = b3Joint_GetBodyB( joint ); + if ( b3Body_IsValid( a ) ) + { + DrawPoint( b3Body_GetWorldCenterOfMass( a ), 8.0f, MakeColor( b3_colorMagenta ) ); + } + if ( b3Body_IsValid( b ) ) + { + DrawPoint( b3Body_GetWorldCenterOfMass( b ), 8.0f, MakeColor( b3_colorMagenta ) ); + } + } + } + + // Left-edge Outline / Detail window plus the keyframe-policy popup. + void DrawSampleWindows() override + { + DrawLoadPopup(); + + if ( m_player == nullptr || m_generating ) + { + return; + } + + float fontSize = ImGui::GetFontSize(); + float panelWidth = 22.0f * fontSize; + float menuBarHeight = ImGui::GetFrameHeight(); + float top = menuBarHeight + 0.5f * fontSize; + + // Stop above the diagnostics drawer when it is open so the panels do not overlap. The 16 em + // drawer height mirrors DrawMetrics. + float bottom = m_context->showMetrics ? ( m_camera->m_height - 16.0f * fontSize - fontSize ) + : ( m_camera->m_height - 0.5f * fontSize ); + + ImGui::SetNextWindowPos( { 0.5f * fontSize, top } ); + ImGui::SetNextWindowSize( { panelWidth, bottom - top } ); + ImGui::Begin( "Outline", nullptr, + ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | + ImGuiWindowFlags_NoTitleBar ); + + ImGui::TextColored( PanelColor( b3_colorGoldenRod ), "Outline" ); + float avail = ImGui::GetContentRegionAvail().y; + ImGui::BeginChild( "OutlineTree", { 0.0f, 0.55f * avail } ); + DrawOutlineTree(); + ImGui::EndChild(); + + ImGui::Separator(); + ImGui::TextColored( PanelColor( b3_colorGoldenRod ), "Detail" ); + ImGui::BeginChild( "DetailPane", { 0.0f, 0.0f } ); + DrawDetail(); + ImGui::EndChild(); + + ImGui::End(); + } + + // Recorded scene tree: bodies by creation ordinal, expandable to their shapes and joints. + // Destroyed bodies keep their ordinal but are not shown, so a stored selection stays put. + void DrawOutlineTree() + { + // A viewport pick asks the tree to reveal its target once: expand the owning body and scroll + // to the row. Consumed at the end so it never fights the user's own expand/collapse. + bool reveal = m_revealSelection; + + int count = b3RecPlayer_GetBodyCount( m_player ); + for ( int ord = 0; ord < count; ++ord ) + { + b3BodyId body = b3RecPlayer_GetBodyId( m_player, ord ); + if ( B3_IS_NULL( body ) || b3Body_IsValid( body ) == false ) + { + continue; + } + + bool ownsSelection = + m_selBodyOrdinal == ord && ( m_selKind == SelBody || m_selKind == SelShape || m_selKind == SelJoint ); + + const char* name = b3Body_GetName( body ); + char label[64]; + snprintf( label, sizeof( label ), "Body %d %s###b%d", ord, + ( name != nullptr && name[0] != '\0' ) ? name : ReplayBodyTypeName( b3Body_GetType( body ) ), ord ); + + ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_SpanAvailWidth; + if ( m_selKind == SelBody && m_selBodyOrdinal == ord ) + { + flags |= ImGuiTreeNodeFlags_Selected; + } + // Reveal a picked shape or joint by expanding its body. + if ( reveal && ownsSelection && m_selKind != SelBody ) + { + ImGui::SetNextItemOpen( true ); + } + bool open = ImGui::TreeNodeEx( label, flags ); + if ( reveal && ownsSelection && m_selKind == SelBody ) + { + ImGui::SetScrollHereY( 0.5f ); + } + if ( ImGui::IsItemClicked() && ImGui::IsItemToggledOpen() == false ) + { + m_selKind = SelBody; + m_selBodyOrdinal = ord; + m_selSlot = -1; + } + if ( open == false ) + { + continue; + } + + b3ShapeId shapes[32]; + int sn = b3Body_GetShapes( body, shapes, 32 ); + for ( int s = 0; s < sn; ++s ) + { + char sl[64]; + snprintf( sl, sizeof( sl ), "Shape %d %s###b%ds%d", s, ReplayShapeTypeName( b3Shape_GetType( shapes[s] ) ), + ord, s ); + ImGuiTreeNodeFlags lf = + ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_NoTreePushOnOpen; + if ( m_selKind == SelShape && m_selBodyOrdinal == ord && m_selSlot == s ) + { + lf |= ImGuiTreeNodeFlags_Selected; + } + ImGui::TreeNodeEx( sl, lf ); + if ( reveal && m_selKind == SelShape && m_selBodyOrdinal == ord && m_selSlot == s ) + { + ImGui::SetScrollHereY( 0.5f ); + } + if ( ImGui::IsItemClicked() ) + { + m_selKind = SelShape; + m_selBodyOrdinal = ord; + m_selSlot = s; + } + } + + b3JointId joints[16]; + int jn = b3Body_GetJoints( body, joints, 16 ); + for ( int j = 0; j < jn; ++j ) + { + char jl[64]; + snprintf( jl, sizeof( jl ), "%s joint###b%dj%d", ReplayJointTypeName( b3Joint_GetType( joints[j] ) ), ord, j ); + ImGuiTreeNodeFlags lf = + ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_NoTreePushOnOpen; + if ( m_selKind == SelJoint && m_selBodyOrdinal == ord && m_selSlot == j ) + { + lf |= ImGuiTreeNodeFlags_Selected; + } + ImGui::TreeNodeEx( jl, lf ); + if ( ImGui::IsItemClicked() ) + { + m_selKind = SelJoint; + m_selBodyOrdinal = ord; + m_selSlot = j; + } + } + + ImGui::TreePop(); + } + + // Spatial queries recorded for the current frame. Selecting one overlays its geometry and + // recorded hits on the world. The list is rebuilt each frame, so a selection is by index only. + int qn = b3RecPlayer_GetFrameQueryCount( m_player ); + char ql[32]; + snprintf( ql, sizeof( ql ), "Queries (%d)###queries", qn ); + if ( ImGui::TreeNodeEx( ql, ImGuiTreeNodeFlags_SpanAvailWidth ) ) + { + for ( int i = 0; i < qn; ++i ) + { + b3RecQueryInfo q = b3RecPlayer_GetFrameQuery( m_player, i ); + char qi[64]; + snprintf( qi, sizeof( qi ), "%s (%d)###q%d", ReplayQueryTypeName( q.type ), q.hitCount, i ); + ImGuiTreeNodeFlags lf = + ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_NoTreePushOnOpen; + if ( m_selKind == SelQuery && m_selQuery == i ) + { + lf |= ImGuiTreeNodeFlags_Selected; + } + ImGui::TreeNodeEx( qi, lf ); + if ( ImGui::IsItemClicked() ) + { + m_selKind = SelQuery; + m_selQuery = i; + } + } + ImGui::TreePop(); + } + + m_revealSelection = false; + } + + // Detail pane for the current selection, resolved to live ids each frame. With nothing selected, + // show the world summary. + void DrawDetail() + { + if ( m_selKind == SelNone ) + { + ImGui::TextWrapped( "Click a node, or a shape in the view." ); + if ( B3_IS_NON_NULL( m_replayWorldId ) ) + { + b3Vec3 g = b3World_GetGravity( m_replayWorldId ); + b3Counters c = b3World_GetCounters( m_replayWorldId ); + ImGui::Text( "gravity (%.2f, %.2f, %.2f)", g.x, g.y, g.z ); + ImGui::Text( "bodies %d shapes %d", c.bodyCount, c.shapeCount ); + ImGui::Text( "contacts %d joints %d", c.contactCount, c.jointCount ); + } + return; + } + + if ( m_selKind == SelQuery ) + { + DrawQueryDetail(); + return; + } + + b3BodyId body = SelectedBody(); + if ( b3Body_IsValid( body ) == false ) + { + ImGui::TextDisabled( "Not present at this frame." ); + return; + } + + DrawBodyDetail( body ); + if ( m_selKind == SelShape ) + { + b3ShapeId shape = SelectedShape(); + if ( b3Shape_IsValid( shape ) ) + { + DrawShapeDetail( shape ); + } + } + else if ( m_selKind == SelJoint ) + { + b3JointId joint = SelectedJoint(); + if ( b3Joint_IsValid( joint ) ) + { + DrawJointDetail( joint ); + } + } + DrawContactDetail( body ); + } + + void DrawBodyDetail( b3BodyId body ) + { + if ( ImGui::CollapsingHeader( "Body", ImGuiTreeNodeFlags_DefaultOpen ) == false ) + { + return; + } + + const char* name = b3Body_GetName( body ); + b3WorldTransform xf = b3Body_GetTransform( body ); + b3Vec3 v = b3Body_GetLinearVelocity( body ); + b3Vec3 w = b3Body_GetAngularVelocity( body ); + float spin; + b3GetAxisAngle( &spin, xf.q ); + + ImGui::Text( "id %d", body.index1 ); + ImGui::Text( "name %s", ( name != nullptr && name[0] != '\0' ) ? name : "(none)" ); + ImGui::Text( "type %s", ReplayBodyTypeName( b3Body_GetType( body ) ) ); + ImGui::Text( "pos (%.3f, %.3f, %.3f)", xf.p.x, xf.p.y, xf.p.z ); + ImGui::Text( "spin %.1f deg", spin * B3_RAD_TO_DEG ); + ImGui::Text( "vel (%.3f, %.3f, %.3f)", v.x, v.y, v.z ); + ImGui::Text( "omega (%.3f, %.3f, %.3f)", w.x, w.y, w.z ); + ImGui::Text( "speed %.3f spin rate %.3f", b3Length( v ), b3Length( w ) ); + ImGui::Text( "mass %.4g kg", b3Body_GetMass( body ) ); + ImGui::Text( "awake %s", b3Body_IsAwake( body ) ? "yes" : "no" ); + ImGui::Text( "enabled %s", b3Body_IsEnabled( body ) ? "yes" : "no" ); + ImGui::Text( "bullet %s", b3Body_IsBullet( body ) ? "yes" : "no" ); + ImGui::Text( "gravity scale %.2f", b3Body_GetGravityScale( body ) ); + ImGui::Text( "shapes %d joints %d", b3Body_GetShapeCount( body ), b3Body_GetJointCount( body ) ); + } + + void DrawShapeDetail( b3ShapeId shape ) + { + if ( ImGui::CollapsingHeader( "Shape", ImGuiTreeNodeFlags_DefaultOpen ) == false ) + { + return; + } + + ImGui::Text( "id %d", shape.index1 ); + ImGui::Text( "type %s", ReplayShapeTypeName( b3Shape_GetType( shape ) ) ); + b3Filter f = b3Shape_GetFilter( shape ); + ImGui::Text( "category 0x%016llx", (unsigned long long)f.categoryBits ); + ImGui::Text( "mask 0x%016llx", (unsigned long long)f.maskBits ); + ImGui::Text( "group %d", f.groupIndex ); + ImGui::Text( "density %.3g", b3Shape_GetDensity( shape ) ); + ImGui::Text( "friction %.3g", b3Shape_GetFriction( shape ) ); + ImGui::Text( "restitution %.3g", b3Shape_GetRestitution( shape ) ); + ImGui::Text( "sensor %s", b3Shape_IsSensor( shape ) ? "yes" : "no" ); + b3SurfaceMaterial mat = b3Shape_GetSurfaceMaterial( shape ); + ImGui::Text( "custom color 0x%06x", (unsigned)mat.customColor ); + b3AABB aabb = b3Shape_GetAABB( shape ); + ImGui::Text( "aabb (%.2f, %.2f, %.2f)", aabb.lowerBound.x, aabb.lowerBound.y, aabb.lowerBound.z ); + ImGui::Text( " (%.2f, %.2f, %.2f)", aabb.upperBound.x, aabb.upperBound.y, aabb.upperBound.z ); + } + + void DrawContactDetail( b3BodyId body ) + { + b3ContactData contacts[32]; + int capacity = b3Body_GetContactCapacity( body ); + if ( capacity > 32 ) + { + capacity = 32; + } + int count = b3Body_GetContactData( body, contacts, capacity ); + + char header[32]; + snprintf( header, sizeof( header ), "Contacts (%d)###contacts", count ); + if ( ImGui::CollapsingHeader( header ) == false ) + { + return; + } + + for ( int i = 0; i < count; ++i ) + { + ImGui::Text( "shapes %d / %d", contacts[i].shapeIdA.index1, contacts[i].shapeIdB.index1 ); + for ( int m = 0; m < contacts[i].manifoldCount; ++m ) + { + const b3Manifold* manifold = &contacts[i].manifolds[m]; + ImGui::Text( "normal (%.2f, %.2f, %.2f)", manifold->normal.x, manifold->normal.y, manifold->normal.z ); + ImGui::Text( "points %d", manifold->pointCount ); + for ( int p = 0; p < manifold->pointCount; ++p ) + { + const b3ManifoldPoint* mp = &manifold->points[p]; + ImGui::Text( " sep %.3f Pn %.2g", mp->separation, mp->normalImpulse ); + } + } + + ImGui::Separator(); + } + } + + void DrawJointDetail( b3JointId joint ) + { + if ( ImGui::CollapsingHeader( "Joint", ImGuiTreeNodeFlags_DefaultOpen ) == false ) + { + return; + } + + b3JointType type = b3Joint_GetType( joint ); + ImGui::Text( "type %s", ReplayJointTypeName( type ) ); + ImGui::Text( "body A %d", b3Joint_GetBodyA( joint ).index1 ); + ImGui::Text( "body B %d", b3Joint_GetBodyB( joint ).index1 ); + ImGui::Text( "collide %s", b3Joint_GetCollideConnected( joint ) ? "yes" : "no" ); + ImGui::Text( "force %.3g", b3Length( b3Joint_GetConstraintForce( joint ) ) ); + ImGui::Text( "torque %.3g", b3Length( b3Joint_GetConstraintTorque( joint ) ) ); + + switch ( type ) + { + case b3_revoluteJoint: + ImGui::Text( "angle %.1f deg", b3RevoluteJoint_GetAngle( joint ) * B3_RAD_TO_DEG ); + break; + case b3_prismaticJoint: + ImGui::Text( "translation %.3f", b3PrismaticJoint_GetTranslation( joint ) ); + break; + case b3_distanceJoint: + ImGui::Text( "length %.3f", b3DistanceJoint_GetCurrentLength( joint ) ); + break; + default: + break; + } + } + + // Detail for the selected recorded query: type, filter, origin, and the recorded hit shapes. + void DrawQueryDetail() + { + int count = b3RecPlayer_GetFrameQueryCount( m_player ); + if ( m_selQuery < 0 || m_selQuery >= count ) + { + ImGui::TextDisabled( "Query not present at this frame." ); + return; + } + + b3RecQueryInfo q = b3RecPlayer_GetFrameQuery( m_player, m_selQuery ); + if ( ImGui::CollapsingHeader( "Query", ImGuiTreeNodeFlags_DefaultOpen ) == false ) + { + return; + } + + ImGui::Text( "type %s", ReplayQueryTypeName( q.type ) ); + ImGui::Text( "category 0x%016llx", (unsigned long long)q.filter.categoryBits ); + ImGui::Text( "mask 0x%016llx", (unsigned long long)q.filter.maskBits ); + if ( q.type != b3_recQueryOverlapAABB ) + { + ImGui::Text( "origin (%.2f, %.2f, %.2f)", q.origin.x, q.origin.y, q.origin.z ); + } + ImGui::Text( "hits %d", q.hitCount ); + + // Hit shape ids as one wrapped list so a many-hit query stays compact. + char line[256]; + int len = 0; + for ( int h = 0; h < q.hitCount && len < (int)sizeof( line ) - 12; ++h ) + { + b3RecQueryHit hit = b3RecPlayer_GetFrameQueryHit( m_player, m_selQuery, h ); + len += snprintf( line + len, sizeof( line ) - len, "%d ", hit.shape.index1 ); + } + if ( q.hitCount > 0 ) + { + ImGui::TextWrapped( "hit shapes: %s", line ); + } + } + + // Timeline tab in the diagnostics drawer: file, transport, keyframe readout, scrubber, divergence. + void DrawMetricsTab() override + { + ImGuiTabItemFlags flags = m_selectTimelineTab ? ImGuiTabItemFlags_SetSelected : 0; + m_selectTimelineTab = false; + if ( ImGui::BeginTabItem( "Timeline", nullptr, flags ) == false ) + { + return; + } + + // File row, always available so a recording can be loaded even when none is open. + ImGui::Text( "File: %s %s", m_path, m_status ); + + if ( m_player == nullptr ) + { + ImGui::EndTabItem(); + return; + } + + float fontSize = ImGui::GetFontSize(); + + // Transport row: buttons, speed, loop, replay worker count. + DrawTransport(); + + ImGui::SameLine(); + const char* speedNames[] = { "0.25x", "0.5x", "1x", "2x", "4x" }; + const float speedValues[] = { 0.25f, 0.5f, 1.0f, 2.0f, 4.0f }; + int speedIndex = 2; + for ( int i = 0; i < 5; ++i ) + { + if ( m_speed == speedValues[i] ) + { + speedIndex = i; + } + } + ImGui::PushItemWidth( 5.0f * fontSize ); + if ( ImGui::Combo( "Speed", &speedIndex, speedNames, 5 ) ) + { + m_speed = speedValues[speedIndex]; + } + ImGui::PopItemWidth(); + ImGui::SameLine(); + ImGui::Checkbox( "Loop", &m_loop ); + ImGui::SameLine(); + + // Replaying at a different worker count re-partitions the constraint graph, a visual + // cross-thread determinism check. The setter applies it without rebuilding the world. + ImGui::PushItemWidth( 6.0f * fontSize ); + if ( ImGui::SliderInt( "Workers", &m_context->workerCount, 1, B3_MAX_WORKERS ) ) + { + b3RecPlayer_SetWorkerCount( m_player, m_context->workerCount ); + } + ImGui::PopItemWidth(); + + double mb = (double)b3RecPlayer_GetKeyframeBytes( m_player ) / ( 1024.0 * 1024.0 ); + ImGui::TextDisabled( "keyframe spacing %d frames, %.1f MB", b3RecPlayer_GetKeyframeInterval( m_player ), mb ); + + // Scrubber seeks both directions; backward uses the keyframe ring. + int scrub = b3RecPlayer_GetFrame( m_player ); + ImGui::PushItemWidth( -FLT_MIN ); + if ( ImGui::SliderInt( "##frame", &scrub, 0, m_info.frameCount ) ) + { + b3RecPlayer_SeekFrame( m_player, scrub ); + m_replayWorldId = b3RecPlayer_GetWorldId( m_player ); + m_frameAccumulator = 0.0f; + m_context->pause = true; + } + ImGui::PopItemWidth(); + + // Mark where the replay first diverged on the scrubber track. + int divergeFrame = b3RecPlayer_GetDivergeFrame( m_player ); + if ( divergeFrame >= 0 && m_info.frameCount > 0 ) + { + ImVec2 lo = ImGui::GetItemRectMin(); + ImVec2 hi = ImGui::GetItemRectMax(); + float t = (float)divergeFrame / (float)m_info.frameCount; + float x = lo.x + t * ( hi.x - lo.x ); + ImGui::GetWindowDrawList()->AddLine( ImVec2( x, lo.y ), ImVec2( x, hi.y ), IM_COL32( 220, 60, 60, 255 ), 2.0f ); + } + + float hz = m_info.timeStep > 0.0f ? 1.0f / m_info.timeStep : 0.0f; + b3Counters c = b3World_GetCounters( m_replayWorldId ); + ImGui::Text( "frames %d", m_info.frameCount ); + ImGui::SameLine(); + ImGui::Text( " %.0f hz, %d sub-steps", hz, m_info.subStepCount ); + ImGui::SameLine(); + ImGui::Text( " bodies %d shapes %d contacts %d joints %d", c.bodyCount, c.shapeCount, c.contactCount, + c.jointCount ); + + if ( divergeFrame >= 0 ) + { + ImGui::SameLine(); + ImGui::TextColored( PanelColor( b3_colorRed ), " diverged at frame %d", divergeFrame ); + } + + ImGui::EndTabItem(); + } + + // Left click selects a shape to inspect by its creation ordinal, so the selection survives a + // backward seek that rebuilds the world. Picking only reads the world, it never creates the drag + // joint the base sample does, so the replay is not mutated. + void MouseDown( b3Vec2 p, int button, int modifiers ) override + { + if ( button != 0 || modifiers != 0 || B3_IS_NULL( m_replayWorldId ) ) + { + return; + } + + PickRay pickRay = m_camera->BuildPickRay( p.x, p.y ); + b3RayResult result = b3World_CastRayClosest( m_replayWorldId, pickRay.origin, pickRay.translation, b3DefaultQueryFilter() ); + SelectShape( result.hit ? result.shapeId : b3_nullShapeId ); + } + + void MouseUp( b3Vec2, int ) override + { + } + + void MouseMove( b3Vec2 ) override + { + } + + static Sample* Create( SampleContext* context ) + { + return new ReplayViewer( context ); + } + + b3RecPlayer* m_player; + b3WorldId m_replayWorldId; // player-owned world we draw and pick; separate from the empty base world + b3RecPlayerInfo m_info; // cached at load for the timeline readout and camera framing + char m_path[256]; + char m_status[128]; + float m_speed; + float m_frameAccumulator; + bool m_loop; + + bool m_selectTimelineTab; // one-shot: focus the Timeline tab on the next draw + bool m_prevShowMetrics; // restore the drawer state on exit + + // Load popup state. A fresh open configures the keyframe policy here, then the popup switches to a + // progress bar while every keyframe is generated up front. Temporaries hold the in-popup edits so + // Cancel leaves the persisted settings untouched. + bool m_requestLoadPopup; + bool m_generating; + int m_popupBudgetMB; + int m_popupMinInterval; + + // Selection by creation ordinal so it survives a backward seek that rebuilds the world. + SelKind m_selKind; + int m_selBodyOrdinal; + int m_selSlot; // shape or joint slot within the selected body + int m_selQuery; // query index, only meaningful for the current frame + bool m_revealSelection; // one-shot: expand and scroll the tree to a viewport pick +}; + +static int sampleReplayViewer = RegisterReplay( "Replay", "Viewer", ReplayViewer::Create ); diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 288a14b..3184204 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -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 diff --git a/src/body.c b/src/body.c index fa81831..d31fa18 100644 --- a/src/body.c +++ b/src/body.c @@ -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 ) diff --git a/src/compound.c b/src/compound.c index b3d1ed9..29da3c6 100644 --- a/src/compound.c +++ b/src/compound.c @@ -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, diff --git a/src/compound.h b/src/compound.h index 510402d..1f4d7e5 100644 --- a/src/compound.h +++ b/src/compound.h @@ -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 ); diff --git a/src/contact.c b/src/contact.c index 4b592f3..3486e3c 100644 --- a/src/contact.c +++ b/src/contact.c @@ -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 = diff --git a/src/distance_joint.c b/src/distance_joint.c index 743f6f2..9185010 100644 --- a/src/distance_joint.c +++ b/src/distance_joint.c @@ -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; } diff --git a/src/height_field.c b/src/height_field.c index aa16fb8..1b0307f 100644 --- a/src/height_field.c +++ b/src/height_field.c @@ -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 ) ); diff --git a/src/joint.c b/src/joint.c index b747598..83bd301 100644 --- a/src/joint.c +++ b/src/joint.c @@ -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; diff --git a/src/mesh_contact.c b/src/mesh_contact.c index 31efde5..d3144b2 100644 --- a/src/mesh_contact.c +++ b/src/mesh_contact.c @@ -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 ); diff --git a/src/motor_joint.c b/src/motor_joint.c index d58b3ce..734d497 100644 --- a/src/motor_joint.c +++ b/src/motor_joint.c @@ -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 diff --git a/src/parallel_joint.c b/src/parallel_joint.c index 591bfe3..7390a21 100644 --- a/src/parallel_joint.c +++ b/src/parallel_joint.c @@ -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; } diff --git a/src/physics_world.c b/src/physics_world.c index c668b15..06eeb40 100644 --- a/src/physics_world.c +++ b/src/physics_world.c @@ -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; } diff --git a/src/physics_world.h b/src/physics_world.h index 9c3092a..8387e2a 100644 --- a/src/physics_world.h +++ b/src/physics_world.h @@ -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; diff --git a/src/prismatic_joint.c b/src/prismatic_joint.c index 499ff40..74f91c3 100644 --- a/src/prismatic_joint.c +++ b/src/prismatic_joint.c @@ -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; } diff --git a/src/recording.c b/src/recording.c new file mode 100644 index 0000000..87dbf04 --- /dev/null +++ b/src/recording.c @@ -0,0 +1,1094 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +#if defined( _MSC_VER ) && !defined( _CRT_SECURE_NO_WARNINGS ) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include "recording.h" + +#include "body.h" +#include "compound.h" +#include "physics_world.h" +#include "world_snapshot.h" + +#include "box3d/box3d.h" +#include "box3d/constants.h" + +#include +#include + +// Buffer helpers + +void b3RecBufAppend( b3RecBuffer* buf, const void* data, int size ) +{ + if ( size <= 0 ) + { + return; + } + + if ( buf->countOnly ) + { + buf->size += size; + return; + } + + if ( buf->size + size > buf->capacity ) + { + int newCap = buf->capacity * 2; + if ( newCap < buf->size + size + 64 ) + { + newCap = buf->size + size + 64; + } + if ( buf->data == NULL ) + { + buf->data = b3Alloc( (size_t)newCap ); + } + else + { + buf->data = b3GrowAlloc( buf->data, buf->capacity, newCap ); + } + buf->capacity = newCap; + } + + memcpy( buf->data + buf->size, data, (size_t)size ); + buf->size += size; +} + +void b3RecBufFree( b3RecBuffer* buf ) +{ + if ( buf->data != NULL ) + { + b3Free( buf->data, (size_t)buf->capacity ); + buf->data = NULL; + buf->capacity = 0; + buf->size = 0; + } +} + +// Write primitives + +void b3RecW_U8( b3RecBuffer* buf, uint8_t v ) +{ + b3RecBufAppend( buf, &v, 1 ); +} + +void b3RecW_U16( b3RecBuffer* buf, uint16_t v ) +{ + uint8_t b[2] = { (uint8_t)v, (uint8_t)( v >> 8 ) }; + b3RecBufAppend( buf, b, 2 ); +} + +void b3RecW_U32( b3RecBuffer* buf, uint32_t v ) +{ + uint8_t b[4] = { (uint8_t)v, (uint8_t)( v >> 8 ), (uint8_t)( v >> 16 ), (uint8_t)( v >> 24 ) }; + b3RecBufAppend( buf, b, 4 ); +} + +void b3RecW_U64( b3RecBuffer* buf, uint64_t v ) +{ + uint8_t b[8] = { (uint8_t)v, (uint8_t)( v >> 8 ), (uint8_t)( v >> 16 ), (uint8_t)( v >> 24 ), + (uint8_t)( v >> 32 ), (uint8_t)( v >> 40 ), (uint8_t)( v >> 48 ), (uint8_t)( v >> 56 ) }; + b3RecBufAppend( buf, b, 8 ); +} + +void b3RecW_I32( b3RecBuffer* buf, int32_t v ) +{ + b3RecW_U32( buf, (uint32_t)v ); +} + +void b3RecW_F32( b3RecBuffer* buf, float v ) +{ + uint32_t bits; + memcpy( &bits, &v, 4 ); + b3RecW_U32( buf, bits ); +} + +void b3RecW_F64( b3RecBuffer* buf, double v ) +{ + uint64_t bits; + memcpy( &bits, &v, 8 ); + b3RecW_U64( buf, bits ); +} + +void b3RecW_BOOL( b3RecBuffer* buf, bool v ) +{ + b3RecW_U8( buf, v ? 1u : 0u ); +} + +void b3RecW_VEC3( b3RecBuffer* buf, b3Vec3 v ) +{ + b3RecW_F32( buf, v.x ); + b3RecW_F32( buf, v.y ); + b3RecW_F32( buf, v.z ); +} + +void b3RecW_QUAT( b3RecBuffer* buf, b3Quat v ) +{ + b3RecW_F32( buf, v.v.x ); + b3RecW_F32( buf, v.v.y ); + b3RecW_F32( buf, v.v.z ); + b3RecW_F32( buf, v.s ); +} + +void b3RecW_TRANSFORM( b3RecBuffer* buf, b3Transform v ) +{ + b3RecW_VEC3( buf, v.p ); + b3RecW_QUAT( buf, v.q ); +} + +// World position at full precision so recordings reproduce the simulation far from the origin. +// In the float build this is three floats, wire-identical to VEC3. +void b3RecW_POSITION( b3RecBuffer* buf, b3Pos v ) +{ +#if defined( BOX3D_DOUBLE_PRECISION ) + b3RecW_F64( buf, v.x ); + b3RecW_F64( buf, v.y ); + b3RecW_F64( buf, v.z ); +#else + b3RecW_F32( buf, v.x ); + b3RecW_F32( buf, v.y ); + b3RecW_F32( buf, v.z ); +#endif +} + +void b3RecW_WORLDXF( b3RecBuffer* buf, b3WorldTransform v ) +{ + b3RecW_POSITION( buf, v.p ); + b3RecW_QUAT( buf, v.q ); +} + +void b3RecW_MATRIX3( b3RecBuffer* buf, b3Matrix3 v ) +{ + b3RecW_VEC3( buf, v.cx ); + b3RecW_VEC3( buf, v.cy ); + b3RecW_VEC3( buf, v.cz ); +} + +void b3RecW_AABB( b3RecBuffer* buf, b3AABB v ) +{ + b3RecW_VEC3( buf, v.lowerBound ); + b3RecW_VEC3( buf, v.upperBound ); +} + +void b3RecW_QUERYFILTER( b3RecBuffer* buf, b3QueryFilter v ) +{ + b3RecW_U64( buf, v.categoryBits ); + b3RecW_U64( buf, v.maskBits ); +} + +// Variable length: count, then count points, then radius. The point cloud lives behind a pointer so +// it cannot ride along as POD. +void b3RecW_SHAPEPROXY( b3RecBuffer* buf, b3ShapeProxy v ) +{ + int count = v.count; + if ( count < 0 ) + count = 0; + if ( count > B3_MAX_SHAPE_CAST_POINTS ) + count = B3_MAX_SHAPE_CAST_POINTS; + b3RecW_I32( buf, count ); + for ( int i = 0; i < count; ++i ) + { + b3RecW_VEC3( buf, v.points[i] ); + } + b3RecW_F32( buf, v.radius ); +} + +void b3RecW_TREESTATS( b3RecBuffer* buf, b3TreeStats v ) +{ + b3RecW_I32( buf, v.nodeVisits ); + b3RecW_I32( buf, v.leafVisits ); +} + +void b3RecW_RAYRESULT( b3RecBuffer* buf, b3RayResult v ) +{ + b3RecW_SHAPEID( buf, v.shapeId ); + b3RecW_POSITION( buf, v.point ); + b3RecW_VEC3( buf, v.normal ); + b3RecW_U64( buf, v.userMaterialId ); + b3RecW_F32( buf, v.fraction ); + b3RecW_I32( buf, v.triangleIndex ); + b3RecW_I32( buf, v.childIndex ); + b3RecW_BOOL( buf, v.hit ); +} + +void b3RecW_PLANERESULT( b3RecBuffer* buf, b3PlaneResult v ) +{ + b3RecW_VEC3( buf, v.plane.normal ); + b3RecW_F32( buf, v.plane.offset ); + b3RecW_VEC3( buf, v.point ); +} + +void b3RecW_WORLDID( b3RecBuffer* buf, b3WorldId v ) +{ + b3RecW_U32( buf, b3StoreWorldId( v ) ); +} + +void b3RecW_BODYID( b3RecBuffer* buf, b3BodyId v ) +{ + b3RecW_U64( buf, b3StoreBodyId( v ) ); +} + +void b3RecW_SHAPEID( b3RecBuffer* buf, b3ShapeId v ) +{ + b3RecW_U64( buf, b3StoreShapeId( v ) ); +} + +void b3RecW_JOINTID( b3RecBuffer* buf, b3JointId v ) +{ + b3RecW_U64( buf, b3StoreJointId( v ) ); +} + +// Pointer-free POD; pointerWidth in the header gates the layout on replay +void b3RecW_SPHERE( b3RecBuffer* buf, b3Sphere v ) +{ + b3RecBufAppend( buf, &v, (int)sizeof( b3Sphere ) ); +} + +void b3RecW_CAPSULE( b3RecBuffer* buf, b3Capsule v ) +{ + b3RecBufAppend( buf, &v, (int)sizeof( b3Capsule ) ); +} + +void b3RecW_GEOMID( b3RecBuffer* buf, uint32_t v ) +{ + b3RecW_U32( buf, v ); +} + +void b3RecW_FILTER( b3RecBuffer* buf, b3Filter v ) +{ + b3RecW_U64( buf, v.categoryBits ); + b3RecW_U64( buf, v.maskBits ); + b3RecW_I32( buf, v.groupIndex ); +} + +void b3RecW_MATERIAL( b3RecBuffer* buf, b3SurfaceMaterial v ) +{ + b3RecW_F32( buf, v.friction ); + b3RecW_F32( buf, v.restitution ); + b3RecW_F32( buf, v.rollingResistance ); + b3RecW_VEC3( buf, v.tangentVelocity ); + b3RecW_U64( buf, v.userMaterialId ); + b3RecW_U32( buf, v.customColor ); +} + +void b3RecW_MASSDATA( b3RecBuffer* buf, b3MassData v ) +{ + b3RecW_F32( buf, v.mass ); + b3RecW_VEC3( buf, v.center ); + b3RecW_MATRIX3( buf, v.inertia ); +} + +void b3RecW_LOCKS( b3RecBuffer* buf, b3MotionLocks v ) +{ + b3RecW_BOOL( buf, v.linearX ); + b3RecW_BOOL( buf, v.linearY ); + b3RecW_BOOL( buf, v.linearZ ); + b3RecW_BOOL( buf, v.angularX ); + b3RecW_BOOL( buf, v.angularY ); + b3RecW_BOOL( buf, v.angularZ ); +} + +void b3RecW_STR( b3RecBuffer* buf, const char* s ) +{ + if ( s == NULL ) + { + b3RecW_U16( buf, 0xFFFFu ); + return; + } + int len = 0; + while ( s[len] != '\0' && len < 65534 ) + { + len++; + } + b3RecW_U16( buf, (uint16_t)len ); + if ( len > 0 ) + { + b3RecBufAppend( buf, s, len ); + } +} + +// Hand-written def helpers. Zero pointer and cookie fields before serializing. +// Readers call b3Default*Def() first to get the cookie, then overwrite fields. + +// Tripwire: each def serializer below is paired with a reader in recording_replay.c, and the two must +// stay field-for-field in sync. Add a field to a def and the size changes, firing the matching assert +// so the writer and reader both get updated. Only enforced on the 64-bit target; each def lists the +// single-precision and double-precision sizes (equal for most), so either build configuration passes. +_Static_assert( sizeof( void* ) != 8 || sizeof( b3ExplosionDef ) == 32 || sizeof( b3ExplosionDef ) == 48, + "b3ExplosionDef changed: update b3RecW_EXPLOSIONDEF and b3RecR_EXPLOSIONDEF together" ); +_Static_assert( sizeof( void* ) != 8 || sizeof( b3BodyDef ) == 104 || sizeof( b3BodyDef ) == 120, + "b3BodyDef changed: update b3RecW_BODYDEF and b3RecR_BODYDEF together" ); +_Static_assert( sizeof( void* ) != 8 || sizeof( b3ShapeDef ) == 120, + "b3ShapeDef changed: update b3RecW_SHAPEDEF and b3RecR_SHAPEDEF together" ); +_Static_assert( sizeof( void* ) != 8 || sizeof( b3ParallelJointDef ) == 128, + "b3ParallelJointDef changed: update b3RecW_PARALLELJOINTDEF and its reader together" ); +_Static_assert( sizeof( void* ) != 8 || sizeof( b3DistanceJointDef ) == 160, + "b3DistanceJointDef changed: update b3RecW_DISTANCEJOINTDEF and its reader together" ); +_Static_assert( sizeof( void* ) != 8 || sizeof( b3FilterJointDef ) == 112, + "b3FilterJointDef changed: update b3RecW_FILTERJOINTDEF and its reader together" ); +_Static_assert( sizeof( void* ) != 8 || sizeof( b3MotorJointDef ) == 168, + "b3MotorJointDef changed: update b3RecW_MOTORJOINTDEF and its reader together" ); +_Static_assert( sizeof( void* ) != 8 || sizeof( b3PrismaticJointDef ) == 152, + "b3PrismaticJointDef changed: update b3RecW_PRISMATICJOINTDEF and its reader together" ); +_Static_assert( sizeof( void* ) != 8 || sizeof( b3RevoluteJointDef ) == 152, + "b3RevoluteJointDef changed: update b3RecW_REVOLUTEJOINTDEF and its reader together" ); +_Static_assert( sizeof( void* ) != 8 || sizeof( b3SphericalJointDef ) == 184, + "b3SphericalJointDef changed: update b3RecW_SPHERICALJOINTDEF and its reader together" ); +_Static_assert( sizeof( void* ) != 8 || sizeof( b3WeldJointDef ) == 128, + "b3WeldJointDef changed: update b3RecW_WELDJOINTDEF and its reader together" ); +_Static_assert( sizeof( void* ) != 8 || sizeof( b3WheelJointDef ) == 184, + "b3WheelJointDef changed: update b3RecW_WHEELJOINTDEF and its reader together" ); + +void b3RecW_EXPLOSIONDEF( b3RecBuffer* buf, b3ExplosionDef v ) +{ + b3RecW_U64( buf, v.maskBits ); + b3RecW_POSITION( buf, v.position ); + b3RecW_F32( buf, v.radius ); + b3RecW_F32( buf, v.falloff ); + b3RecW_F32( buf, v.impulsePerArea ); +} + +void b3RecW_BODYDEF( b3RecBuffer* buf, b3BodyDef v ) +{ + b3RecW_I32( buf, (int32_t)v.type ); + b3RecW_POSITION( buf, v.position ); + b3RecW_QUAT( buf, v.rotation ); + b3RecW_VEC3( buf, v.linearVelocity ); + b3RecW_VEC3( buf, v.angularVelocity ); + b3RecW_F32( buf, v.linearDamping ); + b3RecW_F32( buf, v.angularDamping ); + b3RecW_F32( buf, v.gravityScale ); + b3RecW_F32( buf, v.sleepThreshold ); + b3RecW_STR( buf, v.name ); + // userData: not preserved + b3RecW_U64( buf, 0u ); + b3RecW_LOCKS( buf, v.motionLocks ); + b3RecW_BOOL( buf, v.enableSleep ); + b3RecW_BOOL( buf, v.isAwake ); + b3RecW_BOOL( buf, v.isBullet ); + b3RecW_BOOL( buf, v.isEnabled ); + b3RecW_BOOL( buf, v.allowFastRotation ); + b3RecW_BOOL( buf, v.enableContactRecycling ); + // internalValue omitted +} + +void b3RecW_SHAPEDEF( b3RecBuffer* buf, b3ShapeDef v ) +{ + b3RecW_STR( buf, v.name ); + // userData: not preserved + b3RecW_U64( buf, 0u ); + // Per-triangle materials: length-prefixed so the reader can rebuild the array. + // Guard NULL so a default def (materialCount=0, materials=NULL) round-trips cleanly. + int matCount = ( v.materials != NULL ) ? v.materialCount : 0; + b3RecW_I32( buf, matCount ); + for ( int i = 0; i < matCount; ++i ) + { + b3RecW_MATERIAL( buf, v.materials[i] ); + } + b3RecW_MATERIAL( buf, v.baseMaterial ); + b3RecW_F32( buf, v.density ); + b3RecW_F32( buf, v.explosionScale ); + b3RecW_FILTER( buf, v.filter ); + b3RecW_BOOL( buf, v.enableCustomFiltering ); + b3RecW_BOOL( buf, v.isSensor ); + b3RecW_BOOL( buf, v.enableSensorEvents ); + b3RecW_BOOL( buf, v.enableContactEvents ); + b3RecW_BOOL( buf, v.enableHitEvents ); + b3RecW_BOOL( buf, v.enablePreSolveEvents ); + b3RecW_BOOL( buf, v.invokeContactCreation ); + b3RecW_BOOL( buf, v.updateBodyMass ); + // internalValue omitted +} + +// Joint defs share a base. Body ids are written as packed ids for replay remapping. +static void b3RecW_JointBase( b3RecBuffer* buf, const b3JointDef* base ) +{ + // userData: not preserved + b3RecW_U64( buf, 0u ); + b3RecW_BODYID( buf, base->bodyIdA ); + b3RecW_BODYID( buf, base->bodyIdB ); + b3RecW_TRANSFORM( buf, base->localFrameA ); + b3RecW_TRANSFORM( buf, base->localFrameB ); + b3RecW_F32( buf, base->forceThreshold ); + b3RecW_F32( buf, base->torqueThreshold ); + b3RecW_F32( buf, base->constraintHertz ); + b3RecW_F32( buf, base->constraintDampingRatio ); + b3RecW_F32( buf, base->drawScale ); + b3RecW_BOOL( buf, base->collideConnected ); + // internalValue omitted +} + +void b3RecW_PARALLELJOINTDEF( b3RecBuffer* buf, b3ParallelJointDef v ) +{ + b3RecW_JointBase( buf, &v.base ); + b3RecW_F32( buf, v.hertz ); + b3RecW_F32( buf, v.dampingRatio ); + b3RecW_F32( buf, v.maxTorque ); +} + +void b3RecW_DISTANCEJOINTDEF( b3RecBuffer* buf, b3DistanceJointDef v ) +{ + b3RecW_JointBase( buf, &v.base ); + b3RecW_F32( buf, v.length ); + b3RecW_BOOL( buf, v.enableSpring ); + b3RecW_F32( buf, v.lowerSpringForce ); + b3RecW_F32( buf, v.upperSpringForce ); + b3RecW_F32( buf, v.hertz ); + b3RecW_F32( buf, v.dampingRatio ); + b3RecW_BOOL( buf, v.enableLimit ); + b3RecW_F32( buf, v.minLength ); + b3RecW_F32( buf, v.maxLength ); + b3RecW_BOOL( buf, v.enableMotor ); + b3RecW_F32( buf, v.maxMotorForce ); + b3RecW_F32( buf, v.motorSpeed ); +} + +void b3RecW_FILTERJOINTDEF( b3RecBuffer* buf, b3FilterJointDef v ) +{ + b3RecW_JointBase( buf, &v.base ); +} + +void b3RecW_MOTORJOINTDEF( b3RecBuffer* buf, b3MotorJointDef v ) +{ + b3RecW_JointBase( buf, &v.base ); + b3RecW_VEC3( buf, v.linearVelocity ); + b3RecW_F32( buf, v.maxVelocityForce ); + b3RecW_VEC3( buf, v.angularVelocity ); + b3RecW_F32( buf, v.maxVelocityTorque ); + b3RecW_F32( buf, v.linearHertz ); + b3RecW_F32( buf, v.linearDampingRatio ); + b3RecW_F32( buf, v.maxSpringForce ); + b3RecW_F32( buf, v.angularHertz ); + b3RecW_F32( buf, v.angularDampingRatio ); + b3RecW_F32( buf, v.maxSpringTorque ); +} + +void b3RecW_PRISMATICJOINTDEF( b3RecBuffer* buf, b3PrismaticJointDef v ) +{ + b3RecW_JointBase( buf, &v.base ); + b3RecW_BOOL( buf, v.enableSpring ); + b3RecW_F32( buf, v.hertz ); + b3RecW_F32( buf, v.dampingRatio ); + b3RecW_F32( buf, v.targetTranslation ); + b3RecW_BOOL( buf, v.enableLimit ); + b3RecW_F32( buf, v.lowerTranslation ); + b3RecW_F32( buf, v.upperTranslation ); + b3RecW_BOOL( buf, v.enableMotor ); + b3RecW_F32( buf, v.maxMotorForce ); + b3RecW_F32( buf, v.motorSpeed ); +} + +void b3RecW_REVOLUTEJOINTDEF( b3RecBuffer* buf, b3RevoluteJointDef v ) +{ + b3RecW_JointBase( buf, &v.base ); + b3RecW_F32( buf, v.targetAngle ); + b3RecW_BOOL( buf, v.enableSpring ); + b3RecW_F32( buf, v.hertz ); + b3RecW_F32( buf, v.dampingRatio ); + b3RecW_BOOL( buf, v.enableLimit ); + b3RecW_F32( buf, v.lowerAngle ); + b3RecW_F32( buf, v.upperAngle ); + b3RecW_BOOL( buf, v.enableMotor ); + b3RecW_F32( buf, v.maxMotorTorque ); + b3RecW_F32( buf, v.motorSpeed ); +} + +void b3RecW_SPHERICALJOINTDEF( b3RecBuffer* buf, b3SphericalJointDef v ) +{ + b3RecW_JointBase( buf, &v.base ); + b3RecW_BOOL( buf, v.enableSpring ); + b3RecW_F32( buf, v.hertz ); + b3RecW_F32( buf, v.dampingRatio ); + b3RecW_QUAT( buf, v.targetRotation ); + b3RecW_BOOL( buf, v.enableConeLimit ); + b3RecW_F32( buf, v.coneAngle ); + b3RecW_BOOL( buf, v.enableTwistLimit ); + b3RecW_F32( buf, v.lowerTwistAngle ); + b3RecW_F32( buf, v.upperTwistAngle ); + b3RecW_BOOL( buf, v.enableMotor ); + b3RecW_F32( buf, v.maxMotorTorque ); + b3RecW_VEC3( buf, v.motorVelocity ); +} + +void b3RecW_WELDJOINTDEF( b3RecBuffer* buf, b3WeldJointDef v ) +{ + b3RecW_JointBase( buf, &v.base ); + b3RecW_F32( buf, v.linearHertz ); + b3RecW_F32( buf, v.angularHertz ); + b3RecW_F32( buf, v.linearDampingRatio ); + b3RecW_F32( buf, v.angularDampingRatio ); +} + +void b3RecW_WHEELJOINTDEF( b3RecBuffer* buf, b3WheelJointDef v ) +{ + b3RecW_JointBase( buf, &v.base ); + b3RecW_BOOL( buf, v.enableSuspensionSpring ); + b3RecW_F32( buf, v.suspensionHertz ); + b3RecW_F32( buf, v.suspensionDampingRatio ); + b3RecW_BOOL( buf, v.enableSuspensionLimit ); + b3RecW_F32( buf, v.lowerSuspensionLimit ); + b3RecW_F32( buf, v.upperSuspensionLimit ); + b3RecW_BOOL( buf, v.enableSpinMotor ); + b3RecW_F32( buf, v.maxSpinTorque ); + b3RecW_F32( buf, v.spinSpeed ); + b3RecW_BOOL( buf, v.enableSteering ); + b3RecW_F32( buf, v.steeringHertz ); + b3RecW_F32( buf, v.steeringDampingRatio ); + b3RecW_F32( buf, v.targetSteeringAngle ); + b3RecW_F32( buf, v.maxSteeringTorque ); + b3RecW_BOOL( buf, v.enableSteeringLimit ); + b3RecW_F32( buf, v.lowerSteeringLimit ); + b3RecW_F32( buf, v.upperSteeringLimit ); +} + +// Query recording. A query collects a variable number of hits through a user callback, so the count +// is not known until the callback stops firing. The record is built in a local buffer with a +// reserved hit-count slot, then committed whole under the lock so concurrent query threads never +// interleave records in the shared buffer. + +int b3RecReserveU32( b3RecBuffer* buf ) +{ + int offset = buf->size; + uint8_t zero[4] = { 0, 0, 0, 0 }; + b3RecBufAppend( buf, zero, 4 ); + return offset; +} + +void b3RecPatchU32( b3RecBuffer* buf, int offset, uint32_t v ) +{ + B3_ASSERT( offset >= 0 && offset + 4 <= buf->size ); + uint8_t* p = buf->data + offset; + p[0] = (uint8_t)v; + p[1] = (uint8_t)( v >> 8 ); + p[2] = (uint8_t)( v >> 16 ); + p[3] = (uint8_t)( v >> 24 ); +} + +void b3RecCommitRecord( b3Recording* rec, uint8_t opcode, const uint8_t* payload, int payloadSize ) +{ + B3_ASSERT( payloadSize >= 0 && payloadSize < ( 1 << 24 ) ); + b3LockMutex( rec->lock ); + b3RecW_U8( &rec->buffer, opcode ); + uint8_t sz[3] = { (uint8_t)payloadSize, (uint8_t)( payloadSize >> 8 ), (uint8_t)( payloadSize >> 16 ) }; + b3RecBufAppend( &rec->buffer, sz, 3 ); + b3RecBufAppend( &rec->buffer, payload, payloadSize ); + b3UnlockMutex( rec->lock ); +} + +void b3RecQueryBegin( b3RecQueryWriter* w, void* context ) +{ + w->buf = ( b3RecBuffer ){ 0 }; + w->userFcn.overlapFcn = NULL; + w->userContext = context; + w->hitCount = 0; + w->countOffset = 0; +} + +void b3RecQueryCommit( b3Recording* rec, uint8_t opcode, b3RecQueryWriter* w ) +{ + b3RecCommitRecord( rec, opcode, w->buf.data, w->buf.size ); + b3RecBufFree( &w->buf ); +} + +bool b3RecOverlapTrampoline( b3ShapeId id, void* ctx ) +{ + b3RecQueryWriter* w = (b3RecQueryWriter*)ctx; + // The user fcn is NULL for an unfiltered mover cast: accept all, still record the decision so + // replay reproduces the same per-shape accept stream. + bool ret = w->userFcn.overlapFcn != NULL ? w->userFcn.overlapFcn( id, w->userContext ) : true; + b3RecW_SHAPEID( &w->buf, id ); + b3RecW_BOOL( &w->buf, ret ); + w->hitCount++; + return ret; +} + +float b3RecCastTrampoline( b3ShapeId id, b3Pos point, b3Vec3 normal, float fraction, uint64_t userMaterialId, int triangleIndex, + int childIndex, void* ctx ) +{ + b3RecQueryWriter* w = (b3RecQueryWriter*)ctx; + float ret = w->userFcn.castFcn( id, point, normal, fraction, userMaterialId, triangleIndex, childIndex, w->userContext ); + b3RecW_SHAPEID( &w->buf, id ); + b3RecW_POSITION( &w->buf, point ); + b3RecW_VEC3( &w->buf, normal ); + b3RecW_F32( &w->buf, fraction ); + b3RecW_U64( &w->buf, userMaterialId ); + b3RecW_I32( &w->buf, triangleIndex ); + b3RecW_I32( &w->buf, childIndex ); + b3RecW_F32( &w->buf, ret ); + w->hitCount++; + return ret; +} + +// 3D delivers every plane for one shape in a single call. Record the shape, its plane count, each +// plane, then the user return so replay reproduces the same per-shape batch. One hit per shape. +bool b3RecPlaneTrampoline( b3ShapeId id, const b3PlaneResult* planes, int planeCount, void* ctx ) +{ + b3RecQueryWriter* w = (b3RecQueryWriter*)ctx; + bool ret = w->userFcn.planeFcn( id, planes, planeCount, w->userContext ); + b3RecW_SHAPEID( &w->buf, id ); + b3RecW_I32( &w->buf, planeCount ); + for ( int i = 0; i < planeCount; ++i ) + { + b3RecW_PLANERESULT( &w->buf, planes[i] ); + } + b3RecW_BOOL( &w->buf, ret ); + w->hitCount++; + return ret; +} + +// Record framing + +void b3RecBeginRecord( b3Recording* rec, uint8_t opcode ) +{ + b3RecW_U8( &rec->buffer, opcode ); + rec->recordStart = rec->buffer.size; + // Reserve 3 bytes for the u24 payload size, backpatched in b3RecEndRecord. + uint8_t zero[3] = { 0, 0, 0 }; + b3RecBufAppend( &rec->buffer, zero, 3 ); +} + +void b3RecEndRecord( b3Recording* rec ) +{ + int payloadSize = rec->buffer.size - rec->recordStart - 3; + B3_ASSERT( payloadSize >= 0 && payloadSize < ( 1 << 24 ) ); + uint8_t* p = rec->buffer.data + rec->recordStart; + p[0] = (uint8_t)payloadSize; + p[1] = (uint8_t)( payloadSize >> 8 ); + p[2] = (uint8_t)( payloadSize >> 16 ); +} + +// Codegen pass 1b: arg writers +#define ARG( TAG, field ) b3RecW_##TAG( &rec->buffer, a->field ); +#define B3_REC_OP( op, Name, RET, ... ) \ + void b3RecWriteArgs_##Name( b3Recording* rec, const b3RecArgs_##Name* a ) \ + { \ + __VA_ARGS__ \ + } +#include "recording_ops.inl" +#undef B3_REC_OP +#undef ARG + +// Codegen: full writers +#define B3_REC_OP( op, Name, RET, ... ) \ + void b3RecWrite_##Name( b3Recording* rec, const b3RecArgs_##Name* a ) \ + { \ + b3RecBeginRecord( rec, (uint8_t)( op ) ); \ + b3RecWriteArgs_##Name( rec, a ); \ + b3RecEndRecord( rec ); \ + } +#include "recording_ops.inl" +#undef B3_REC_OP + +// Codegen: create-op writers that append the returned id inside the record +#define B3_REC_RETWRITE( op, Name, idType, idW ) \ + void b3RecWriteRet_##Name( b3Recording* rec, const b3RecArgs_##Name* a, idType id ) \ + { \ + b3RecBeginRecord( rec, (uint8_t)( op ) ); \ + b3RecWriteArgs_##Name( rec, a ); \ + idW( &rec->buffer, id ); \ + b3RecEndRecord( rec ); \ + } +#define B3_REC_RETWRITE_RET_NONE( op, Name ) +#define B3_REC_RETWRITE_RET_BODYID( op, Name ) B3_REC_RETWRITE( op, Name, b3BodyId, b3RecW_BODYID ) +#define B3_REC_RETWRITE_RET_SHAPEID( op, Name ) B3_REC_RETWRITE( op, Name, b3ShapeId, b3RecW_SHAPEID ) +#define B3_REC_RETWRITE_RET_JOINTID( op, Name ) B3_REC_RETWRITE( op, Name, b3JointId, b3RecW_JOINTID ) +#define B3_REC_OP( op, Name, RET, ... ) B3_REC_RETWRITE_##RET( op, Name ) +#include "recording_ops.inl" +#undef B3_REC_OP +#undef B3_REC_RETWRITE_RET_NONE +#undef B3_REC_RETWRITE_RET_BODYID +#undef B3_REC_RETWRITE_RET_SHAPEID +#undef B3_REC_RETWRITE_RET_JOINTID +#undef B3_REC_RETWRITE + +// Geometry registry + +// Fold a 32-bit hash into 64 bits. Collisions are caught by the byteCount+memcmp fallback. +uint64_t b3Hash64Blob( const uint8_t* bytes, int n ) +{ + uint32_t h = b3Hash( B3_HASH_INIT, bytes, n ); + return (uint64_t)h | ( (uint64_t)b3NonZeroHash( ~h ) << 32 ); +} + +// Content hash to entry id, so dedup is O(1) average instead of a linear scan. A 64-bit content-hash +// collision between distinct blobs is still caught by the byteCount + memcmp check, so it can never +// return the wrong id; the worst case is a missed dedup in that astronomically unlikely event. +#define NAME b3GeometryHashMap +#define KEY_TY uint64_t +#define VAL_TY uint32_t +#define HASH_FN vt_hash_integer +#define CMPR_FN vt_cmpr_integer +#define MALLOC_FN b3Alloc +#define FREE_FN b3Free +#include "verstable.h" + +uint32_t b3InternGeometry( b3GeometryRegistry* reg, b3GeometryKind kind, uint64_t contentHash, + uint8_t* bytes, int byteCount ) +{ + if ( reg->dedupMap == NULL ) + { + b3GeometryHashMap* fresh = (b3GeometryHashMap*)b3Alloc( sizeof( b3GeometryHashMap ) ); + b3GeometryHashMap_init( fresh ); + reg->dedupMap = fresh; + } + b3GeometryHashMap* map = (b3GeometryHashMap*)reg->dedupMap; + + b3GeometryHashMap_itr itr = b3GeometryHashMap_get( map, contentHash ); + bool hashPresent = b3GeometryHashMap_is_end( itr ) == false; + if ( hashPresent ) + { + b3GeometryEntry* e = reg->entries + itr.data->val; + if ( e->byteCount == byteCount && memcmp( e->bytes, bytes, (size_t)byteCount ) == 0 ) + { + // Duplicate: the caller transferred ownership; return existing id + b3Free( bytes, (size_t)byteCount ); + return e->id; + } + // Same hash, different bytes: a 64-bit collision. Store a new entry and leave the map pointing + // at the first, so only a later blob identical to this rare one would miss dedup. + } + + // New entry — grow the array if needed + if ( reg->count >= reg->capacity ) + { + int newCap = reg->capacity < 8 ? 8 : reg->capacity * 2; + reg->entries = (b3GeometryEntry*)b3GrowAlloc( reg->entries, + reg->capacity * (int)sizeof( b3GeometryEntry ), + newCap * (int)sizeof( b3GeometryEntry ) ); + reg->capacity = newCap; + } + + uint32_t id = (uint32_t)reg->count; + b3GeometryEntry* entry = reg->entries + reg->count; + entry->contentHash = contentHash; + entry->id = id; + entry->kind = kind; + entry->byteCount = byteCount; + entry->bytes = bytes; // take ownership + reg->count++; + + // Only the first entry for a given hash goes in the map; a hash hit is verified by memcmp above. + if ( hashPresent == false ) + { + b3GeometryHashMap_insert( map, contentHash, id ); + } + return id; +} + +void b3FreeRegistry( b3GeometryRegistry* reg ) +{ + for ( int i = 0; i < reg->count; ++i ) + { + b3Free( reg->entries[i].bytes, (size_t)reg->entries[i].byteCount ); + } + if ( reg->entries != NULL ) + { + b3Free( reg->entries, (size_t)( reg->capacity * (int)sizeof( b3GeometryEntry ) ) ); + } + if ( reg->dedupMap != NULL ) + { + b3GeometryHashMap_cleanup( (b3GeometryHashMap*)reg->dedupMap ); + b3Free( reg->dedupMap, sizeof( b3GeometryHashMap ) ); + } + reg->entries = NULL; + reg->count = 0; + reg->capacity = 0; + reg->dedupMap = NULL; +} + +// Write the trailing registry block: u32 entryCount then per-entry { u8 kind, u32 byteCount, bytes }. +void b3RecWriteRegistry( b3Recording* rec ) +{ + b3RecW_U32( &rec->buffer, (uint32_t)rec->registry.count ); + for ( int i = 0; i < rec->registry.count; ++i ) + { + b3GeometryEntry* e = rec->registry.entries + i; + b3RecW_U8( &rec->buffer, (uint8_t)e->kind ); + b3RecW_U32( &rec->buffer, (uint32_t)e->byteCount ); + b3RecBufAppend( &rec->buffer, e->bytes, e->byteCount ); + } +} + +// Lifecycle + +b3Recording* b3CreateRecording( int byteCapacity ) +{ + b3Recording* rec = (b3Recording*)b3Alloc( sizeof( b3Recording ) ); + *rec = (b3Recording){ 0 }; + + int initCap = byteCapacity > 0 ? byteCapacity : 65536; + rec->buffer.data = (uint8_t*)b3Alloc( (size_t)initCap ); + rec->buffer.capacity = initCap; + rec->buffer.size = 0; + rec->lock = b3CreateMutex(); + return rec; +} + +void b3DestroyRecording( b3Recording* recording ) +{ + if ( recording == NULL ) + { + return; + } + + b3RecBufFree( &recording->buffer ); + b3FreeRegistry( &recording->registry ); + b3DestroyMutex( recording->lock ); + b3Free( recording, sizeof( b3Recording ) ); +} + +const uint8_t* b3Recording_GetData( const b3Recording* recording ) +{ + return recording->buffer.data; +} + +int b3Recording_GetSize( const b3Recording* recording ) +{ + return recording->buffer.size; +} + +void b3RecAccumulateBounds( b3Recording* rec, b3AABB bounds ) +{ + rec->accumulatedBounds = rec->haveBounds ? b3AABB_Union( rec->accumulatedBounds, bounds ) : bounds; + rec->haveBounds = true; +} + +void b3StartRecordingIntoBuffer( b3World* world, b3Recording* recording ) +{ + // Reset so a recording handle can be reused for a fresh session + recording->buffer.size = 0; + recording->recordStart = 0; + recording->haveBounds = false; + b3FreeRegistry( &recording->registry ); + + b3RecHeader hdr = { 0 }; + hdr.magic = B3_REC_MAGIC; + hdr.versionMajor = B3_REC_VERSION_MAJOR; + hdr.versionMinor = B3_REC_VERSION_MINOR; + hdr.pointerWidth = (uint8_t)sizeof( void* ); + hdr.bigEndian = 0; + hdr.validationEnabled = B3_ENABLE_VALIDATION ? 1u : 0u; + hdr.lengthScale = b3GetLengthUnitsPerMeter(); + hdr.registryOffset = 0; // backpatched in b3StopRecordingInternal + hdr.registryByteCount = 0; + + world->recording = recording; + + // Every recording is snapshot-seeded. The seed blob follows the header so replay restores in + // place and the world id stays stable across a restart or backward scrub. An empty world still + // serializes a valid blob, so there is no from-creation special case. + b3RecBuffer snapBuf = { 0 }; + b3SerializeWorld( world, &snapBuf, recording ); + hdr.snapshotSize = (uint64_t)snapBuf.size; + + b3RecBufAppend( &recording->buffer, &hdr, (int)sizeof( hdr ) ); + b3RecBufAppend( &recording->buffer, snapBuf.data, snapBuf.size ); + b3RecBufFree( &snapBuf ); + + // Anchor the recording with the current world state hash so replay can assert + // determinism from the very first step. + b3WorldId worldId = { (uint16_t)( world->worldId + 1 ), world->generation }; + b3RecArgs_StateHash stateHash = { worldId, b3HashWorldState( world ) }; + b3RecWrite_StateHash( recording, &stateHash ); +} + +void b3StopRecordingInternal( b3World* world ) +{ + if ( world->recording == NULL ) + { + return; + } + + b3Recording* rec = world->recording; + world->recording = NULL; + + // Write accumulated bounds so a viewer can frame the whole recorded motion + b3RecArgs_RecordingBounds rb = { 0 }; + if ( rec->haveBounds ) + { + rb.bounds = rec->accumulatedBounds; + } + b3RecWrite_RecordingBounds( rec, &rb ); + + // End-of-stream marker; the buffer is now self-contained + b3WorldId wid = { (uint16_t)( world->worldId + 1 ), world->generation }; + b3RecArgs_DestroyWorld a = { wid }; + b3RecWrite_DestroyWorld( rec, &a ); + + // Write the trailing registry block + int registryOffset = rec->buffer.size; + b3RecWriteRegistry( rec ); + int registryByteCount = rec->buffer.size - registryOffset; + + // Backpatch registryOffset and registryByteCount into the header + uint8_t* hdrBytes = rec->buffer.data; + uint64_t regOff = (uint64_t)registryOffset; + uint64_t regSz = (uint64_t)registryByteCount; + // Little-endian backpatch in place; offsetof keeps this correct if the header layout shifts + uint8_t* pOff = hdrBytes + offsetof( b3RecHeader, registryOffset ); + uint8_t* pSz = hdrBytes + offsetof( b3RecHeader, registryByteCount ); + for ( int i = 0; i < 8; ++i ) + { + pOff[i] = (uint8_t)( regOff >> ( 8 * i ) ); + pSz[i] = (uint8_t)( regSz >> ( 8 * i ) ); + } +} + +// Convenience file I/O + +bool b3SaveRecordingToFile( const b3Recording* recording, const char* path ) +{ + if ( recording == NULL || path == NULL ) + { + return false; + } + + FILE* f = fopen( path, "wb" ); + if ( f == NULL ) + { + return false; + } + + size_t written = fwrite( recording->buffer.data, 1, (size_t)recording->buffer.size, f ); + fclose( f ); + return (int)written == recording->buffer.size; +} + +b3Recording* b3LoadRecordingFromFile( const char* path ) +{ + if ( path == NULL ) + { + return NULL; + } + + FILE* f = fopen( path, "rb" ); + if ( f == NULL ) + { + return NULL; + } + + if ( fseek( f, 0, SEEK_END ) != 0 ) + { + fclose( f ); + return NULL; + } + + long fileSize = ftell( f ); + // Anything smaller than the fixed header can't be a recording + if ( fileSize < (long)sizeof( b3RecHeader ) || fileSize > INT_MAX ) + { + fclose( f ); + return NULL; + } + fseek( f, 0, SEEK_SET ); + + b3Recording* rec = b3CreateRecording( (int)fileSize ); + size_t readSize = fread( rec->buffer.data, 1, (size_t)fileSize, f ); + fclose( f ); + + if ( (long)readSize != fileSize ) + { + b3DestroyRecording( rec ); + return NULL; + } + + // Validate magic so a wrong file fails at load rather than deep in the player + b3RecHeader hdr; + memcpy( &hdr, rec->buffer.data, sizeof( hdr ) ); + if ( hdr.magic != B3_REC_MAGIC ) + { + b3DestroyRecording( rec ); + return NULL; + } + + rec->buffer.size = (int)fileSize; + return rec; +} + +// Geometry interning helpers + +uint32_t b3RecInternHull( b3Recording* rec, const b3HullData* hull ) +{ + int byteCount = hull->byteCount; + uint8_t* bytes = (uint8_t*)b3Alloc( (size_t)byteCount ); + memcpy( bytes, hull, (size_t)byteCount ); + uint64_t h = b3Hash64Blob( bytes, byteCount ); + return b3InternGeometry( &rec->registry, b3_geometryHull, h, bytes, byteCount ); +} + +uint32_t b3RecInternMesh( b3Recording* rec, const b3MeshData* mesh ) +{ + int byteCount = mesh->byteCount; + uint8_t* bytes = (uint8_t*)b3Alloc( (size_t)byteCount ); + memcpy( bytes, mesh, (size_t)byteCount ); + uint64_t h = b3Hash64Blob( bytes, byteCount ); + return b3InternGeometry( &rec->registry, b3_geometryMesh, h, bytes, byteCount ); +} + +uint32_t b3RecInternHeightField( b3Recording* rec, const b3HeightFieldData* hf ) +{ + int byteCount = hf->byteCount; + uint8_t* bytes = (uint8_t*)b3Alloc( (size_t)byteCount ); + memcpy( bytes, hf, (size_t)byteCount ); + uint64_t h = b3Hash64Blob( bytes, byteCount ); + return b3InternGeometry( &rec->registry, b3_geometryHeightField, h, bytes, byteCount ); +} + +uint32_t b3RecInternCompound( b3Recording* rec, const b3CompoundData* compound ) +{ + int byteCount = compound->byteCount; + uint8_t* bytes = (uint8_t*)b3Alloc( (size_t)byteCount ); + memcpy( bytes, compound, (size_t)byteCount ); + // Null the tree node pointer in the copy so the canonical bytes are pointer-free. + // b3ConvertBytesToCompound fixes it back on load via nodeOffset. + ( (b3CompoundData*)bytes )->tree.nodes = NULL; + uint64_t h = b3Hash64Blob( bytes, byteCount ); + return b3InternGeometry( &rec->registry, b3_geometryCompound, h, bytes, byteCount ); +} + +uint64_t b3HashWorldState( b3World* world ) +{ + uint64_t hash = B3_SNAP_FNV_INIT; + const uint64_t prime = B3_SNAP_FNV_PRIME; + + int bodyCount = world->bodies.count; + for ( int i = 0; i < bodyCount; ++i ) + { + b3Body* body = world->bodies.data + i; + if ( body->id != i ) + { + // Free or never-used slot + continue; + } + + b3BodySim* sim = b3GetBodySim( world, body ); + + uint32_t bits; + +#define B3_HASH_FLOAT( f ) \ + memcpy( &bits, &( f ), 4 ); \ + hash = ( hash ^ (uint64_t)bits ) * prime; + + hash = b3FnvMixPosition( hash, sim->transform.p ); + B3_HASH_FLOAT( sim->transform.q.v.x ) + B3_HASH_FLOAT( sim->transform.q.v.y ) + B3_HASH_FLOAT( sim->transform.q.v.z ) + B3_HASH_FLOAT( sim->transform.q.s ) + + b3BodyState* state = b3GetBodyState( world, body ); + if ( state != NULL ) + { + B3_HASH_FLOAT( state->linearVelocity.x ) + B3_HASH_FLOAT( state->linearVelocity.y ) + B3_HASH_FLOAT( state->linearVelocity.z ) + B3_HASH_FLOAT( state->angularVelocity.x ) + B3_HASH_FLOAT( state->angularVelocity.y ) + B3_HASH_FLOAT( state->angularVelocity.z ) + } + +#undef B3_HASH_FLOAT + } + + return hash; +} diff --git a/src/recording.h b/src/recording.h new file mode 100644 index 0000000..11c6d77 --- /dev/null +++ b/src/recording.h @@ -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 +#include +#include +#include + +// 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 ); diff --git a/src/recording_ops.inl b/src/recording_ops.inl new file mode 100644 index 0000000..abeb5e7 --- /dev/null +++ b/src/recording_ops.inl @@ -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 ) ) diff --git a/src/recording_replay.c b/src/recording_replay.c new file mode 100644 index 0000000..737b111 --- /dev/null +++ b/src/recording_replay.c @@ -0,0 +1,3250 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +#if defined( _MSC_VER ) && !defined( _CRT_SECURE_NO_WARNINGS ) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include "recording_replay.h" + +#include "body.h" +#include "compound.h" +#include "physics_world.h" +#include "world_snapshot.h" + +#include "box3d/box3d.h" + +#include +#include +#include + +// Read primitives + +static void b3RecRdrCheck( b3RecReader* rdr, int size ) +{ + if ( size < 0 || (int64_t)rdr->cursor + (int64_t)size > (int64_t)rdr->size ) + { + rdr->ok = false; + } +} + +static void b3RecRdrBlob( b3RecReader* rdr, void* out, int size ) +{ + b3RecRdrCheck( rdr, size ); + if ( !rdr->ok ) + { + memset( out, 0, (size_t)size ); + return; + } + memcpy( out, rdr->data + rdr->cursor, (size_t)size ); + rdr->cursor += size; +} + +uint8_t b3RecR_U8( b3RecReader* rdr ) +{ + b3RecRdrCheck( rdr, 1 ); + if ( !rdr->ok ) + { + return 0; + } + return rdr->data[rdr->cursor++]; +} + +uint16_t b3RecR_U16( b3RecReader* rdr ) +{ + b3RecRdrCheck( rdr, 2 ); + if ( !rdr->ok ) + { + return 0; + } + uint16_t v = (uint16_t)rdr->data[rdr->cursor] | ( (uint16_t)rdr->data[rdr->cursor + 1] << 8 ); + rdr->cursor += 2; + return v; +} + +uint32_t b3RecR_U24( b3RecReader* rdr ) +{ + b3RecRdrCheck( rdr, 3 ); + if ( !rdr->ok ) + { + return 0; + } + uint32_t v = (uint32_t)rdr->data[rdr->cursor] | ( (uint32_t)rdr->data[rdr->cursor + 1] << 8 ) | + ( (uint32_t)rdr->data[rdr->cursor + 2] << 16 ); + rdr->cursor += 3; + return v; +} + +uint32_t b3RecR_U32( b3RecReader* rdr ) +{ + b3RecRdrCheck( rdr, 4 ); + if ( !rdr->ok ) + { + return 0; + } + uint32_t v = (uint32_t)rdr->data[rdr->cursor] | ( (uint32_t)rdr->data[rdr->cursor + 1] << 8 ) | + ( (uint32_t)rdr->data[rdr->cursor + 2] << 16 ) | ( (uint32_t)rdr->data[rdr->cursor + 3] << 24 ); + rdr->cursor += 4; + return v; +} + +uint64_t b3RecR_U64( b3RecReader* rdr ) +{ + b3RecRdrCheck( rdr, 8 ); + if ( !rdr->ok ) + { + return 0; + } + uint64_t v = (uint64_t)rdr->data[rdr->cursor] | ( (uint64_t)rdr->data[rdr->cursor + 1] << 8 ) | + ( (uint64_t)rdr->data[rdr->cursor + 2] << 16 ) | ( (uint64_t)rdr->data[rdr->cursor + 3] << 24 ) | + ( (uint64_t)rdr->data[rdr->cursor + 4] << 32 ) | ( (uint64_t)rdr->data[rdr->cursor + 5] << 40 ) | + ( (uint64_t)rdr->data[rdr->cursor + 6] << 48 ) | ( (uint64_t)rdr->data[rdr->cursor + 7] << 56 ); + rdr->cursor += 8; + return v; +} + +int32_t b3RecR_I32( b3RecReader* rdr ) +{ + return (int32_t)b3RecR_U32( rdr ); +} + +float b3RecR_F32( b3RecReader* rdr ) +{ + uint32_t bits = b3RecR_U32( rdr ); + float v; + memcpy( &v, &bits, 4 ); + return v; +} + +double b3RecR_F64( b3RecReader* rdr ) +{ + uint64_t bits = b3RecR_U64( rdr ); + double v; + memcpy( &v, &bits, 8 ); + return v; +} + +bool b3RecR_BOOL( b3RecReader* rdr ) +{ + return b3RecR_U8( rdr ) != 0u; +} + +b3Vec3 b3RecR_VEC3( b3RecReader* rdr ) +{ + b3Vec3 v; + v.x = b3RecR_F32( rdr ); + v.y = b3RecR_F32( rdr ); + v.z = b3RecR_F32( rdr ); + return v; +} + +b3Quat b3RecR_QUAT( b3RecReader* rdr ) +{ + b3Quat q; + q.v.x = b3RecR_F32( rdr ); + q.v.y = b3RecR_F32( rdr ); + q.v.z = b3RecR_F32( rdr ); + q.s = b3RecR_F32( rdr ); + return q; +} + +b3Transform b3RecR_TRANSFORM( b3RecReader* rdr ) +{ + b3Transform t; + t.p = b3RecR_VEC3( rdr ); + t.q = b3RecR_QUAT( rdr ); + return t; +} + +b3Pos b3RecR_POSITION( b3RecReader* rdr ) +{ + b3Pos p; +#if defined( BOX3D_DOUBLE_PRECISION ) + p.x = b3RecR_F64( rdr ); + p.y = b3RecR_F64( rdr ); + p.z = b3RecR_F64( rdr ); +#else + p.x = b3RecR_F32( rdr ); + p.y = b3RecR_F32( rdr ); + p.z = b3RecR_F32( rdr ); +#endif + return p; +} + +b3WorldTransform b3RecR_WORLDXF( b3RecReader* rdr ) +{ + b3WorldTransform t; + t.p = b3RecR_POSITION( rdr ); + t.q = b3RecR_QUAT( rdr ); + return t; +} + +b3Matrix3 b3RecR_MATRIX3( b3RecReader* rdr ) +{ + b3Matrix3 m; + m.cx = b3RecR_VEC3( rdr ); + m.cy = b3RecR_VEC3( rdr ); + m.cz = b3RecR_VEC3( rdr ); + return m; +} + +b3AABB b3RecR_AABB( b3RecReader* rdr ) +{ + b3AABB v; + v.lowerBound = b3RecR_VEC3( rdr ); + v.upperBound = b3RecR_VEC3( rdr ); + return v; +} + +b3QueryFilter b3RecR_QUERYFILTER( b3RecReader* rdr ) +{ + b3QueryFilter f; + f.categoryBits = b3RecR_U64( rdr ); + f.maskBits = b3RecR_U64( rdr ); + return f; +} + +// Reserve reader scratch for a count taken from an untrusted file. Every recorded element +// consumes at least one byte, so a valid count can never exceed the bytes left in the file. +// Reject anything larger (or negative, or that would overflow the byte size) by failing the read +// rather than allocating wildly. Contents are not preserved; callers overwrite before use. +static bool b3RecReserveScratch( b3RecReader* rdr, void** data, int* cap, int need, int elemSize ) +{ + int remaining = rdr->size - rdr->cursor; + if ( need < 0 || remaining < 0 || need > remaining || need > INT_MAX / elemSize ) + { + rdr->ok = false; + return false; + } + if ( need <= *cap ) + { + return true; + } + int newCap = need <= INT_MAX / elemSize - 8 ? need + 8 : need; + if ( *data != NULL ) + { + b3Free( *data, (size_t)*cap * (size_t)elemSize ); + } + *data = b3Alloc( (size_t)newCap * (size_t)elemSize ); + *cap = newCap; + return true; +} + +// Variable length, mirrors b3RecW_SHAPEPROXY: count, count points, radius. The decoded proxy borrows +// the reader's scratch for its point cloud, valid until the next proxy read. +b3ShapeProxy b3RecR_SHAPEPROXY( b3RecReader* rdr ) +{ + b3ShapeProxy p = { 0 }; + int count = b3RecR_I32( rdr ); + if ( count < 0 ) + count = 0; + if ( count > B3_MAX_SHAPE_CAST_POINTS ) + count = B3_MAX_SHAPE_CAST_POINTS; + if ( count > 0 && b3RecReserveScratch( rdr, (void**)&rdr->proxyScratch, &rdr->proxyScratchCap, count, (int)sizeof( b3Vec3 ) ) ) + { + for ( int i = 0; i < count; ++i ) + { + rdr->proxyScratch[i] = b3RecR_VEC3( rdr ); + } + p.points = rdr->proxyScratch; + p.count = count; + } + p.radius = b3RecR_F32( rdr ); + return p; +} + +b3TreeStats b3RecR_TREESTATS( b3RecReader* rdr ) +{ + b3TreeStats v; + v.nodeVisits = b3RecR_I32( rdr ); + v.leafVisits = b3RecR_I32( rdr ); + return v; +} + +b3RayResult b3RecR_RAYRESULT( b3RecReader* rdr ) +{ + b3RayResult v = { 0 }; + // shapeId keeps the recorded world0; b3RecMakeShapeId is applied at compare time + v.shapeId = b3RecR_SHAPEID( rdr ); + v.point = b3RecR_POSITION( rdr ); + v.normal = b3RecR_VEC3( rdr ); + v.userMaterialId = b3RecR_U64( rdr ); + v.fraction = b3RecR_F32( rdr ); + v.triangleIndex = b3RecR_I32( rdr ); + v.childIndex = b3RecR_I32( rdr ); + v.hit = b3RecR_BOOL( rdr ); + return v; +} + +b3PlaneResult b3RecR_PLANERESULT( b3RecReader* rdr ) +{ + b3PlaneResult v; + v.plane.normal = b3RecR_VEC3( rdr ); + v.plane.offset = b3RecR_F32( rdr ); + v.point = b3RecR_VEC3( rdr ); + return v; +} + +b3WorldId b3RecR_WORLDID( b3RecReader* rdr ) +{ + return b3LoadWorldId( b3RecR_U32( rdr ) ); +} + +b3BodyId b3RecR_BODYID( b3RecReader* rdr ) +{ + return b3LoadBodyId( b3RecR_U64( rdr ) ); +} + +b3ShapeId b3RecR_SHAPEID( b3RecReader* rdr ) +{ + return b3LoadShapeId( b3RecR_U64( rdr ) ); +} + +b3JointId b3RecR_JOINTID( b3RecReader* rdr ) +{ + return b3LoadJointId( b3RecR_U64( rdr ) ); +} + +b3Sphere b3RecR_SPHERE( b3RecReader* rdr ) +{ + b3Sphere s; + b3RecRdrBlob( rdr, &s, (int)sizeof( s ) ); + return s; +} + +b3Capsule b3RecR_CAPSULE( b3RecReader* rdr ) +{ + b3Capsule c; + b3RecRdrBlob( rdr, &c, (int)sizeof( c ) ); + return c; +} + +uint32_t b3RecR_GEOMID( b3RecReader* rdr ) +{ + return b3RecR_U32( rdr ); +} + +b3Filter b3RecR_FILTER( b3RecReader* rdr ) +{ + b3Filter f; + f.categoryBits = b3RecR_U64( rdr ); + f.maskBits = b3RecR_U64( rdr ); + f.groupIndex = b3RecR_I32( rdr ); + return f; +} + +b3SurfaceMaterial b3RecR_MATERIAL( b3RecReader* rdr ) +{ + b3SurfaceMaterial m = b3DefaultSurfaceMaterial(); + m.friction = b3RecR_F32( rdr ); + m.restitution = b3RecR_F32( rdr ); + m.rollingResistance = b3RecR_F32( rdr ); + m.tangentVelocity = b3RecR_VEC3( rdr ); + m.userMaterialId = b3RecR_U64( rdr ); + m.customColor = b3RecR_U32( rdr ); + return m; +} + +b3MassData b3RecR_MASSDATA( b3RecReader* rdr ) +{ + b3MassData md; + md.mass = b3RecR_F32( rdr ); + md.center = b3RecR_VEC3( rdr ); + md.inertia = b3RecR_MATRIX3( rdr ); + return md; +} + +b3MotionLocks b3RecR_LOCKS( b3RecReader* rdr ) +{ + b3MotionLocks locks; + locks.linearX = b3RecR_BOOL( rdr ); + locks.linearY = b3RecR_BOOL( rdr ); + locks.linearZ = b3RecR_BOOL( rdr ); + locks.angularX = b3RecR_BOOL( rdr ); + locks.angularY = b3RecR_BOOL( rdr ); + locks.angularZ = b3RecR_BOOL( rdr ); + return locks; +} + +// Rotating set of static string buffers, valid until the next 4 STR reads. +const char* b3RecR_STR( b3RecReader* rdr ) +{ + char* buf = rdr->strBufs[rdr->strNext]; + rdr->strNext = ( rdr->strNext + 1 ) & 3; + + uint16_t len = b3RecR_U16( rdr ); + if ( len == 0xFFFFu ) + { + return NULL; + } + + int n = (int)len; + if ( n > B3_NAME_LENGTH ) + { + n = B3_NAME_LENGTH; + } + b3RecRdrCheck( rdr, (int)len ); + if ( rdr->ok && n > 0 ) + { + memcpy( buf, rdr->data + rdr->cursor, (size_t)n ); + } + rdr->cursor += (int)len; + buf[n] = '\0'; + return buf; +} + +// Def readers: start from b3Default*Def() then overlay each serialized field +// in the exact order the writer produced them. + +b3ExplosionDef b3RecR_EXPLOSIONDEF( b3RecReader* rdr ) +{ + b3ExplosionDef def = b3DefaultExplosionDef(); + def.maskBits = b3RecR_U64( rdr ); + def.position = b3RecR_POSITION( rdr ); + def.radius = b3RecR_F32( rdr ); + def.falloff = b3RecR_F32( rdr ); + def.impulsePerArea = b3RecR_F32( rdr ); + return def; +} + +b3BodyDef b3RecR_BODYDEF( b3RecReader* rdr ) +{ + b3BodyDef def = b3DefaultBodyDef(); + def.type = (b3BodyType)b3RecR_I32( rdr ); + def.position = b3RecR_POSITION( rdr ); + def.rotation = b3RecR_QUAT( rdr ); + def.linearVelocity = b3RecR_VEC3( rdr ); + def.angularVelocity = b3RecR_VEC3( rdr ); + def.linearDamping = b3RecR_F32( rdr ); + def.angularDamping = b3RecR_F32( rdr ); + def.gravityScale = b3RecR_F32( rdr ); + def.sleepThreshold = b3RecR_F32( rdr ); + def.name = b3RecR_STR( rdr ); + (void)b3RecR_U64( rdr ); // userData placeholder + def.motionLocks = b3RecR_LOCKS( rdr ); + def.enableSleep = b3RecR_BOOL( rdr ); + def.isAwake = b3RecR_BOOL( rdr ); + def.isBullet = b3RecR_BOOL( rdr ); + def.isEnabled = b3RecR_BOOL( rdr ); + def.allowFastRotation = b3RecR_BOOL( rdr ); + def.enableContactRecycling = b3RecR_BOOL( rdr ); + def.userData = NULL; + return def; +} + +b3ShapeDef b3RecR_SHAPEDEF( b3RecReader* rdr ) +{ + b3ShapeDef def = b3DefaultShapeDef(); + def.name = b3RecR_STR( rdr ); + (void)b3RecR_U64( rdr ); // userData placeholder + + int matCount = b3RecR_I32( rdr ); + if ( matCount < 0 ) + { + matCount = 0; + } + if ( matCount > 0 && b3RecReserveScratch( rdr, (void**)&rdr->matScratch, &rdr->matScratchCap, matCount, (int)sizeof( b3SurfaceMaterial ) ) ) + { + for ( int i = 0; i < matCount; ++i ) + { + rdr->matScratch[i] = b3RecR_MATERIAL( rdr ); + } + def.materials = rdr->matScratch; + def.materialCount = matCount; + } + else + { + for ( int i = 0; i < matCount; ++i ) + { + (void)b3RecR_MATERIAL( rdr ); + } + def.materials = NULL; + def.materialCount = 0; + } + + def.baseMaterial = b3RecR_MATERIAL( rdr ); + def.density = b3RecR_F32( rdr ); + def.explosionScale = b3RecR_F32( rdr ); + def.filter = b3RecR_FILTER( rdr ); + def.enableCustomFiltering = b3RecR_BOOL( rdr ); + def.isSensor = b3RecR_BOOL( rdr ); + def.enableSensorEvents = b3RecR_BOOL( rdr ); + def.enableContactEvents = b3RecR_BOOL( rdr ); + def.enableHitEvents = b3RecR_BOOL( rdr ); + def.enablePreSolveEvents = b3RecR_BOOL( rdr ); + def.invokeContactCreation = b3RecR_BOOL( rdr ); + def.updateBodyMass = b3RecR_BOOL( rdr ); + def.userData = NULL; + return def; +} + +// Shared base for all joint defs. Body ids come in with recorded world0; callers remap them. +static void b3RecR_JointBase( b3RecReader* rdr, b3JointDef* base ) +{ + (void)b3RecR_U64( rdr ); // userData + base->bodyIdA = b3RecR_BODYID( rdr ); + base->bodyIdB = b3RecR_BODYID( rdr ); + base->localFrameA = b3RecR_TRANSFORM( rdr ); + base->localFrameB = b3RecR_TRANSFORM( rdr ); + base->forceThreshold = b3RecR_F32( rdr ); + base->torqueThreshold = b3RecR_F32( rdr ); + base->constraintHertz = b3RecR_F32( rdr ); + base->constraintDampingRatio = b3RecR_F32( rdr ); + base->drawScale = b3RecR_F32( rdr ); + base->collideConnected = b3RecR_BOOL( rdr ); + base->userData = NULL; +} + +b3ParallelJointDef b3RecR_PARALLELJOINTDEF( b3RecReader* rdr ) +{ + b3ParallelJointDef def = b3DefaultParallelJointDef(); + b3RecR_JointBase( rdr, &def.base ); + def.hertz = b3RecR_F32( rdr ); + def.dampingRatio = b3RecR_F32( rdr ); + def.maxTorque = b3RecR_F32( rdr ); + return def; +} + +b3DistanceJointDef b3RecR_DISTANCEJOINTDEF( b3RecReader* rdr ) +{ + b3DistanceJointDef def = b3DefaultDistanceJointDef(); + b3RecR_JointBase( rdr, &def.base ); + def.length = b3RecR_F32( rdr ); + def.enableSpring = b3RecR_BOOL( rdr ); + def.lowerSpringForce = b3RecR_F32( rdr ); + def.upperSpringForce = b3RecR_F32( rdr ); + def.hertz = b3RecR_F32( rdr ); + def.dampingRatio = b3RecR_F32( rdr ); + def.enableLimit = b3RecR_BOOL( rdr ); + def.minLength = b3RecR_F32( rdr ); + def.maxLength = b3RecR_F32( rdr ); + def.enableMotor = b3RecR_BOOL( rdr ); + def.maxMotorForce = b3RecR_F32( rdr ); + def.motorSpeed = b3RecR_F32( rdr ); + return def; +} + +b3FilterJointDef b3RecR_FILTERJOINTDEF( b3RecReader* rdr ) +{ + b3FilterJointDef def = b3DefaultFilterJointDef(); + b3RecR_JointBase( rdr, &def.base ); + return def; +} + +b3MotorJointDef b3RecR_MOTORJOINTDEF( b3RecReader* rdr ) +{ + b3MotorJointDef def = b3DefaultMotorJointDef(); + b3RecR_JointBase( rdr, &def.base ); + def.linearVelocity = b3RecR_VEC3( rdr ); + def.maxVelocityForce = b3RecR_F32( rdr ); + def.angularVelocity = b3RecR_VEC3( rdr ); + def.maxVelocityTorque = b3RecR_F32( rdr ); + def.linearHertz = b3RecR_F32( rdr ); + def.linearDampingRatio = b3RecR_F32( rdr ); + def.maxSpringForce = b3RecR_F32( rdr ); + def.angularHertz = b3RecR_F32( rdr ); + def.angularDampingRatio = b3RecR_F32( rdr ); + def.maxSpringTorque = b3RecR_F32( rdr ); + return def; +} + +b3PrismaticJointDef b3RecR_PRISMATICJOINTDEF( b3RecReader* rdr ) +{ + b3PrismaticJointDef def = b3DefaultPrismaticJointDef(); + b3RecR_JointBase( rdr, &def.base ); + def.enableSpring = b3RecR_BOOL( rdr ); + def.hertz = b3RecR_F32( rdr ); + def.dampingRatio = b3RecR_F32( rdr ); + def.targetTranslation = b3RecR_F32( rdr ); + def.enableLimit = b3RecR_BOOL( rdr ); + def.lowerTranslation = b3RecR_F32( rdr ); + def.upperTranslation = b3RecR_F32( rdr ); + def.enableMotor = b3RecR_BOOL( rdr ); + def.maxMotorForce = b3RecR_F32( rdr ); + def.motorSpeed = b3RecR_F32( rdr ); + return def; +} + +b3RevoluteJointDef b3RecR_REVOLUTEJOINTDEF( b3RecReader* rdr ) +{ + b3RevoluteJointDef def = b3DefaultRevoluteJointDef(); + b3RecR_JointBase( rdr, &def.base ); + def.targetAngle = b3RecR_F32( rdr ); + def.enableSpring = b3RecR_BOOL( rdr ); + def.hertz = b3RecR_F32( rdr ); + def.dampingRatio = b3RecR_F32( rdr ); + def.enableLimit = b3RecR_BOOL( rdr ); + def.lowerAngle = b3RecR_F32( rdr ); + def.upperAngle = b3RecR_F32( rdr ); + def.enableMotor = b3RecR_BOOL( rdr ); + def.maxMotorTorque = b3RecR_F32( rdr ); + def.motorSpeed = b3RecR_F32( rdr ); + return def; +} + +b3SphericalJointDef b3RecR_SPHERICALJOINTDEF( b3RecReader* rdr ) +{ + b3SphericalJointDef def = b3DefaultSphericalJointDef(); + b3RecR_JointBase( rdr, &def.base ); + def.enableSpring = b3RecR_BOOL( rdr ); + def.hertz = b3RecR_F32( rdr ); + def.dampingRatio = b3RecR_F32( rdr ); + def.targetRotation = b3RecR_QUAT( rdr ); + def.enableConeLimit = b3RecR_BOOL( rdr ); + def.coneAngle = b3RecR_F32( rdr ); + def.enableTwistLimit = b3RecR_BOOL( rdr ); + def.lowerTwistAngle = b3RecR_F32( rdr ); + def.upperTwistAngle = b3RecR_F32( rdr ); + def.enableMotor = b3RecR_BOOL( rdr ); + def.maxMotorTorque = b3RecR_F32( rdr ); + def.motorVelocity = b3RecR_VEC3( rdr ); + return def; +} + +b3WeldJointDef b3RecR_WELDJOINTDEF( b3RecReader* rdr ) +{ + b3WeldJointDef def = b3DefaultWeldJointDef(); + b3RecR_JointBase( rdr, &def.base ); + def.linearHertz = b3RecR_F32( rdr ); + def.angularHertz = b3RecR_F32( rdr ); + def.linearDampingRatio = b3RecR_F32( rdr ); + def.angularDampingRatio = b3RecR_F32( rdr ); + return def; +} + +b3WheelJointDef b3RecR_WHEELJOINTDEF( b3RecReader* rdr ) +{ + b3WheelJointDef def = b3DefaultWheelJointDef(); + b3RecR_JointBase( rdr, &def.base ); + def.enableSuspensionSpring = b3RecR_BOOL( rdr ); + def.suspensionHertz = b3RecR_F32( rdr ); + def.suspensionDampingRatio = b3RecR_F32( rdr ); + def.enableSuspensionLimit = b3RecR_BOOL( rdr ); + def.lowerSuspensionLimit = b3RecR_F32( rdr ); + def.upperSuspensionLimit = b3RecR_F32( rdr ); + def.enableSpinMotor = b3RecR_BOOL( rdr ); + def.maxSpinTorque = b3RecR_F32( rdr ); + def.spinSpeed = b3RecR_F32( rdr ); + def.enableSteering = b3RecR_BOOL( rdr ); + def.steeringHertz = b3RecR_F32( rdr ); + def.steeringDampingRatio = b3RecR_F32( rdr ); + def.targetSteeringAngle = b3RecR_F32( rdr ); + def.maxSteeringTorque = b3RecR_F32( rdr ); + def.enableSteeringLimit = b3RecR_BOOL( rdr ); + def.lowerSteeringLimit = b3RecR_F32( rdr ); + def.upperSteeringLimit = b3RecR_F32( rdr ); + return def; +} + +// Outliner body tracking. Defined after the player struct; forward declared here because the +// create/destroy dispatch sits above that struct. +static void b3RecTrackBodyCreate( b3RecPlayer* player, b3BodyId id ); +static void b3RecTrackBodyDestroy( b3RecPlayer* player, b3BodyId id ); + +// Id retargeting: replace world0 with the replay world's slot index. + +static b3BodyId b3RecMakeBodyId( b3RecReader* rdr, b3BodyId recorded ) +{ + b3BodyId id; + id.index1 = recorded.index1; + id.world0 = (uint16_t)( rdr->replayWorldId.index1 - 1u ); + id.generation = recorded.generation; + return id; +} + +static b3ShapeId b3RecMakeShapeId( b3RecReader* rdr, b3ShapeId recorded ) +{ + b3ShapeId id; + id.index1 = recorded.index1; + id.world0 = (uint16_t)( rdr->replayWorldId.index1 - 1u ); + id.generation = recorded.generation; + return id; +} + +static b3JointId b3RecMakeJointId( b3RecReader* rdr, b3JointId recorded ) +{ + b3JointId id; + id.index1 = recorded.index1; + id.world0 = (uint16_t)( rdr->replayWorldId.index1 - 1u ); + id.generation = recorded.generation; + return id; +} + +// A create op appends the returned id after args. index1 and generation must match; +// world0 always differs so we ignore it. +static void b3RecCheckId( b3RecReader* rdr, const char* kind, int gotIndex, unsigned gotGen, + int recIndex, unsigned recGen ) +{ + if ( gotIndex != recIndex || gotGen != recGen ) + { + printf( "b3ReplayFile: %s id mismatch (rec index1=%d gen=%u, got index1=%d gen=%u)\n", + kind, recIndex, recGen, gotIndex, gotGen ); + rdr->ok = false; + } +} + +static void b3RecCheckBodyId( b3RecReader* rdr, b3BodyId got, b3BodyId rec ) +{ + b3RecCheckId( rdr, "body", got.index1, got.generation, rec.index1, rec.generation ); +} + +static void b3RecCheckShapeId( b3RecReader* rdr, b3ShapeId got, b3ShapeId rec ) +{ + b3RecCheckId( rdr, "shape", got.index1, got.generation, rec.index1, rec.generation ); +} + +static void b3RecCheckJointId( b3RecReader* rdr, b3JointId got, b3JointId rec ) +{ + b3RecCheckId( rdr, "joint", got.index1, got.generation, rec.index1, rec.generation ); +} + +// Registry slot reconstruction. Returns the live pointer for the given slot, building it +// on first use. The hull case is handled inline at the call site since it doesn't cache. + +static void* b3RecGetLiveMesh( b3RegistrySlot* slot ) +{ + // Mesh is a self-contained blob used by reference, with no pointer fixup. Hand back the pristine + // bytes directly: they already outlive the world and are freed at teardown, so a copy would just + // double the memory. Compound can't do this, see b3RecGetLiveCompound. + return slot->bytes; +} + +static void* b3RecGetLiveHeightField( b3RegistrySlot* slot ) +{ + // Self-contained blob used by reference, like b3RecGetLiveMesh. The bytes already are a + // valid b3HeightFieldData with no pointer fixup, so hand them back directly. + return slot->bytes; +} + +static void* b3RecGetLiveCompound( b3RegistrySlot* slot ) +{ + if ( slot->live != NULL ) + { + return slot->live; + } + // The copy is unavoidable here: b3ConvertBytesToCompound rewrites its input in place, while the + // pristine bytes must survive for keyframe registry seeding (b3RecSeedKeyframeRegistry). So we + // keep both the serialized bytes and a separate converted live object. + slot->live = b3Alloc( (size_t)slot->byteCount ); + memcpy( slot->live, slot->bytes, (size_t)slot->byteCount ); + b3ConvertBytesToCompound( (uint8_t*)slot->live, slot->byteCount ); + return slot->live; +} + +// Dispatch functions, one per op + +static void b3RecDispatch_DestroyWorld( const b3RecArgs_DestroyWorld* a, b3RecReader* rdr ) +{ + (void)a; + (void)rdr; + // End-of-session marker. The replay world is torn down in b3ValidateReplay, not here. +} + +static void b3RecDispatch_Step( const b3RecArgs_Step* a, b3RecReader* rdr ) +{ + (void)a; + b3World_Step( rdr->replayWorldId, a->dt, a->subStepCount ); +} + +static void b3RecDispatch_WorldEnableSleeping( const b3RecArgs_WorldEnableSleeping* a, b3RecReader* rdr ) +{ + b3World_EnableSleeping( rdr->replayWorldId, a->flag ); +} + +static void b3RecDispatch_WorldEnableContinuous( const b3RecArgs_WorldEnableContinuous* a, b3RecReader* rdr ) +{ + b3World_EnableContinuous( rdr->replayWorldId, a->flag ); +} + +static void b3RecDispatch_WorldSetRestitutionThreshold( const b3RecArgs_WorldSetRestitutionThreshold* a, b3RecReader* rdr ) +{ + b3World_SetRestitutionThreshold( rdr->replayWorldId, a->value ); +} + +static void b3RecDispatch_WorldSetHitEventThreshold( const b3RecArgs_WorldSetHitEventThreshold* a, b3RecReader* rdr ) +{ + b3World_SetHitEventThreshold( rdr->replayWorldId, a->value ); +} + +static void b3RecDispatch_WorldSetGravity( const b3RecArgs_WorldSetGravity* a, b3RecReader* rdr ) +{ + b3World_SetGravity( rdr->replayWorldId, a->gravity ); +} + +static void b3RecDispatch_WorldExplode( const b3RecArgs_WorldExplode* a, b3RecReader* rdr ) +{ + b3World_Explode( rdr->replayWorldId, &a->def ); +} + +static void b3RecDispatch_WorldSetContactTuning( const b3RecArgs_WorldSetContactTuning* a, b3RecReader* rdr ) +{ + b3World_SetContactTuning( rdr->replayWorldId, a->hertz, a->dampingRatio, a->contactSpeed ); +} + +static void b3RecDispatch_WorldSetContactRecycleDistance( const b3RecArgs_WorldSetContactRecycleDistance* a, b3RecReader* rdr ) +{ + b3World_SetContactRecycleDistance( rdr->replayWorldId, a->recycleDistance ); +} + +static void b3RecDispatch_WorldSetMaximumLinearSpeed( const b3RecArgs_WorldSetMaximumLinearSpeed* a, b3RecReader* rdr ) +{ + b3World_SetMaximumLinearSpeed( rdr->replayWorldId, a->maximumLinearSpeed ); +} + +static void b3RecDispatch_WorldEnableWarmStarting( const b3RecArgs_WorldEnableWarmStarting* a, b3RecReader* rdr ) +{ + b3World_EnableWarmStarting( rdr->replayWorldId, a->flag ); +} + +static void b3RecDispatch_WorldRebuildStaticTree( const b3RecArgs_WorldRebuildStaticTree* a, b3RecReader* rdr ) +{ + (void)a; + b3World_RebuildStaticTree( rdr->replayWorldId ); +} + +static void b3RecDispatch_WorldEnableSpeculative( const b3RecArgs_WorldEnableSpeculative* a, b3RecReader* rdr ) +{ + b3World_EnableSpeculative( rdr->replayWorldId, a->flag ); +} + +static void b3RecDispatch_CreateBody( const b3RecArgs_CreateBody* a, b3RecReader* rdr ) +{ + b3BodyId recId = b3RecR_BODYID( rdr ); + b3BodyId gotId = b3CreateBody( rdr->replayWorldId, &a->def ); + b3RecCheckBodyId( rdr, gotId, recId ); + if ( rdr->owner != NULL ) + { + b3RecTrackBodyCreate( rdr->owner, gotId ); + } +} + +static void b3RecDispatch_DestroyBody( const b3RecArgs_DestroyBody* a, b3RecReader* rdr ) +{ + b3BodyId id = b3RecMakeBodyId( rdr, a->body ); + if ( rdr->owner != NULL ) + { + b3RecTrackBodyDestroy( rdr->owner, id ); + } + b3DestroyBody( id ); +} + +static void b3RecDispatch_BodySetTransform( const b3RecArgs_BodySetTransform* a, b3RecReader* rdr ) +{ + b3Body_SetTransform( b3RecMakeBodyId( rdr, a->body ), a->position, a->rotation ); +} + +static void b3RecDispatch_BodySetLinearVelocity( const b3RecArgs_BodySetLinearVelocity* a, b3RecReader* rdr ) +{ + b3Body_SetLinearVelocity( b3RecMakeBodyId( rdr, a->body ), a->v ); +} + +static void b3RecDispatch_BodySetType( const b3RecArgs_BodySetType* a, b3RecReader* rdr ) +{ + b3Body_SetType( b3RecMakeBodyId( rdr, a->body ), (b3BodyType)a->type ); +} + +static void b3RecDispatch_BodySetName( const b3RecArgs_BodySetName* a, b3RecReader* rdr ) +{ + b3Body_SetName( b3RecMakeBodyId( rdr, a->body ), a->name ); +} + +static void b3RecDispatch_BodySetAngularVelocity( const b3RecArgs_BodySetAngularVelocity* a, b3RecReader* rdr ) +{ + b3Body_SetAngularVelocity( b3RecMakeBodyId( rdr, a->body ), a->w ); +} + +static void b3RecDispatch_BodySetTargetTransform( const b3RecArgs_BodySetTargetTransform* a, b3RecReader* rdr ) +{ + b3Body_SetTargetTransform( b3RecMakeBodyId( rdr, a->body ), a->target, a->timeStep, a->wake ); +} + +static void b3RecDispatch_BodyApplyForce( const b3RecArgs_BodyApplyForce* a, b3RecReader* rdr ) +{ + b3Body_ApplyForce( b3RecMakeBodyId( rdr, a->body ), a->force, a->point, a->wake ); +} + +static void b3RecDispatch_BodyApplyForceToCenter( const b3RecArgs_BodyApplyForceToCenter* a, b3RecReader* rdr ) +{ + b3Body_ApplyForceToCenter( b3RecMakeBodyId( rdr, a->body ), a->force, a->wake ); +} + +static void b3RecDispatch_BodyApplyTorque( const b3RecArgs_BodyApplyTorque* a, b3RecReader* rdr ) +{ + b3Body_ApplyTorque( b3RecMakeBodyId( rdr, a->body ), a->torque, a->wake ); +} + +static void b3RecDispatch_BodyApplyLinearImpulse( const b3RecArgs_BodyApplyLinearImpulse* a, b3RecReader* rdr ) +{ + b3Body_ApplyLinearImpulse( b3RecMakeBodyId( rdr, a->body ), a->impulse, a->point, a->wake ); +} + +static void b3RecDispatch_BodyApplyLinearImpulseToCenter( const b3RecArgs_BodyApplyLinearImpulseToCenter* a, b3RecReader* rdr ) +{ + b3Body_ApplyLinearImpulseToCenter( b3RecMakeBodyId( rdr, a->body ), a->impulse, a->wake ); +} + +static void b3RecDispatch_BodyApplyAngularImpulse( const b3RecArgs_BodyApplyAngularImpulse* a, b3RecReader* rdr ) +{ + b3Body_ApplyAngularImpulse( b3RecMakeBodyId( rdr, a->body ), a->impulse, a->wake ); +} + +static void b3RecDispatch_BodySetMassData( const b3RecArgs_BodySetMassData* a, b3RecReader* rdr ) +{ + b3Body_SetMassData( b3RecMakeBodyId( rdr, a->body ), a->massData ); +} + +static void b3RecDispatch_BodyApplyMassFromShapes( const b3RecArgs_BodyApplyMassFromShapes* a, b3RecReader* rdr ) +{ + b3Body_ApplyMassFromShapes( b3RecMakeBodyId( rdr, a->body ) ); +} + +static void b3RecDispatch_BodySetLinearDamping( const b3RecArgs_BodySetLinearDamping* a, b3RecReader* rdr ) +{ + b3Body_SetLinearDamping( b3RecMakeBodyId( rdr, a->body ), a->damping ); +} + +static void b3RecDispatch_BodySetAngularDamping( const b3RecArgs_BodySetAngularDamping* a, b3RecReader* rdr ) +{ + b3Body_SetAngularDamping( b3RecMakeBodyId( rdr, a->body ), a->damping ); +} + +static void b3RecDispatch_BodySetGravityScale( const b3RecArgs_BodySetGravityScale* a, b3RecReader* rdr ) +{ + b3Body_SetGravityScale( b3RecMakeBodyId( rdr, a->body ), a->scale ); +} + +static void b3RecDispatch_BodySetAwake( const b3RecArgs_BodySetAwake* a, b3RecReader* rdr ) +{ + b3Body_SetAwake( b3RecMakeBodyId( rdr, a->body ), a->awake ); +} + +static void b3RecDispatch_BodyEnableSleep( const b3RecArgs_BodyEnableSleep* a, b3RecReader* rdr ) +{ + b3Body_EnableSleep( b3RecMakeBodyId( rdr, a->body ), a->flag ); +} + +static void b3RecDispatch_BodySetSleepThreshold( const b3RecArgs_BodySetSleepThreshold* a, b3RecReader* rdr ) +{ + b3Body_SetSleepThreshold( b3RecMakeBodyId( rdr, a->body ), a->threshold ); +} + +static void b3RecDispatch_BodyDisable( const b3RecArgs_BodyDisable* a, b3RecReader* rdr ) +{ + b3Body_Disable( b3RecMakeBodyId( rdr, a->body ) ); +} + +static void b3RecDispatch_BodyEnable( const b3RecArgs_BodyEnable* a, b3RecReader* rdr ) +{ + b3Body_Enable( b3RecMakeBodyId( rdr, a->body ) ); +} + +static void b3RecDispatch_BodySetMotionLocks( const b3RecArgs_BodySetMotionLocks* a, b3RecReader* rdr ) +{ + b3Body_SetMotionLocks( b3RecMakeBodyId( rdr, a->body ), a->locks ); +} + +static void b3RecDispatch_BodySetBullet( const b3RecArgs_BodySetBullet* a, b3RecReader* rdr ) +{ + b3Body_SetBullet( b3RecMakeBodyId( rdr, a->body ), a->flag ); +} + +static void b3RecDispatch_BodyEnableContactRecycling( const b3RecArgs_BodyEnableContactRecycling* a, b3RecReader* rdr ) +{ + b3Body_EnableContactRecycling( b3RecMakeBodyId( rdr, a->body ), a->flag ); +} + +static void b3RecDispatch_BodyEnableHitEvents( const b3RecArgs_BodyEnableHitEvents* a, b3RecReader* rdr ) +{ + b3Body_EnableHitEvents( b3RecMakeBodyId( rdr, a->body ), a->flag ); +} + +static void b3RecDispatch_CreateSphereShape( const b3RecArgs_CreateSphereShape* a, b3RecReader* rdr ) +{ + b3ShapeId recId = b3RecR_SHAPEID( rdr ); + b3BodyId bodyId = b3RecMakeBodyId( rdr, a->body ); + b3ShapeId gotId = b3CreateSphereShape( bodyId, &a->def, &a->sphere ); + b3RecCheckShapeId( rdr, gotId, recId ); +} + +static void b3RecDispatch_CreateCapsuleShape( const b3RecArgs_CreateCapsuleShape* a, b3RecReader* rdr ) +{ + b3ShapeId recId = b3RecR_SHAPEID( rdr ); + b3BodyId bodyId = b3RecMakeBodyId( rdr, a->body ); + b3ShapeId gotId = b3CreateCapsuleShape( bodyId, &a->def, &a->capsule ); + b3RecCheckShapeId( rdr, gotId, recId ); +} + +static void b3RecDispatch_CreateHullShape( const b3RecArgs_CreateHullShape* a, b3RecReader* rdr ) +{ + b3ShapeId recId = b3RecR_SHAPEID( rdr ); + if ( !rdr->ok ) + { + return; + } + uint32_t id = a->geometryId; + if ( id >= (uint32_t)rdr->slotCount ) + { + printf( "b3ReplayFile: hull geometryId %u out of range\n", id ); + rdr->ok = false; + return; + } + b3RegistrySlot* slot = rdr->slots + id; + b3BodyId bodyId = b3RecMakeBodyId( rdr, a->body ); + // Hull is cloned by b3CreateHullShape into the world DB; no caching needed. + b3ShapeId gotId = b3CreateHullShape( bodyId, &a->def, (const b3HullData*)slot->bytes ); + b3RecCheckShapeId( rdr, gotId, recId ); +} + +static void b3RecDispatch_CreateMeshShape( const b3RecArgs_CreateMeshShape* a, b3RecReader* rdr ) +{ + b3ShapeId recId = b3RecR_SHAPEID( rdr ); + if ( !rdr->ok ) + { + return; + } + uint32_t id = a->geometryId; + if ( id >= (uint32_t)rdr->slotCount ) + { + printf( "b3ReplayFile: mesh geometryId %u out of range\n", id ); + rdr->ok = false; + return; + } + b3RegistrySlot* slot = rdr->slots + id; + const b3MeshData* mesh = (const b3MeshData*)b3RecGetLiveMesh( slot ); + b3BodyId bodyId = b3RecMakeBodyId( rdr, a->body ); + b3ShapeId gotId = b3CreateMeshShape( bodyId, &a->def, mesh, a->scale ); + b3RecCheckShapeId( rdr, gotId, recId ); +} + +static void b3RecDispatch_CreateHeightFieldShape( const b3RecArgs_CreateHeightFieldShape* a, b3RecReader* rdr ) +{ + b3ShapeId recId = b3RecR_SHAPEID( rdr ); + if ( !rdr->ok ) + { + return; + } + uint32_t id = a->geometryId; + if ( id >= (uint32_t)rdr->slotCount ) + { + printf( "b3ReplayFile: heightfield geometryId %u out of range\n", id ); + rdr->ok = false; + return; + } + b3RegistrySlot* slot = rdr->slots + id; + const b3HeightFieldData* hf = (const b3HeightFieldData*)b3RecGetLiveHeightField( slot ); + if ( hf == NULL ) + { + printf( "b3ReplayFile: heightfield geometry %u is corrupt\n", id ); + rdr->ok = false; + return; + } + b3BodyId bodyId = b3RecMakeBodyId( rdr, a->body ); + b3ShapeId gotId = b3CreateHeightFieldShape( bodyId, &a->def, hf ); + b3RecCheckShapeId( rdr, gotId, recId ); +} + +static void b3RecDispatch_CreateCompoundShape( const b3RecArgs_CreateCompoundShape* a, b3RecReader* rdr ) +{ + b3ShapeId recId = b3RecR_SHAPEID( rdr ); + if ( !rdr->ok ) + { + return; + } + uint32_t id = a->geometryId; + if ( id >= (uint32_t)rdr->slotCount ) + { + printf( "b3ReplayFile: compound geometryId %u out of range\n", id ); + rdr->ok = false; + return; + } + b3RegistrySlot* slot = rdr->slots + id; + const b3CompoundData* compound = (const b3CompoundData*)b3RecGetLiveCompound( slot ); + b3BodyId bodyId = b3RecMakeBodyId( rdr, a->body ); + // b3CreateCompoundShape takes a non-const def pointer; cast away const for the scratch def + b3ShapeDef shapeDef = a->def; + b3ShapeId gotId = b3CreateCompoundShape( bodyId, &shapeDef, compound ); + b3RecCheckShapeId( rdr, gotId, recId ); +} + +static void b3RecDispatch_DestroyShape( const b3RecArgs_DestroyShape* a, b3RecReader* rdr ) +{ + b3DestroyShape( b3RecMakeShapeId( rdr, a->shape ), a->updateBodyMass ); +} + +static void b3RecDispatch_ShapeSetDensity( const b3RecArgs_ShapeSetDensity* a, b3RecReader* rdr ) +{ + b3Shape_SetDensity( b3RecMakeShapeId( rdr, a->shape ), a->density, a->updateBodyMass ); +} + +static void b3RecDispatch_ShapeSetFriction( const b3RecArgs_ShapeSetFriction* a, b3RecReader* rdr ) +{ + b3Shape_SetFriction( b3RecMakeShapeId( rdr, a->shape ), a->friction ); +} + +static void b3RecDispatch_ShapeSetRestitution( const b3RecArgs_ShapeSetRestitution* a, b3RecReader* rdr ) +{ + b3Shape_SetRestitution( b3RecMakeShapeId( rdr, a->shape ), a->restitution ); +} + +static void b3RecDispatch_ShapeSetSurfaceMaterial( const b3RecArgs_ShapeSetSurfaceMaterial* a, b3RecReader* rdr ) +{ + b3Shape_SetSurfaceMaterial( b3RecMakeShapeId( rdr, a->shape ), a->material ); +} + +static void b3RecDispatch_ShapeSetFilter( const b3RecArgs_ShapeSetFilter* a, b3RecReader* rdr ) +{ + b3Shape_SetFilter( b3RecMakeShapeId( rdr, a->shape ), a->filter, a->invokeContacts ); +} + +static void b3RecDispatch_ShapeEnableSensorEvents( const b3RecArgs_ShapeEnableSensorEvents* a, b3RecReader* rdr ) +{ + b3Shape_EnableSensorEvents( b3RecMakeShapeId( rdr, a->shape ), a->flag ); +} + +static void b3RecDispatch_ShapeEnableContactEvents( const b3RecArgs_ShapeEnableContactEvents* a, b3RecReader* rdr ) +{ + b3Shape_EnableContactEvents( b3RecMakeShapeId( rdr, a->shape ), a->flag ); +} + +static void b3RecDispatch_ShapeEnablePreSolveEvents( const b3RecArgs_ShapeEnablePreSolveEvents* a, b3RecReader* rdr ) +{ + b3Shape_EnablePreSolveEvents( b3RecMakeShapeId( rdr, a->shape ), a->flag ); +} + +static void b3RecDispatch_ShapeEnableHitEvents( const b3RecArgs_ShapeEnableHitEvents* a, b3RecReader* rdr ) +{ + b3Shape_EnableHitEvents( b3RecMakeShapeId( rdr, a->shape ), a->flag ); +} + +static void b3RecDispatch_ShapeSetSphere( const b3RecArgs_ShapeSetSphere* a, b3RecReader* rdr ) +{ + b3Shape_SetSphere( b3RecMakeShapeId( rdr, a->shape ), &a->sphere ); +} + +static void b3RecDispatch_ShapeSetCapsule( const b3RecArgs_ShapeSetCapsule* a, b3RecReader* rdr ) +{ + b3Shape_SetCapsule( b3RecMakeShapeId( rdr, a->shape ), &a->capsule ); +} + +static void b3RecDispatch_ShapeApplyWind( const b3RecArgs_ShapeApplyWind* a, b3RecReader* rdr ) +{ + b3Shape_ApplyWind( b3RecMakeShapeId( rdr, a->shape ), a->wind, a->drag, a->lift, a->maxSpeed, a->wake ); +} + +// Joint creates: remap body ids in the def before calling the API. + +static void b3RecDispatch_CreateParallelJoint( const b3RecArgs_CreateParallelJoint* a, b3RecReader* rdr ) +{ + b3JointId recId = b3RecR_JOINTID( rdr ); + b3ParallelJointDef def = a->def; + def.base.bodyIdA = b3RecMakeBodyId( rdr, def.base.bodyIdA ); + def.base.bodyIdB = b3RecMakeBodyId( rdr, def.base.bodyIdB ); + b3RecCheckJointId( rdr, b3CreateParallelJoint( rdr->replayWorldId, &def ), recId ); +} + +static void b3RecDispatch_CreateDistanceJoint( const b3RecArgs_CreateDistanceJoint* a, b3RecReader* rdr ) +{ + b3JointId recId = b3RecR_JOINTID( rdr ); + b3DistanceJointDef def = a->def; + def.base.bodyIdA = b3RecMakeBodyId( rdr, def.base.bodyIdA ); + def.base.bodyIdB = b3RecMakeBodyId( rdr, def.base.bodyIdB ); + b3RecCheckJointId( rdr, b3CreateDistanceJoint( rdr->replayWorldId, &def ), recId ); +} + +static void b3RecDispatch_CreateFilterJoint( const b3RecArgs_CreateFilterJoint* a, b3RecReader* rdr ) +{ + b3JointId recId = b3RecR_JOINTID( rdr ); + b3FilterJointDef def = a->def; + def.base.bodyIdA = b3RecMakeBodyId( rdr, def.base.bodyIdA ); + def.base.bodyIdB = b3RecMakeBodyId( rdr, def.base.bodyIdB ); + b3RecCheckJointId( rdr, b3CreateFilterJoint( rdr->replayWorldId, &def ), recId ); +} + +static void b3RecDispatch_CreateMotorJoint( const b3RecArgs_CreateMotorJoint* a, b3RecReader* rdr ) +{ + b3JointId recId = b3RecR_JOINTID( rdr ); + b3MotorJointDef def = a->def; + def.base.bodyIdA = b3RecMakeBodyId( rdr, def.base.bodyIdA ); + def.base.bodyIdB = b3RecMakeBodyId( rdr, def.base.bodyIdB ); + b3RecCheckJointId( rdr, b3CreateMotorJoint( rdr->replayWorldId, &def ), recId ); +} + +static void b3RecDispatch_CreatePrismaticJoint( const b3RecArgs_CreatePrismaticJoint* a, b3RecReader* rdr ) +{ + b3JointId recId = b3RecR_JOINTID( rdr ); + b3PrismaticJointDef def = a->def; + def.base.bodyIdA = b3RecMakeBodyId( rdr, def.base.bodyIdA ); + def.base.bodyIdB = b3RecMakeBodyId( rdr, def.base.bodyIdB ); + b3RecCheckJointId( rdr, b3CreatePrismaticJoint( rdr->replayWorldId, &def ), recId ); +} + +static void b3RecDispatch_CreateRevoluteJoint( const b3RecArgs_CreateRevoluteJoint* a, b3RecReader* rdr ) +{ + b3JointId recId = b3RecR_JOINTID( rdr ); + b3RevoluteJointDef def = a->def; + def.base.bodyIdA = b3RecMakeBodyId( rdr, def.base.bodyIdA ); + def.base.bodyIdB = b3RecMakeBodyId( rdr, def.base.bodyIdB ); + b3RecCheckJointId( rdr, b3CreateRevoluteJoint( rdr->replayWorldId, &def ), recId ); +} + +static void b3RecDispatch_CreateSphericalJoint( const b3RecArgs_CreateSphericalJoint* a, b3RecReader* rdr ) +{ + b3JointId recId = b3RecR_JOINTID( rdr ); + b3SphericalJointDef def = a->def; + def.base.bodyIdA = b3RecMakeBodyId( rdr, def.base.bodyIdA ); + def.base.bodyIdB = b3RecMakeBodyId( rdr, def.base.bodyIdB ); + b3RecCheckJointId( rdr, b3CreateSphericalJoint( rdr->replayWorldId, &def ), recId ); +} + +static void b3RecDispatch_CreateWeldJoint( const b3RecArgs_CreateWeldJoint* a, b3RecReader* rdr ) +{ + b3JointId recId = b3RecR_JOINTID( rdr ); + b3WeldJointDef def = a->def; + def.base.bodyIdA = b3RecMakeBodyId( rdr, def.base.bodyIdA ); + def.base.bodyIdB = b3RecMakeBodyId( rdr, def.base.bodyIdB ); + b3RecCheckJointId( rdr, b3CreateWeldJoint( rdr->replayWorldId, &def ), recId ); +} + +static void b3RecDispatch_CreateWheelJoint( const b3RecArgs_CreateWheelJoint* a, b3RecReader* rdr ) +{ + b3JointId recId = b3RecR_JOINTID( rdr ); + b3WheelJointDef def = a->def; + def.base.bodyIdA = b3RecMakeBodyId( rdr, def.base.bodyIdA ); + def.base.bodyIdB = b3RecMakeBodyId( rdr, def.base.bodyIdB ); + b3RecCheckJointId( rdr, b3CreateWheelJoint( rdr->replayWorldId, &def ), recId ); +} + +static void b3RecDispatch_DestroyJoint( const b3RecArgs_DestroyJoint* a, b3RecReader* rdr ) +{ + b3DestroyJoint( b3RecMakeJointId( rdr, a->joint ), a->wakeAttached ); +} + +static void b3RecDispatch_JointSetLocalFrameA( const b3RecArgs_JointSetLocalFrameA* a, b3RecReader* rdr ) +{ + b3Joint_SetLocalFrameA( b3RecMakeJointId( rdr, a->joint ), a->localFrame ); +} + +static void b3RecDispatch_JointSetLocalFrameB( const b3RecArgs_JointSetLocalFrameB* a, b3RecReader* rdr ) +{ + b3Joint_SetLocalFrameB( b3RecMakeJointId( rdr, a->joint ), a->localFrame ); +} + +static void b3RecDispatch_JointSetCollideConnected( const b3RecArgs_JointSetCollideConnected* a, b3RecReader* rdr ) +{ + b3Joint_SetCollideConnected( b3RecMakeJointId( rdr, a->joint ), a->shouldCollide ); +} + +static void b3RecDispatch_JointWakeBodies( const b3RecArgs_JointWakeBodies* a, b3RecReader* rdr ) +{ + b3Joint_WakeBodies( b3RecMakeJointId( rdr, a->joint ) ); +} + +static void b3RecDispatch_JointSetConstraintTuning( const b3RecArgs_JointSetConstraintTuning* a, b3RecReader* rdr ) +{ + b3Joint_SetConstraintTuning( b3RecMakeJointId( rdr, a->joint ), a->hertz, a->dampingRatio ); +} + +static void b3RecDispatch_JointSetForceThreshold( const b3RecArgs_JointSetForceThreshold* a, b3RecReader* rdr ) +{ + b3Joint_SetForceThreshold( b3RecMakeJointId( rdr, a->joint ), a->threshold ); +} + +static void b3RecDispatch_JointSetTorqueThreshold( const b3RecArgs_JointSetTorqueThreshold* a, b3RecReader* rdr ) +{ + b3Joint_SetTorqueThreshold( b3RecMakeJointId( rdr, a->joint ), a->threshold ); +} + +static void b3RecDispatch_ParallelJointSetSpringHertz( const b3RecArgs_ParallelJointSetSpringHertz* a, b3RecReader* rdr ) +{ + b3ParallelJoint_SetSpringHertz( b3RecMakeJointId( rdr, a->joint ), a->hertz ); +} + +static void b3RecDispatch_ParallelJointSetSpringDampingRatio( const b3RecArgs_ParallelJointSetSpringDampingRatio* a, + b3RecReader* rdr ) +{ + b3ParallelJoint_SetSpringDampingRatio( b3RecMakeJointId( rdr, a->joint ), a->dampingRatio ); +} + +static void b3RecDispatch_ParallelJointSetMaxTorque( const b3RecArgs_ParallelJointSetMaxTorque* a, b3RecReader* rdr ) +{ + b3ParallelJoint_SetMaxTorque( b3RecMakeJointId( rdr, a->joint ), a->maxTorque ); +} + +static void b3RecDispatch_DistanceJointSetLength( const b3RecArgs_DistanceJointSetLength* a, b3RecReader* rdr ) +{ + b3DistanceJoint_SetLength( b3RecMakeJointId( rdr, a->joint ), a->length ); +} + +static void b3RecDispatch_DistanceJointEnableSpring( const b3RecArgs_DistanceJointEnableSpring* a, b3RecReader* rdr ) +{ + b3DistanceJoint_EnableSpring( b3RecMakeJointId( rdr, a->joint ), a->enableSpring ); +} + +static void b3RecDispatch_DistanceJointSetSpringForceRange( const b3RecArgs_DistanceJointSetSpringForceRange* a, + b3RecReader* rdr ) +{ + b3DistanceJoint_SetSpringForceRange( b3RecMakeJointId( rdr, a->joint ), a->lowerForce, a->upperForce ); +} + +static void b3RecDispatch_DistanceJointSetSpringHertz( const b3RecArgs_DistanceJointSetSpringHertz* a, b3RecReader* rdr ) +{ + b3DistanceJoint_SetSpringHertz( b3RecMakeJointId( rdr, a->joint ), a->hertz ); +} + +static void b3RecDispatch_DistanceJointSetSpringDampingRatio( const b3RecArgs_DistanceJointSetSpringDampingRatio* a, + b3RecReader* rdr ) +{ + b3DistanceJoint_SetSpringDampingRatio( b3RecMakeJointId( rdr, a->joint ), a->dampingRatio ); +} + +static void b3RecDispatch_DistanceJointEnableLimit( const b3RecArgs_DistanceJointEnableLimit* a, b3RecReader* rdr ) +{ + b3DistanceJoint_EnableLimit( b3RecMakeJointId( rdr, a->joint ), a->enableLimit ); +} + +static void b3RecDispatch_DistanceJointSetLengthRange( const b3RecArgs_DistanceJointSetLengthRange* a, b3RecReader* rdr ) +{ + b3DistanceJoint_SetLengthRange( b3RecMakeJointId( rdr, a->joint ), a->minLength, a->maxLength ); +} + +static void b3RecDispatch_DistanceJointEnableMotor( const b3RecArgs_DistanceJointEnableMotor* a, b3RecReader* rdr ) +{ + b3DistanceJoint_EnableMotor( b3RecMakeJointId( rdr, a->joint ), a->enableMotor ); +} + +static void b3RecDispatch_DistanceJointSetMotorSpeed( const b3RecArgs_DistanceJointSetMotorSpeed* a, b3RecReader* rdr ) +{ + b3DistanceJoint_SetMotorSpeed( b3RecMakeJointId( rdr, a->joint ), a->motorSpeed ); +} + +static void b3RecDispatch_DistanceJointSetMaxMotorForce( const b3RecArgs_DistanceJointSetMaxMotorForce* a, b3RecReader* rdr ) +{ + b3DistanceJoint_SetMaxMotorForce( b3RecMakeJointId( rdr, a->joint ), a->force ); +} + +static void b3RecDispatch_MotorJointSetLinearVelocity( const b3RecArgs_MotorJointSetLinearVelocity* a, b3RecReader* rdr ) +{ + b3MotorJoint_SetLinearVelocity( b3RecMakeJointId( rdr, a->joint ), a->velocity ); +} + +static void b3RecDispatch_MotorJointSetAngularVelocity( const b3RecArgs_MotorJointSetAngularVelocity* a, b3RecReader* rdr ) +{ + b3MotorJoint_SetAngularVelocity( b3RecMakeJointId( rdr, a->joint ), a->velocity ); +} + +static void b3RecDispatch_MotorJointSetMaxVelocityForce( const b3RecArgs_MotorJointSetMaxVelocityForce* a, b3RecReader* rdr ) +{ + b3MotorJoint_SetMaxVelocityForce( b3RecMakeJointId( rdr, a->joint ), a->maxForce ); +} + +static void b3RecDispatch_MotorJointSetMaxVelocityTorque( const b3RecArgs_MotorJointSetMaxVelocityTorque* a, b3RecReader* rdr ) +{ + b3MotorJoint_SetMaxVelocityTorque( b3RecMakeJointId( rdr, a->joint ), a->maxTorque ); +} + +static void b3RecDispatch_MotorJointSetLinearHertz( const b3RecArgs_MotorJointSetLinearHertz* a, b3RecReader* rdr ) +{ + b3MotorJoint_SetLinearHertz( b3RecMakeJointId( rdr, a->joint ), a->hertz ); +} + +static void b3RecDispatch_MotorJointSetLinearDampingRatio( const b3RecArgs_MotorJointSetLinearDampingRatio* a, b3RecReader* rdr ) +{ + b3MotorJoint_SetLinearDampingRatio( b3RecMakeJointId( rdr, a->joint ), a->damping ); +} + +static void b3RecDispatch_MotorJointSetAngularHertz( const b3RecArgs_MotorJointSetAngularHertz* a, b3RecReader* rdr ) +{ + b3MotorJoint_SetAngularHertz( b3RecMakeJointId( rdr, a->joint ), a->hertz ); +} + +static void b3RecDispatch_MotorJointSetAngularDampingRatio( const b3RecArgs_MotorJointSetAngularDampingRatio* a, + b3RecReader* rdr ) +{ + b3MotorJoint_SetAngularDampingRatio( b3RecMakeJointId( rdr, a->joint ), a->damping ); +} + +static void b3RecDispatch_MotorJointSetMaxSpringForce( const b3RecArgs_MotorJointSetMaxSpringForce* a, b3RecReader* rdr ) +{ + b3MotorJoint_SetMaxSpringForce( b3RecMakeJointId( rdr, a->joint ), a->maxForce ); +} + +static void b3RecDispatch_MotorJointSetMaxSpringTorque( const b3RecArgs_MotorJointSetMaxSpringTorque* a, b3RecReader* rdr ) +{ + b3MotorJoint_SetMaxSpringTorque( b3RecMakeJointId( rdr, a->joint ), a->maxTorque ); +} + +static void b3RecDispatch_PrismaticJointEnableSpring( const b3RecArgs_PrismaticJointEnableSpring* a, b3RecReader* rdr ) +{ + b3PrismaticJoint_EnableSpring( b3RecMakeJointId( rdr, a->joint ), a->enableSpring ); +} + +static void b3RecDispatch_PrismaticJointSetSpringHertz( const b3RecArgs_PrismaticJointSetSpringHertz* a, b3RecReader* rdr ) +{ + b3PrismaticJoint_SetSpringHertz( b3RecMakeJointId( rdr, a->joint ), a->hertz ); +} + +static void b3RecDispatch_PrismaticJointSetSpringDampingRatio( const b3RecArgs_PrismaticJointSetSpringDampingRatio* a, + b3RecReader* rdr ) +{ + b3PrismaticJoint_SetSpringDampingRatio( b3RecMakeJointId( rdr, a->joint ), a->dampingRatio ); +} + +static void b3RecDispatch_PrismaticJointSetTargetTranslation( const b3RecArgs_PrismaticJointSetTargetTranslation* a, + b3RecReader* rdr ) +{ + b3PrismaticJoint_SetTargetTranslation( b3RecMakeJointId( rdr, a->joint ), a->translation ); +} + +static void b3RecDispatch_PrismaticJointEnableLimit( const b3RecArgs_PrismaticJointEnableLimit* a, b3RecReader* rdr ) +{ + b3PrismaticJoint_EnableLimit( b3RecMakeJointId( rdr, a->joint ), a->enableLimit ); +} + +static void b3RecDispatch_PrismaticJointSetLimits( const b3RecArgs_PrismaticJointSetLimits* a, b3RecReader* rdr ) +{ + b3PrismaticJoint_SetLimits( b3RecMakeJointId( rdr, a->joint ), a->lower, a->upper ); +} + +static void b3RecDispatch_PrismaticJointEnableMotor( const b3RecArgs_PrismaticJointEnableMotor* a, b3RecReader* rdr ) +{ + b3PrismaticJoint_EnableMotor( b3RecMakeJointId( rdr, a->joint ), a->enableMotor ); +} + +static void b3RecDispatch_PrismaticJointSetMotorSpeed( const b3RecArgs_PrismaticJointSetMotorSpeed* a, b3RecReader* rdr ) +{ + b3PrismaticJoint_SetMotorSpeed( b3RecMakeJointId( rdr, a->joint ), a->motorSpeed ); +} + +static void b3RecDispatch_PrismaticJointSetMaxMotorForce( const b3RecArgs_PrismaticJointSetMaxMotorForce* a, b3RecReader* rdr ) +{ + b3PrismaticJoint_SetMaxMotorForce( b3RecMakeJointId( rdr, a->joint ), a->force ); +} + +static void b3RecDispatch_RevoluteJointEnableSpring( const b3RecArgs_RevoluteJointEnableSpring* a, b3RecReader* rdr ) +{ + b3RevoluteJoint_EnableSpring( b3RecMakeJointId( rdr, a->joint ), a->enableSpring ); +} + +static void b3RecDispatch_RevoluteJointSetSpringHertz( const b3RecArgs_RevoluteJointSetSpringHertz* a, b3RecReader* rdr ) +{ + b3RevoluteJoint_SetSpringHertz( b3RecMakeJointId( rdr, a->joint ), a->hertz ); +} + +static void b3RecDispatch_RevoluteJointSetSpringDampingRatio( const b3RecArgs_RevoluteJointSetSpringDampingRatio* a, + b3RecReader* rdr ) +{ + b3RevoluteJoint_SetSpringDampingRatio( b3RecMakeJointId( rdr, a->joint ), a->dampingRatio ); +} + +static void b3RecDispatch_RevoluteJointSetTargetAngle( const b3RecArgs_RevoluteJointSetTargetAngle* a, b3RecReader* rdr ) +{ + b3RevoluteJoint_SetTargetAngle( b3RecMakeJointId( rdr, a->joint ), a->angle ); +} + +static void b3RecDispatch_RevoluteJointEnableLimit( const b3RecArgs_RevoluteJointEnableLimit* a, b3RecReader* rdr ) +{ + b3RevoluteJoint_EnableLimit( b3RecMakeJointId( rdr, a->joint ), a->enableLimit ); +} + +static void b3RecDispatch_RevoluteJointSetLimits( const b3RecArgs_RevoluteJointSetLimits* a, b3RecReader* rdr ) +{ + b3RevoluteJoint_SetLimits( b3RecMakeJointId( rdr, a->joint ), a->lower, a->upper ); +} + +static void b3RecDispatch_RevoluteJointEnableMotor( const b3RecArgs_RevoluteJointEnableMotor* a, b3RecReader* rdr ) +{ + b3RevoluteJoint_EnableMotor( b3RecMakeJointId( rdr, a->joint ), a->enableMotor ); +} + +static void b3RecDispatch_RevoluteJointSetMotorSpeed( const b3RecArgs_RevoluteJointSetMotorSpeed* a, b3RecReader* rdr ) +{ + b3RevoluteJoint_SetMotorSpeed( b3RecMakeJointId( rdr, a->joint ), a->motorSpeed ); +} + +static void b3RecDispatch_RevoluteJointSetMaxMotorTorque( const b3RecArgs_RevoluteJointSetMaxMotorTorque* a, b3RecReader* rdr ) +{ + b3RevoluteJoint_SetMaxMotorTorque( b3RecMakeJointId( rdr, a->joint ), a->torque ); +} + +static void b3RecDispatch_SphericalJointEnableConeLimit( const b3RecArgs_SphericalJointEnableConeLimit* a, b3RecReader* rdr ) +{ + b3SphericalJoint_EnableConeLimit( b3RecMakeJointId( rdr, a->joint ), a->enableLimit ); +} + +static void b3RecDispatch_SphericalJointSetConeLimit( const b3RecArgs_SphericalJointSetConeLimit* a, b3RecReader* rdr ) +{ + b3SphericalJoint_SetConeLimit( b3RecMakeJointId( rdr, a->joint ), a->angleRadians ); +} + +static void b3RecDispatch_SphericalJointEnableTwistLimit( const b3RecArgs_SphericalJointEnableTwistLimit* a, b3RecReader* rdr ) +{ + b3SphericalJoint_EnableTwistLimit( b3RecMakeJointId( rdr, a->joint ), a->enableLimit ); +} + +static void b3RecDispatch_SphericalJointSetTwistLimits( const b3RecArgs_SphericalJointSetTwistLimits* a, b3RecReader* rdr ) +{ + b3SphericalJoint_SetTwistLimits( b3RecMakeJointId( rdr, a->joint ), a->lower, a->upper ); +} + +static void b3RecDispatch_SphericalJointEnableSpring( const b3RecArgs_SphericalJointEnableSpring* a, b3RecReader* rdr ) +{ + b3SphericalJoint_EnableSpring( b3RecMakeJointId( rdr, a->joint ), a->enableSpring ); +} + +static void b3RecDispatch_SphericalJointSetSpringHertz( const b3RecArgs_SphericalJointSetSpringHertz* a, b3RecReader* rdr ) +{ + b3SphericalJoint_SetSpringHertz( b3RecMakeJointId( rdr, a->joint ), a->hertz ); +} + +static void b3RecDispatch_SphericalJointSetSpringDampingRatio( const b3RecArgs_SphericalJointSetSpringDampingRatio* a, + b3RecReader* rdr ) +{ + b3SphericalJoint_SetSpringDampingRatio( b3RecMakeJointId( rdr, a->joint ), a->dampingRatio ); +} + +static void b3RecDispatch_SphericalJointSetTargetRotation( const b3RecArgs_SphericalJointSetTargetRotation* a, + b3RecReader* rdr ) +{ + b3SphericalJoint_SetTargetRotation( b3RecMakeJointId( rdr, a->joint ), a->targetRotation ); +} + +static void b3RecDispatch_SphericalJointEnableMotor( const b3RecArgs_SphericalJointEnableMotor* a, b3RecReader* rdr ) +{ + b3SphericalJoint_EnableMotor( b3RecMakeJointId( rdr, a->joint ), a->enableMotor ); +} + +static void b3RecDispatch_SphericalJointSetMotorVelocity( const b3RecArgs_SphericalJointSetMotorVelocity* a, b3RecReader* rdr ) +{ + b3SphericalJoint_SetMotorVelocity( b3RecMakeJointId( rdr, a->joint ), a->motorVelocity ); +} + +static void b3RecDispatch_SphericalJointSetMaxMotorTorque( const b3RecArgs_SphericalJointSetMaxMotorTorque* a, b3RecReader* rdr ) +{ + b3SphericalJoint_SetMaxMotorTorque( b3RecMakeJointId( rdr, a->joint ), a->torque ); +} + +static void b3RecDispatch_WeldJointSetLinearHertz( const b3RecArgs_WeldJointSetLinearHertz* a, b3RecReader* rdr ) +{ + b3WeldJoint_SetLinearHertz( b3RecMakeJointId( rdr, a->joint ), a->hertz ); +} + +static void b3RecDispatch_WeldJointSetLinearDampingRatio( const b3RecArgs_WeldJointSetLinearDampingRatio* a, b3RecReader* rdr ) +{ + b3WeldJoint_SetLinearDampingRatio( b3RecMakeJointId( rdr, a->joint ), a->dampingRatio ); +} + +static void b3RecDispatch_WeldJointSetAngularHertz( const b3RecArgs_WeldJointSetAngularHertz* a, b3RecReader* rdr ) +{ + b3WeldJoint_SetAngularHertz( b3RecMakeJointId( rdr, a->joint ), a->hertz ); +} + +static void b3RecDispatch_WeldJointSetAngularDampingRatio( const b3RecArgs_WeldJointSetAngularDampingRatio* a, b3RecReader* rdr ) +{ + b3WeldJoint_SetAngularDampingRatio( b3RecMakeJointId( rdr, a->joint ), a->dampingRatio ); +} + +static void b3RecDispatch_WheelJointEnableSuspension( const b3RecArgs_WheelJointEnableSuspension* a, b3RecReader* rdr ) +{ + b3WheelJoint_EnableSuspension( b3RecMakeJointId( rdr, a->joint ), a->flag ); +} + +static void b3RecDispatch_WheelJointSetSuspensionHertz( const b3RecArgs_WheelJointSetSuspensionHertz* a, b3RecReader* rdr ) +{ + b3WheelJoint_SetSuspensionHertz( b3RecMakeJointId( rdr, a->joint ), a->hertz ); +} + +static void b3RecDispatch_WheelJointSetSuspensionDampingRatio( const b3RecArgs_WheelJointSetSuspensionDampingRatio* a, + b3RecReader* rdr ) +{ + b3WheelJoint_SetSuspensionDampingRatio( b3RecMakeJointId( rdr, a->joint ), a->dampingRatio ); +} + +static void b3RecDispatch_WheelJointEnableSuspensionLimit( const b3RecArgs_WheelJointEnableSuspensionLimit* a, + b3RecReader* rdr ) +{ + b3WheelJoint_EnableSuspensionLimit( b3RecMakeJointId( rdr, a->joint ), a->flag ); +} + +static void b3RecDispatch_WheelJointSetSuspensionLimits( const b3RecArgs_WheelJointSetSuspensionLimits* a, b3RecReader* rdr ) +{ + b3WheelJoint_SetSuspensionLimits( b3RecMakeJointId( rdr, a->joint ), a->lower, a->upper ); +} + +static void b3RecDispatch_WheelJointEnableSpinMotor( const b3RecArgs_WheelJointEnableSpinMotor* a, b3RecReader* rdr ) +{ + b3WheelJoint_EnableSpinMotor( b3RecMakeJointId( rdr, a->joint ), a->flag ); +} + +static void b3RecDispatch_WheelJointSetSpinMotorSpeed( const b3RecArgs_WheelJointSetSpinMotorSpeed* a, b3RecReader* rdr ) +{ + b3WheelJoint_SetSpinMotorSpeed( b3RecMakeJointId( rdr, a->joint ), a->speed ); +} + +static void b3RecDispatch_WheelJointSetMaxSpinTorque( const b3RecArgs_WheelJointSetMaxSpinTorque* a, b3RecReader* rdr ) +{ + b3WheelJoint_SetMaxSpinTorque( b3RecMakeJointId( rdr, a->joint ), a->torque ); +} + +static void b3RecDispatch_WheelJointEnableSteering( const b3RecArgs_WheelJointEnableSteering* a, b3RecReader* rdr ) +{ + b3WheelJoint_EnableSteering( b3RecMakeJointId( rdr, a->joint ), a->flag ); +} + +static void b3RecDispatch_WheelJointSetSteeringHertz( const b3RecArgs_WheelJointSetSteeringHertz* a, b3RecReader* rdr ) +{ + b3WheelJoint_SetSteeringHertz( b3RecMakeJointId( rdr, a->joint ), a->hertz ); +} + +static void b3RecDispatch_WheelJointSetSteeringDampingRatio( const b3RecArgs_WheelJointSetSteeringDampingRatio* a, + b3RecReader* rdr ) +{ + b3WheelJoint_SetSteeringDampingRatio( b3RecMakeJointId( rdr, a->joint ), a->dampingRatio ); +} + +static void b3RecDispatch_WheelJointSetMaxSteeringTorque( const b3RecArgs_WheelJointSetMaxSteeringTorque* a, b3RecReader* rdr ) +{ + b3WheelJoint_SetMaxSteeringTorque( b3RecMakeJointId( rdr, a->joint ), a->torque ); +} + +static void b3RecDispatch_WheelJointEnableSteeringLimit( const b3RecArgs_WheelJointEnableSteeringLimit* a, b3RecReader* rdr ) +{ + b3WheelJoint_EnableSteeringLimit( b3RecMakeJointId( rdr, a->joint ), a->flag ); +} + +static void b3RecDispatch_WheelJointSetSteeringLimits( const b3RecArgs_WheelJointSetSteeringLimits* a, b3RecReader* rdr ) +{ + b3WheelJoint_SetSteeringLimits( b3RecMakeJointId( rdr, a->joint ), a->lower, a->upper ); +} + +static void b3RecDispatch_WheelJointSetTargetSteeringAngle( const b3RecArgs_WheelJointSetTargetSteeringAngle* a, + b3RecReader* rdr ) +{ + b3WheelJoint_SetTargetSteeringAngle( b3RecMakeJointId( rdr, a->joint ), a->radians ); +} + +static void b3RecDispatch_StateHash( const b3RecArgs_StateHash* a, b3RecReader* rdr ) +{ + b3World* world = b3GetWorldFromId( rdr->replayWorldId ); + uint64_t computed = b3HashWorldState( world ); + if ( computed != a->hash ) + { + printf( "b3ReplayFile: StateHash mismatch (recorded=0x%llX, computed=0x%llX)\n", + (unsigned long long)a->hash, (unsigned long long)computed ); + rdr->diverged = true; + } +} + +static void b3RecDispatch_RecordingBounds( const b3RecArgs_RecordingBounds* a, b3RecReader* rdr ) +{ + // Primary resolve is the open-time scan, this keeps the value right if it ever moves earlier + if ( rdr->owner != NULL ) + { + rdr->owner->bounds = a->bounds; + } +} + +// Spatial query replay. The recorded inputs come through the manifest; here the variable-length hit +// tail is read back, the query re-issued against the replay world, and each callback hit compared to +// what was recorded. Any mismatch latches rdr->diverged. When a player owns the reader the hits are +// also stashed for the viewer overlay. The stash helpers dereference the player struct, defined later +// in this file, so they are forward declared and implemented in Block B below. + +static void b3RecGrow( void** data, int* capacity, int need, int keep, int elemSize ); +static b3RecDrawQuery* b3RecStashQueryBegin( b3RecPlayer* player, int kind, const b3RecRecordedHit* hits, int hitCount ); + +// 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, so a corrupt count fails the read. +void b3RecEnsureHits( b3RecReader* rdr, int n ) +{ + b3RecReserveScratch( rdr, (void**)&rdr->hits, &rdr->hitCap, n, (int)sizeof( b3RecRecordedHit ) ); +} + +// Bitwise float compare so the determinism check is exact, not within a tolerance. +static bool b3RecF32Differs( float a, float b ) +{ + uint32_t ua, ub; + memcpy( &ua, &a, 4 ); + memcpy( &ub, &b, 4 ); + return ua != ub; +} + +static bool b3RecVec3Differs( b3Vec3 a, b3Vec3 b ) +{ + return b3RecF32Differs( a.x, b.x ) || b3RecF32Differs( a.y, b.y ) || b3RecF32Differs( a.z, b.z ); +} + +// Shared context for the replay trampolines: walks recorded hits in order, flagging any divergence +// from the re-issued query. +typedef struct b3RecReplayQueryCtx +{ + b3RecReader* rdr; + const b3RecRecordedHit* hits; + int count; + int cursor; +} b3RecReplayQueryCtx; + +static bool b3RecReplayOverlapTrampoline( b3ShapeId id, void* ctx ) +{ + b3RecReplayQueryCtx* rc = ctx; + if ( rc->cursor >= rc->count ) + { + rc->rdr->diverged = true; + return false; + } + const b3RecRecordedHit* h = &rc->hits[rc->cursor++]; + if ( id.index1 != h->id.index1 || id.generation != h->id.generation ) + { + rc->rdr->diverged = true; + } + return h->userReturnB; +} + +// The mover filter has the same bool(shapeId, ctx) shape as an overlap callback, so it replays the +// same way. A distinct typed wrapper keeps the function-pointer types clean. +static bool b3RecReplayMoverFilterTrampoline( b3ShapeId id, void* ctx ) +{ + return b3RecReplayOverlapTrampoline( id, ctx ); +} + +static float b3RecReplayCastTrampoline( b3ShapeId id, b3Pos point, b3Vec3 normal, float fraction, uint64_t userMaterialId, + int triangleIndex, int childIndex, void* ctx ) +{ + b3RecReplayQueryCtx* rc = ctx; + if ( rc->cursor >= rc->count ) + { + rc->rdr->diverged = true; + return 0.0f; + } + const b3RecRecordedHit* h = &rc->hits[rc->cursor++]; + // Positions compared through a full-width delta, truncating both sides would pass vacuously far + // from the origin. + if ( id.index1 != h->id.index1 || id.generation != h->id.generation || + b3RecVec3Differs( b3SubPos( point, h->point ), b3Vec3_zero ) || b3RecVec3Differs( normal, h->normal ) || + b3RecF32Differs( fraction, h->fraction ) || userMaterialId != h->userMaterialId || triangleIndex != h->triangleIndex || + childIndex != h->childIndex ) + { + rc->rdr->diverged = true; + } + return h->userReturnF; +} + +// 3D delivers a whole shape's planes in one call. The recorded group starts at the cursor with its +// plane count and user return replicated on each hit, so compare the batch and advance by the +// recorded count to stay aligned with the stream even when the count itself diverged. +static bool b3RecReplayPlaneTrampoline( b3ShapeId id, const b3PlaneResult* planes, int planeCount, void* ctx ) +{ + b3RecReplayQueryCtx* rc = ctx; + if ( rc->cursor >= rc->count ) + { + rc->rdr->diverged = true; + return true; + } + const b3RecRecordedHit* head = &rc->hits[rc->cursor]; + int recordedCount = head->planeCount; + bool ret = head->userReturnB; + if ( id.index1 != head->id.index1 || id.generation != head->id.generation || recordedCount != planeCount ) + { + rc->rdr->diverged = true; + } + int n = recordedCount < planeCount ? recordedCount : planeCount; + for ( int i = 0; i < n; ++i ) + { + const b3RecRecordedHit* h = &rc->hits[rc->cursor + i]; + if ( b3RecVec3Differs( h->plane.plane.normal, planes[i].plane.normal ) || + b3RecF32Differs( h->plane.plane.offset, planes[i].plane.offset ) || + b3RecVec3Differs( h->plane.point, planes[i].point ) ) + { + rc->rdr->diverged = true; + } + } + rc->cursor += recordedCount; + return ret; +} + +// Copy a decoded proxy's points into a draw record so the overlay does not depend on reader scratch. +static void b3RecStashProxy( b3RecDrawQuery* q, const b3ShapeProxy* proxy ) +{ + int count = proxy->count; + if ( count > B3_MAX_SHAPE_CAST_POINTS ) + count = B3_MAX_SHAPE_CAST_POINTS; + q->proxyCount = count; + q->proxyRadius = proxy->radius; + for ( int i = 0; i < count; ++i ) + { + q->proxyPoints[i] = proxy->points[i]; + } +} + +static void b3RecDispatch_QueryOverlapAABB( const b3RecArgs_QueryOverlapAABB* a, b3RecReader* rdr ) +{ + uint32_t n = b3RecR_U32( rdr ); + b3RecEnsureHits( rdr, (int)n ); + if ( !rdr->ok ) + return; + for ( uint32_t i = 0; i < n; ++i ) + { + rdr->hits[i].id = b3RecMakeShapeId( rdr, b3RecR_SHAPEID( rdr ) ); + rdr->hits[i].userReturnB = b3RecR_BOOL( rdr ); + } + (void)b3RecR_TREESTATS( rdr ); + if ( !rdr->ok ) + return; + b3RecReplayQueryCtx rc = { rdr, rdr->hits, (int)n, 0 }; + b3World_OverlapAABB( rdr->replayWorldId, a->aabb, a->filter, b3RecReplayOverlapTrampoline, &rc ); + if ( rc.cursor != (int)n ) + rdr->diverged = true; + if ( rdr->owner ) + { + b3RecDrawQuery* q = b3RecStashQueryBegin( rdr->owner, B3_RECQ_OVERLAP_AABB, rdr->hits, (int)n ); + q->filter = a->filter; + q->aabb = a->aabb; + } +} + +static void b3RecDispatch_QueryOverlapShape( const b3RecArgs_QueryOverlapShape* a, b3RecReader* rdr ) +{ + uint32_t n = b3RecR_U32( rdr ); + b3RecEnsureHits( rdr, (int)n ); + if ( !rdr->ok ) + return; + for ( uint32_t i = 0; i < n; ++i ) + { + rdr->hits[i].id = b3RecMakeShapeId( rdr, b3RecR_SHAPEID( rdr ) ); + rdr->hits[i].userReturnB = b3RecR_BOOL( rdr ); + } + (void)b3RecR_TREESTATS( rdr ); + if ( !rdr->ok ) + return; + b3RecReplayQueryCtx rc = { rdr, rdr->hits, (int)n, 0 }; + b3World_OverlapShape( rdr->replayWorldId, a->origin, &a->proxy, a->filter, b3RecReplayOverlapTrampoline, &rc ); + if ( rc.cursor != (int)n ) + rdr->diverged = true; + if ( rdr->owner ) + { + b3RecDrawQuery* q = b3RecStashQueryBegin( rdr->owner, B3_RECQ_OVERLAP_SHAPE, rdr->hits, (int)n ); + q->filter = a->filter; + q->origin = a->origin; + b3RecStashProxy( q, &a->proxy ); + } +} + +static void b3RecDispatch_QueryCastRay( const b3RecArgs_QueryCastRay* a, b3RecReader* rdr ) +{ + uint32_t n = b3RecR_U32( rdr ); + b3RecEnsureHits( rdr, (int)n ); + if ( !rdr->ok ) + return; + for ( uint32_t i = 0; i < n; ++i ) + { + rdr->hits[i].id = b3RecMakeShapeId( rdr, b3RecR_SHAPEID( rdr ) ); + rdr->hits[i].point = b3RecR_POSITION( rdr ); + rdr->hits[i].normal = b3RecR_VEC3( rdr ); + rdr->hits[i].fraction = b3RecR_F32( rdr ); + rdr->hits[i].userMaterialId = b3RecR_U64( rdr ); + rdr->hits[i].triangleIndex = b3RecR_I32( rdr ); + rdr->hits[i].childIndex = b3RecR_I32( rdr ); + rdr->hits[i].userReturnF = b3RecR_F32( rdr ); + } + (void)b3RecR_TREESTATS( rdr ); + if ( !rdr->ok ) + return; + b3RecReplayQueryCtx rc = { rdr, rdr->hits, (int)n, 0 }; + b3World_CastRay( rdr->replayWorldId, a->origin, a->translation, a->filter, b3RecReplayCastTrampoline, &rc ); + if ( rc.cursor != (int)n ) + rdr->diverged = true; + if ( rdr->owner ) + { + b3RecDrawQuery* q = b3RecStashQueryBegin( rdr->owner, B3_RECQ_CAST_RAY, rdr->hits, (int)n ); + q->filter = a->filter; + q->origin = a->origin; + q->translation = a->translation; + } +} + +static void b3RecDispatch_QueryCastShape( const b3RecArgs_QueryCastShape* a, b3RecReader* rdr ) +{ + uint32_t n = b3RecR_U32( rdr ); + b3RecEnsureHits( rdr, (int)n ); + if ( !rdr->ok ) + return; + for ( uint32_t i = 0; i < n; ++i ) + { + rdr->hits[i].id = b3RecMakeShapeId( rdr, b3RecR_SHAPEID( rdr ) ); + rdr->hits[i].point = b3RecR_POSITION( rdr ); + rdr->hits[i].normal = b3RecR_VEC3( rdr ); + rdr->hits[i].fraction = b3RecR_F32( rdr ); + rdr->hits[i].userMaterialId = b3RecR_U64( rdr ); + rdr->hits[i].triangleIndex = b3RecR_I32( rdr ); + rdr->hits[i].childIndex = b3RecR_I32( rdr ); + rdr->hits[i].userReturnF = b3RecR_F32( rdr ); + } + (void)b3RecR_TREESTATS( rdr ); + if ( !rdr->ok ) + return; + b3RecReplayQueryCtx rc = { rdr, rdr->hits, (int)n, 0 }; + b3World_CastShape( rdr->replayWorldId, a->origin, &a->proxy, a->translation, a->filter, b3RecReplayCastTrampoline, &rc ); + if ( rc.cursor != (int)n ) + rdr->diverged = true; + if ( rdr->owner ) + { + b3RecDrawQuery* q = b3RecStashQueryBegin( rdr->owner, B3_RECQ_CAST_SHAPE, rdr->hits, (int)n ); + q->filter = a->filter; + q->origin = a->origin; + q->translation = a->translation; + b3RecStashProxy( q, &a->proxy ); + } +} + +static void b3RecDispatch_QueryCastRayClosest( const b3RecArgs_QueryCastRayClosest* a, b3RecReader* rdr ) +{ + b3RayResult rec = b3RecR_RAYRESULT( rdr ); + if ( !rdr->ok ) + return; + b3RayResult got = b3World_CastRayClosest( rdr->replayWorldId, a->origin, a->translation, a->filter ); + b3ShapeId recId = b3RecMakeShapeId( rdr, rec.shapeId ); + if ( got.hit != rec.hit || + ( got.hit && ( got.shapeId.index1 != recId.index1 || got.shapeId.generation != recId.generation || + b3RecVec3Differs( b3SubPos( got.point, rec.point ), b3Vec3_zero ) || + b3RecVec3Differs( got.normal, rec.normal ) || b3RecF32Differs( got.fraction, rec.fraction ) || + got.userMaterialId != rec.userMaterialId ) ) ) + { + rdr->diverged = true; + } + if ( rdr->owner ) + { + // Stash the closest result as a single pooled hit so the shared draw loop renders its point. + b3RecRecordedHit h = { 0 }; + h.id = recId; + h.point = rec.point; + h.normal = rec.normal; + h.fraction = rec.fraction; + b3RecDrawQuery* q = b3RecStashQueryBegin( rdr->owner, B3_RECQ_CAST_RAY_CLOSEST, &h, rec.hit ? 1 : 0 ); + q->filter = a->filter; + q->origin = a->origin; + q->translation = a->translation; + q->rayResult = rec; + } +} + +static void b3RecDispatch_QueryCastMover( const b3RecArgs_QueryCastMover* a, b3RecReader* rdr ) +{ + uint32_t n = b3RecR_U32( rdr ); + b3RecEnsureHits( rdr, (int)n ); + if ( !rdr->ok ) + return; + for ( uint32_t i = 0; i < n; ++i ) + { + rdr->hits[i].id = b3RecMakeShapeId( rdr, b3RecR_SHAPEID( rdr ) ); + rdr->hits[i].userReturnB = b3RecR_BOOL( rdr ); + } + float recFraction = b3RecR_F32( rdr ); + if ( !rdr->ok ) + return; + b3RecReplayQueryCtx rc = { rdr, rdr->hits, (int)n, 0 }; + float got = b3World_CastMover( rdr->replayWorldId, a->origin, &a->mover, a->translation, a->filter, + b3RecReplayMoverFilterTrampoline, &rc ); + if ( rc.cursor != (int)n || b3RecF32Differs( got, recFraction ) ) + rdr->diverged = true; + if ( rdr->owner ) + { + b3RecDrawQuery* q = b3RecStashQueryBegin( rdr->owner, B3_RECQ_CAST_MOVER, NULL, 0 ); + q->filter = a->filter; + q->origin = a->origin; + q->mover = a->mover; + q->translation = a->translation; + q->castFraction = recFraction; + } +} + +static void b3RecDispatch_QueryCollideMover( const b3RecArgs_QueryCollideMover* a, b3RecReader* rdr ) +{ + // Recorded as shapeCount groups, each: shapeId, planeCount, planeCount planes, user return. Flatten + // into one hit per plane with the group's count and return replicated, so the replay walker can + // re-group per shape. + uint32_t shapeCount = b3RecR_U32( rdr ); + int total = 0; + for ( uint32_t s = 0; s < shapeCount; ++s ) + { + b3ShapeId id = b3RecMakeShapeId( rdr, b3RecR_SHAPEID( rdr ) ); + int planeCount = b3RecR_I32( rdr ); + if ( planeCount < 0 ) + planeCount = 0; + b3RecEnsureHits( rdr, total + planeCount ); + if ( !rdr->ok ) + return; + for ( int i = 0; i < planeCount; ++i ) + { + rdr->hits[total + i].plane = b3RecR_PLANERESULT( rdr ); + } + bool ret = b3RecR_BOOL( rdr ); + for ( int i = 0; i < planeCount; ++i ) + { + rdr->hits[total + i].id = id; + rdr->hits[total + i].planeCount = planeCount; + rdr->hits[total + i].userReturnB = ret; + } + total += planeCount; + } + if ( !rdr->ok ) + return; + b3RecReplayQueryCtx rc = { rdr, rdr->hits, total, 0 }; + b3World_CollideMover( rdr->replayWorldId, a->origin, &a->mover, a->filter, b3RecReplayPlaneTrampoline, &rc ); + if ( rc.cursor != total ) + rdr->diverged = true; + if ( rdr->owner ) + { + b3RecDrawQuery* q = b3RecStashQueryBegin( rdr->owner, B3_RECQ_COLLIDE_MOVER, rdr->hits, total ); + q->filter = a->filter; + q->origin = a->origin; + q->mover = a->mover; + } +} + +// X-macro dispatch switch: read opcode+u24 payloadSize, dispatch, skip unknown ops. +// Returns the opcode dispatched, or -1 when the stream is exhausted or broken. + +static int b3RecDispatchOne( b3RecReader* rdr ) +{ + if ( rdr->cursor >= rdr->size || !rdr->ok ) + { + return -1; + } + uint8_t opcode = b3RecR_U8( rdr ); + uint32_t payloadSize = b3RecR_U24( rdr ); + if ( !rdr->ok ) + { + return -1; + } + int payloadStart = rdr->cursor; + + switch ( opcode ) + { +#define ARG( TAG, field ) a.field = b3RecR_##TAG( rdr ); +#define B3_REC_OP( op, Name, RET, ... ) \ + case op: \ + { \ + b3RecArgs_##Name a; \ + memset( &a, 0, sizeof( a ) ); \ + __VA_ARGS__ \ + if ( rdr->ok ) \ + { \ + b3RecDispatch_##Name( &a, rdr ); \ + } \ + break; \ + } +#include "recording_ops.inl" +#undef B3_REC_OP +#undef ARG + default: + printf( "b3ReplayFile: unknown opcode 0x%02X, skipping %u bytes\n", opcode, payloadSize ); + // payloadStart is in bounds, so size - payloadStart is the bytes left to skip over + if ( payloadSize > (uint32_t)( rdr->size - payloadStart ) ) + { + rdr->ok = false; + } + else + { + rdr->cursor = payloadStart + (int)payloadSize; + } + break; + } + return (int)(unsigned)opcode; +} + +// Public entry point + +bool b3ValidateReplay( const void* data, int size, int workerCount ) +{ + b3RecPlayer* player = b3RecPlayer_Create( data, size, workerCount ); + if ( player == NULL ) + { + return false; + } + + while ( b3RecPlayer_StepFrame( player ) ) + { + if ( player->rdr.diverged ) + { + break; + } + } + + bool ok = player->rdr.ok && player->rdr.diverged == false; + b3RecPlayer_Destroy( player ); + return ok; +} + +// b3RecPlayer implementation + +#define B3_REC_KEYFRAME_INTERVAL_DEFAULT 16 +#define B3_REC_KEYFRAME_BUDGET_DEFAULT ( (size_t)512 * 1024 * 1024 ) + +// Overflow-safe growth for the player's accumulating arrays. Counts come from the replay itself, +// not the file, so this only guards the byte-size multiply. Preserves keep elements. +static void b3RecGrow( void** data, int* capacity, int need, int keep, int elemSize ) +{ + if ( need <= *capacity ) + { + return; + } + int newCap = *capacity == 0 ? 8 : 2 * *capacity; + if ( newCap < need ) + { + newCap = need; + } + void* grown = b3Alloc( (size_t)newCap * (size_t)elemSize ); + if ( *data != NULL ) + { + if ( keep > 0 ) + { + memcpy( grown, *data, (size_t)keep * (size_t)elemSize ); + } + b3Free( *data, (size_t)*capacity * (size_t)elemSize ); + } + *data = grown; + *capacity = newCap; +} + +// Block B: per-frame query store helpers. Forward declared above the query dispatchers, which run +// before the player struct is defined, so the player-dereferencing code lives here. + +static void b3RecGrowFrameQueries( b3RecPlayer* player ) +{ + b3RecGrow( (void**)&player->frameQueries, &player->frameQueryCap, player->frameQueryCount + 1, player->frameQueryCount, + (int)sizeof( b3RecDrawQuery ) ); +} + +static void b3RecGrowFrameHits( b3RecPlayer* player, int need ) +{ + b3RecGrow( (void**)&player->frameHits, &player->frameHitCap, player->frameHitCount + need, player->frameHitCount, + (int)sizeof( b3RecRecordedHit ) ); +} + +// Push a draw record for one query and copy its hits into the per-frame store. Ids in hits[] are +// already remapped to the replay world by the dispatcher. +static b3RecDrawQuery* b3RecStashQueryBegin( b3RecPlayer* player, int kind, const b3RecRecordedHit* hits, int hitCount ) +{ + b3RecGrowFrameQueries( player ); + b3RecDrawQuery* q = &player->frameQueries[player->frameQueryCount]; + memset( q, 0, sizeof( *q ) ); + q->kind = kind; + q->hitStart = player->frameHitCount; + q->hitCount = hitCount; + b3RecGrowFrameHits( player, hitCount ); + for ( int i = 0; i < hitCount; ++i ) + { + player->frameHits[player->frameHitCount + i] = hits[i]; + } + player->frameHitCount += hitCount; + player->frameQueryCount++; + return q; +} + +// Append a created body to the outliner list. Ordinals are creation order and never reused. +static void b3RecTrackBodyCreate( b3RecPlayer* player, b3BodyId id ) +{ + b3RecGrow( (void**)&player->bodyIds, &player->bodyIdCap, player->bodyIdCount + 1, player->bodyIdCount, + (int)sizeof( b3BodyId ) ); + player->bodyIds[player->bodyIdCount] = id; + player->bodyIdCount += 1; +} + +// Leave a hole so later ordinals do not shift, keeping a stored selection stable. +static void b3RecTrackBodyDestroy( b3RecPlayer* player, b3BodyId id ) +{ + for ( int i = 0; i < player->bodyIdCount; ++i ) + { + if ( B3_ID_EQUALS( player->bodyIds[i], id ) ) + { + player->bodyIds[i] = b3_nullBodyId; + return; + } + } +} + +// Snapshot bodies are restored as a struct image and never hit the CreateBody hook the tracker keys +// on, so the seed world must be walked once to populate the outliner list. Slot order is stable. +static void b3RecSeedBodyIds( b3RecPlayer* player ) +{ + b3World* world = b3GetWorldFromId( player->rdr.replayWorldId ); + player->bodyIdCount = 0; + int count = world->bodies.count; + for ( int i = 0; i < count; ++i ) + { + if ( world->bodies.data[i].id != i ) + { + continue; // free slot + } + b3RecTrackBodyCreate( player, b3MakeBodyId( world, i ) ); + } +} + +// Seed the outliner list from the current world and save it as the frame-0 restore copy. +static void b3RecSeedFrame0BodyIds( b3RecPlayer* player ) +{ + b3RecSeedBodyIds( player ); + if ( player->frame0BodyIds != NULL ) + { + b3Free( player->frame0BodyIds, (size_t)player->frame0BodyIdCount * sizeof( b3BodyId ) ); + player->frame0BodyIds = NULL; + } + player->frame0BodyIdCount = player->bodyIdCount; + if ( player->bodyIdCount > 0 ) + { + player->frame0BodyIds = (b3BodyId*)b3Alloc( (size_t)player->bodyIdCount * sizeof( b3BodyId ) ); + memcpy( player->frame0BodyIds, player->bodyIds, (size_t)player->bodyIdCount * sizeof( b3BodyId ) ); + } +} + +// Load the trailing registry block and fill rdr->slots/slotCount. +// Returns true on success. On failure sets rdr->ok = false and returns false. +static bool b3RecLoadSlots( b3RecReader* rdr, const void* data, int size, uint64_t registryOffset, uint64_t registryByteCount ) +{ + if ( registryOffset == 0 || registryByteCount == 0 ) + { + rdr->slots = NULL; + rdr->slotCount = 0; + return true; + } + + int regStart = (int)registryOffset; + int regEnd = regStart + (int)registryByteCount; + if ( regEnd > size ) + { + printf( "b3ReplayFile: registry block out of bounds\n" ); + return false; + } + if ( regStart + 4 > size ) + { + printf( "b3ReplayFile: registry too small\n" ); + return false; + } + + const uint8_t* rp = (const uint8_t*)data + regStart; + uint32_t count = (uint32_t)rp[0] | ( (uint32_t)rp[1] << 8 ) | ( (uint32_t)rp[2] << 16 ) | ( (uint32_t)rp[3] << 24 ); + rp += 4; + + if ( count == 0 ) + { + rdr->slots = NULL; + rdr->slotCount = 0; + return true; + } + + b3RegistrySlot* slots = (b3RegistrySlot*)b3Alloc( (size_t)count * sizeof( b3RegistrySlot ) ); + memset( slots, 0, (size_t)count * sizeof( b3RegistrySlot ) ); + + const uint8_t* dataEnd = (const uint8_t*)data + regEnd; + for ( uint32_t i = 0; i < count; ++i ) + { + if ( rp + 5 > dataEnd ) + { + printf( "b3ReplayFile: registry truncated at entry %u\n", i ); + for ( uint32_t j = 0; j < i; ++j ) + { + if ( slots[j].bytes != NULL ) + { + b3Free( slots[j].bytes, (size_t)slots[j].byteCount ); + } + } + b3Free( slots, (size_t)count * sizeof( b3RegistrySlot ) ); + return false; + } + uint8_t kind = rp[0]; + uint32_t byteCount = (uint32_t)rp[1] | ( (uint32_t)rp[2] << 8 ) | ( (uint32_t)rp[3] << 16 ) | ( (uint32_t)rp[4] << 24 ); + rp += 5; + if ( rp + byteCount > dataEnd ) + { + printf( "b3ReplayFile: registry entry %u bytes out of bounds\n", i ); + for ( uint32_t j = 0; j < i; ++j ) + { + if ( slots[j].bytes != NULL ) + { + b3Free( slots[j].bytes, (size_t)slots[j].byteCount ); + } + } + b3Free( slots, (size_t)count * sizeof( b3RegistrySlot ) ); + return false; + } + uint8_t* bytes = (uint8_t*)b3Alloc( byteCount > 0 ? (size_t)byteCount : 1u ); + if ( byteCount > 0 ) + { + memcpy( bytes, rp, (size_t)byteCount ); + } + rp += byteCount; + slots[i].kind = (b3GeometryKind)kind; + slots[i].byteCount = (int)byteCount; + slots[i].bytes = bytes; + slots[i].live = NULL; + } + + rdr->slots = slots; + rdr->slotCount = (int)count; + return true; +} + +// Free slots loaded by b3RecLoadSlots. +static void b3RecFreeSlots( b3RegistrySlot* slots, int slotCount ) +{ + if ( slots == NULL ) + { + return; + } + for ( int i = 0; i < slotCount; ++i ) + { + b3RegistrySlot* slot = slots + i; + if ( slot->live != NULL ) + { + switch ( slot->kind ) + { + // Mesh and height field have no separate live object; they borrow the bytes freed below. + case b3_geometryCompound: + b3Free( slot->live, (size_t)slot->byteCount ); + break; + default: + break; + } + } + if ( slot->bytes != NULL ) + { + b3Free( slot->bytes, slot->byteCount > 0 ? (size_t)slot->byteCount : 1u ); + } + } + b3Free( slots, (size_t)slotCount * sizeof( b3RegistrySlot ) ); +} + +// Walk the op stream once without dispatching: count Step ops and grab the first step's tuning. +static void b3RecScanFile( b3RecPlayer* player ) +{ + const uint8_t* data = player->data; + int size = player->registryEnd; + int cursor = player->headerEnd; + int frameCount = 0; + bool gotStep = false; + + while ( cursor + 4 <= size ) + { + uint8_t opcode = data[cursor]; + uint32_t payloadSize = (uint32_t)data[cursor + 1] | ( (uint32_t)data[cursor + 2] << 8 ) | ( (uint32_t)data[cursor + 3] << 16 ); + int payloadStart = cursor + 4; + if ( payloadStart + (int)payloadSize > size ) + { + break; + } + if ( opcode == b3_recOpStep ) + { + frameCount += 1; + if ( !gotStep && payloadSize >= 12 ) + { + uint32_t dtBits = (uint32_t)data[payloadStart + 4] | ( (uint32_t)data[payloadStart + 5] << 8 ) | + ( (uint32_t)data[payloadStart + 6] << 16 ) | ( (uint32_t)data[payloadStart + 7] << 24 ); + memcpy( &player->recordedDt, &dtBits, 4 ); + player->recordedSubStepCount = (int)( (uint32_t)data[payloadStart + 8] | ( (uint32_t)data[payloadStart + 9] << 8 ) | + ( (uint32_t)data[payloadStart + 10] << 16 ) | ( (uint32_t)data[payloadStart + 11] << 24 ) ); + gotStep = true; + } + } + else if ( opcode == 0xF2 && payloadSize >= (uint32_t)sizeof( b3AABB ) ) // RecordingBounds + { + // Payload is a single b3AABB (lower xyz, upper xyz as f32), written at stop so the + // viewer can frame the whole recorded motion without playing to the end. + memcpy( &player->bounds, data + payloadStart, sizeof( b3AABB ) ); + } + cursor = payloadStart + (int)payloadSize; + } + player->frameCount = frameCount; +} + +// Free one keyframe's heap. +static void b3FreeKeyframe( b3RecKeyframe* kf ) +{ + if ( kf->image != NULL ) + { + b3Free( kf->image, (size_t)kf->imageCapacity ); + } + if ( kf->bodyIds != NULL ) + { + b3Free( kf->bodyIds, (size_t)kf->bodyIdCount * sizeof( b3BodyId ) ); + } +} + +// Pre-populate keyframeRec's registry to mirror rdr.slots so geometry ids stay stable during +// b3SerializeWorld. b3InternGeometry deduplicates so the count stays constant. +static void b3RecSeedKeyframeRegistry( b3RecPlayer* player ) +{ + b3GeometryRegistry* reg = &player->keyframeRec->registry; + for ( int i = 0; i < player->rdr.slotCount; ++i ) + { + b3RegistrySlot* slot = player->rdr.slots + i; + // Copy so b3InternGeometry can take ownership (it frees on dedup, which won't happen + // since we're inserting fresh entries in order). + int n = slot->byteCount > 0 ? slot->byteCount : 1; + uint8_t* copy = (uint8_t*)b3Alloc( (size_t)n ); + if ( slot->byteCount > 0 ) + { + memcpy( copy, slot->bytes, (size_t)slot->byteCount ); + } + uint64_t h = b3Hash64Blob( slot->bytes, slot->byteCount ); + uint32_t id = b3InternGeometry( reg, slot->kind, h, copy, slot->byteCount ); + // Each slot should get id == its index since we seed in order. + B3_ASSERT( id == (uint32_t)i ); + (void)id; + } +} + +// Capture a restore-point keyframe for the just-completed frame. rdr.cursor already points to +// the next frame's Step op. +static void b3RecCaptureKeyframe( b3RecPlayer* player ) +{ + b3World* world = b3GetWorldFromId( player->rdr.replayWorldId ); + b3RecBuffer buf = { 0 }; + + int regCountBefore = player->keyframeRec->registry.count; + b3SerializeWorld( world, &buf, player->keyframeRec ); + // Registry must not grow: all geometry was pre-seeded. + B3_ASSERT( player->keyframeRec->registry.count == regCountBefore ); + + size_t bodyBytes = (size_t)player->bodyIdCount * sizeof( b3BodyId ); + size_t newBytes = (size_t)buf.capacity + bodyBytes; + + // Make room under the budget by doubling the spacing and evicting off-grid keyframes. + while ( player->keyframeCount > 0 && player->keyframeBytes + newBytes > player->keyframeBudget ) + { + player->keyframeInterval *= 2; + int kept = 0; + size_t keptBytes = 0; + for ( int i = 0; i < player->keyframeCount; ++i ) + { + b3RecKeyframe* kf = player->keyframes + i; + if ( kf->frame % player->keyframeInterval == 0 ) + { + player->keyframes[kept] = *kf; + keptBytes += (size_t)kf->imageCapacity + (size_t)kf->bodyIdCount * sizeof( b3BodyId ); + kept += 1; + } + else + { + b3FreeKeyframe( kf ); + } + } + bool progress = ( kept < player->keyframeCount ); + player->keyframeCount = kept; + player->keyframeBytes = keptBytes; + if ( !progress ) + { + break; + } + } + + // Grow the keyframe ring if needed. + if ( player->keyframeCount >= player->keyframeCapacity ) + { + int newCap = player->keyframeCapacity < 8 ? 8 : player->keyframeCapacity * 2; + player->keyframes = (b3RecKeyframe*)b3GrowAlloc( player->keyframes, + player->keyframeCapacity * (int)sizeof( b3RecKeyframe ), + newCap * (int)sizeof( b3RecKeyframe ) ); + player->keyframeCapacity = newCap; + } + + b3RecKeyframe* kf = player->keyframes + player->keyframeCount; + kf->image = buf.data; + kf->imageSize = buf.size; + kf->imageCapacity = buf.capacity; + kf->frame = player->frame; + kf->cursor = player->rdr.cursor; + kf->divergeFrame = player->divergeFrame; + kf->diverged = player->rdr.diverged; + kf->bodyIdCount = player->bodyIdCount; + kf->bodyIds = NULL; + if ( bodyBytes > 0 ) + { + kf->bodyIds = (b3BodyId*)b3Alloc( bodyBytes ); + memcpy( kf->bodyIds, player->bodyIds, bodyBytes ); + } + + player->keyframeBytes += newBytes; + player->keyframeCount += 1; + player->lastKeyframeFrame = player->frame; +} + +// Restore the world in-place from a keyframe image. +static void b3RecPlayerRestoreKeyframe( b3RecPlayer* player, const b3RecKeyframe* kf ) +{ + b3World* world = b3GetWorldFromId( player->rdr.replayWorldId ); + if ( b3DeserializeIntoShell( kf->image, kf->imageSize, world, &player->rdr ) == false ) + { + player->rdr.ok = false; + return; + } + player->rdr.cursor = kf->cursor; + player->rdr.ok = true; + player->rdr.diverged = kf->diverged; + player->frame = kf->frame; + player->divergeFrame = kf->divergeFrame; + player->atEnd = false; + + // Restore the outliner list verbatim so ordinals match this frame. + b3RecGrow( (void**)&player->bodyIds, &player->bodyIdCap, kf->bodyIdCount, 0, (int)sizeof( b3BodyId ) ); + player->bodyIdCount = kf->bodyIdCount; + if ( kf->bodyIdCount > 0 ) + { + memcpy( player->bodyIds, kf->bodyIds, (size_t)kf->bodyIdCount * sizeof( b3BodyId ) ); + } +} + +// Create a replay world carrying the host debug-shape callbacks. Every world the player +// stands up funnels through here so the sample renderer can draw replayed shapes. +static b3WorldId b3RecPlayerCreateWorld( const b3RecPlayer* player ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + worldDef.createDebugShape = player->createDebugShape; + worldDef.destroyDebugShape = player->destroyDebugShape; + worldDef.userDebugShapeContext = player->debugShapeContext; + // Carry the requested worker count so a rebuild on Restart or backward seek keeps the same + // graph partitioning. Replaying at a different count than recorded is a determinism check. + worldDef.workerCount = b3MaxInt( 1, player->recordedWorkerCount ); + return b3CreateWorld( &worldDef ); +} + +b3RecPlayer* b3RecPlayer_Create( const void* data, int size, int workerCount ) +{ + if ( data == NULL || size < (int)sizeof( b3RecHeader ) ) + { + printf( "b3RecPlayer_Create: recording too small\n" ); + return NULL; + } + + b3RecHeader hdr; + memcpy( &hdr, data, sizeof( hdr ) ); + + if ( hdr.magic != B3_REC_MAGIC ) + { + printf( "b3RecPlayer_Create: bad magic 0x%08X\n", hdr.magic ); + return NULL; + } + // Only the major version is breaking. Minor bumps are additive op-stream changes that keep the + // header shape, and the dispatcher skips opcodes it doesn't know, so a minor mismatch still loads. + if ( hdr.versionMajor != B3_REC_VERSION_MAJOR ) + { + printf( "b3RecPlayer_Create: version mismatch %u.%u vs %u.%u\n", + hdr.versionMajor, hdr.versionMinor, B3_REC_VERSION_MAJOR, B3_REC_VERSION_MINOR ); + return NULL; + } + if ( hdr.pointerWidth != (uint8_t)sizeof( void* ) ) + { + printf( "b3RecPlayer_Create: pointer width mismatch %u vs %u\n", hdr.pointerWidth, (unsigned)sizeof( void* ) ); + return NULL; + } + if ( hdr.bigEndian != 0 ) + { + printf( "b3RecPlayer_Create: big-endian recording not supported\n" ); + return NULL; + } + + // Every recording is snapshot-seeded: the seed blob sits between the header and the op stream. + if ( hdr.snapshotSize == 0 ) + { + printf( "b3RecPlayer_Create: missing snapshot seed\n" ); + return NULL; + } + + // snapshotSize and registryOffset are 64-bit and come from the file. Validate in 64-bit so a + // hostile value can't wrap when narrowed to int, then narrow once the bounds are known good. + uint64_t headerEnd64 = (uint64_t)sizeof( b3RecHeader ) + hdr.snapshotSize; + uint64_t registryEnd64 = ( hdr.registryOffset != 0 ) ? hdr.registryOffset : (uint64_t)size; + + if ( headerEnd64 < sizeof( b3RecHeader ) || headerEnd64 > registryEnd64 || registryEnd64 > (uint64_t)size ) + { + printf( "b3RecPlayer_Create: corrupt offsets\n" ); + return NULL; + } + + int headerEnd = (int)headerEnd64; + int registryEnd = (int)registryEnd64; + + // Own a private copy so the caller can free their buffer right away. + uint8_t* copy = (uint8_t*)b3Alloc( (size_t)size ); + memcpy( copy, data, (size_t)size ); + + b3RecPlayer* player = (b3RecPlayer*)b3Alloc( sizeof( b3RecPlayer ) ); + memset( player, 0, sizeof( b3RecPlayer ) ); + + player->data = copy; + player->size = size; + player->headerEnd = headerEnd; + player->registryEnd = registryEnd; + player->lengthScale = hdr.lengthScale; + player->previousLengthScale = b3GetLengthUnitsPerMeter(); + player->frame = 0; + player->frameCount = 0; + player->recordedDt = 0.0f; + player->recordedSubStepCount = 0; + player->recordedWorkerCount = workerCount; + player->atEnd = false; + player->divergeFrame = -1; + player->keyframeMinInterval = B3_REC_KEYFRAME_INTERVAL_DEFAULT; + player->keyframeInterval = B3_REC_KEYFRAME_INTERVAL_DEFAULT; + player->keyframeBudget = B3_REC_KEYFRAME_BUDGET_DEFAULT; + player->lastKeyframeFrame = 0; + + // Set length scale so replay reproduces the same tuning constants. + if ( hdr.lengthScale > 0.0f ) + { + b3SetLengthUnitsPerMeter( hdr.lengthScale ); + } + + // Count frames and read first step's dt so the viewer can show hz up front. + b3RecScanFile( player ); + + // Create the replay world. Debug-shape callbacks are NULL here; the sample wires + // them right after Create via b3RecPlayer_SetDebugShapeCallbacks, which rebuilds. + b3WorldId worldId = b3RecPlayerCreateWorld( player ); + + // Initialize the reader. + player->rdr.data = copy; + player->rdr.size = size; + player->rdr.cursor = headerEnd; + player->rdr.replayWorldId = worldId; + player->rdr.ok = true; + player->rdr.diverged = false; + player->rdr.owner = player; + + // Load the trailing geometry registry. + if ( !b3RecLoadSlots( &player->rdr, copy, size, hdr.registryOffset, hdr.registryByteCount ) ) + { + b3DestroyWorld( worldId ); + b3Free( copy, (size_t)size ); + b3Free( player, sizeof( b3RecPlayer ) ); + return NULL; + } + + // Restore the seed snapshot to stand up the replay world. The blob doubles as the frame-0 + // restore image, owned by the copy held above. + { + int snapStart = (int)sizeof( b3RecHeader ); + int snapSize = (int)hdr.snapshotSize; + b3World* replayWorld = b3GetWorldFromId( worldId ); + if ( b3DeserializeIntoShell( copy + snapStart, snapSize, replayWorld, &player->rdr ) == false ) + { + printf( "b3RecPlayer_Create: snapshot deserialization failed\n" ); + b3DestroyWorld( worldId ); + b3RecFreeSlots( player->rdr.slots, player->rdr.slotCount ); + b3Free( copy, (size_t)size ); + b3Free( player, sizeof( b3RecPlayer ) ); + return NULL; + } + player->rdr.cursor = headerEnd; + player->frame0Image = copy + snapStart; + player->frame0Size = snapSize; + } + + // Seed the outliner from the restored world (snapshot bodies bypass the create hook) and save + // the frame-0 restore copy. + b3RecSeedFrame0BodyIds( player ); + + // Build the keyframe recording with a pre-seeded registry that mirrors rdr.slots, + // so b3SerializeWorld geometry ids stay stable across captures. + player->keyframeRec = b3CreateRecording( 0 ); + b3RecSeedKeyframeRegistry( player ); + + return player; +} + +void b3RecPlayer_Destroy( b3RecPlayer* player ) +{ + if ( player == NULL ) + { + return; + } + + if ( b3World_IsValid( player->rdr.replayWorldId ) ) + { + b3DestroyWorld( player->rdr.replayWorldId ); + } + + // Free live geometry after destroying the world (slot->live may be used by the world). + b3RecFreeSlots( player->rdr.slots, player->rdr.slotCount ); + + // Free reader scratch. + if ( player->rdr.matScratch != NULL ) + { + b3Free( player->rdr.matScratch, (size_t)player->rdr.matScratchCap * sizeof( b3SurfaceMaterial ) ); + } + if ( player->rdr.proxyScratch != NULL ) + { + b3Free( player->rdr.proxyScratch, (size_t)player->rdr.proxyScratchCap * sizeof( b3Vec3 ) ); + } + if ( player->rdr.hits != NULL ) + { + b3Free( player->rdr.hits, (size_t)player->rdr.hitCap * sizeof( b3RecRecordedHit ) ); + } + + // Free the per-frame query store. + if ( player->frameQueries != NULL ) + { + b3Free( player->frameQueries, (size_t)player->frameQueryCap * sizeof( b3RecDrawQuery ) ); + } + if ( player->frameHits != NULL ) + { + b3Free( player->frameHits, (size_t)player->frameHitCap * sizeof( b3RecRecordedHit ) ); + } + + // Free keyframe ring. + for ( int i = 0; i < player->keyframeCount; ++i ) + { + b3FreeKeyframe( player->keyframes + i ); + } + if ( player->keyframes != NULL ) + { + b3Free( player->keyframes, (size_t)player->keyframeCapacity * sizeof( b3RecKeyframe ) ); + } + + // The keyframe recording owns only its buffer and registry; b3DestroyRecording frees both. + if ( player->keyframeRec != NULL ) + { + b3DestroyRecording( player->keyframeRec ); + } + + // Free the outliner body lists. + if ( player->bodyIds != NULL ) + { + b3Free( player->bodyIds, (size_t)player->bodyIdCap * sizeof( b3BodyId ) ); + } + if ( player->frame0BodyIds != NULL ) + { + b3Free( player->frame0BodyIds, (size_t)player->frame0BodyIdCount * sizeof( b3BodyId ) ); + } + + // frame0Image points into the owned data copy, not separately allocated. + + b3Free( player->data, (size_t)player->size ); + + // Restore the global length scale. + b3SetLengthUnitsPerMeter( player->previousLengthScale ); + + b3Free( player, sizeof( b3RecPlayer ) ); +} + +bool b3RecPlayer_StepFrame( b3RecPlayer* player ) +{ + if ( player->atEnd ) + { + return false; + } + + // Reset the per-frame query store before this frame's records are dispatched. + player->frameQueryCount = 0; + player->frameHitCount = 0; + + // A frame is its leading inputs (queries and between-step mutators), one Step, and the Step's + // trailing StateHash. Queries are recorded before the Step they belong to, so they stash here + // against the world state they were computed for. + bool stepped = false; + for ( ;; ) + { + if ( player->rdr.cursor >= player->registryEnd || !player->rdr.ok ) + { + player->atEnd = true; + return stepped; + } + + // Once stepped, the StateHash is the only record still belonging to this frame. Anything else + // begins the next frame, so stop and let the next StepFrame consume it. Capture a keyframe at + // the boundary. + if ( stepped && player->rdr.data[player->rdr.cursor] != b3_recOpStateHash ) + { + if ( player->frame > player->lastKeyframeFrame && player->frame % player->keyframeInterval == 0 ) + { + b3RecCaptureKeyframe( player ); + } + return true; + } + + int op = b3RecDispatchOne( &player->rdr ); + if ( op < 0 ) + { + player->atEnd = true; + return stepped; + } + if ( op == b3_recOpDestroyWorld ) // end of recording + { + player->atEnd = true; + return stepped; + } + if ( op == b3_recOpStep ) + { + player->frame += 1; + stepped = true; + } + else if ( op == b3_recOpStateHash ) // trailing record of the frame just stepped + { + // Latch the first frame whose state hash diverged. The hash belongs to the frame Step just + // advanced, so latch against the current frame, not the next Step which would be one late. + if ( player->divergeFrame < 0 && player->rdr.diverged ) + { + player->divergeFrame = player->frame; + } + } + } +} + +void b3RecPlayer_Restart( b3RecPlayer* player ) +{ + // Restore the frame-0 image in place so the replay world id stays stable across a restart or + // backward scrub. Stepping resumes at the first Step, which rebuilds the body list deterministically. + b3World* world = b3GetWorldFromId( player->rdr.replayWorldId ); + if ( b3DeserializeIntoShell( player->frame0Image, player->frame0Size, world, &player->rdr ) == false ) + { + player->rdr.ok = false; + return; + } + player->rdr.cursor = player->headerEnd; + player->rdr.ok = true; + player->rdr.diverged = false; + player->frame = 0; + player->divergeFrame = -1; + player->atEnd = false; + + // Frame 0 is the pre-step snapshot with no recorded queries, so clear the per-frame store. This + // keeps the last stepped frame's queries from lingering on a restart or a backward scrub to 0. + player->frameQueryCount = 0; + player->frameHitCount = 0; + + // Roll the outliner body list back to its frame-0 contents. + b3RecGrow( (void**)&player->bodyIds, &player->bodyIdCap, player->frame0BodyIdCount, 0, (int)sizeof( b3BodyId ) ); + player->bodyIdCount = player->frame0BodyIdCount; + if ( player->frame0BodyIdCount > 0 ) + { + memcpy( player->bodyIds, player->frame0BodyIds, (size_t)player->frame0BodyIdCount * sizeof( b3BodyId ) ); + } +} + +void b3RecPlayer_SeekFrame( b3RecPlayer* player, int targetFrame ) +{ + if ( player == NULL ) + { + return; + } + if ( targetFrame < 0 ) + { + targetFrame = 0; + } + + // Find the best keyframe strictly before the target. + const b3RecKeyframe* best = NULL; + for ( int i = 0; i < player->keyframeCount; ++i ) + { + const b3RecKeyframe* kf = player->keyframes + i; + if ( kf->frame < targetFrame && ( best == NULL || kf->frame > best->frame ) ) + { + best = kf; + } + } + + if ( targetFrame < player->frame ) + { + // Backward seek: restore keyframe or restart from frame 0. + if ( best != NULL ) + { + b3RecPlayerRestoreKeyframe( player, best ); + } + else + { + b3RecPlayer_Restart( player ); + } + } + else if ( best != NULL && best->frame > player->frame ) + { + // Forward seek that can skip ahead via a keyframe. + b3RecPlayerRestoreKeyframe( player, best ); + } + + while ( player->frame < targetFrame && b3RecPlayer_StepFrame( player ) ) + { + } +} + +b3WorldId b3RecPlayer_GetWorldId( const b3RecPlayer* player ) +{ + return player != NULL ? player->rdr.replayWorldId : b3_nullWorldId; +} + +int b3RecPlayer_GetFrame( const b3RecPlayer* player ) +{ + return player != NULL ? player->frame : 0; +} + +int b3RecPlayer_GetFrameCount( const b3RecPlayer* player ) +{ + return player != NULL ? player->frameCount : 0; +} + +bool b3RecPlayer_IsAtEnd( const b3RecPlayer* player ) +{ + return player != NULL ? player->atEnd : true; +} + +bool b3RecPlayer_HasDiverged( const b3RecPlayer* player ) +{ + return player != NULL ? player->rdr.diverged : false; +} + +b3RecPlayerInfo b3RecPlayer_GetInfo( const b3RecPlayer* player ) +{ + b3RecPlayerInfo info = { 0 }; + if ( player != NULL ) + { + info.frameCount = player->frameCount; + info.workerCount = player->recordedWorkerCount; + info.timeStep = player->recordedDt; + info.subStepCount = player->recordedSubStepCount; + info.lengthScale = player->lengthScale; + info.bounds = player->bounds; + } + return info; +} + +int b3RecPlayer_GetDivergeFrame( const b3RecPlayer* player ) +{ + return player != NULL ? player->divergeFrame : -1; +} + +void b3RecPlayer_SetWorkerCount( b3RecPlayer* player, int count ) +{ + if ( player == NULL ) + { + return; + } + + player->recordedWorkerCount = b3ClampInt( count, 1, B3_MAX_WORKERS ); + + // Apply to the live world now so the next steps re-partition without a rebuild. Worker count is + // host state, not part of a keyframe image, so it survives an in-place restore. A rebuild on + // Restart or deep backward seek picks the count back up through b3RecPlayerCreateWorld. + if ( b3World_IsValid( player->rdr.replayWorldId ) ) + { + b3World_SetWorkerCount( player->rdr.replayWorldId, player->recordedWorkerCount ); + } +} + +void b3RecPlayer_SetKeyframePolicy( b3RecPlayer* player, size_t budgetBytes, int minIntervalFrames ) +{ + if ( player == NULL ) + { + return; + } + if ( budgetBytes > 0 ) + { + player->keyframeBudget = budgetBytes; + } + if ( minIntervalFrames > 0 ) + { + player->keyframeMinInterval = minIntervalFrames; + } + + // Drop the ring so it repopulates under the new policy on the next replay. + for ( int i = 0; i < player->keyframeCount; ++i ) + { + b3FreeKeyframe( player->keyframes + i ); + } + player->keyframeCount = 0; + player->keyframeBytes = 0; + player->keyframeInterval = player->keyframeMinInterval; + player->lastKeyframeFrame = 0; +} + +size_t b3RecPlayer_GetKeyframeBudget( const b3RecPlayer* player ) +{ + return player != NULL ? player->keyframeBudget : 0; +} + +int b3RecPlayer_GetKeyframeMinInterval( const b3RecPlayer* player ) +{ + return player != NULL ? player->keyframeMinInterval : 0; +} + +int b3RecPlayer_GetKeyframeInterval( const b3RecPlayer* player ) +{ + return player != NULL ? player->keyframeInterval : 0; +} + +size_t b3RecPlayer_GetKeyframeBytes( const b3RecPlayer* player ) +{ + return player != NULL ? player->keyframeBytes : 0; +} + +int b3RecPlayer_GetBodyCount( const b3RecPlayer* player ) +{ + return player != NULL ? player->bodyIdCount : 0; +} + +b3BodyId b3RecPlayer_GetBodyId( const b3RecPlayer* player, int index ) +{ + if ( player == NULL || index < 0 || index >= player->bodyIdCount ) + { + return b3_nullBodyId; + } + return player->bodyIds[index]; +} + +// Highlight each reported overlap shape by its AABB. Skip any destroyed since the query, per the +// b3Shape_GetAABB contract that overlap results may contain stale shapes. +static void b3RecDrawHitBounds( const b3RecPlayer* player, const b3RecDrawQuery* q, b3DebugDraw* draw ) +{ + if ( draw->DrawBoundsFcn == NULL ) + { + return; + } + for ( int hi = q->hitStart; hi < q->hitStart + q->hitCount; ++hi ) + { + b3ShapeId id = player->frameHits[hi].id; + if ( b3Shape_IsValid( id ) == false ) + { + continue; + } + draw->DrawBoundsFcn( b3Shape_GetAABB( id ), b3_colorMagenta, draw->context ); + } +} + +// Draw a recorded shape proxy at basePos. A lone point with no radius draws a fat point, a lone point +// with a radius draws a translucent sphere, and a multi-point cloud draws its points. Capsule and hull +// proxies are rare and fall through to the point cloud for now. +static void b3RecDrawProxy( b3DebugDraw* draw, b3Pos basePos, const b3RecDrawQuery* q, b3HexColor color ) +{ + if ( q->proxyCount == 1 ) + { + b3Pos p = b3OffsetPos( basePos, q->proxyPoints[0] ); + if ( q->proxyRadius > 0.0f ) + { + if ( draw->DrawSphereFcn ) + { + draw->DrawSphereFcn( p, q->proxyRadius, color, 0.5f, draw->context ); + } + } + else if ( draw->DrawPointFcn ) + { + draw->DrawPointFcn( p, 10.0f, color, draw->context ); + } + } + else if ( q->proxyCount >= 2 && draw->DrawPointFcn ) + { + for ( int i = 0; i < q->proxyCount; ++i ) + { + draw->DrawPointFcn( b3OffsetPos( basePos, q->proxyPoints[i] ), 6.0f, color, draw->context ); + } + } +} + +void b3RecPlayer_DrawFrameQueries( b3RecPlayer* player, b3DebugDraw* draw, int queryIndex ) +{ + if ( player == NULL || draw == NULL ) + { + return; + } + + // queryIndex < 0 draws every query, otherwise just the one selected in the viewer. + for ( int qi = 0; qi < player->frameQueryCount; ++qi ) + { + if ( queryIndex >= 0 && qi != queryIndex ) + { + continue; + } + + const b3RecDrawQuery* q = &player->frameQueries[qi]; + + switch ( q->kind ) + { + case B3_RECQ_CAST_RAY: + case B3_RECQ_CAST_RAY_CLOSEST: + { + b3Pos origin = q->origin; + b3Pos end = b3OffsetPos( origin, q->translation ); + if ( draw->DrawSegmentFcn ) + { + draw->DrawSegmentFcn( origin, end, b3_colorYellow, draw->context ); + } + for ( int hi = q->hitStart; hi < q->hitStart + q->hitCount; ++hi ) + { + const b3RecRecordedHit* h = &player->frameHits[hi]; + if ( draw->DrawPointFcn ) + { + draw->DrawPointFcn( h->point, 4.0f, b3_colorYellow, draw->context ); + } + if ( draw->DrawSegmentFcn ) + { + draw->DrawSegmentFcn( h->point, b3OffsetPos( h->point, b3MulSV( 0.2f, h->normal ) ), b3_colorYellowGreen, + draw->context ); + } + } + break; + } + case B3_RECQ_CAST_SHAPE: + { + // Draw the cast line and the proxy at its start, then each hit point and normal. + if ( draw->DrawSegmentFcn ) + { + draw->DrawSegmentFcn( q->origin, b3OffsetPos( q->origin, q->translation ), b3_colorSkyBlue, + draw->context ); + } + b3RecDrawProxy( draw, q->origin, q, b3_colorLightGreen ); + for ( int hi = q->hitStart; hi < q->hitStart + q->hitCount; ++hi ) + { + const b3RecRecordedHit* h = &player->frameHits[hi]; + if ( draw->DrawPointFcn ) + { + draw->DrawPointFcn( h->point, 4.0f, b3_colorSkyBlue, draw->context ); + } + if ( draw->DrawSegmentFcn ) + { + draw->DrawSegmentFcn( h->point, b3OffsetPos( h->point, b3MulSV( 0.2f, h->normal ) ), + b3_colorLightSkyBlue, draw->context ); + } + if (draw->DrawSphereFcn) + { + b3Pos p = b3OffsetPos(q->origin, b3MulSV(h->fraction, q->translation)); + b3RecDrawProxy( draw, p, q, b3_colorSkyBlue ); + } + } + break; + } + case B3_RECQ_CAST_MOVER: + case B3_RECQ_COLLIDE_MOVER: + { + // 3D debug draw has no solid capsule, so draw the mover axis and its end caps. + b3Pos c1 = b3OffsetPos( q->origin, q->mover.center1 ); + b3Pos c2 = b3OffsetPos( q->origin, q->mover.center2 ); + b3HexColor c = q->kind == B3_RECQ_CAST_MOVER ? b3_colorLightSkyBlue : b3_colorTan; + if ( draw->DrawSegmentFcn ) + { + draw->DrawSegmentFcn( c1, c2, c, draw->context ); + } + if ( draw->DrawPointFcn ) + { + draw->DrawPointFcn( c1, 4.0f, c, draw->context ); + draw->DrawPointFcn( c2, 4.0f, c, draw->context ); + } + // Collide-mover stashes one hit per collision plane, origin relative. Cast-mover stashes + // no hits, so this loop is a no-op there. + for ( int hi = q->hitStart; hi < q->hitStart + q->hitCount; ++hi ) + { + const b3RecRecordedHit* h = &player->frameHits[hi]; + b3Pos point = b3OffsetPos( q->origin, h->plane.point ); + if ( draw->DrawSegmentFcn ) + { + draw->DrawSegmentFcn( point, b3OffsetPos( point, b3MulSV( 0.2f, h->plane.plane.normal ) ), + b3_colorOrange, draw->context ); + } + } + break; + } + case B3_RECQ_OVERLAP_AABB: + { + if ( draw->DrawBoundsFcn ) + { + draw->DrawBoundsFcn( q->aabb, b3_colorLimeGreen, draw->context ); + } + b3RecDrawHitBounds( player, q, draw ); + break; + } + case B3_RECQ_OVERLAP_SHAPE: + { + // The overlap proxy sits at the origin; draw it, then the overlapping shape bounds. + b3RecDrawProxy( draw, q->origin, q, b3_colorLimeGreen ); + b3RecDrawHitBounds( player, q, draw ); + break; + } + default: + break; + } + } +} + +// The internal b3RecQueryKind values match the public b3RecQueryType, so the kind copies across as a +// plain cast. Pin the first and last kinds to catch enum drift. +_Static_assert( b3_recQueryOverlapAABB == 0 && B3_RECQ_OVERLAP_AABB == 0, "query type enum drift" ); +_Static_assert( b3_recQueryCollideMover == 6 && B3_RECQ_COLLIDE_MOVER == 6, "query type enum drift" ); + +int b3RecPlayer_GetFrameQueryCount( const b3RecPlayer* player ) +{ + return player != NULL ? player->frameQueryCount : 0; +} + +b3RecQueryInfo b3RecPlayer_GetFrameQuery( const b3RecPlayer* player, int index ) +{ + b3RecQueryInfo info = { 0 }; + if ( player == NULL || index < 0 || index >= player->frameQueryCount ) + { + return info; + } + + const b3RecDrawQuery* q = &player->frameQueries[index]; + info.type = (b3RecQueryType)q->kind; + info.filter = q->filter; + info.aabb = q->aabb; + info.origin = q->origin; + info.translation = q->translation; + info.hitCount = q->hitCount; + return info; +} + +b3RecQueryHit b3RecPlayer_GetFrameQueryHit( const b3RecPlayer* player, int queryIndex, int hitIndex ) +{ + b3RecQueryHit hit = { 0 }; + if ( player == NULL || queryIndex < 0 || queryIndex >= player->frameQueryCount ) + { + return hit; + } + + const b3RecDrawQuery* q = &player->frameQueries[queryIndex]; + if ( hitIndex < 0 || hitIndex >= q->hitCount ) + { + return hit; + } + + const b3RecRecordedHit* h = &player->frameHits[q->hitStart + hitIndex]; + hit.shape = h->id; + hit.point = h->point; + hit.normal = h->normal; + hit.fraction = h->fraction; + return hit; +} + +void b3RecPlayer_SetDebugShapeCallbacks( b3RecPlayer* player, b3CreateDebugShapeCallback* createDebugShape, + b3DestroyDebugShapeCallback* destroyDebugShape, void* context ) +{ + if ( player == NULL ) + { + return; + } + + player->createDebugShape = createDebugShape; + player->destroyDebugShape = destroyDebugShape; + player->debugShapeContext = context; + + // A world fixes its debug-shape callbacks at creation, so rebuild frame 0 under the new + // wiring. The old world held no adapter shapes (its callbacks were NULL), so the tear-down + // is balanced. Geometry slots are byte blobs reused as-is, the same path Restart relies on. + if ( b3World_IsValid( player->rdr.replayWorldId ) ) + { + b3DestroyWorld( player->rdr.replayWorldId ); + } + player->rdr.replayWorldId = b3RecPlayerCreateWorld( player ); + player->rdr.cursor = player->headerEnd; + player->rdr.ok = true; + player->rdr.diverged = false; + player->frame = 0; + player->divergeFrame = -1; + player->atEnd = false; + + // Re-seed the world so its shapes are recreated through the new callbacks. + b3World* world = b3GetWorldFromId( player->rdr.replayWorldId ); + if ( b3DeserializeIntoShell( player->frame0Image, player->frame0Size, world, &player->rdr ) == false ) + { + player->rdr.ok = false; + return; + } + player->rdr.cursor = player->headerEnd; + + // Rebuild the outliner from the frame-0 world that was just stood up under the new callbacks. + b3RecSeedFrame0BodyIds( player ); +} diff --git a/src/recording_replay.h b/src/recording_replay.h new file mode 100644 index 0000000..857690a --- /dev/null +++ b/src/recording_replay.h @@ -0,0 +1,240 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "recording.h" + +#include +#include + +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 ); diff --git a/src/revolute_joint.c b/src/revolute_joint.c index 24ae8f4..2cad93c 100644 --- a/src/revolute_joint.c +++ b/src/revolute_joint.c @@ -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; } diff --git a/src/shape.c b/src/shape.c index bc1abe1..e3b295b 100644 --- a/src/shape.c +++ b/src/shape.c @@ -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 ); diff --git a/src/shape.h b/src/shape.h index b9d2935..2c83fec 100644 --- a/src/shape.h +++ b/src/shape.h @@ -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; diff --git a/src/spherical_joint.c b/src/spherical_joint.c index 91d26c4..3634a57 100644 --- a/src/spherical_joint.c +++ b/src/spherical_joint.c @@ -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; } diff --git a/src/types.c b/src/types.c index 5c2dfca..f4bec14 100644 --- a/src/types.c +++ b/src/types.c @@ -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; diff --git a/src/weld_joint.c b/src/weld_joint.c index eb0f95d..611b714 100644 --- a/src/weld_joint.c +++ b/src/weld_joint.c @@ -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; } diff --git a/src/wheel_joint.c b/src/wheel_joint.c index 8423a66..05665e9 100644 --- a/src/wheel_joint.c +++ b/src/wheel_joint.c @@ -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; } diff --git a/src/world_snapshot.c b/src/world_snapshot.c new file mode 100644 index 0000000..84c7b91 --- /dev/null +++ b/src/world_snapshot.c @@ -0,0 +1,1287 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +#if defined( _MSC_VER ) && !defined( _CRT_SECURE_NO_WARNINGS ) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include "world_snapshot.h" + +#include "bitset.h" +#include "body.h" +#include "broad_phase.h" +#include "compound.h" +#include "constraint_graph.h" +#include "contact.h" +#include "container.h" +#include "core.h" +#include "id_pool.h" +#include "island.h" +#include "joint.h" +#include "physics_world.h" +#include "recording.h" +#include "sensor.h" +#include "shape.h" +#include "solver_set.h" +#include "table.h" + +#include "box3d/box3d.h" +#include "box3d/collision.h" +#include "box3d/types.h" + +#include + +// Snapshot image magic 'BNS3' and version +#define B3_SNAP_MAGIC 0x33534E42u +#define B3_SNAP_VERSION 1u + +#define B3_SNAP_FLAG_VALIDATION 0x1u +#define B3_SNAP_FLAG_DOUBLE_PRECISION 0x2u + +// Layout hash over all POD-copied structs + key constants. +// Changing a struct size updates this, catching ABI drift early. +static uint32_t b3ComputeLayoutHash( void ) +{ + uint32_t h = 2166136261u; +#define MIX( x ) \ + h ^= (uint32_t)( x ); \ + h *= 16777619u; + MIX( sizeof( b3Body ) ) + MIX( sizeof( b3BodySim ) ) + MIX( sizeof( b3BodyState ) ) + MIX( sizeof( b3Shape ) ) + MIX( sizeof( b3Contact ) ) + MIX( sizeof( b3Manifold ) ) + MIX( sizeof( b3Joint ) ) + MIX( sizeof( b3JointSim ) ) + MIX( sizeof( b3Island ) ) + MIX( sizeof( b3IslandSim ) ) + MIX( sizeof( b3ContactLink ) ) + MIX( sizeof( b3JointLink ) ) + MIX( sizeof( b3Sensor ) ) + MIX( sizeof( b3Visitor ) ) + MIX( sizeof( b3SolverSet ) ) + MIX( sizeof( b3GraphColor ) ) + MIX( sizeof( b3DynamicTree ) ) + MIX( sizeof( b3TreeNode ) ) + MIX( sizeof( b3SetItem ) ) + MIX( sizeof( b3IdPool ) ) + MIX( sizeof( b3SurfaceMaterial ) ) + MIX( sizeof( b3ContactSpec ) ) + MIX( sizeof( b3TriangleCache ) ) + MIX( B3_GRAPH_COLOR_COUNT ) + MIX( b3_bodyTypeCount ) + MIX( sizeof( void* ) ) +#undef MIX + return h; +} + +typedef struct b3SnapHeader +{ + uint32_t magic; + uint32_t version; + uint32_t layoutHash; + uint32_t flags; +} b3SnapHeader; + +// Bounds-checked read cursor +typedef struct b3SnapReader +{ + const uint8_t* data; + int cursor; + int size; + bool ok; +} b3SnapReader; + +static void b3SnapRCheck( b3SnapReader* r, int need ) +{ + if ( need < 0 || (int64_t)r->cursor + (int64_t)need > (int64_t)r->size ) + { + r->ok = false; + } +} + +static void b3SnapR_Bytes( b3SnapReader* r, void* dst, int n ) +{ + b3SnapRCheck( r, n ); + if ( !r->ok ) + { + return; + } + memcpy( dst, r->data + r->cursor, n ); + r->cursor += n; +} + +static int b3SnapR_I32( b3SnapReader* r ) +{ + int32_t v = 0; + b3SnapR_Bytes( r, &v, 4 ); + return (int)v; +} + +static uint32_t b3SnapR_U32( b3SnapReader* r ) +{ + uint32_t v = 0; + b3SnapR_Bytes( r, &v, 4 ); + return v; +} + +static void b3SnapW_I32( b3RecBuffer* buf, int v ) +{ + int32_t w = (int32_t)v; + b3RecBufAppend( buf, &w, 4 ); +} + +static void b3SnapW_U32( b3RecBuffer* buf, uint32_t v ) +{ + b3RecBufAppend( buf, &v, 4 ); +} + +static void b3SnapW_Bytes( b3RecBuffer* buf, const void* src, int n ) +{ + b3RecBufAppend( buf, src, n ); +} + +// Bounds check before allocating from image +static bool b3SnapCheckCount( const b3SnapReader* r, int count, int memSize, int minStreamBytes ) +{ + if ( count < 0 || memSize < 0 || minStreamBytes < 0 ) + { + return false; + } + if ( memSize > 0 && count > 0x7FFFFFFF / memSize ) + { + return false; + } + int64_t remaining = (int64_t)r->size - (int64_t)r->cursor; + return (int64_t)count * (int64_t)minStreamBytes <= remaining; +} + +// POD array: count + raw bytes +#define b3SerPodArray( buf, arr ) \ + do \ + { \ + b3SnapW_I32( buf, ( arr ).count ); \ + if ( ( arr ).count > 0 ) \ + { \ + b3SnapW_Bytes( buf, ( arr ).data, ( arr ).count * (int)sizeof( *( arr ).data ) ); \ + } \ + } \ + while ( 0 ) + +#define b3DesPodArray( r, arr ) \ + do \ + { \ + int cnt = b3SnapR_I32( r ); \ + int elemSize = (int)sizeof( *( arr ).data ); \ + if ( (r)->ok && b3SnapCheckCount( r, cnt, elemSize, elemSize ) == false ) \ + { \ + (r)->ok = false; \ + } \ + if ( (r)->ok && cnt > 0 ) \ + { \ + b3Array_Resize( arr, cnt ); \ + b3SnapR_Bytes( r, ( arr ).data, cnt * elemSize ); \ + } \ + else if ( (r)->ok ) \ + { \ + ( arr ).count = 0; \ + } \ + } \ + while ( 0 ) + +// Id pool: nextIndex + freeArray +static void b3SerIdPool( b3RecBuffer* buf, const b3IdPool* pool ) +{ + b3SnapW_I32( buf, pool->nextIndex ); + b3SerPodArray( buf, pool->freeArray ); +} + +static void b3DesIdPool( b3SnapReader* r, b3IdPool* pool ) +{ + pool->nextIndex = b3SnapR_I32( r ); + b3DesPodArray( r, pool->freeArray ); +} + +// BitSet: blockCount + raw words +static void b3SerBitSet( b3RecBuffer* buf, const b3BitSet* bs ) +{ + b3SnapW_U32( buf, bs->blockCount ); + if ( bs->blockCount > 0 ) + { + b3SnapW_Bytes( buf, bs->bits, (int)( bs->blockCount * sizeof( uint64_t ) ) ); + } +} + +static void b3DesBitSet( b3SnapReader* r, b3BitSet* bs ) +{ + uint32_t blockCount = b3SnapR_U32( r ); + if ( r->ok && b3SnapCheckCount( r, (int)blockCount, (int)sizeof( uint64_t ), (int)sizeof( uint64_t ) ) == false ) + { + r->ok = false; + } + b3DestroyBitSet( bs ); + if ( !r->ok ) + { + return; + } + uint32_t blockCapacity = blockCount > 0 ? blockCount : 1; + bs->bits = (uint64_t*)b3Alloc( blockCapacity * sizeof( uint64_t ) ); + memset( bs->bits, 0, blockCapacity * sizeof( uint64_t ) ); + bs->blockCapacity = blockCapacity; + bs->blockCount = blockCount; + if ( blockCount > 0 ) + { + b3SnapR_Bytes( r, bs->bits, (int)( blockCount * sizeof( uint64_t ) ) ); + } +} + +// HashSet: capacity + count + raw items (probe order depends on layout) +static void b3SerHashSet( b3RecBuffer* buf, const b3HashSet* hs ) +{ + b3SnapW_U32( buf, hs->capacity ); + b3SnapW_U32( buf, hs->count ); + if ( hs->capacity > 0 ) + { + b3SnapW_Bytes( buf, hs->items, (int)( hs->capacity * sizeof( b3SetItem ) ) ); + } +} + +static void b3DesHashSet( b3SnapReader* r, b3HashSet* hs ) +{ + uint32_t cap = b3SnapR_U32( r ); + uint32_t cnt = b3SnapR_U32( r ); + bool valid = b3SnapCheckCount( r, (int)cap, (int)sizeof( b3SetItem ), (int)sizeof( b3SetItem ) ) && + ( cap & ( cap - 1 ) ) == 0 && cnt <= cap; + if ( r->ok && valid == false && ( cap != 0 || cnt != 0 ) ) + { + r->ok = false; + } + b3DestroySet( hs ); + if ( !r->ok ) + { + return; + } + if ( cap > 0 ) + { + hs->items = (b3SetItem*)b3Alloc( cap * sizeof( b3SetItem ) ); + hs->capacity = cap; + hs->count = cnt; + b3SnapR_Bytes( r, hs->items, (int)( cap * sizeof( b3SetItem ) ) ); + } + else + { + hs->items = NULL; + hs->capacity = 0; + hs->count = 0; + } +} + +// DynamicTree: version, scalars, full nodeCapacity nodes (rebuild scratch excluded) +static void b3SerTree( b3RecBuffer* buf, const b3DynamicTree* tree ) +{ + b3SnapW_Bytes( buf, &tree->version, sizeof( uint64_t ) ); + b3SnapW_I32( buf, tree->root ); + b3SnapW_I32( buf, tree->nodeCount ); + b3SnapW_I32( buf, tree->nodeCapacity ); + b3SnapW_I32( buf, tree->freeList ); + b3SnapW_I32( buf, tree->proxyCount ); + if ( tree->nodeCapacity > 0 ) + { + b3SnapW_Bytes( buf, tree->nodes, tree->nodeCapacity * (int)sizeof( b3TreeNode ) ); + } +} + +static void b3DesTree( b3SnapReader* r, b3DynamicTree* tree ) +{ + uint64_t version; + b3SnapR_Bytes( r, &version, sizeof( uint64_t ) ); + int root = b3SnapR_I32( r ); + int nodeCount = b3SnapR_I32( r ); + int nodeCapacity = b3SnapR_I32( r ); + int freeList = b3SnapR_I32( r ); + int proxyCount = b3SnapR_I32( r ); + + if ( r->ok && b3SnapCheckCount( r, nodeCapacity, (int)sizeof( b3TreeNode ), (int)sizeof( b3TreeNode ) ) == false ) + { + r->ok = false; + } + + // Free existing allocation including any rebuild scratch + b3Free( tree->nodes, tree->nodeCapacity * (int)sizeof( b3TreeNode ) ); + b3Free( tree->leafIndices, tree->rebuildCapacity * (int)sizeof( int ) ); + b3Free( tree->leafBoxes, tree->rebuildCapacity * (int)sizeof( b3AABB ) ); + b3Free( tree->leafCenters, tree->rebuildCapacity * (int)sizeof( b3Vec3 ) ); + b3Free( tree->binIndices, tree->rebuildCapacity * (int)sizeof( int ) ); + tree->nodes = NULL; + tree->leafIndices = NULL; + tree->leafBoxes = NULL; + tree->leafCenters = NULL; + tree->binIndices = NULL; + tree->nodeCapacity = 0; + tree->rebuildCapacity = 0; + + if ( !r->ok ) + { + return; + } + + tree->version = version; + tree->root = root; + tree->nodeCount = nodeCount; + tree->nodeCapacity = nodeCapacity; + tree->freeList = freeList; + tree->proxyCount = proxyCount; + + if ( nodeCapacity > 0 ) + { + tree->nodes = (b3TreeNode*)b3Alloc( nodeCapacity * (int)sizeof( b3TreeNode ) ); + b3SnapR_Bytes( r, tree->nodes, nodeCapacity * (int)sizeof( b3TreeNode ) ); + } +} + +// Solver set: setIndex + 4 arrays (note: contactIndices is int array, not contactSims) +static void b3SerSolverSet( b3RecBuffer* buf, const b3SolverSet* set ) +{ + b3SnapW_I32( buf, set->setIndex ); + b3SerPodArray( buf, set->bodySims ); + b3SerPodArray( buf, set->bodyStates ); + b3SerPodArray( buf, set->jointSims ); + b3SerPodArray( buf, set->contactIndices ); + b3SerPodArray( buf, set->islandSims ); +} + +static void b3DesSolverSet( b3SnapReader* r, b3SolverSet* set ) +{ + set->setIndex = b3SnapR_I32( r ); + b3DesPodArray( r, set->bodySims ); + b3DesPodArray( r, set->bodyStates ); + b3DesPodArray( r, set->jointSims ); + b3DesPodArray( r, set->contactIndices ); + b3DesPodArray( r, set->islandSims ); +} + +// Graph color: bodySet (non-overflow only) + jointSims + convexContacts + contacts +static void b3SerGraphColor( b3RecBuffer* buf, const b3GraphColor* color, bool isOverflow ) +{ + if ( !isOverflow ) + { + b3SerBitSet( buf, &color->bodySet ); + } + b3SerPodArray( buf, color->jointSims ); + b3SerPodArray( buf, color->convexContacts ); + b3SerPodArray( buf, color->contacts ); + // wideConstraints / manifoldConstraints / contactConstraints are transient, not serialized +} + +static void b3DesGraphColor( b3SnapReader* r, b3GraphColor* color, bool isOverflow ) +{ + if ( !isOverflow ) + { + b3DesBitSet( r, &color->bodySet ); + } + b3DesPodArray( r, color->jointSims ); + b3DesPodArray( r, color->convexContacts ); + b3DesPodArray( r, color->contacts ); + // Transient pointers left at NULL/0 from shell +} + +// World simulation scalars (never host/callback/worker state) +static void b3SerWorldConfig( b3RecBuffer* buf, const b3World* world ) +{ + b3SnapW_Bytes( buf, &world->gravity, sizeof( b3Vec3 ) ); + b3SnapW_Bytes( buf, &world->hitEventThreshold, sizeof( float ) ); + b3SnapW_Bytes( buf, &world->restitutionThreshold, sizeof( float ) ); + b3SnapW_Bytes( buf, &world->maxLinearSpeed, sizeof( float ) ); + b3SnapW_Bytes( buf, &world->contactSpeed, sizeof( float ) ); + b3SnapW_Bytes( buf, &world->contactHertz, sizeof( float ) ); + b3SnapW_Bytes( buf, &world->contactDampingRatio, sizeof( float ) ); + b3SnapW_Bytes( buf, &world->contactRecycleDistance, sizeof( float ) ); + b3SnapW_Bytes( buf, &world->stepIndex, sizeof( uint64_t ) ); + b3SnapW_I32( buf, world->splitIslandId ); + b3SnapW_Bytes( buf, &world->inv_h, sizeof( float ) ); + b3SnapW_Bytes( buf, &world->inv_dt, sizeof( float ) ); + b3SnapW_I32( buf, world->endEventArrayIndex ); + b3SnapW_Bytes( buf, &world->maxCapacity, sizeof( b3Capacity ) ); + uint8_t flags = 0; + flags |= world->enableSleep ? 0x01u : 0u; + flags |= world->enableWarmStarting ? 0x02u : 0u; + flags |= world->enableContinuous ? 0x04u : 0u; + flags |= world->enableSpeculative ? 0x08u : 0u; + b3RecBufAppend( buf, &flags, 1 ); +} + +static void b3DesWorldConfig( b3SnapReader* r, b3World* world ) +{ + b3SnapR_Bytes( r, &world->gravity, sizeof( b3Vec3 ) ); + b3SnapR_Bytes( r, &world->hitEventThreshold, sizeof( float ) ); + b3SnapR_Bytes( r, &world->restitutionThreshold, sizeof( float ) ); + b3SnapR_Bytes( r, &world->maxLinearSpeed, sizeof( float ) ); + b3SnapR_Bytes( r, &world->contactSpeed, sizeof( float ) ); + b3SnapR_Bytes( r, &world->contactHertz, sizeof( float ) ); + b3SnapR_Bytes( r, &world->contactDampingRatio, sizeof( float ) ); + b3SnapR_Bytes( r, &world->contactRecycleDistance, sizeof( float ) ); + b3SnapR_Bytes( r, &world->stepIndex, sizeof( uint64_t ) ); + world->splitIslandId = b3SnapR_I32( r ); + b3SnapR_Bytes( r, &world->inv_h, sizeof( float ) ); + b3SnapR_Bytes( r, &world->inv_dt, sizeof( float ) ); + world->endEventArrayIndex = b3SnapR_I32( r ); + b3SnapR_Bytes( r, &world->maxCapacity, sizeof( b3Capacity ) ); + uint8_t flags = 0; + b3SnapR_Bytes( r, &flags, 1 ); + world->enableSleep = ( flags & 0x01u ) != 0; + world->enableWarmStarting = ( flags & 0x02u ) != 0; + world->enableContinuous = ( flags & 0x04u ) != 0; + world->enableSpeculative = ( flags & 0x08u ) != 0; +} + +// Shapes carry pointer fields: materials, userData, userShape, and the geometry union. +// Serialize the POD scalars with pointers nulled, then the owned materials array, then geometry. +// A single material lives inline in the struct image. The name is a fixed array, also inline. +// Hull/mesh/heightField/compound are interned into the recording registry; sphere/capsule inline. +static void b3SerShapes( b3RecBuffer* buf, b3World* world, b3Recording* rec ) +{ + int count = world->shapes.count; + b3SnapW_I32( buf, count ); + + for ( int i = 0; i < count; ++i ) + { + b3Shape shape = world->shapes.data[i]; + bool isLive = ( shape.id == i ); + + // Null out pointer fields before writing the raw struct + shape.materials = NULL; + shape.userData = NULL; + shape.userShape = NULL; + // Zero the geometry union so free-slot images have deterministic bytes + if ( !isLive ) + { + memset( &shape.capsule, 0, sizeof( shape.capsule ) ); + } + b3SnapW_Bytes( buf, &shape, sizeof( b3Shape ) ); + + if ( !isLive ) + { + // Free slot: no materials or geometry + b3SnapW_I32( buf, 0 ); // materialCount + b3SnapW_I32( buf, -1 ); // geometry kind sentinel + continue; + } + + // Owned material array. Only multi material meshes and compounds have one. A single material + // already rode along inline in the struct image, so write a zero length for it. + const b3Shape* src = world->shapes.data + i; + if ( src->materials != NULL ) + { + b3SnapW_I32( buf, src->materialCount ); + b3SnapW_Bytes( buf, src->materials, src->materialCount * (int)sizeof( b3SurfaceMaterial ) ); + } + else + { + b3SnapW_I32( buf, 0 ); + } + + // Geometry + switch ( src->type ) + { + case b3_sphereShape: + b3SnapW_I32( buf, (int)b3_sphereShape ); + b3SnapW_Bytes( buf, &src->sphere, sizeof( b3Sphere ) ); + break; + case b3_capsuleShape: + b3SnapW_I32( buf, (int)b3_capsuleShape ); + b3SnapW_Bytes( buf, &src->capsule, sizeof( b3Capsule ) ); + break; + case b3_hullShape: + { + b3SnapW_I32( buf, (int)b3_hullShape ); + uint32_t gid = b3RecInternHull( rec, src->hull ); + b3SnapW_U32( buf, gid ); + break; + } + case b3_meshShape: + { + b3SnapW_I32( buf, (int)b3_meshShape ); + uint32_t gid = b3RecInternMesh( rec, src->mesh.data ); + b3SnapW_U32( buf, gid ); + b3SnapW_Bytes( buf, &src->mesh.scale, sizeof( b3Vec3 ) ); + break; + } + case b3_heightShape: + { + b3SnapW_I32( buf, (int)b3_heightShape ); + uint32_t gid = b3RecInternHeightField( rec, src->heightField ); + b3SnapW_U32( buf, gid ); + break; + } + case b3_compoundShape: + { + b3SnapW_I32( buf, (int)b3_compoundShape ); + uint32_t gid = b3RecInternCompound( rec, src->compound ); + b3SnapW_U32( buf, gid ); + break; + } + default: + // A live shape must have a known geometry type. Fail loudly rather than emit a shape + // with no geometry that would silently lose its collision on restore. + B3_ASSERT( false ); + b3SnapW_I32( buf, -1 ); + break; + } + } +} + +static void b3DesShapes( b3SnapReader* r, b3World* world, b3RecReader* rdr ) +{ + int count = b3SnapR_I32( r ); + if ( r->ok && b3SnapCheckCount( r, count, (int)sizeof( b3Shape ), (int)sizeof( b3Shape ) ) == false ) + { + r->ok = false; + } + if ( !r->ok ) + { + return; + } + + // Save renderer handles before the array is wiped. A keyframe restore is a deterministic replay + // state, so a live shape that still occupies the same slot with the same generation is the same + // shape with the same geometry. Carrying its handle over avoids tearing down and rebuilding every + // GPU mesh on each seek, which the host (a 3D renderer) would otherwise pay for. Handles that are + // not reclaimed below belong to shapes that are gone or were replaced, and get released so the host + // pool does not leak across seeks. Box2D has no such handles, so its restore skips all of this. + int oldShapeCount = world->shapes.count; + void** savedUserShape = NULL; + uint16_t* savedGeneration = NULL; + if ( oldShapeCount > 0 ) + { + savedUserShape = (void**)b3Alloc( (size_t)oldShapeCount * sizeof( void* ) ); + savedGeneration = (uint16_t*)b3Alloc( (size_t)oldShapeCount * sizeof( uint16_t ) ); + for ( int i = 0; i < oldShapeCount; ++i ) + { + b3Shape* old = world->shapes.data + i; + bool oldLive = ( old->id == i ); + savedUserShape[i] = oldLive ? old->userShape : NULL; + savedGeneration[i] = old->generation; + } + } + + b3Array_Resize( world->shapes, count ); + memset( world->shapes.data, 0, (size_t)count * sizeof( b3Shape ) ); + + for ( int i = 0; i < count && r->ok; ++i ) + { + b3Shape* dst = world->shapes.data + i; + b3SnapR_Bytes( r, dst, sizeof( b3Shape ) ); + // Pointer fields were written as NULL; set them cleanly + dst->materials = NULL; + dst->userData = NULL; + dst->userShape = NULL; + memset( &dst->capsule, 0, sizeof( dst->capsule ) ); + + bool isLive = ( dst->id == i ); + + // Carry the renderer handle over when the same shape still occupies this slot. Consumed + // handles are nulled so the teardown sweep only releases the ones that vanished. + if ( isLive && i < oldShapeCount && savedUserShape != NULL && savedUserShape[i] != NULL && + savedGeneration[i] == dst->generation ) + { + dst->userShape = savedUserShape[i]; + savedUserShape[i] = NULL; + } + + // Serializer writes: matCount, matData, geoKind, geoData + int matCount = b3SnapR_I32( r ); + + if ( !r->ok ) + { + break; + } + + if ( !isLive ) + { + // Free slot: matCount=0, geoKind=-1 + (void)matCount; + b3SnapR_I32( r ); // consume the geoKind sentinel + continue; + } + + // Owned material array (written before geoKind in serializer). A zero length means the single + // material is already inline in the restored struct image, so leave materialCount as restored. + if ( matCount > 0 ) + { + if ( b3SnapCheckCount( r, matCount, (int)sizeof( b3SurfaceMaterial ), (int)sizeof( b3SurfaceMaterial ) ) == false ) + { + r->ok = false; + break; + } + dst->materialCount = matCount; + dst->materials = (b3SurfaceMaterial*)b3Alloc( (size_t)matCount * sizeof( b3SurfaceMaterial ) ); + b3SnapR_Bytes( r, dst->materials, matCount * (int)sizeof( b3SurfaceMaterial ) ); + } + else + { + dst->materials = NULL; + } + + int geoKind = b3SnapR_I32( r ); + + // Geometry + switch ( (b3ShapeType)geoKind ) + { + case b3_sphereShape: + b3SnapR_Bytes( r, &dst->sphere, sizeof( b3Sphere ) ); + break; + case b3_capsuleShape: + b3SnapR_Bytes( r, &dst->capsule, sizeof( b3Capsule ) ); + break; + case b3_hullShape: + { + uint32_t gid = b3SnapR_U32( r ); + if ( !r->ok ) + { + break; + } + if ( rdr == NULL || gid >= (uint32_t)rdr->slotCount ) + { + r->ok = false; + break; + } + // Hull is cloned into the world DB; pass raw bytes directly + b3RegistrySlot* slot = rdr->slots + gid; + dst->hull = b3AddHullToDatabase( world, (const b3HullData*)slot->bytes ); + break; + } + case b3_meshShape: + { + uint32_t gid = b3SnapR_U32( r ); + b3Vec3 scale; + b3SnapR_Bytes( r, &scale, sizeof( b3Vec3 ) ); + if ( !r->ok ) + { + break; + } + if ( rdr == NULL || gid >= (uint32_t)rdr->slotCount ) + { + r->ok = false; + break; + } + b3RegistrySlot* slot = rdr->slots + gid; + // Mesh is a self-contained blob used by reference; point straight at the pristine bytes. + dst->mesh.data = (const b3MeshData*)slot->bytes; + dst->mesh.scale = scale; + break; + } + case b3_heightShape: + { + uint32_t gid = b3SnapR_U32( r ); + if ( !r->ok ) + { + break; + } + if ( rdr == NULL || gid >= (uint32_t)rdr->slotCount ) + { + r->ok = false; + break; + } + b3RegistrySlot* slot = rdr->slots + gid; + // Self-contained blob used by reference; point straight at the pristine bytes. + dst->heightField = (const b3HeightFieldData*)slot->bytes; + break; + } + case b3_compoundShape: + { + uint32_t gid = b3SnapR_U32( r ); + if ( !r->ok ) + { + break; + } + if ( rdr == NULL || gid >= (uint32_t)rdr->slotCount ) + { + r->ok = false; + break; + } + b3RegistrySlot* slot = rdr->slots + gid; + if ( slot->live == NULL ) + { + slot->live = b3Alloc( (size_t)slot->byteCount ); + memcpy( slot->live, slot->bytes, (size_t)slot->byteCount ); + b3ConvertBytesToCompound( (uint8_t*)slot->live, slot->byteCount ); + } + dst->compound = (const b3CompoundData*)slot->live; + break; + } + default: + // Unknown geometry kind means a corrupt or unsupported snapshot. Fail the load instead + // of leaving a shape with no geometry. + r->ok = false; + break; + } + } + + // Release handles for shapes that are gone or were replaced this restore, so the host pool and any + // GPU resources they pinned do not leak across seeks. + if ( savedUserShape != NULL ) + { + for ( int i = 0; i < oldShapeCount; ++i ) + { + if ( savedUserShape[i] != NULL && world->destroyDebugShape != NULL ) + { + world->destroyDebugShape( savedUserShape[i], world->userDebugShapeContext ); + } + } + b3Free( savedUserShape, (size_t)oldShapeCount * sizeof( void* ) ); + b3Free( savedGeneration, (size_t)oldShapeCount * sizeof( uint16_t ) ); + } +} + +// Contact serialization. b3Contact is not fully POD: +// - manifolds: heap array of b3Manifold, allocated via b3AllocateManifolds +// - meshContact.triangleCache: heap b3Array, active when b3_simMeshContact flag is set +// Serialize: raw struct (with nulled manifolds/triangleCache), then manifolds, then triangleCache. +static void b3SerContacts( b3RecBuffer* buf, b3World* world ) +{ + int count = world->contacts.count; + b3SnapW_I32( buf, count ); + + for ( int i = 0; i < count; ++i ) + { + const b3Contact* c = world->contacts.data + i; + bool isLive = ( c->contactId == i ); + + // Write raw struct with pointer fields zeroed + b3Contact copy = *c; + copy.manifolds = NULL; + copy.bodySimIndexA = B3_NULL_INDEX; + copy.bodySimIndexB = B3_NULL_INDEX; + if ( copy.flags & b3_simMeshContact ) + { + copy.meshContact.triangleCache.data = NULL; + copy.meshContact.triangleCache.count = 0; + copy.meshContact.triangleCache.capacity = 0; + } + b3SnapW_Bytes( buf, ©, sizeof( b3Contact ) ); + + if ( !isLive ) + { + // Free slot: no heap data + b3SnapW_I32( buf, 0 ); // manifoldCount + // No triangleCache + continue; + } + + // Manifolds + b3SnapW_I32( buf, c->manifoldCount ); + if ( c->manifoldCount > 0 && c->manifolds != NULL ) + { + b3SnapW_Bytes( buf, c->manifolds, c->manifoldCount * (int)sizeof( b3Manifold ) ); + } + + // Mesh triangleCache + if ( c->flags & b3_simMeshContact ) + { + b3SnapW_I32( buf, c->meshContact.triangleCache.count ); + if ( c->meshContact.triangleCache.count > 0 ) + { + b3SnapW_Bytes( buf, c->meshContact.triangleCache.data, + c->meshContact.triangleCache.count * (int)sizeof( b3TriangleCache ) ); + } + } + } +} + +static void b3DesContacts( b3SnapReader* r, b3World* world ) +{ + int count = b3SnapR_I32( r ); + if ( r->ok && b3SnapCheckCount( r, count, (int)sizeof( b3Contact ), (int)sizeof( b3Contact ) ) == false ) + { + r->ok = false; + } + if ( !r->ok ) + { + return; + } + + b3Array_Resize( world->contacts, count ); + memset( world->contacts.data, 0, (size_t)count * sizeof( b3Contact ) ); + + for ( int i = 0; i < count && r->ok; ++i ) + { + b3Contact* dst = world->contacts.data + i; + b3SnapR_Bytes( r, dst, sizeof( b3Contact ) ); + dst->manifolds = NULL; + dst->bodySimIndexA = B3_NULL_INDEX; + dst->bodySimIndexB = B3_NULL_INDEX; + if ( dst->flags & b3_simMeshContact ) + { + dst->meshContact.triangleCache.data = NULL; + dst->meshContact.triangleCache.count = 0; + dst->meshContact.triangleCache.capacity = 0; + } + + bool isLive = ( dst->contactId == i ); + + int manifoldCount = b3SnapR_I32( r ); + + if ( !r->ok ) + { + break; + } + + if ( isLive && manifoldCount > 0 ) + { + if ( b3SnapCheckCount( r, manifoldCount, (int)sizeof( b3Manifold ), (int)sizeof( b3Manifold ) ) == false ) + { + r->ok = false; + break; + } + dst->manifolds = b3AllocateManifolds( world, manifoldCount ); + dst->manifoldCount = manifoldCount; + b3SnapR_Bytes( r, dst->manifolds, manifoldCount * (int)sizeof( b3Manifold ) ); + } + else + { + dst->manifolds = NULL; + dst->manifoldCount = 0; + } + + // Mesh triangleCache + if ( isLive && ( dst->flags & b3_simMeshContact ) ) + { + int cacheCount = b3SnapR_I32( r ); + if ( !r->ok ) + { + break; + } + if ( cacheCount > 0 ) + { + if ( b3SnapCheckCount( r, cacheCount, (int)sizeof( b3TriangleCache ), (int)sizeof( b3TriangleCache ) ) == false ) + { + r->ok = false; + break; + } + b3Array_Resize( dst->meshContact.triangleCache, cacheCount ); + b3SnapR_Bytes( r, dst->meshContact.triangleCache.data, cacheCount * (int)sizeof( b3TriangleCache ) ); + } + } + } +} + +// Free per-object heap that b3DeserializeIntoShell will overwrite, +// so restoring over a populated world doesn't leak. +static void b3FreeLiveSimElements( b3World* world ) +{ + // Shape heap: materials and hull DB references + for ( int i = 0; i < world->shapes.count; ++i ) + { + b3Shape* s = world->shapes.data + i; + if ( s->id != i ) + { + continue; + } + // A single material lives inline (materials == NULL). Multi material meshes and compounds own + // the array, so free it exactly as b3DestroyShapeAllocations does. + if ( s->materials != NULL ) + { + b3Free( s->materials, (size_t)s->materialCount * sizeof( b3SurfaceMaterial ) ); + s->materials = NULL; + s->materialCount = 0; + } + // Hull is ref-counted in the world DB; release before overwrite so re-adding is ref-neutral. + if ( s->type == b3_hullShape && s->hull != NULL ) + { + b3RemoveHullFromDatabase( world, s->hull ); + s->hull = NULL; + } + // name / userData / userShape are host-owned; do not free + } + + // Contact heap: manifolds + mesh triangleCache + for ( int i = 0; i < world->contacts.count; ++i ) + { + b3Contact* c = world->contacts.data + i; + if ( c->contactId == i ) + { + if ( c->manifolds != NULL ) + { + b3FreeManifolds( world, c->manifolds, c->manifoldCount ); + c->manifolds = NULL; + c->manifoldCount = 0; + } + if ( c->flags & b3_simMeshContact ) + { + b3Array_Destroy( c->meshContact.triangleCache ); + } + } + } + + // Sensor heap: inner arrays + for ( int i = 0; i < world->sensors.count; ++i ) + { + b3Sensor* sensor = world->sensors.data + i; + b3Array_Destroy( sensor->hits ); + b3Array_Destroy( sensor->overlaps1 ); + b3Array_Destroy( sensor->overlaps2 ); + } + + // Island heap: inner arrays + for ( int i = 0; i < world->islands.count; ++i ) + { + b3Island* island = world->islands.data + i; + b3Array_Destroy( island->bodies ); + b3Array_Destroy( island->contacts ); + b3Array_Destroy( island->joints ); + } +} + +int b3SerializeWorld( b3World* world, b3RecBuffer* buf, b3Recording* rec ) +{ + int startSize = buf->size; + + // Snapshot header + b3SnapHeader hdr; + hdr.magic = B3_SNAP_MAGIC; + hdr.version = B3_SNAP_VERSION; + hdr.layoutHash = b3ComputeLayoutHash(); + hdr.flags = B3_ENABLE_VALIDATION ? B3_SNAP_FLAG_VALIDATION : 0u; +#if defined( BOX3D_DOUBLE_PRECISION ) + hdr.flags |= B3_SNAP_FLAG_DOUBLE_PRECISION; +#endif + b3SnapW_Bytes( buf, &hdr, (int)sizeof( hdr ) ); + + // World scalars + b3SerWorldConfig( buf, world ); + + // 6 id pools (Box3D has no chainIdPool) + b3SerIdPool( buf, &world->bodyIdPool ); + b3SerIdPool( buf, &world->shapeIdPool ); + b3SerIdPool( buf, &world->contactIdPool ); + b3SerIdPool( buf, &world->jointIdPool ); + b3SerIdPool( buf, &world->islandIdPool ); + b3SerIdPool( buf, &world->solverSetIdPool ); + + // Solver sets + int setCount = world->solverSets.count; + b3SnapW_I32( buf, setCount ); + for ( int i = 0; i < setCount; ++i ) + { + b3SerSolverSet( buf, world->solverSets.data + i ); + } + + // Sparse body array (userData is host wiring, zero it on the copy) + { + int bodyCount = world->bodies.count; + b3SnapW_I32( buf, bodyCount ); + for ( int i = 0; i < bodyCount; ++i ) + { + b3Body elem = world->bodies.data[i]; + elem.userData = NULL; + b3SnapW_Bytes( buf, &elem, sizeof( b3Body ) ); + } + } + + // Shape sparse array with geometry interning + b3SerShapes( buf, world, rec ); + + // Contact sparse array with manifold and mesh triangleCache + b3SerContacts( buf, world ); + + // Joint sparse array (userData scrubbed) + { + int jointCount = world->joints.count; + b3SnapW_I32( buf, jointCount ); + for ( int i = 0; i < jointCount; ++i ) + { + b3Joint elem = world->joints.data[i]; + elem.userData = NULL; + b3SnapW_Bytes( buf, &elem, sizeof( b3Joint ) ); + } + } + + // Sensors: shapeId + 3 inner arrays each + { + int sensorCount = world->sensors.count; + b3SnapW_I32( buf, sensorCount ); + for ( int i = 0; i < sensorCount; ++i ) + { + b3Sensor* s = world->sensors.data + i; + b3SnapW_I32( buf, s->shapeId ); + b3SerPodArray( buf, s->hits ); + b3SerPodArray( buf, s->overlaps1 ); + b3SerPodArray( buf, s->overlaps2 ); + } + } + + // Islands: 4 scalars + 3 inner arrays each + { + int islandCount = world->islands.count; + b3SnapW_I32( buf, islandCount ); + for ( int i = 0; i < islandCount; ++i ) + { + b3Island* island = world->islands.data + i; + b3SnapW_I32( buf, island->setIndex ); + b3SnapW_I32( buf, island->localIndex ); + b3SnapW_I32( buf, island->islandId ); + b3SnapW_I32( buf, island->constraintRemoveCount ); + b3SerPodArray( buf, island->bodies ); + b3SerPodArray( buf, island->contacts ); + b3SerPodArray( buf, island->joints ); + } + } + + // Broad phase + b3BroadPhase* bp = &world->broadPhase; + for ( int t = 0; t < b3_bodyTypeCount; ++t ) + { + b3SerTree( buf, &bp->trees[t] ); + } + for ( int t = 0; t < b3_bodyTypeCount; ++t ) + { + b3SerBitSet( buf, &bp->movedProxies[t] ); + } + b3SerPodArray( buf, bp->moveArray ); + b3SerHashSet( buf, &bp->pairSet ); + + // Constraint graph + b3ConstraintGraph* graph = &world->constraintGraph; + for ( int c = 0; c < B3_GRAPH_COLOR_COUNT; ++c ) + { + b3SerGraphColor( buf, &graph->colors[c], c == B3_OVERFLOW_INDEX ); + } + + return buf->size - startSize; +} + +bool b3DeserializeIntoShell( const uint8_t* data, int size, b3World* world, b3RecReader* rdr ) +{ + if ( data == NULL || size < (int)sizeof( b3SnapHeader ) ) + { + return false; + } + + // Validate header + b3SnapHeader hdr; + memcpy( &hdr, data, sizeof( hdr ) ); + if ( hdr.magic != B3_SNAP_MAGIC || hdr.version != B3_SNAP_VERSION ) + { + printf( "b3DeserializeIntoShell: bad magic/version\n" ); + return false; + } + bool imageDouble = ( hdr.flags & B3_SNAP_FLAG_DOUBLE_PRECISION ) != 0; +#if defined( BOX3D_DOUBLE_PRECISION ) + bool buildDouble = true; +#else + bool buildDouble = false; +#endif + if ( imageDouble != buildDouble ) + { + printf( "b3DeserializeIntoShell: precision mismatch\n" ); + return false; + } + if ( hdr.layoutHash != b3ComputeLayoutHash() ) + { + printf( "b3DeserializeIntoShell: layout hash mismatch\n" ); + return false; + } + + b3SnapReader readerStorage; + b3SnapReader* r = &readerStorage; + r->data = data; + r->cursor = (int)sizeof( b3SnapHeader ); + r->size = size; + r->ok = true; + + // Free existing per-object heap before overwriting + b3FreeLiveSimElements( world ); + + // 1. World scalars + b3DesWorldConfig( r, world ); + + // 2. 6 id pools; destroy the pre-created sets' pool state first + b3DesIdPool( r, &world->bodyIdPool ); + b3DesIdPool( r, &world->shapeIdPool ); + b3DesIdPool( r, &world->contactIdPool ); + b3DesIdPool( r, &world->jointIdPool ); + b3DesIdPool( r, &world->islandIdPool ); + b3DesIdPool( r, &world->solverSetIdPool ); + + // 3. Solver sets: destroy inner arrays of existing sets first + for ( int i = 0; i < world->solverSets.count; ++i ) + { + b3SolverSet* set = world->solverSets.data + i; + b3Array_Destroy( set->bodySims ); + b3Array_Destroy( set->bodyStates ); + b3Array_Destroy( set->jointSims ); + b3Array_Destroy( set->contactIndices ); + b3Array_Destroy( set->islandSims ); + } + + int setCount = b3SnapR_I32( r ); + if ( r->ok && b3SnapCheckCount( r, setCount, (int)sizeof( b3SolverSet ), 6 * (int)sizeof( int ) ) == false ) + { + r->ok = false; + } + if ( r->ok ) + { + b3Array_Resize( world->solverSets, setCount ); + memset( world->solverSets.data, 0, (size_t)setCount * sizeof( b3SolverSet ) ); + for ( int i = 0; i < setCount; ++i ) + { + b3DesSolverSet( r, world->solverSets.data + i ); + } + } + + if ( !r->ok ) + { + return false; + } + + // 4. Body sparse array + { + int bodyCount = b3SnapR_I32( r ); + if ( r->ok && b3SnapCheckCount( r, bodyCount, (int)sizeof( b3Body ), (int)sizeof( b3Body ) ) == false ) + { + r->ok = false; + } + if ( r->ok ) + { + b3Array_Resize( world->bodies, bodyCount ); + for ( int i = 0; i < bodyCount; ++i ) + { + b3SnapR_Bytes( r, world->bodies.data + i, sizeof( b3Body ) ); + world->bodies.data[i].userData = NULL; + } + } + } + + if ( !r->ok ) + { + return false; + } + + // 5. Shape sparse array + b3DesShapes( r, world, rdr ); + + if ( !r->ok ) + { + return false; + } + + // 6. Contact sparse array + b3DesContacts( r, world ); + + if ( !r->ok ) + { + return false; + } + + // 7. Joint sparse array + { + int jointCount = b3SnapR_I32( r ); + if ( r->ok && b3SnapCheckCount( r, jointCount, (int)sizeof( b3Joint ), (int)sizeof( b3Joint ) ) == false ) + { + r->ok = false; + } + if ( r->ok ) + { + b3Array_Resize( world->joints, jointCount ); + for ( int i = 0; i < jointCount; ++i ) + { + b3SnapR_Bytes( r, world->joints.data + i, sizeof( b3Joint ) ); + world->joints.data[i].userData = NULL; + } + } + } + + // 8. Sensors + { + b3Array_Destroy( world->sensors ); + b3Array_Create( world->sensors ); + + int sensorCount = b3SnapR_I32( r ); + if ( r->ok && b3SnapCheckCount( r, sensorCount, (int)sizeof( b3Sensor ), 4 * (int)sizeof( int ) ) == false ) + { + r->ok = false; + } + if ( r->ok ) + { + b3Array_Resize( world->sensors, sensorCount ); + memset( world->sensors.data, 0, (size_t)sensorCount * sizeof( b3Sensor ) ); + } + + for ( int i = 0; i < sensorCount && r->ok; ++i ) + { + b3Sensor* s = world->sensors.data + i; + s->shapeId = b3SnapR_I32( r ); + b3Array_Create( s->hits ); + b3Array_Create( s->overlaps1 ); + b3Array_Create( s->overlaps2 ); + b3DesPodArray( r, s->hits ); + b3DesPodArray( r, s->overlaps1 ); + b3DesPodArray( r, s->overlaps2 ); + } + } + + // 9. Islands + { + b3Array_Destroy( world->islands ); + b3Array_Create( world->islands ); + + int islandCount = b3SnapR_I32( r ); + if ( r->ok && b3SnapCheckCount( r, islandCount, (int)sizeof( b3Island ), 7 * (int)sizeof( int ) ) == false ) + { + r->ok = false; + } + if ( r->ok ) + { + b3Array_Resize( world->islands, islandCount ); + memset( world->islands.data, 0, (size_t)islandCount * sizeof( b3Island ) ); + } + + for ( int i = 0; i < islandCount && r->ok; ++i ) + { + b3Island* island = world->islands.data + i; + island->setIndex = b3SnapR_I32( r ); + island->localIndex = b3SnapR_I32( r ); + island->islandId = b3SnapR_I32( r ); + island->constraintRemoveCount = b3SnapR_I32( r ); + b3Array_Create( island->bodies ); + b3Array_Create( island->contacts ); + b3Array_Create( island->joints ); + b3DesPodArray( r, island->bodies ); + b3DesPodArray( r, island->contacts ); + b3DesPodArray( r, island->joints ); + } + } + + // 10. Broad phase + { + b3BroadPhase* bp = &world->broadPhase; + + for ( int t = 0; t < b3_bodyTypeCount; ++t ) + { + b3DesTree( r, &bp->trees[t] ); + } + for ( int t = 0; t < b3_bodyTypeCount; ++t ) + { + b3DesBitSet( r, &bp->movedProxies[t] ); + } + + b3Array_Destroy( bp->moveArray ); + b3Array_Create( bp->moveArray ); + b3DesPodArray( r, bp->moveArray ); + + b3DesHashSet( r, &bp->pairSet ); + // Transient moveResults/movePairs stay at shell's NULL/0 + } + + // 11. Constraint graph + { + b3ConstraintGraph* graph = &world->constraintGraph; + for ( int c = 0; c < B3_GRAPH_COLOR_COUNT; ++c ) + { + b3DesGraphColor( r, &graph->colors[c], c == B3_OVERFLOW_INDEX ); + } + } + + return r->ok; +} diff --git a/src/world_snapshot.h b/src/world_snapshot.h new file mode 100644 index 0000000..7bf0065 --- /dev/null +++ b/src/world_snapshot.h @@ -0,0 +1,21 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "recording.h" +#include "recording_replay.h" + +#include +#include + +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 ); diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 2c64ced..a07a66b 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -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 diff --git a/test/main.c b/test/main.c index 703923d..930f771 100644 --- a/test/main.c +++ b/test/main.c @@ -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 ); diff --git a/test/test_compound.c b/test/test_compound.c index 55ac86d..7fac23f 100644 --- a/test/test_compound.c +++ b/test/test_compound.c @@ -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 ); diff --git a/test/test_height_field.c b/test/test_height_field.c index e7e83c3..2dd3fc6 100644 --- a/test/test_height_field.c +++ b/test/test_height_field.c @@ -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 diff --git a/test/test_recording.c b/test/test_recording.c new file mode 100644 index 0000000..ad9e150 --- /dev/null +++ b/test/test_recording.c @@ -0,0 +1,1502 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +#if defined( _MSC_VER ) && !defined( _CRT_SECURE_NO_WARNINGS ) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include "box3d/box3d.h" +#include "box3d/collision.h" +#include "test_macros.h" + +#include "physics_world.h" +#include "recording.h" + +#include +#include +#include + +static const char* s_recPath = "recording_allops_test.b3rec"; + +// Sphere round-trip: record/step/stop, then replay and validate. +static int SphereRoundTrip( void ) +{ + b3Recording* rec = b3CreateRecording( 0 ); + ENSURE( rec != NULL ); + + b3WorldDef worldDef = b3DefaultWorldDef(); + b3WorldId worldId = b3CreateWorld( &worldDef ); + + b3World_StartRecording( worldId, rec ); + + // Set a non-default gravity so the setter op appears in the stream. + b3World_SetGravity( worldId, (b3Vec3){ 0.0f, -10.0f, 0.0f } ); + + // Static ground + b3BodyDef groundDef = b3DefaultBodyDef(); + groundDef.type = b3_staticBody; + b3BodyId groundId = b3CreateBody( worldId, &groundDef ); + + b3BoxHull groundBox = b3MakeBoxHull( 50.0f, 1.0f, 50.0f ); + b3ShapeDef groundShapeDef = b3DefaultShapeDef(); + b3CreateHullShape( groundId, &groundShapeDef, &groundBox.base ); + + // Dynamic body with a sphere shape + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = (b3Pos){ 0.0f, 5.0f, 0.0f }; + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + + b3Sphere sphere; + sphere.center = (b3Vec3){ 0.0f, 0.0f, 0.0f }; + sphere.radius = 0.5f; + b3ShapeDef sphereDef = b3DefaultShapeDef(); + sphereDef.density = 1.0f; + b3CreateSphereShape( bodyId, &sphereDef, &sphere ); + + float timeStep = 1.0f / 60.0f; + int subStepCount = 4; + for ( int i = 0; i < 30; ++i ) + { + b3World_Step( worldId, timeStep, subStepCount ); + } + + b3World_StopRecording( worldId ); + b3DestroyWorld( worldId ); + + ENSURE( b3ValidateReplay( b3Recording_GetData( rec ), b3Recording_GetSize( rec ), 1 ) ); + + b3DestroyRecording( rec ); + return 0; +} + +// Hull dedup: three bodies sharing the same hull should produce one registry entry. +static int HullDedup( void ) +{ + // Build a small convex hull + b3Vec3 pts[8] = { + { -1.0f, -1.0f, -1.0f }, { 1.0f, -1.0f, -1.0f }, + { 1.0f, 1.0f, -1.0f }, { -1.0f, 1.0f, -1.0f }, + { -1.0f, -1.0f, 1.0f }, { 1.0f, -1.0f, 1.0f }, + { 1.0f, 1.0f, 1.0f }, { -1.0f, 1.0f, 1.0f }, + }; + b3HullData* hull = b3CreateHull( pts, 8, 8 ); + ENSURE( hull != NULL ); + + b3Recording* rec = b3CreateRecording( 0 ); + ENSURE( rec != NULL ); + + b3WorldDef worldDef = b3DefaultWorldDef(); + b3WorldId worldId = b3CreateWorld( &worldDef ); + + b3World_StartRecording( worldId, rec ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.density = 1.0f; + + for ( int i = 0; i < 3; ++i ) + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = (b3Pos){ (float)( i * 3 ), 5.0f, 0.0f }; + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + b3CreateHullShape( bodyId, &shapeDef, hull ); + } + + float timeStep = 1.0f / 60.0f; + for ( int i = 0; i < 5; ++i ) + { + b3World_Step( worldId, timeStep, 4 ); + } + + b3World_StopRecording( worldId ); + b3DestroyWorld( worldId ); + b3DestroyHull( hull ); + + // Validate the replay + ENSURE( b3ValidateReplay( b3Recording_GetData( rec ), b3Recording_GetSize( rec ), 1 ) ); + + // Confirm the registry was deduped to 1 hull entry. + // Parse registryOffset from the header and count entries. + const uint8_t* bytes = b3Recording_GetData( rec ); + int sz = b3Recording_GetSize( rec ); + ENSURE( sz >= 48 ); + + uint64_t regOff = 0; + memcpy( ®Off, bytes + 32, 8 ); // registryOffset at offset 32 in b3RecHeader + ENSURE( regOff != 0 && (int)regOff + 4 <= sz ); + + // entryCount is a little-endian u32 at the start of the registry block + const uint8_t* rp = bytes + (int)regOff; + uint32_t entryCount = (uint32_t)rp[0] | ( (uint32_t)rp[1] << 8 ) | + ( (uint32_t)rp[2] << 16 ) | ( (uint32_t)rp[3] << 24 ); + ENSURE( entryCount == 1 ); + + b3DestroyRecording( rec ); + return 0; +} + +// Mid-stream snapshot with only dynamic bodies floating in air (no contacts). +static int MidStreamNoContacts( void ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + b3WorldId worldId = b3CreateWorld( &worldDef ); + + b3World_SetGravity( worldId, (b3Vec3){ 0.0f, -10.0f, 0.0f } ); + + b3Sphere sphere; + sphere.center = (b3Vec3){ 0.0f, 0.0f, 0.0f }; + sphere.radius = 0.5f; + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.density = 1.0f; + + // A few dynamic bodies well apart from each other so no contacts form + for ( int i = 0; i < 4; ++i ) + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = (b3Pos){ (float)( i * 10 ), 50.0f, 0.0f }; + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + b3CreateSphereShape( bodyId, &shapeDef, &sphere ); + } + + float timeStep = 1.0f / 60.0f; + int subStepCount = 4; + for ( int i = 0; i < 10; ++i ) + { + b3World_Step( worldId, timeStep, subStepCount ); + } + + // Start recording mid-stream, with a snapshot of the current world + b3Recording* rec = b3CreateRecording( 0 ); + ENSURE( rec != NULL ); + b3World_StartRecording( worldId, rec ); + + for ( int i = 0; i < 30; ++i ) + { + b3World_Step( worldId, timeStep, subStepCount ); + } + + b3World_StopRecording( worldId ); + b3DestroyWorld( worldId ); + + ENSURE( b3ValidateReplay( b3Recording_GetData( rec ), b3Recording_GetSize( rec ), 1 ) ); + + b3DestroyRecording( rec ); + return 0; +} + +// Mid-stream snapshot with contacts: bodies touching ground with warm-start manifolds. +static int MidStreamContacts( void ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + b3WorldId worldId = b3CreateWorld( &worldDef ); + + b3World_SetGravity( worldId, (b3Vec3){ 0.0f, -10.0f, 0.0f } ); + + // Static ground using a box hull + { + b3BodyDef groundDef = b3DefaultBodyDef(); + groundDef.type = b3_staticBody; + b3BodyId groundId = b3CreateBody( worldId, &groundDef ); + + b3BoxHull groundBox = b3MakeBoxHull( 50.0f, 1.0f, 50.0f ); + b3ShapeDef groundShape = b3DefaultShapeDef(); + b3CreateHullShape( groundId, &groundShape, &groundBox.base ); + } + + b3ShapeDef dynamicShape = b3DefaultShapeDef(); + dynamicShape.density = 1.0f; + + // A few dynamic boxes dropped onto the ground + for ( int i = 0; i < 3; ++i ) + { + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = (b3Pos){ (float)( i * 2 ) - 2.0f, 5.0f, 0.0f }; + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + b3CreateHullShape( bodyId, &dynamicShape, &box.base ); + } + + float timeStep = 1.0f / 60.0f; + int subStepCount = 4; + + // Let the scene settle: bodies hit ground, build manifolds, islands, graph colors + for ( int i = 0; i < 60; ++i ) + { + b3World_Step( worldId, timeStep, subStepCount ); + } + + // Start recording with snapshot of the settled world (contacts, islands, warm starts) + b3Recording* rec = b3CreateRecording( 0 ); + ENSURE( rec != NULL ); + b3World_StartRecording( worldId, rec ); + + for ( int i = 0; i < 30; ++i ) + { + b3World_Step( worldId, timeStep, subStepCount ); + } + + b3World_StopRecording( worldId ); + b3DestroyWorld( worldId ); + + ENSURE( b3ValidateReplay( b3Recording_GetData( rec ), b3Recording_GetSize( rec ), 1 ) ); + + b3DestroyRecording( rec ); + return 0; +} + +// Record a scene with hull boxes settling on a ground plane, create a player, step to +// the end recording per-frame world hashes, then seek backward to several frames and +// verify each reproduces the recorded hash exactly. +static int ScrubBackward( void ) +{ + b3Recording* rec = b3CreateRecording( 0 ); + ENSURE( rec != NULL ); + + b3WorldDef worldDef = b3DefaultWorldDef(); + b3WorldId worldId = b3CreateWorld( &worldDef ); + + b3World_SetGravity( worldId, (b3Vec3){ 0.0f, -10.0f, 0.0f } ); + + b3World_StartRecording( worldId, rec ); + + // Static ground + { + b3BodyDef groundDef = b3DefaultBodyDef(); + groundDef.type = b3_staticBody; + b3BodyId groundId = b3CreateBody( worldId, &groundDef ); + b3BoxHull groundBox = b3MakeBoxHull( 20.0f, 1.0f, 20.0f ); + b3ShapeDef groundShape = b3DefaultShapeDef(); + b3CreateHullShape( groundId, &groundShape, &groundBox.base ); + } + + // A small stack of dynamic hull boxes + b3ShapeDef boxShape = b3DefaultShapeDef(); + boxShape.density = 1.0f; + for ( int i = 0; i < 4; ++i ) + { + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = (b3Pos){ 0.0f, 2.0f + (float)i * 1.5f, 0.0f }; + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + b3CreateHullShape( bodyId, &boxShape, &box.base ); + } + + float timeStep = 1.0f / 60.0f; + int subStepCount = 4; + int totalFrames = 80; + for ( int i = 0; i < totalFrames; ++i ) + { + b3World_Step( worldId, timeStep, subStepCount ); + } + + b3World_StopRecording( worldId ); + b3DestroyWorld( worldId ); + + const uint8_t* data = b3Recording_GetData( rec ); + int sz = b3Recording_GetSize( rec ); + + // Create the player + b3RecPlayer* player = b3RecPlayer_Create( data, sz, 1 ); + ENSURE( player != NULL ); + ENSURE( b3RecPlayer_GetFrameCount( player ) == totalFrames ); + + // Forward pass: record per-frame hashes + uint64_t* hashes = (uint64_t*)b3Alloc( (size_t)( totalFrames + 1 ) * sizeof( uint64_t ) ); + hashes[0] = 0; // frame 0 before any step + + while ( !b3RecPlayer_IsAtEnd( player ) ) + { + b3RecPlayer_StepFrame( player ); + int f = b3RecPlayer_GetFrame( player ); + if ( f <= totalFrames ) + { + b3WorldId wid = b3RecPlayer_GetWorldId( player ); + b3World* w = b3GetWorldFromId( wid ); + hashes[f] = b3HashWorldState( w ); + } + } + ENSURE( b3RecPlayer_GetFrame( player ) == totalFrames ); + ENSURE( !b3RecPlayer_HasDiverged( player ) ); + + // Backward seek to several interesting frames and verify hash matches + int seekTargets[] = { totalFrames, totalFrames / 2, 5, totalFrames - 1, 0, 1 }; + int seekCount = (int)( sizeof( seekTargets ) / sizeof( seekTargets[0] ) ); + for ( int k = 0; k < seekCount; ++k ) + { + int target = seekTargets[k]; + b3RecPlayer_SeekFrame( player, target ); + ENSURE( b3RecPlayer_GetFrame( player ) == target ); + ENSURE( !b3RecPlayer_HasDiverged( player ) ); + + if ( target > 0 ) + { + b3WorldId wid = b3RecPlayer_GetWorldId( player ); + b3World* w = b3GetWorldFromId( wid ); + uint64_t got = b3HashWorldState( w ); + ENSURE( got == hashes[target] ); + } + } + + b3Free( hashes, (size_t)( totalFrames + 1 ) * sizeof( uint64_t ) ); + b3RecPlayer_Destroy( player ); + b3DestroyRecording( rec ); + return 0; +} + +// Record a scene that includes a mesh shape, create a player, seek backward, verify +// it works and no divergence is reported. Also checks the keyframe-by-geometry-id +// invariant: keyframeRec registry count should not grow beyond initial slot count. +static int SeekWithHull( void ) +{ + b3Vec3 pts[8] = { + { -1.0f, -1.0f, -1.0f }, { 1.0f, -1.0f, -1.0f }, + { 1.0f, 1.0f, -1.0f }, { -1.0f, 1.0f, -1.0f }, + { -1.0f, -1.0f, 1.0f }, { 1.0f, -1.0f, 1.0f }, + { 1.0f, 1.0f, 1.0f }, { -1.0f, 1.0f, 1.0f }, + }; + b3HullData* hull = b3CreateHull( pts, 8, 8 ); + ENSURE( hull != NULL ); + + b3Recording* rec = b3CreateRecording( 0 ); + ENSURE( rec != NULL ); + + b3WorldDef worldDef = b3DefaultWorldDef(); + b3WorldId worldId = b3CreateWorld( &worldDef ); + + b3World_SetGravity( worldId, (b3Vec3){ 0.0f, -10.0f, 0.0f } ); + b3World_StartRecording( worldId, rec ); + + // Static ground + { + b3BodyDef groundDef = b3DefaultBodyDef(); + groundDef.type = b3_staticBody; + b3BodyId groundId = b3CreateBody( worldId, &groundDef ); + b3BoxHull groundBox = b3MakeBoxHull( 20.0f, 1.0f, 20.0f ); + b3ShapeDef gs = b3DefaultShapeDef(); + b3CreateHullShape( groundId, &gs, &groundBox.base ); + } + + // Dynamic bodies using the custom hull + b3ShapeDef sd = b3DefaultShapeDef(); + sd.density = 1.0f; + for ( int i = 0; i < 3; ++i ) + { + b3BodyDef bd = b3DefaultBodyDef(); + bd.type = b3_dynamicBody; + bd.position = (b3Pos){ (float)( i * 4 ) - 4.0f, 5.0f, 0.0f }; + b3BodyId bodyId = b3CreateBody( worldId, &bd ); + b3CreateHullShape( bodyId, &sd, hull ); + } + + float timeStep = 1.0f / 60.0f; + int totalFrames = 40; + for ( int i = 0; i < totalFrames; ++i ) + { + b3World_Step( worldId, timeStep, 4 ); + } + + b3World_StopRecording( worldId ); + b3DestroyWorld( worldId ); + b3DestroyHull( hull ); + + const uint8_t* data = b3Recording_GetData( rec ); + int sz = b3Recording_GetSize( rec ); + + b3RecPlayer* player = b3RecPlayer_Create( data, sz, 1 ); + ENSURE( player != NULL ); + + // Step to end + while ( !b3RecPlayer_IsAtEnd( player ) ) + { + b3RecPlayer_StepFrame( player ); + } + ENSURE( !b3RecPlayer_HasDiverged( player ) ); + + int midFrame = totalFrames / 2; + b3RecPlayer_SeekFrame( player, midFrame ); + ENSURE( b3RecPlayer_GetFrame( player ) == midFrame ); + ENSURE( !b3RecPlayer_HasDiverged( player ) ); + + b3RecPlayer_SeekFrame( player, 0 ); + ENSURE( b3RecPlayer_GetFrame( player ) == 0 ); + + b3RecPlayer_Destroy( player ); + b3DestroyRecording( rec ); + return 0; +} + +// Host debug-shape callbacks just count create/destroy so the test can prove the player +// wires them into every world it builds. The returned token is opaque to the engine. +typedef struct +{ + int created; + int destroyed; +} DebugShapeCounters; + +static void* RecTestCreateDebugShape( const b3DebugShape* debugShape, void* userContext ) +{ + (void)debugShape; + DebugShapeCounters* counters = (DebugShapeCounters*)userContext; + counters->created += 1; + return userContext; // any non-NULL token; engine stores and hands it back to destroy +} + +static void RecTestDestroyDebugShape( void* userShape, void* userContext ) +{ + (void)userShape; + DebugShapeCounters* counters = (DebugShapeCounters*)userContext; + counters->destroyed += 1; +} + +static bool RecTestDrawShape( void* userShape, b3WorldTransform transform, b3HexColor color, void* context ) +{ + (void)userShape; + (void)transform; + (void)color; + (void)context; + return true; +} + +// b3World_Draw lazily fires createDebugShape for shapes entering the draw set, the same way the +// sample renderer does. Drive a draw so the player's wired callbacks actually run. +static void RecTestDrawWorld( b3WorldId worldId ) +{ + b3DebugDraw draw = b3DefaultDebugDraw(); + draw.DrawShapeFcn = RecTestDrawShape; + draw.drawShapes = true; + float big = 1.0e6f; + draw.drawingBounds = (b3AABB){ { -big, -big, -big }, { big, big, big } }; + b3World_Draw( worldId, &draw, B3_DEFAULT_MASK_BITS ); +} + +// The 3D sample renderer builds per-shape GPU meshes through createDebugShape, so the replay +// world must carry the host callbacks. Verify b3RecPlayer_SetDebugShapeCallbacks rewinds, fires +// the callbacks for every replayed shape, keeps them across a backward-seek world rebuild, and +// balances create/destroy at teardown. +static int DebugShapeCallbacks( void ) +{ + b3Recording* rec = b3CreateRecording( 0 ); + ENSURE( rec != NULL ); + + b3WorldDef worldDef = b3DefaultWorldDef(); + b3WorldId worldId = b3CreateWorld( &worldDef ); + + b3World_StartRecording( worldId, rec ); + b3World_SetGravity( worldId, (b3Vec3){ 0.0f, -10.0f, 0.0f } ); + + b3BodyDef groundDef = b3DefaultBodyDef(); + groundDef.type = b3_staticBody; + b3BodyId groundId = b3CreateBody( worldId, &groundDef ); + b3BoxHull groundBox = b3MakeBoxHull( 20.0f, 1.0f, 20.0f ); + b3ShapeDef groundShape = b3DefaultShapeDef(); + b3CreateHullShape( groundId, &groundShape, &groundBox.base ); + + // Four dynamic boxes sharing one hull: ground + 4 boxes = 5 shapes total. + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + b3ShapeDef boxShape = b3DefaultShapeDef(); + boxShape.density = 1.0f; + for ( int i = 0; i < 4; ++i ) + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = (b3Pos){ 0.0f, 1.0f + 1.1f * (float)i, 0.0f }; + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + b3CreateHullShape( bodyId, &boxShape, &box.base ); + } + + int totalFrames = 30; + for ( int i = 0; i < totalFrames; ++i ) + { + b3World_Step( worldId, 1.0f / 60.0f, 4 ); + } + b3World_StopRecording( worldId ); + b3DestroyWorld( worldId ); + + // Round-trip through a file, mirroring the replay sample's Generate/Load path exactly. + const char* path = "replay_test.b3rec"; + ENSURE( b3SaveRecordingToFile( rec, path ) ); + b3Recording* loaded = b3LoadRecordingFromFile( path ); + ENSURE( loaded != NULL ); + + b3RecPlayer* player = b3RecPlayer_Create( b3Recording_GetData( loaded ), b3Recording_GetSize( loaded ), 1 ); + ENSURE( player != NULL ); + + // Wiring the callbacks rebuilds the world and rewinds to frame 0. + DebugShapeCounters counters = { 0, 0 }; + b3RecPlayer_SetDebugShapeCallbacks( player, RecTestCreateDebugShape, RecTestDestroyDebugShape, &counters ); + ENSURE( b3RecPlayer_GetFrame( player ) == 0 ); + + // Replay to the end, then draw: createDebugShape fires once per shape (ground + 4 boxes = 5). + while ( !b3RecPlayer_IsAtEnd( player ) ) + { + b3RecPlayer_StepFrame( player ); + } + RecTestDrawWorld( b3RecPlayer_GetWorldId( player ) ); + ENSURE( counters.created >= 5 ); + ENSURE( !b3RecPlayer_HasDiverged( player ) ); + + // A backward seek restores the empty seed in place, releasing the live debug shapes, then forward + // stepping recreates them through the callbacks, so more creates fire. + int createdBefore = counters.created; + b3RecPlayer_SeekFrame( player, 0 ); + b3RecPlayer_SeekFrame( player, totalFrames ); + RecTestDrawWorld( b3RecPlayer_GetWorldId( player ) ); + ENSURE( counters.created > createdBefore ); + + // Teardown destroys the final world; every live shape is released, so the counts balance. + b3RecPlayer_Destroy( player ); + ENSURE( counters.created == counters.destroyed ); + + b3DestroyRecording( loaded ); + b3DestroyRecording( rec ); + remove( path ); + return 0; +} + +// Exercise the viewer-facing player accessors: recording info, creation-ordinal body tracking +// (seeded from a snapshot), divergence frame, and keyframe policy. Recording starts after the +// bodies exist, so the snapshot seeds the outliner list and ordinals are stable from frame 0. +static int PlayerAccessors( void ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + b3WorldId worldId = b3CreateWorld( &worldDef ); + b3World_SetGravity( worldId, (b3Vec3){ 0.0f, -10.0f, 0.0f } ); + + // Static ground (creation ordinal 0) + b3BodyDef groundDef = b3DefaultBodyDef(); + groundDef.type = b3_staticBody; + b3BodyId groundId = b3CreateBody( worldId, &groundDef ); + b3BoxHull groundBox = b3MakeBoxHull( 20.0f, 1.0f, 20.0f ); + b3ShapeDef groundShape = b3DefaultShapeDef(); + b3CreateHullShape( groundId, &groundShape, &groundBox.base ); + + // Four dynamic boxes (ordinals 1..4) + const int dynamicCount = 4; + b3ShapeDef boxShape = b3DefaultShapeDef(); + boxShape.density = 1.0f; + for ( int i = 0; i < dynamicCount; ++i ) + { + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = (b3Pos){ 0.0f, 2.0f + (float)i * 1.5f, 0.0f }; + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + b3CreateHullShape( bodyId, &boxShape, &box.base ); + } + + float timeStep = 1.0f / 60.0f; + int subStepCount = 4; + + // Settle, then record with a snapshot of the populated world. + for ( int i = 0; i < 10; ++i ) + { + b3World_Step( worldId, timeStep, subStepCount ); + } + + b3Recording* rec = b3CreateRecording( 0 ); + ENSURE( rec != NULL ); + b3World_StartRecording( worldId, rec ); + + int totalFrames = 80; + for ( int i = 0; i < totalFrames; ++i ) + { + b3World_Step( worldId, timeStep, subStepCount ); + } + b3World_StopRecording( worldId ); + b3DestroyWorld( worldId ); + + b3RecPlayer* player = b3RecPlayer_Create( b3Recording_GetData( rec ), b3Recording_GetSize( rec ), 1 ); + ENSURE( player != NULL ); + + // Info reflects the recorded tuning and a non-degenerate bounds. + b3RecPlayerInfo info = b3RecPlayer_GetInfo( player ); + ENSURE( info.frameCount == totalFrames ); + ENSURE( info.subStepCount == subStepCount ); + ENSURE( info.timeStep > 0.0f ); + b3Vec3 extent = b3Sub( info.bounds.upperBound, info.bounds.lowerBound ); + ENSURE( extent.x > 0.0f && extent.y > 0.0f && extent.z > 0.0f ); + + // Body ordinals: ground + 4 dynamic, seeded from the snapshot and present at frame 0. + ENSURE( b3RecPlayer_GetBodyCount( player ) == 1 + dynamicCount ); + b3BodyId ground = b3RecPlayer_GetBodyId( player, 0 ); + ENSURE( b3Body_IsValid( ground ) ); + ENSURE( b3Body_GetType( ground ) == b3_staticBody ); + for ( int i = 1; i <= dynamicCount; ++i ) + { + b3BodyId id = b3RecPlayer_GetBodyId( player, i ); + ENSURE( b3Body_IsValid( id ) ); + ENSURE( b3Body_GetType( id ) == b3_dynamicBody ); + } + ENSURE( B3_IS_NULL( b3RecPlayer_GetBodyId( player, 1 + dynamicCount ) ) ); + + // No divergence on a clean serial replay. + b3RecPlayer_SeekFrame( player, totalFrames ); + ENSURE( !b3RecPlayer_HasDiverged( player ) ); + ENSURE( b3RecPlayer_GetDivergeFrame( player ) == -1 ); + + // Ordinals survive a backward seek that restores from a keyframe. + b3BodyId before = b3RecPlayer_GetBodyId( player, 2 ); + b3RecPlayer_SeekFrame( player, totalFrames / 2 ); + b3RecPlayer_SeekFrame( player, totalFrames ); + b3BodyId after = b3RecPlayer_GetBodyId( player, 2 ); + ENSURE( B3_ID_EQUALS( before, after ) ); + + // Keyframe policy: defaults present, setter takes effect and clears the ring. + ENSURE( b3RecPlayer_GetKeyframeMinInterval( player ) == 16 ); + b3RecPlayer_SetKeyframePolicy( player, (size_t)256 * 1024 * 1024, 8 ); + ENSURE( b3RecPlayer_GetKeyframeMinInterval( player ) == 8 ); + ENSURE( b3RecPlayer_GetKeyframeInterval( player ) == 8 ); + ENSURE( b3RecPlayer_GetKeyframeBudget( player ) == (size_t)256 * 1024 * 1024 ); + ENSURE( b3RecPlayer_GetKeyframeBytes( player ) == 0 ); + + b3RecPlayer_Destroy( player ); + b3DestroyRecording( rec ); + return 0; +} + +// A keyframe restore is a deterministic replay state, so shapes that persist must keep their renderer +// handle rather than being torn down and rebuilt every seek. Record a snapshot-seeded session (shapes +// exist at frame 0), replay with handle callbacks, scrub backward across keyframes repeatedly, and +// verify no new handles are built per restore and the create/destroy counts still balance at teardown. +static int KeyframeHandleReuse( void ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + b3WorldId worldId = b3CreateWorld( &worldDef ); + b3World_SetGravity( worldId, (b3Vec3){ 0.0f, -10.0f, 0.0f } ); + + b3BodyDef groundDef = b3DefaultBodyDef(); + groundDef.type = b3_staticBody; + b3BodyId groundId = b3CreateBody( worldId, &groundDef ); + b3BoxHull groundBox = b3MakeBoxHull( 20.0f, 1.0f, 20.0f ); + b3ShapeDef groundShape = b3DefaultShapeDef(); + b3CreateHullShape( groundId, &groundShape, &groundBox.base ); + + const int dynamicCount = 5; + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + b3ShapeDef boxShape = b3DefaultShapeDef(); + boxShape.density = 1.0f; + for ( int i = 0; i < dynamicCount; ++i ) + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = (b3Pos){ 0.0f, 1.0f + 1.1f * (float)i, 0.0f }; + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + b3CreateHullShape( bodyId, &boxShape, &box.base ); + } + int shapeCount = 1 + dynamicCount; + + // Settle, then record with a snapshot of the populated world so shapes exist at frame 0. + for ( int i = 0; i < 10; ++i ) + { + b3World_Step( worldId, 1.0f / 60.0f, 4 ); + } + + b3Recording* rec = b3CreateRecording( 0 ); + ENSURE( rec != NULL ); + b3World_StartRecording( worldId, rec ); + + int totalFrames = 80; + for ( int i = 0; i < totalFrames; ++i ) + { + b3World_Step( worldId, 1.0f / 60.0f, 4 ); + } + b3World_StopRecording( worldId ); + b3DestroyWorld( worldId ); + + b3RecPlayer* player = b3RecPlayer_Create( b3Recording_GetData( rec ), b3Recording_GetSize( rec ), 1 ); + ENSURE( player != NULL ); + + DebugShapeCounters counters = { 0, 0 }; + b3RecPlayer_SetDebugShapeCallbacks( player, RecTestCreateDebugShape, RecTestDestroyDebugShape, &counters ); + + // Replay to the end and draw: one handle per shape. + b3RecPlayer_SeekFrame( player, totalFrames ); + RecTestDrawWorld( b3RecPlayer_GetWorldId( player ) ); + ENSURE( !b3RecPlayer_HasDiverged( player ) ); + ENSURE( counters.created == shapeCount ); + + // Scrub backward and forward across keyframes. Each restore keeps the persistent shapes' handles, + // so drawing builds no new ones. + int createdAfterFirstDraw = counters.created; + int seekTargets[] = { 40, 70, 20, 60, 8, 75 }; + for ( int k = 0; k < (int)( sizeof( seekTargets ) / sizeof( seekTargets[0] ) ); ++k ) + { + b3RecPlayer_SeekFrame( player, seekTargets[k] ); + RecTestDrawWorld( b3RecPlayer_GetWorldId( player ) ); + } + ENSURE( counters.created == createdAfterFirstDraw ); + + // Teardown releases exactly the live handles, so the leak-free invariant holds. + b3RecPlayer_Destroy( player ); + ENSURE( counters.created == counters.destroyed ); + + b3DestroyRecording( rec ); + return 0; +} + +static bool QueryReplayOverlapFcn( b3ShapeId shapeId, void* context ) +{ + (void)shapeId; + (void)context; + return true; +} + +static float QueryReplayCastFcn( b3ShapeId shapeId, b3Pos point, b3Vec3 normal, float fraction, uint64_t userMaterialId, + int triangleIndex, int childIndex, void* context ) +{ + (void)shapeId; + (void)point; + (void)normal; + (void)userMaterialId; + (void)triangleIndex; + (void)childIndex; + (void)context; + // Return the fraction to keep the closest hit, exercising the recorded user-return path. + return fraction; +} + +static bool QueryReplayPlaneFcn( b3ShapeId shapeId, const b3PlaneResult* planes, int planeCount, void* context ) +{ + (void)shapeId; + (void)planes; + (void)planeCount; + (void)context; + return true; +} + +static bool QueryReplayMoverFilterFcn( b3ShapeId shapeId, void* context ) +{ + (void)shapeId; + (void)context; + return true; +} + +// Issue all seven world queries each frame, then replay. Every query is re-issued against the replay +// world and compared to what was recorded, so a clean (non-diverged) replay proves the queries +// reproduce. Also opens a player and confirms the per-frame query store surfaces all seven. +static int QueryReplay( void ) +{ + b3Recording* rec = b3CreateRecording( 0 ); + ENSURE( rec != NULL ); + + b3WorldDef worldDef = b3DefaultWorldDef(); + b3WorldId worldId = b3CreateWorld( &worldDef ); + b3World_SetGravity( worldId, (b3Vec3){ 0.0f, -10.0f, 0.0f } ); + + b3BodyDef groundDef = b3DefaultBodyDef(); + groundDef.type = b3_staticBody; + b3BodyId groundId = b3CreateBody( worldId, &groundDef ); + b3BoxHull groundBox = b3MakeBoxHull( 20.0f, 1.0f, 20.0f ); + b3ShapeDef groundShape = b3DefaultShapeDef(); + b3CreateHullShape( groundId, &groundShape, &groundBox.base ); + + // A few dynamic spheres for the queries to find. + for ( int i = 0; i < 4; ++i ) + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = (b3Pos){ (float)i - 1.5f, 3.0f, 0.0f }; + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, 0.5f }; + b3ShapeDef sphereDef = b3DefaultShapeDef(); + sphereDef.density = 1.0f; + b3CreateSphereShape( bodyId, &sphereDef, &sphere ); + } + + b3World_StartRecording( worldId, rec ); + + b3QueryFilter filter = b3DefaultQueryFilter(); + + const int totalFrames = 30; + for ( int i = 0; i < totalFrames; ++i ) + { + b3Pos origin = { 0.0f, 6.0f, 0.0f }; + b3Vec3 translation = { 0.0f, -8.0f, 0.0f }; + b3AABB aabb = { { -5.0f, -1.0f, -5.0f }, { 5.0f, 6.0f, 5.0f } }; + + b3Vec3 proxyPts = { 0.0f, 0.0f, 0.0f }; + b3ShapeProxy proxy = { &proxyPts, 1, 0.5f }; + b3Capsule mover = { { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 0.3f }; + + b3World_OverlapAABB( worldId, aabb, filter, QueryReplayOverlapFcn, NULL ); + b3World_OverlapShape( worldId, origin, &proxy, filter, QueryReplayOverlapFcn, NULL ); + b3World_CastRay( worldId, origin, translation, filter, QueryReplayCastFcn, NULL ); + b3World_CastRayClosest( worldId, origin, translation, filter ); + b3World_CastShape( worldId, origin, &proxy, translation, filter, QueryReplayCastFcn, NULL ); + b3World_CastMover( worldId, origin, &mover, translation, filter, QueryReplayMoverFilterFcn, NULL ); + b3World_CollideMover( worldId, origin, &mover, filter, QueryReplayPlaneFcn, NULL ); + + b3World_Step( worldId, 1.0f / 60.0f, 4 ); + } + + b3World_StopRecording( worldId ); + b3DestroyWorld( worldId ); + + // Headless validation: re-issues every recorded query and compares the results. + ENSURE( b3ValidateReplay( b3Recording_GetData( rec ), b3Recording_GetSize( rec ), 1 ) ); + + // Player path: seek to a mid frame and confirm the per-frame store holds all seven queries. + b3RecPlayer* player = b3RecPlayer_Create( b3Recording_GetData( rec ), b3Recording_GetSize( rec ), 1 ); + ENSURE( player != NULL ); + + b3RecPlayer_SeekFrame( player, 15 ); + ENSURE( !b3RecPlayer_HasDiverged( player ) ); + ENSURE( b3RecPlayer_GetFrameQueryCount( player ) == 7 ); + + b3RecQueryInfo first = b3RecPlayer_GetFrameQuery( player, 0 ); + ENSURE( first.type == b3_recQueryOverlapAABB ); + + // The ray cast should find at least the ground, so its recorded hit list is non-empty. + bool sawCastRay = false; + for ( int qi = 0; qi < b3RecPlayer_GetFrameQueryCount( player ); ++qi ) + { + b3RecQueryInfo info = b3RecPlayer_GetFrameQuery( player, qi ); + if ( info.type == b3_recQueryCastRay ) + { + sawCastRay = true; + ENSURE( info.hitCount > 0 ); + } + } + ENSURE( sawCastRay ); + + b3RecPlayer_Destroy( player ); + b3DestroyRecording( rec ); + return 0; +} + +// Empty world: recording starts with no bodies and none are ever created. The empty world is still +// seed-serialized like any other, so replay validates and Restart restores in place with a stable +// world id rather than tearing down and rebuilding the world. +static int EmptyWorldRoundTrip( void ) +{ + b3Recording* rec = b3CreateRecording( 0 ); + ENSURE( rec != NULL ); + + b3WorldDef worldDef = b3DefaultWorldDef(); + b3WorldId worldId = b3CreateWorld( &worldDef ); + + b3World_StartRecording( worldId, rec ); + b3World_SetGravity( worldId, (b3Vec3){ 0.0f, -10.0f, 0.0f } ); + + for ( int i = 0; i < 10; ++i ) + { + b3World_Step( worldId, 1.0f / 60.0f, 4 ); + } + + b3World_StopRecording( worldId ); + b3DestroyWorld( worldId ); + + const uint8_t* data = b3Recording_GetData( rec ); + int size = b3Recording_GetSize( rec ); + + // The seed snapshot is written even with no bodies. + b3RecHeader hdr; + memcpy( &hdr, data, sizeof( hdr ) ); + ENSURE( hdr.snapshotSize > 0 ); + + ENSURE( b3ValidateReplay( data, size, 1 ) ); + + // Restart restores in place, so the replay world id survives a rewind. + b3RecPlayer* player = b3RecPlayer_Create( data, size, 1 ); + ENSURE( player != NULL ); + + uint32_t worldKey = b3StoreWorldId( b3RecPlayer_GetWorldId( player ) ); + while ( !b3RecPlayer_IsAtEnd( player ) ) + { + b3RecPlayer_StepFrame( player ); + } + b3RecPlayer_Restart( player ); + ENSURE( b3StoreWorldId( b3RecPlayer_GetWorldId( player ) ) == worldKey ); + ENSURE( b3RecPlayer_GetFrame( player ) == 0 ); + ENSURE( !b3RecPlayer_HasDiverged( player ) ); + + b3RecPlayer_Destroy( player ); + b3DestroyRecording( rec ); + return 0; +} + +// Exercise every recorded op in a single session, then validate replay at two worker +// counts, round-trip through a file, and drive the incremental player. Mirrors the +// comprehensive RecordingTest in Box2D's test suite (box2d/test/test_recording.c). +static int RecTestAssertDbg( const char* cond, const char* file, int line ) +{ + fprintf( stderr, "BOX3D ASSERTION: %s, %s:%d\n", cond, file, line ); + fflush( stderr ); + return 1; +} + +static int AllOps( void ) +{ + b3Recording* rec = b3CreateRecording( 0 ); + ENSURE( rec != NULL ); + + b3WorldDef worldDef = b3DefaultWorldDef(); + worldDef.workerCount = 1; + b3WorldId worldId = b3CreateWorld( &worldDef ); + ENSURE( b3World_IsValid( worldId ) ); + + b3World_StartRecording( worldId, rec ); + + // Static ground with a box-hull shape + b3BodyDef groundDef = b3DefaultBodyDef(); + groundDef.type = b3_staticBody; + b3BodyId groundId = b3CreateBody( worldId, &groundDef ); + ENSURE( b3Body_IsValid( groundId ) ); + b3BoxHull groundBox = b3MakeBoxHull( 50.0f, 1.0f, 50.0f ); + b3ShapeDef groundShapeDef = b3DefaultShapeDef(); + b3ShapeId groundShapeId = b3CreateHullShape( groundId, &groundShapeDef, &groundBox.base ); + ENSURE( b3Shape_IsValid( groundShapeId ) ); + + // Dynamic body with a sphere shape. The name is intentionally longer than B3_NAME_LENGTH so + // replay exercises the over-length name path in the body def reader. + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = (b3Pos){ 0.0f, 5.0f, 0.0f }; + bodyDef.name = "testBodyWithVeryLongNameThatExceedsTheNameLength"; + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + ENSURE( b3Body_IsValid( bodyId ) ); + + b3ShapeDef sphereShapeDef = b3DefaultShapeDef(); + sphereShapeDef.density = 1.0f; + b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, 0.5f }; + b3ShapeId sphereShapeId = b3CreateSphereShape( bodyId, &sphereShapeDef, &sphere ); + ENSURE( b3Shape_IsValid( sphereShapeId ) ); + + // Capsule shape on a second dynamic body + b3BodyDef capsuleBodyDef = b3DefaultBodyDef(); + capsuleBodyDef.type = b3_dynamicBody; + capsuleBodyDef.position = (b3Pos){ 3.0f, 5.0f, 0.0f }; + b3BodyId capsuleBodyId = b3CreateBody( worldId, &capsuleBodyDef ); + ENSURE( b3Body_IsValid( capsuleBodyId ) ); + + b3ShapeDef capsuleShapeDef = b3DefaultShapeDef(); + capsuleShapeDef.density = 1.0f; + b3Capsule capsule = { { 0.0f, -0.4f, 0.0f }, { 0.0f, 0.4f, 0.0f }, 0.25f }; + b3ShapeId capsuleShapeId = b3CreateCapsuleShape( capsuleBodyId, &capsuleShapeDef, &capsule ); + ENSURE( b3Shape_IsValid( capsuleShapeId ) ); + + // Custom hull shape on a third dynamic body + b3Vec3 hullPts[8] = { + { -0.5f, -0.5f, -0.5f }, { 0.5f, -0.5f, -0.5f }, + { 0.5f, 0.5f, -0.5f }, { -0.5f, 0.5f, -0.5f }, + { -0.5f, -0.5f, 0.5f }, { 0.5f, -0.5f, 0.5f }, + { 0.5f, 0.5f, 0.5f }, { -0.5f, 0.5f, 0.5f }, + }; + b3HullData* customHull = b3CreateHull( hullPts, 8, 8 ); + ENSURE( customHull != NULL ); + + b3BodyDef hullBodyDef = b3DefaultBodyDef(); + hullBodyDef.type = b3_dynamicBody; + hullBodyDef.position = (b3Pos){ -3.0f, 5.0f, 0.0f }; + b3BodyId hullBodyId = b3CreateBody( worldId, &hullBodyDef ); + ENSURE( b3Body_IsValid( hullBodyId ) ); + + b3ShapeDef hullShapeDef = b3DefaultShapeDef(); + hullShapeDef.density = 1.0f; + b3ShapeId hullShapeId = b3CreateHullShape( hullBodyId, &hullShapeDef, customHull ); + ENSURE( b3Shape_IsValid( hullShapeId ) ); + + // Box hull shape on a fourth dynamic body (b3MakeBoxHull path) + b3BodyDef boxBodyDef = b3DefaultBodyDef(); + boxBodyDef.type = b3_dynamicBody; + boxBodyDef.position = (b3Pos){ 6.0f, 5.0f, 0.0f }; + b3BodyId boxBodyId = b3CreateBody( worldId, &boxBodyDef ); + ENSURE( b3Body_IsValid( boxBodyId ) ); + + b3ShapeDef boxShapeDef = b3DefaultShapeDef(); + boxShapeDef.density = 2.0f; + b3BoxHull boxHull = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + b3ShapeId boxShapeId = b3CreateHullShape( boxBodyId, &boxShapeDef, &boxHull.base ); + ENSURE( b3Shape_IsValid( boxShapeId ) ); + + // Mesh, height field, and compound static shapes (3D-only) + b3BodyDef meshBodyDef = b3DefaultBodyDef(); + meshBodyDef.type = b3_staticBody; + meshBodyDef.position = (b3Pos){ 20.0f, 0.0f, 0.0f }; + b3BodyId meshBodyId = b3CreateBody( worldId, &meshBodyDef ); + b3MeshData* meshData = b3CreateGridMesh( 3, 3, 2.0f, 0, false ); + ENSURE( meshData != NULL ); + b3ShapeDef meshShapeDef = b3DefaultShapeDef(); + b3CreateMeshShape( meshBodyId, &meshShapeDef, meshData, (b3Vec3){ 1.0f, 1.0f, 1.0f } ); + + b3BodyDef hfBodyDef = b3DefaultBodyDef(); + hfBodyDef.type = b3_staticBody; + hfBodyDef.position = (b3Pos){ -20.0f, 0.0f, 0.0f }; + b3BodyId hfBodyId = b3CreateBody( worldId, &hfBodyDef ); + b3HeightFieldData* hf = b3CreateGrid( 4, 4, (b3Vec3){ 2.0f, 1.0f, 2.0f }, false ); + ENSURE( hf != NULL ); + b3ShapeDef hfShapeDef = b3DefaultShapeDef(); + b3CreateHeightFieldShape( hfBodyId, &hfShapeDef, hf ); + + b3BodyDef compoundBodyDef = b3DefaultBodyDef(); + compoundBodyDef.type = b3_staticBody; + compoundBodyDef.position = (b3Pos){ 30.0f, 0.0f, 0.0f }; + b3BodyId compoundBodyId = b3CreateBody( worldId, &compoundBodyDef ); + b3CompoundSphereDef compSphere; + compSphere.sphere = (b3Sphere){ { 0.0f, 0.0f, 0.0f }, 1.0f }; + compSphere.material = b3DefaultSurfaceMaterial(); + b3CompoundDef compoundDef; + memset( &compoundDef, 0, sizeof( compoundDef ) ); + compoundDef.spheres = &compSphere; + compoundDef.sphereCount = 1; + b3CompoundData* compound = b3CreateCompound( &compoundDef ); + ENSURE( compound != NULL ); + b3ShapeDef compoundShapeDef = b3DefaultShapeDef(); + b3CreateCompoundShape( compoundBodyId, &compoundShapeDef, compound ); + + // Throwaway shape to exercise DestroyShape + b3Sphere tmpSphere = { { 0.0f, 0.0f, 0.0f }, 0.1f }; + b3ShapeId tmpShapeId = b3CreateSphereShape( capsuleBodyId, &capsuleShapeDef, &tmpSphere ); + b3DestroyShape( tmpShapeId, true ); + + // Shape mutators: SetFriction, SetRestitution, SetDensity, SetSurfaceMaterial, SetFilter, + // EnableSensorEvents, EnableContactEvents, EnableHitEvents, EnablePreSolveEvents, ApplyWind, + // SetSphere, SetCapsule + b3Shape_SetFriction( boxShapeId, 0.3f ); + b3Shape_SetRestitution( capsuleShapeId, 0.5f ); + b3Shape_SetDensity( boxShapeId, 3.0f, true ); + b3SurfaceMaterial surfMat = b3DefaultSurfaceMaterial(); + surfMat.friction = 0.7f; + surfMat.restitution = 0.1f; + b3Shape_SetSurfaceMaterial( capsuleShapeId, surfMat ); + b3Filter shapeFilter = b3DefaultFilter(); + shapeFilter.categoryBits = 0x2; + b3Shape_SetFilter( boxShapeId, shapeFilter, false ); + b3Shape_EnableSensorEvents( capsuleShapeId, true ); + b3Shape_EnableContactEvents( capsuleShapeId, true ); + b3Shape_EnableHitEvents( boxShapeId, true ); + b3Shape_EnablePreSolveEvents( boxShapeId, true ); + b3Shape_ApplyWind( capsuleShapeId, (b3Vec3){ 1.0f, 0.0f, 0.0f }, 0.1f, 0.0f, 10.0f, true ); + b3Sphere newSphere = { { 0.0f, 0.0f, 0.0f }, 0.45f }; + b3Shape_SetSphere( sphereShapeId, &newSphere ); + b3Capsule newCapsule = { { 0.0f, -0.3f, 0.0f }, { 0.0f, 0.3f, 0.0f }, 0.3f }; + b3Shape_SetCapsule( capsuleShapeId, &newCapsule ); + + // Body mutators: SetTransform, SetLinearVelocity/AngularVelocity (Vec3), SetName, + // damping, gravity scale, sleep threshold, SetAwake, EnableSleep, SetBullet, SetMotionLocks, + // SetMassData, ApplyMassFromShapes, SetType, SetTargetTransform, Disable/Enable, EnableContactRecycling, + // EnableHitEvents, all force/impulse/torque variants + b3Body_SetTransform( bodyId, (b3Pos){ 1.0f, 6.0f, 0.0f }, b3Quat_identity ); + b3Body_SetLinearVelocity( bodyId, (b3Vec3){ 0.5f, 0.0f, 0.0f } ); + b3Body_SetAngularVelocity( bodyId, (b3Vec3){ 0.0f, 0.25f, 0.0f } ); + b3Body_SetName( bodyId, "renamedBody" ); + b3Body_SetLinearDamping( bodyId, 0.1f ); + b3Body_SetAngularDamping( bodyId, 0.05f ); + b3Body_SetGravityScale( bodyId, 0.9f ); + b3Body_SetSleepThreshold( bodyId, 0.02f ); + b3Body_EnableSleep( bodyId, false ); + b3Body_SetBullet( bodyId, true ); + b3Body_EnableContactRecycling( bodyId, false ); + b3Body_EnableHitEvents( bodyId, true ); + b3Body_SetMotionLocks( bodyId, (b3MotionLocks){ false, false, false, false, false, true } ); + b3MassData massData; + massData.mass = 2.0f; + massData.center = (b3Vec3){ 0.0f, 0.0f, 0.0f }; + massData.inertia = b3Mat3_identity; + b3Body_SetMassData( bodyId, massData ); + b3Body_ApplyMassFromShapes( bodyId ); + b3Body_SetType( capsuleBodyId, b3_kinematicBody ); + b3Body_SetType( capsuleBodyId, b3_dynamicBody ); + b3Body_SetAwake( bodyId, true ); + + // Kinematic body to exercise SetTargetTransform + b3BodyDef kinematicDef = b3DefaultBodyDef(); + kinematicDef.type = b3_kinematicBody; + kinematicDef.position = (b3Pos){ -6.0f, 5.0f, 0.0f }; + b3BodyId kinematicId = b3CreateBody( worldId, &kinematicDef ); + b3BoxHull kinBox = b3MakeBoxHull( 0.4f, 0.4f, 0.4f ); + b3ShapeDef kinShapeDef = b3DefaultShapeDef(); + b3CreateHullShape( kinematicId, &kinShapeDef, &kinBox.base ); + b3WorldTransform kinTarget; + kinTarget.p = (b3Pos){ -5.0f, 5.0f, 0.0f }; + kinTarget.q = b3Quat_identity; + b3Body_SetTargetTransform( kinematicId, kinTarget, 1.0f / 60.0f, true ); + + // Body to exercise Disable/Enable + b3BodyDef disableDef = b3DefaultBodyDef(); + disableDef.type = b3_dynamicBody; + disableDef.position = (b3Pos){ 9.0f, 5.0f, 0.0f }; + b3BodyId disableId = b3CreateBody( worldId, &disableDef ); + b3Sphere disableSphere = { { 0.0f, 0.0f, 0.0f }, 0.3f }; + b3CreateSphereShape( disableId, &sphereShapeDef, &disableSphere ); + b3Body_Disable( disableId ); + b3Body_Enable( disableId ); + + // Force/impulse/torque (Vec3 args in 3D) + b3Body_ApplyForce( bodyId, (b3Vec3){ 0.0f, 50.0f, 0.0f }, (b3Pos){ 1.0f, 6.0f, 0.0f }, true ); + b3Body_ApplyForceToCenter( bodyId, (b3Vec3){ 5.0f, 0.0f, 0.0f }, true ); + b3Body_ApplyTorque( bodyId, (b3Vec3){ 0.0f, 1.0f, 0.0f }, true ); + b3Body_ApplyLinearImpulse( bodyId, (b3Vec3){ 0.1f, 0.0f, 0.0f }, (b3Pos){ 1.0f, 6.0f, 0.0f }, true ); + b3Body_ApplyLinearImpulseToCenter( bodyId, (b3Vec3){ 0.0f, 0.1f, 0.0f }, true ); + b3Body_ApplyAngularImpulse( bodyId, (b3Vec3){ 0.0f, 0.05f, 0.0f }, true ); + + // Joint bodies: a row of dynamic bodies connected by each joint type + b3BodyId jb[9]; + for ( int i = 0; i < 9; ++i ) + { + b3BodyDef jbd = b3DefaultBodyDef(); + jbd.type = b3_dynamicBody; + jbd.position = (b3Pos){ -8.0f + (float)i * 2.0f, 10.0f, 0.0f }; + jb[i] = b3CreateBody( worldId, &jbd ); + b3Sphere js = { { 0.0f, 0.0f, 0.0f }, 0.25f }; + b3ShapeDef jsd = b3DefaultShapeDef(); + jsd.density = 1.0f; + b3CreateSphereShape( jb[i], &jsd, &js ); + } + + // Revolute joint with full setter coverage and the generic joint mutators + b3RevoluteJointDef revDef = b3DefaultRevoluteJointDef(); + revDef.base.bodyIdA = jb[0]; + revDef.base.bodyIdB = jb[1]; + revDef.base.localFrameA.p = (b3Vec3){ 1.0f, 0.0f, 0.0f }; + revDef.base.localFrameB.p = (b3Vec3){ -1.0f, 0.0f, 0.0f }; + b3JointId revId = b3CreateRevoluteJoint( worldId, &revDef ); + ENSURE( b3Joint_IsValid( revId ) ); + b3RevoluteJoint_EnableLimit( revId, true ); + b3RevoluteJoint_SetLimits( revId, -1.0f, 1.0f ); + b3RevoluteJoint_EnableMotor( revId, true ); + b3RevoluteJoint_SetMotorSpeed( revId, 0.5f ); + b3RevoluteJoint_SetMaxMotorTorque( revId, 10.0f ); + b3RevoluteJoint_EnableSpring( revId, true ); + b3RevoluteJoint_SetSpringHertz( revId, 2.0f ); + b3RevoluteJoint_SetSpringDampingRatio( revId, 0.5f ); + b3RevoluteJoint_SetTargetAngle( revId, 0.25f ); + b3Joint_SetLocalFrameA( revId, (b3Transform){ (b3Vec3){ 1.0f, 0.0f, 0.0f }, b3Quat_identity } ); + b3Joint_SetLocalFrameB( revId, (b3Transform){ (b3Vec3){ -1.0f, 0.0f, 0.0f }, b3Quat_identity } ); + b3Joint_SetConstraintTuning( revId, 60.0f, 2.0f ); + b3Joint_SetForceThreshold( revId, 100.0f ); + b3Joint_SetTorqueThreshold( revId, 50.0f ); + b3Joint_SetCollideConnected( revId, false ); + b3Joint_WakeBodies( revId ); + + // Distance joint + b3DistanceJointDef distDef = b3DefaultDistanceJointDef(); + distDef.base.bodyIdA = jb[1]; + distDef.base.bodyIdB = jb[2]; + distDef.length = 2.0f; + b3JointId distId = b3CreateDistanceJoint( worldId, &distDef ); + b3DistanceJoint_SetLength( distId, 2.2f ); + b3DistanceJoint_EnableSpring( distId, true ); + b3DistanceJoint_SetSpringHertz( distId, 3.0f ); + b3DistanceJoint_SetSpringDampingRatio( distId, 0.4f ); + b3DistanceJoint_SetSpringForceRange( distId, -50.0f, 50.0f ); + b3DistanceJoint_EnableLimit( distId, true ); + b3DistanceJoint_SetLengthRange( distId, 1.0f, 4.0f ); + b3DistanceJoint_EnableMotor( distId, true ); + b3DistanceJoint_SetMotorSpeed( distId, 0.3f ); + b3DistanceJoint_SetMaxMotorForce( distId, 5.0f ); + + // Filter joint (plus a throwaway to exercise DestroyJoint) + b3FilterJointDef filterDef = b3DefaultFilterJointDef(); + filterDef.base.bodyIdA = jb[2]; + filterDef.base.bodyIdB = jb[3]; + b3JointId filterId = b3CreateFilterJoint( worldId, &filterDef ); + ENSURE( b3Joint_IsValid( filterId ) ); + + b3DistanceJointDef tmpJointDef = b3DefaultDistanceJointDef(); + tmpJointDef.base.bodyIdA = jb[0]; + tmpJointDef.base.bodyIdB = jb[8]; + tmpJointDef.length = 5.0f; + b3JointId tmpJointId = b3CreateDistanceJoint( worldId, &tmpJointDef ); + b3DestroyJoint( tmpJointId, true ); + + // Motor joint (Vec3 velocities in 3D) + b3MotorJointDef motorDef = b3DefaultMotorJointDef(); + motorDef.base.bodyIdA = jb[3]; + motorDef.base.bodyIdB = jb[4]; + b3JointId motorId = b3CreateMotorJoint( worldId, &motorDef ); + b3MotorJoint_SetLinearVelocity( motorId, (b3Vec3){ 0.1f, 0.0f, 0.0f } ); + b3MotorJoint_SetAngularVelocity( motorId, (b3Vec3){ 0.0f, 0.2f, 0.0f } ); + b3MotorJoint_SetMaxVelocityForce( motorId, 10.0f ); + b3MotorJoint_SetMaxVelocityTorque( motorId, 10.0f ); + b3MotorJoint_SetLinearHertz( motorId, 2.0f ); + b3MotorJoint_SetLinearDampingRatio( motorId, 0.5f ); + b3MotorJoint_SetAngularHertz( motorId, 2.0f ); + b3MotorJoint_SetAngularDampingRatio( motorId, 0.5f ); + b3MotorJoint_SetMaxSpringForce( motorId, 20.0f ); + b3MotorJoint_SetMaxSpringTorque( motorId, 20.0f ); + + // Prismatic joint + b3PrismaticJointDef prisDef = b3DefaultPrismaticJointDef(); + prisDef.base.bodyIdA = jb[4]; + prisDef.base.bodyIdB = jb[5]; + b3JointId prisId = b3CreatePrismaticJoint( worldId, &prisDef ); + b3PrismaticJoint_EnableSpring( prisId, true ); + b3PrismaticJoint_SetSpringHertz( prisId, 2.0f ); + b3PrismaticJoint_SetSpringDampingRatio( prisId, 0.5f ); + b3PrismaticJoint_SetTargetTranslation( prisId, 0.1f ); + b3PrismaticJoint_EnableLimit( prisId, true ); + b3PrismaticJoint_SetLimits( prisId, -1.0f, 1.0f ); + b3PrismaticJoint_EnableMotor( prisId, true ); + b3PrismaticJoint_SetMotorSpeed( prisId, 0.2f ); + b3PrismaticJoint_SetMaxMotorForce( prisId, 8.0f ); + + // Spherical joint (3D-only) + b3SphericalJointDef sphDef = b3DefaultSphericalJointDef(); + sphDef.base.bodyIdA = jb[5]; + sphDef.base.bodyIdB = jb[6]; + b3JointId sphId = b3CreateSphericalJoint( worldId, &sphDef ); + b3SphericalJoint_EnableConeLimit( sphId, true ); + b3SphericalJoint_SetConeLimit( sphId, 0.5f ); + b3SphericalJoint_EnableTwistLimit( sphId, true ); + b3SphericalJoint_SetTwistLimits( sphId, -0.3f, 0.3f ); + b3SphericalJoint_EnableSpring( sphId, true ); + b3SphericalJoint_SetSpringHertz( sphId, 3.0f ); + b3SphericalJoint_SetSpringDampingRatio( sphId, 0.5f ); + b3SphericalJoint_SetTargetRotation( sphId, b3Quat_identity ); + b3SphericalJoint_EnableMotor( sphId, true ); + b3SphericalJoint_SetMotorVelocity( sphId, (b3Vec3){ 0.0f, 0.1f, 0.0f } ); + b3SphericalJoint_SetMaxMotorTorque( sphId, 5.0f ); + + // Weld joint + b3WeldJointDef weldDef = b3DefaultWeldJointDef(); + weldDef.base.bodyIdA = jb[6]; + weldDef.base.bodyIdB = jb[7]; + b3JointId weldId = b3CreateWeldJoint( worldId, &weldDef ); + b3WeldJoint_SetLinearHertz( weldId, 5.0f ); + b3WeldJoint_SetLinearDampingRatio( weldId, 0.6f ); + b3WeldJoint_SetAngularHertz( weldId, 5.0f ); + b3WeldJoint_SetAngularDampingRatio( weldId, 0.6f ); + + // Wheel joint (Box3D uses Suspension/Spin/Steering naming) + b3WheelJointDef wheelDef = b3DefaultWheelJointDef(); + wheelDef.base.bodyIdA = jb[7]; + wheelDef.base.bodyIdB = jb[8]; + b3JointId wheelId = b3CreateWheelJoint( worldId, &wheelDef ); + b3WheelJoint_EnableSuspension( wheelId, true ); + b3WheelJoint_SetSuspensionHertz( wheelId, 4.0f ); + b3WheelJoint_SetSuspensionDampingRatio( wheelId, 0.7f ); + b3WheelJoint_EnableSuspensionLimit( wheelId, true ); + b3WheelJoint_SetSuspensionLimits( wheelId, -0.5f, 0.5f ); + b3WheelJoint_EnableSpinMotor( wheelId, true ); + b3WheelJoint_SetSpinMotorSpeed( wheelId, 1.0f ); + b3WheelJoint_SetMaxSpinTorque( wheelId, 6.0f ); + b3WheelJoint_EnableSteering( wheelId, true ); + b3WheelJoint_SetSteeringHertz( wheelId, 2.0f ); + b3WheelJoint_SetSteeringDampingRatio( wheelId, 0.5f ); + b3WheelJoint_SetMaxSteeringTorque( wheelId, 3.0f ); + b3WheelJoint_EnableSteeringLimit( wheelId, true ); + b3WheelJoint_SetSteeringLimits( wheelId, -0.5f, 0.5f ); + b3WheelJoint_SetTargetSteeringAngle( wheelId, 0.1f ); + + // Parallel joint (3D-only) + b3ParallelJointDef parallelDef = b3DefaultParallelJointDef(); + parallelDef.base.bodyIdA = groundId; + parallelDef.base.bodyIdB = bodyId; + b3JointId parallelId = b3CreateParallelJoint( worldId, ¶llelDef ); + b3ParallelJoint_SetSpringHertz( parallelId, 2.0f ); + b3ParallelJoint_SetSpringDampingRatio( parallelId, 0.5f ); + b3ParallelJoint_SetMaxTorque( parallelId, 20.0f ); + + // World config mutators + b3World_SetGravity( worldId, (b3Vec3){ 0.0f, -9.8f, 0.0f } ); + b3World_EnableSleeping( worldId, true ); + b3World_EnableContinuous( worldId, false ); + b3World_EnableWarmStarting( worldId, true ); + b3World_EnableSpeculative( worldId, true ); + b3World_SetRestitutionThreshold( worldId, 1.5f ); + b3World_SetHitEventThreshold( worldId, 2.0f ); + b3World_SetContactTuning( worldId, 30.0f, 10.0f, 3.0f ); + b3World_SetContactRecycleDistance( worldId, 0.05f ); + b3World_SetMaximumLinearSpeed( worldId, 100.0f ); + b3World_RebuildStaticTree( worldId ); + + b3ExplosionDef explosion = b3DefaultExplosionDef(); + explosion.position = (b3Pos){ 0.0f, 5.0f, 0.0f }; + explosion.radius = 3.0f; + explosion.falloff = 1.0f; + explosion.impulsePerArea = 2.0f; + b3World_Explode( worldId, &explosion ); + + // Pre-step queries + b3QueryFilter qfilter = b3DefaultQueryFilter(); + b3AABB qaabb = { { -10.0f, -5.0f, -10.0f }, { 10.0f, 15.0f, 10.0f } }; + b3World_OverlapAABB( worldId, qaabb, qfilter, QueryReplayOverlapFcn, NULL ); + b3Pos qorigin = { 0.0f, 15.0f, 0.0f }; + b3Vec3 proxyPts = { 0.0f, 0.0f, 0.0f }; + b3ShapeProxy proxy = { &proxyPts, 1, 0.5f }; + b3World_OverlapShape( worldId, qorigin, &proxy, qfilter, QueryReplayOverlapFcn, NULL ); + b3Vec3 qTranslation = { 0.0f, -20.0f, 0.0f }; + b3World_CastRay( worldId, qorigin, qTranslation, qfilter, QueryReplayCastFcn, NULL ); + b3World_CastRayClosest( worldId, qorigin, qTranslation, qfilter ); + b3World_CastShape( worldId, qorigin, &proxy, qTranslation, qfilter, QueryReplayCastFcn, NULL ); + b3Capsule mover = { { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 0.3f }; + b3World_CastMover( worldId, qorigin, &mover, qTranslation, qfilter, QueryReplayMoverFilterFcn, NULL ); + b3World_CollideMover( worldId, qorigin, &mover, qfilter, QueryReplayPlaneFcn, NULL ); + + float timeStep = 1.0f / 60.0f; + int subStepCount = 4; + for ( int i = 0; i < 12; ++i ) + { + // Inject mutators mid-simulation + if ( i == 6 ) + { + b3Body_ApplyLinearImpulseToCenter( capsuleBodyId, (b3Vec3){ 2.0f, 0.0f, 0.0f }, true ); + b3Body_SetGravityScale( bodyId, 1.0f ); + } + + // Issue queries mid-loop to exercise recording across steps + if ( i == 3 ) + { + b3World_OverlapAABB( worldId, qaabb, qfilter, QueryReplayOverlapFcn, NULL ); + b3World_CastRay( worldId, qorigin, qTranslation, qfilter, QueryReplayCastFcn, NULL ); + } + + b3World_Step( worldId, timeStep, subStepCount ); + } + + b3World_StopRecording( worldId ); + b3DestroyWorld( worldId ); + + // Free geometry allocated for this subtest + b3DestroyHull( customHull ); + b3DestroyMesh( meshData ); + b3DestroyHeightField( hf ); + b3DestroyCompound( compound ); + + const uint8_t* recData = b3Recording_GetData( rec ); + int recSize = b3Recording_GetSize( rec ); + ENSURE( recSize > 0 ); + + // Replay headless at worker count 1 and 4, a cross-thread determinism check matching Box2D. + ENSURE( b3ValidateReplay( recData, recSize, 1 ) ); + ENSURE( b3ValidateReplay( recData, recSize, 4 ) ); + + // File round-trip + ENSURE( b3SaveRecordingToFile( rec, s_recPath ) ); + b3Recording* loaded = b3LoadRecordingFromFile( s_recPath ); + ENSURE( loaded != NULL ); + ENSURE( b3ValidateReplay( b3Recording_GetData( loaded ), b3Recording_GetSize( loaded ), 1 ) ); + b3DestroyRecording( loaded ); + + // Drive the incremental player. Exercises per-frame stepping, restart, getters, and the + // draw path beyond what b3ValidateReplay covers. + { + b3RecPlayer* player = b3RecPlayer_Create( recData, recSize, 1 ); + ENSURE( player != NULL ); + + b3RecPlayerInfo info = b3RecPlayer_GetInfo( player ); + b3Vec3 recExtents = b3Sub( info.bounds.upperBound, info.bounds.lowerBound ); + ENSURE( recExtents.x > 0.0f && recExtents.y > 0.0f ); + + // Build a no-op b3DebugDraw to exercise the draw path headlessly + b3DebugDraw dd = b3DefaultDebugDraw(); + dd.DrawShapeFcn = RecTestDrawShape; + dd.drawShapes = true; + dd.drawingBounds = (b3AABB){ { -1.0e6f, -1.0e6f, -1.0e6f }, { 1.0e6f, 1.0e6f, 1.0e6f } }; + + int frames = 0; + while ( b3RecPlayer_StepFrame( player ) ) + { + if ( frames % 2 == 0 ) + { + b3RecPlayer_DrawFrameQueries( player, &dd, -1 ); + } + frames += 1; + } + ENSURE( frames == 12 ); + ENSURE( b3RecPlayer_GetFrame( player ) == 12 ); + ENSURE( b3RecPlayer_IsAtEnd( player ) ); + ENSURE( b3RecPlayer_HasDiverged( player ) == false ); + + // The trailing DestroyWorld is an end marker; the world stays valid after end + ENSURE( b3World_IsValid( b3RecPlayer_GetWorldId( player ) ) ); + + // Restart reproduces the same run without reloading the file + b3RecPlayer_Restart( player ); + ENSURE( b3RecPlayer_GetFrame( player ) == 0 ); + ENSURE( b3RecPlayer_IsAtEnd( player ) == false ); + + int frames2 = 0; + while ( b3RecPlayer_StepFrame( player ) ) + { + frames2 += 1; + } + ENSURE( frames2 == 12 ); + ENSURE( b3RecPlayer_HasDiverged( player ) == false ); + + b3RecPlayer_Destroy( player ); + } + + b3DestroyRecording( rec ); + remove( s_recPath ); + return 0; +} + +// Patch the reserved header bytes to nonzero and confirm b3ValidateReplay ignores them. +// Guards a future change that starts validating them or shrinks the header. +static int ReservedHeaderBytes( void ) +{ + b3Recording* rec = b3CreateRecording( 0 ); + ENSURE( rec != NULL ); + + b3WorldDef worldDef = b3DefaultWorldDef(); + b3WorldId worldId = b3CreateWorld( &worldDef ); + b3World_StartRecording( worldId, rec ); + b3World_SetGravity( worldId, (b3Vec3){ 0.0f, -10.0f, 0.0f } ); + + b3BodyDef bd = b3DefaultBodyDef(); + bd.type = b3_dynamicBody; + bd.position = (b3Pos){ 0.0f, 5.0f, 0.0f }; + b3BodyId bodyId = b3CreateBody( worldId, &bd ); + b3Sphere s = { { 0.0f, 0.0f, 0.0f }, 0.5f }; + b3ShapeDef sd = b3DefaultShapeDef(); + sd.density = 1.0f; + b3CreateSphereShape( bodyId, &sd, &s ); + + for ( int i = 0; i < 10; ++i ) + { + b3World_Step( worldId, 1.0f / 60.0f, 4 ); + } + + b3World_StopRecording( worldId ); + b3DestroyWorld( worldId ); + + const uint8_t* recData = b3Recording_GetData( rec ); + int recSize = b3Recording_GetSize( rec ); + ENSURE( recSize >= (int)sizeof( b3RecHeader ) ); + + // Patch reserved fields at their byte offsets in b3RecHeader: + // byte 11 : reserved (uint8_t at offset 11) + // bytes 16-19 : reserved2 (uint32_t at offset 16) + // bytes 20-23 : reserved3 (uint32_t at offset 20) + uint8_t* patched = (uint8_t*)b3Alloc( (size_t)recSize ); + memcpy( patched, recData, (size_t)recSize ); + patched[11] = 0xAB; + patched[16] = 0xCD; + patched[17] = 0xEF; + patched[18] = 0x12; + patched[19] = 0x34; + patched[20] = 0x56; + patched[21] = 0x78; + patched[22] = 0x9A; + patched[23] = 0xBC; + ENSURE( b3ValidateReplay( patched, recSize, 1 ) ); + b3Free( patched, (size_t)recSize ); + + b3DestroyRecording( rec ); + return 0; +} + +int RecordingTest( void ) +{ + RUN_SUBTEST( SphereRoundTrip ); + RUN_SUBTEST( EmptyWorldRoundTrip ); + RUN_SUBTEST( HullDedup ); + RUN_SUBTEST( MidStreamNoContacts ); + RUN_SUBTEST( MidStreamContacts ); + RUN_SUBTEST( ScrubBackward ); + RUN_SUBTEST( SeekWithHull ); + RUN_SUBTEST( DebugShapeCallbacks ); + RUN_SUBTEST( PlayerAccessors ); + RUN_SUBTEST( KeyframeHandleReuse ); + RUN_SUBTEST( QueryReplay ); + RUN_SUBTEST( AllOps ); + RUN_SUBTEST( ReservedHeaderBytes ); + return 0; +} diff --git a/test/test_world.c b/test/test_world.c index 94ae102..062dca3 100644 --- a/test/test_world.c +++ b/test/test_world.c @@ -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