diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index f50869d..1f20d68 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -115,6 +115,24 @@ jobs: working-directory: build run: ./bin/test + # Build-only: running the wasm test needs a node + pthread/SharedArrayBuffer harness. + # This still catches compile breaks in the box3d library and the test target. + emscripten: + name: emscripten + runs-on: ubuntu-latest + timeout-minutes: 8 + if: github.event_name != 'pull_request' || github.event.pull_request.draft == false + steps: + - uses: actions/checkout@v6 + + - uses: mymindstorm/setup-emsdk@v14 + + - name: Configure CMake + run: emcmake cmake -B build -DCMAKE_BUILD_TYPE=Debug -DBOX3D_SAMPLES=OFF -DBUILD_SHARED_LIBS=OFF -DBOX3D_VALIDATE=ON + + - name: Build + run: cmake --build build --config Debug + samples: name: ${{ matrix.name }} runs-on: ${{ matrix.os }} diff --git a/CMakeLists.txt b/CMakeLists.txt index 6360666..85b6134 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -72,7 +72,7 @@ if (MSVC OR APPLE OR UNIX) endif() endif() else() - if(MSVC) + if(MSVC AND CMAKE_CXX_COMPILER_ID STREQUAL "MSVC" AND PROJECT_IS_TOP_LEVEL) # enable hot reloading add_compile_options("$<$:/ZI>") add_link_options("$<$:/INCREMENTAL>") @@ -90,6 +90,25 @@ option(BOX3D_DISABLE_SIMD "Disable SIMD math (slower)" OFF) option(BOX3D_COMPILE_WARNING_AS_ERROR "Compile warnings as errors" OFF) option(BOX3D_DOUBLE_PRECISION "Enable double precision for large worlds" OFF) +# Emscripten maps the SSE2 path onto wasm SIMD128. simd.h is a header included by +# non-library targets like the tests, so these flags must be directory-wide, not +# PRIVATE to the box3d library. +if (EMSCRIPTEN AND NOT BOX3D_DISABLE_SIMD) + add_compile_options(-msimd128 -msse2) +endif() + +# Emscripten pthread support. Must precede add_subdirectory(src) so the box3d library +# objects are built with the same atomics/bulk-memory features as the executables that +# link them, otherwise wasm-ld rejects --shared-memory. Top level only, so a FetchContent +# consumer keeps control of its own threading model. +if (EMSCRIPTEN AND PROJECT_IS_TOP_LEVEL) + set(EMSCRIPTEN_PTHREADS_COMPILER_FLAGS "-pthread -s USE_PTHREADS=1") + set(EMSCRIPTEN_PTHREADS_LINKER_FLAGS "${EMSCRIPTEN_PTHREADS_COMPILER_FLAGS} -s ALLOW_MEMORY_GROWTH") + string(APPEND CMAKE_C_FLAGS " ${EMSCRIPTEN_PTHREADS_COMPILER_FLAGS}") + string(APPEND CMAKE_CXX_FLAGS " ${EMSCRIPTEN_PTHREADS_COMPILER_FLAGS}") + string(APPEND CMAKE_EXE_LINKER_FLAGS " ${EMSCRIPTEN_PTHREADS_LINKER_FLAGS}") +endif() + set(CMAKE_EXPORT_COMPILE_COMMANDS ON) set_property(GLOBAL PROPERTY USE_FOLDERS ON) set(CMAKE_VERBOSE_MAKEFILE ON) @@ -123,16 +142,6 @@ if(PROJECT_IS_TOP_LEVEL) option(BOX3D_BUILD_SHADERS "Recompile shaders with sokol-shdc" OFF) if(BOX3D_UNIT_TESTS OR BOX3D_SAMPLES OR BOX3D_BENCHMARKS) - - # Emscripten pthread support - if(EMSCRIPTEN) - set(EMSCRIPTEN_PTHREADS_COMPILER_FLAGS "-pthread -s USE_PTHREADS=1") - set(EMSCRIPTEN_PTHREADS_LINKER_FLAGS "${EMSCRIPTEN_PTHREADS_COMPILER_FLAGS} -s ALLOW_MEMORY_GROWTH") - string(APPEND CMAKE_C_FLAGS " ${EMSCRIPTEN_PTHREADS_COMPILER_FLAGS}") - string(APPEND CMAKE_CXX_FLAGS " ${EMSCRIPTEN_PTHREADS_COMPILER_FLAGS}") - string(APPEND CMAKE_EXE_LINKER_FLAGS " ${EMSCRIPTEN_PTHREADS_LINKER_FLAGS}") - endif() - add_subdirectory(shared) endif() diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8aeaa27..156c648 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -97,4 +97,4 @@ conventions and use clang format. ## Questions? Open a [Discussion](../../discussions) — that's the best place for anything not -covered here. Thanks for helping make PROJECT_NAME better! +covered here. Thanks for helping make Box3D better! diff --git a/README.md b/README.md index 3f7a66a..baf138e 100644 --- a/README.md +++ b/README.md @@ -87,6 +87,14 @@ Run the samples app (must be in the Box3D directory). - Select the samples scheme - Build and run the samples +## Building for Web + +- [Emscripten SDK](https://emscripten.org/docs/getting_started/downloads.html) +- `emcmake cmake -B build -DBOX3D_SAMPLES=OFF` +- `cmake --build build` + +Box3D uses SSE2 with WebAssembly. Define `BOX3D_DISABLE_SIMD` to disable SSE2. + ## Building and installing - mkdir build @@ -138,7 +146,7 @@ You will need a compiler that supports C17 to build the Box3D library. You will need a compiler that supports C++20 to build the samples. -Box3D uses SSE2 and Neon SIMD math to improve performance. This can be disabled by defining `BOX3D_DISABLE_SIMD`. +Box3D uses SSE2 and Neon SIMD math to improve performance. SIMD can be disabled by defining `BOX3D_DISABLE_SIMD`. ## Documentation diff --git a/build_vs2022.bat b/build_vs2022.bat new file mode 100644 index 0000000..bf862e7 --- /dev/null +++ b/build_vs2022.bat @@ -0,0 +1,24 @@ +@echo off +rem Use this batch file to generate Visual Studio 2022 project files for box3d. +rem +rem Usage: +rem build_vs2022.bat Configure or update project files in build\ +rem build_vs2022.bat fresh Delete build\ first, then configure from scratch +rem +rem Re-running without "fresh" updates the existing project files in place. +rem CMake rewrites .vcxproj/.sln files atomically, so this works even while +rem Visual Studio has the solution open -- VS will detect the change and +rem prompt to reload. + +if /i "%~1"=="fresh" ( + if exist build ( + echo Fresh build requested, removing build\ ... + rmdir /s /q build + if exist build ( + echo ERROR: failed to remove build\ -- is something holding files open? + exit /b 1 + ) + ) +) + +cmake -S . -B build -G "Visual Studio 17 2022" diff --git a/docs/foundation.md b/docs/foundation.md index 607b266..f8a9b58 100644 --- a/docs/foundation.md +++ b/docs/foundation.md @@ -1,8 +1,10 @@ # Foundations + Box3D provides minimal base functionality for allocation hooks and vector math. The C interface allows most runtime data and types to be defined internally in the `src` folder. ## Assertions + Box3D will assert on bad input. This includes things like sending in NaN or infinity for values. It will assert if you use negative values for things that should only be positive, such as density. @@ -13,6 +15,7 @@ You may wish to capture assertions in your application. In that case use `b3SetA lets you override the debugger break and/or perform your own error handling. ## Allocation + Box3D uses memory efficiently and minimizes per-frame allocations by pooling memory. The engine quickly adapts to the simulation size. After the first step or two of simulation there should be no further per-frame allocations. @@ -29,6 +32,7 @@ You can provide a custom allocator using `b3SetAllocator()` and query the total allocated using `b3GetByteCount()`. ## Version + The `b3Version` structure holds the current version so you can query it at run-time using `b3GetVersion()`. @@ -120,90 +124,62 @@ b3Transform inv = b3InvertTransform(t); ``` ### b3Matrix3 + 3×3 matrix stored as three column vectors `cx`, `cy`, `cz`. Primarily used for inertia tensors and rotation matrices. Useful operations include `b3MulMV` (matrix-vector multiply), `b3MulMM` (matrix-matrix multiply), `b3Transpose`, `b3InvertMatrix`, and `b3MakeMatrixFromQuat`. ### b3AABB + Axis-aligned bounding box with `lowerBound` and `upperBound` as `b3Vec3`. Helpers include `b3AABB_Overlaps`, `b3AABB_Contains`, `b3AABB_ContainsPoint`, `b3AABB_Union`, `b3AABB_Center`, `b3AABB_Extents`, `b3AABB_Inflate`, and `b3AABB_Transform`. ## Multithreading {#multi} -Box3D has been highly optimized for multithreading. Multithreading is not required and by -default Box3D runs single-threaded. If performance matters, you should consider wiring up -the multithreading interface. -Box3D does **not** create threads itself. You supply your own thread pool and hook it up through -the world definition before calling `b3CreateWorld`. See `b3EnqueueTaskCallback`, -`b3FinishTaskCallback`, `b3WorldDef::workerCount`, `b3WorldDef::enqueueTask`, and -`b3WorldDef::finishTask`: +Box3D has been optimized for multithreading. Multithreading is not required and by default Box3D will run single-threaded. If performance is important for your application, you should consider using the multithreading features. + +### Internal scheduler + +Box3D has a built-in task scheduler that creates threads. You can use the built-in scheduler by setting the worker count in the world definition. This example shows how to use 4 workers. In this case Box3D will create 3 threads, and count the thread that calls `b3World_Step` as the fourth worker. I recommend to use the core count of the CPU as the worker count, not counting hyper-threads or efficiency cores. ```c b3WorldDef worldDef = b3DefaultWorldDef(); -worldDef.workerCount = myThreadCount; -worldDef.enqueueTask = MyEnqueueTask; -worldDef.finishTask = MyFinishTask; -worldDef.userTaskContext = myScheduler; - -b3WorldId worldId = b3CreateWorld(&worldDef); +worldDef.workerCount = 4; ``` -Your `MyEnqueueTask` callback receives a `b3TaskCallback*` function pointer plus a context -pointer that must be forwarded to the task exactly once on a worker thread. Return a non-null -`void*` handle representing your pending task object, or null if the work was executed -serially inside the callback (Box3D then skips the corresponding `b3FinishTaskCallback`). +### External scheduler + +You can optionally connect your own task scheduler if you want more control. Multithreading is established for each Box3D world you create and must be hooked up to the world definition. See `b3TaskCallback()`, `b3EnqueueTaskCallback()`, and `b3FinishTaskCallback()` for more details. Also see `b3WorldDef::workerCount`, `b3WorldDef::enqueueTask`, and `b3WorldDef::finishTask`. ```c -// Enqueue callback signature +// Implement b3EnqueueTaskCallback void* MyEnqueueTask(b3TaskCallback* task, void* taskContext, void* userContext, const char* taskName) { MyTask* t = AllocTask(); t->task = task; t->taskContext = taskContext; - SubmitToThreadPool(t); // runs task(taskContext) on a worker - return t; // non-null => Box3D will call MyFinishTask(t, ...) + SubmitToThreadPool(t); + return t; } -// Finish callback signature +// Implement b3FinishTaskCallback void MyFinishTask(void* userTask, void* userContext) { MyTask* t = (MyTask*)userTask; WaitForCompletion(t); FreeTask(t); } -``` - -`MyFinishTask` must block until the task has completed. Because the step blocks here on the tasks it -spawned, `b3World_Step` holds its stack across every fork and join inside the step. This has a -consequence for how you drive it. Run `b3World_Step` from a thread you can dedicate to the step, or -from a fiber that `MyFinishTask` can park so the underlying thread is freed to run the queued tasks. -In a job system that cannot park a job's stack, do not call `b3World_Step` from inside a job: a job -that blocks on the sub-jobs it spawned without yielding its thread starves the workers it is waiting -on and can deadlock. The alternative is help-while-wait, where the waiting thread runs other pending -tasks itself. This is what the in-tree scheduler does, which is why it needs no fiber. - -Box3D ships an in-tree scheduler (`src/scheduler.h`) used by the test suite and samples. -You can adapt it or use it directly: - -```c -#include "scheduler.h" - -b3Scheduler* scheduler = b3CreateScheduler(workerCount); b3WorldDef worldDef = b3DefaultWorldDef(); -worldDef.workerCount = workerCount; -worldDef.enqueueTask = b3SchedulerEnqueueTask; -worldDef.finishTask = b3SchedulerFinishTask; -worldDef.userTaskContext = scheduler; - -b3WorldId worldId = b3CreateWorld(&worldDef); -// ... simulate ... -b3DestroyWorld(worldId); -b3DestroyScheduler(scheduler); +worldDef.enqueueTask = MyEnqueueTask; +worldDef.finishTask = MyFinishTask; +worldDef.workerCount = GetMyWorkerCount(); ``` +### Threading model + The multithreading design for Box3D is focused on [data parallelism](https://en.wikipedia.org/wiki/Data_parallelism). The goal is to use multiple cores to finish the world simulation as fast as possible. Box3D multithreading is not designed for [task parallelism](https://en.wikipedia.org/wiki/Task_parallelism). @@ -213,26 +189,34 @@ main thread. Those are examples of task parallelism. So when you design your game loop, you should let Box3D *go wide* and use multiple cores to finish its work quickly, without other threads interacting with the Box3D world at the same time. +It is expected that the thread that calls `b3World_Step` participates in making progress. Do not call +`b3World_Step` and park that fiber. Tasks will only be enqueued on the thread that calls `b3World_Step`. +`MyFinishTask` must block until the task has completed. Ideally your scheduler is helping make progress +when `MyFinishTask` is called. + +### Avoiding race conditions + In a multithreaded environment you must be careful to avoid [race conditions](https://en.wikipedia.org/wiki/Race_condition). Modifying the world while it is simulating will lead to unpredictable behavior and is never safe. -It is also not safe to read data from a Box3D world while it is simulating; Box3D may move data +It is also not safe to read data from a Box3D world while it is simulating. Box3D may move data structures to improve cache performance, so you could easily read garbage. > **Caution**: -> Do not perform read or write operations on a Box3D world during `b3World_Step()` - -> **Caution**: -> Do not write to the Box3D world from multiple threads +> Do not perform read or write operations on a Box3D world during `b3World_Step()`. +> Do not write to the Box3D world from multiple threads. Any operation that wakes +> a body is not thread-safe. It *is safe* to do ray-casts, shape-casts, and overlap tests from multiple threads outside of `b3World_Step()`. Generally any read-only operation is safe to do multithreaded outside of `b3World_Step()`. This can be very useful if you have multithreaded game logic. ## Multithreading Multiple Worlds + Some applications may wish to create multiple Box3D worlds and simulate them on different threads. This works fine because Box3D has very limited use of globals. There are a few caveats: + - You will get a race condition if you create or destroy Box3D worlds from multiple threads. Use a mutex to guard those operations. - If you simulate multiple Box3D worlds simultaneously, they should probably not share a task system. Otherwise you risk preemption between worlds competing for the same workers. - Any callbacks you hook up to Box3D must be thread-safe, including memory allocators. diff --git a/docs/images/manifolds.svg b/docs/images/manifolds.svg index 564fe9f..30d3a51 100644 --- a/docs/images/manifolds.svg +++ b/docs/images/manifolds.svg @@ -2,22 +2,23 @@ + inkscape:export-ydpi="90" + viewBox="-4 -4 285 205" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns="http://www.w3.org/2000/svg" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:dc="http://purl.org/dc/elements/1.1/"> + fit-margin-bottom="0" + inkscape:showpageshadow="2" + inkscape:pagecheckerboard="0" + inkscape:deskcolor="#d1d1d1" /> @@ -135,7 +139,6 @@ image/svg+xml - diff --git a/docs/overview.md b/docs/overview.md index 6d7473d..dd488e9 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -1,4 +1,10 @@ # Overview {#mainpage} + +> **Caution**: +> The written part of this manual is a work in progress. +> It will be updated as v1.0 approaches. +> The reference section should be complete and accurate. + Box3D is a 3D rigid body simulation library for games. Programmers can use it in their games to make objects move in realistic ways and make the game world more interactive. From the game engine's point of view, @@ -14,6 +20,7 @@ engine begin with the `b3` prefix. Hopefully this is sufficient to avoid name clashing with your application. ## Prerequisites + In this manual I'll assume you are familiar with basic physics concepts, such as mass, force, torque, and impulses. If not, please first consult Google search and Wikipedia. @@ -33,6 +40,7 @@ should be comfortable with compiling, linking, and debugging. > Box3D. There are many resources for this online. ## Scope + This manual covers the majority of the Box3D API. However, not every aspect is covered. Please look at the Reference section and samples application included with Box3D to learn more. @@ -45,6 +53,7 @@ Box3D may be out of sync with this manual. > latest version on the main branch. ## Feedback and Bugs + Please file bugs and feature requests here: [Box3D Issues](https://github.com/erincatto/box3d/issues) diff --git a/docs/simulation.md b/docs/simulation.md index 456de15..9a778e7 100644 --- a/docs/simulation.md +++ b/docs/simulation.md @@ -704,22 +704,25 @@ instead of bodies. Since you can attach multiple shapes to a body, this allows f possible setups. For example, you can make a vehicle that is heavier in the back. ### Density + The shape density is used to compute the mass properties of the parent body. The density can be zero or positive. You should generally use similar densities for all your shapes. This will improve stacking stability. -The mass of a body is not adjusted when you set the density. You must -call `b3Body_ApplyMassFromShapes()` for this to occur. Generally you should establish -the shape density in `b3ShapeDef` and avoid modifying it later because this -can be expensive, especially on a compound body. +You may adjust the density of an existing body. You may choose to update the body mass immediately +or defer for a later call to `b3Body_ApplyMassFromShapes()`. Generally you should establish +the shape density in `b3ShapeDef` and avoid modifying it later because this can be expensive, +especially on a body with many shapes. ```c -b3Shape_SetDensity(myShapeId, 5.0f, true); +bool updateMass = false; +b3Shape_SetDensity(myShapeId, 5.0f, updateMass); b3Body_ApplyMassFromShapes(myBodyId); ``` ### Friction + Friction is used to make objects slide along each other realistically. Box3D supports static and dynamic friction, but uses the same parameter for both. Box3D attempts to simulate friction accurately and the friction @@ -745,6 +748,7 @@ shapeDef.baseMaterial.friction = 0.5f; ``` ### Restitution + [Restitution](https://en.wikipedia.org/wiki/Coefficient_of_restitution) is used to make objects bounce. The restitution value is usually set to be between 0 and 1. Consider dropping a ball on a table. @@ -772,6 +776,7 @@ shapeDef.baseMaterial.restitution = 0.3f; ``` ### Friction and Restitution Callbacks + Advanced users can override friction and restitution mixing using `b3FrictionCallback` and `b3RestitutionCallback`. These should be very lightweight functions because they are called frequently. The callbacks receive the two friction (or restitution) values @@ -794,6 +799,7 @@ worldDef.frictionCallback = MyFrictionCallback; ``` ### Filtering {#filtering} + Collision filtering allows you to efficiently prevent collision between shapes. For example, say you make a character that rides a bicycle. You want the bicycle to collide with the terrain and the character to collide with @@ -866,6 +872,7 @@ Collision groups have a higher priority than categories and masks. Note that additional collision filtering occurs automatically in Box3D. Here is a list: + - A shape on a static body can only collide with a dynamic body. - A shape on a kinematic body can only collide with a dynamic body. - Shapes on the same body never collide with each other. @@ -878,6 +885,7 @@ an existing shape using `b3Shape_GetFilter()` and it causes contacts to be destroyed. ### Sensors + Sometimes game logic needs to know when two shapes overlap yet there should be no collision response. This is done by using sensors. A sensor is a shape that detects overlap but does not produce a response. diff --git a/extern/sokol/sokol_app.h b/extern/sokol/sokol_app.h index 37dcc38..8ab8baf 100644 --- a/extern/sokol/sokol_app.h +++ b/extern/sokol/sokol_app.h @@ -5893,7 +5893,9 @@ _SOKOL_PRIVATE void _sapp_macos_frame(void) { [NSApp activateIgnoringOtherApps:YES]; [_sapp.macos.window makeKeyAndOrderFront:nil]; _sapp_macos_update_dimensions(); - [NSEvent setMouseCoalescingEnabled:NO]; + + // See https://github.com/erincatto/box3d/issues/37 + // [NSEvent setMouseCoalescingEnabled:NO]; // workaround for window not being focused during a long init callback // for details see: https://github.com/floooh/sokol/pull/982 diff --git a/include/box3d/box3d.h b/include/box3d/box3d.h index 2275663..3baff6a 100644 --- a/include/box3d/box3d.h +++ b/include/box3d/box3d.h @@ -315,12 +315,12 @@ 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 + 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. @@ -335,10 +335,15 @@ B3_API b3RecPlayer* b3RecPlayer_Create( const void* data, int size, int workerCo /// 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. +/// 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 ); +/// Sub-step one frame. This will sub-step and return immediately after body creation. +/// The next call will execute the time step. This allows bodies to be rendered +/// at the creation pose. +B3_API void b3RecPlayer_SubStepFrame( b3RecPlayer* player ); + /// Rewind to frame 0 (in-place restore so the world id stays stable). B3_API void b3RecPlayer_Restart( b3RecPlayer* player ); @@ -358,6 +363,9 @@ 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 the op stream is paused between body creation and world step. +B3_API bool b3RecPlayer_IsAtPreStep( const b3RecPlayer* player ); + /// @return true when any StateHash mismatch has been detected B3_API bool b3RecPlayer_HasDiverged( const b3RecPlayer* player ); @@ -412,7 +420,7 @@ B3_API b3BodyId b3RecPlayer_GetBodyId( const b3RecPlayer* player, int index ); /// @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 ); + 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. @@ -438,23 +446,23 @@ typedef enum b3RecQueryType typedef struct b3RecQueryInfo { b3RecQueryType type; - b3QueryFilter filter; - b3AABB aabb; // world-space bounds of the query, swept for casts - b3Pos origin; // query origin (zero for overlap AABB) - b3Vec3 translation; // ray and cast translation - int hitCount; // number of recorded results - uint64_t key; // identity key, the hash of (id, name), 0 if untagged - uint64_t id; // query id, 0 if none - const char* name; // query label, NULL if none + b3QueryFilter filter; + b3AABB aabb; // world-space bounds of the query, swept for casts + b3Pos origin; // query origin (zero for overlap AABB) + b3Vec3 translation; // ray and cast translation + int hitCount; // number of recorded results + uint64_t key; // identity key, the hash of (id, name), 0 if untagged + uint64_t id; // query id, 0 if none + const char* name; // query label, NULL if none } b3RecQueryInfo; /// One result of a recorded spatial query. typedef struct b3RecQueryHit { b3ShapeId shape; - b3Pos point; - b3Vec3 normal; - float fraction; + b3Pos point; + b3Vec3 normal; + float fraction; } b3RecQueryHit; /// @return the number of spatial queries recorded for the most recently replayed frame @@ -767,8 +775,8 @@ B3_API bool b3Body_OverlapShape( b3BodyId bodyId, b3Pos origin, const b3ShapePro b3WorldTransform bodyTransform ); /// Collide a character mover with a specific body using a specified body transform. -B3_API int b3Body_CollideMover( b3BodyId bodyId, b3BodyPlaneResult* bodyPlanes, int planeCapacity, b3Pos origin, const b3Capsule* mover, - b3QueryFilter filter, b3WorldTransform bodyTransform ); +B3_API int b3Body_CollideMover( b3BodyId bodyId, b3BodyPlaneResult* bodyPlanes, int planeCapacity, b3Pos origin, + const b3Capsule* mover, b3QueryFilter filter, b3WorldTransform bodyTransform ); /** @} */ // body diff --git a/include/box3d/collision.h b/include/box3d/collision.h index 30cc957..99c1b1e 100644 --- a/include/box3d/collision.h +++ b/include/box3d/collision.h @@ -81,9 +81,6 @@ B3_API b3TreeStats b3DynamicTree_RayCast( const b3DynamicTree* tree, const b3Ray B3_API b3TreeStats b3DynamicTree_BoxCast( const b3DynamicTree* tree, const b3BoxCastInput* input, uint64_t maskBits, bool requireAllBits, b3TreeBoxCastCallbackFcn* callback, void* context ); -/// Validate this tree. For testing. -B3_API void b3DynamicTree_Validate( const b3DynamicTree* tree ); - /// Get the height of the binary tree. B3_API int b3DynamicTree_GetHeight( const b3DynamicTree* tree ); diff --git a/include/box3d/math_functions.h b/include/box3d/math_functions.h index 7ef7354..b1f65ac 100644 --- a/include/box3d/math_functions.h +++ b/include/box3d/math_functions.h @@ -155,9 +155,6 @@ B3_INLINE int b3ClampInt( int a, int lower, int upper ) return a < lower ? lower : ( upper < a ? upper : a ); } -/// @return is this float valid (finite and not NaN). -B3_API bool b3IsValidFloat( float a ); - /// @return the absolute value of a float. B3_INLINE float b3AbsFloat( float a ) { diff --git a/include/box3d/types.h b/include/box3d/types.h index 2c75977..f193807 100644 --- a/include/box3d/types.h +++ b/include/box3d/types.h @@ -505,6 +505,7 @@ typedef struct b3ShapeDef bool invokeContactCreation; /// Should the body update the mass properties when this shape is created. Default is true. + /// Warning: if this is false, you MUST call b3Body_ApplyMassFromShapes or b3Body_SetMassData before simulating the world. bool updateBodyMass; /// Used internally to detect a valid definition. DO NOT SET. diff --git a/samples/main.cpp b/samples/main.cpp index 073f284..c97cd8b 100644 --- a/samples/main.cpp +++ b/samples/main.cpp @@ -482,6 +482,16 @@ sapp_desc sokol_main( int argc, char** argv ) { s_sampleOverride = atoi( argv[++i] ); } + else if ( strcmp( argv[i], "--replay" ) == 0 && i + 1 < argc ) + { + const char* path = argv[++i]; + + if ( g_replayIndex >= 0 ) + { + snprintf( s_context.replayFile, sizeof( s_context.replayFile ), "%s", path ); + s_sampleOverride = g_replayIndex; + } + } } sapp_desc desc{}; diff --git a/samples/sample_replay.cpp b/samples/sample_replay.cpp index cc8b3e1..30e1b3b 100644 --- a/samples/sample_replay.cpp +++ b/samples/sample_replay.cpp @@ -226,6 +226,7 @@ public: m_speed = 1.0f; m_frameAccumulator = 0.0f; m_loop = false; + m_subStepOnCreate = false; m_selKind = SelNone; m_selBodyOrdinal = -1; m_selSlot = -1; @@ -493,20 +494,30 @@ public: } // Advance one recorded step and keep the world pointer current (stable forward, refreshed cheaply). - void AdvanceOne() + // Staged first parks at a frame's pre-integration pose when it spawns bodies, so the creation + // transform is drawn before the solver moves them; the next advance runs the step. + void AdvanceOne( bool staged ) { - b3RecPlayer_StepFrame( m_player ); + if ( staged ) + { + b3RecPlayer_SubStepFrame( m_player ); + } + else + { + b3RecPlayer_StepFrame( m_player ); + } m_replayWorldId = b3RecPlayer_GetWorldId( m_player ); } void Step() override { + SetDrawOrigin( m_camera->DrawOrigin() ); + // 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->DrawOrigin() ); return; } @@ -517,7 +528,7 @@ public: m_context->singleStep = b3MaxInt( 0, m_context->singleStep - 1 ); if ( b3RecPlayer_IsAtEnd( m_player ) == false ) { - AdvanceOne(); + AdvanceOne( m_subStepOnCreate ); } m_frameAccumulator = 0.0f; } @@ -541,7 +552,7 @@ public: break; } } - AdvanceOne(); + AdvanceOne( false ); } } @@ -549,8 +560,6 @@ public: m_stepCount = b3RecPlayer_GetFrame( m_player ); } - SetDrawOrigin( m_camera->DrawOrigin() ); - if ( B3_IS_NULL( m_replayWorldId ) ) { DrawScreenStringFormat( 5, m_textLine, MakeColor( b3_colorLightGray ), "%s", m_status ); @@ -714,8 +723,17 @@ public: ImGui::SameLine(); if ( ImGui::Button( ">" ) ) { - b3RecPlayer_SeekFrame( m_player, frame + 1 ); - m_replayWorldId = b3RecPlayer_GetWorldId( m_player ); + // Staged forward keeps the creation-pose park reachable and resumes it; a plain seek + // always lands on a whole frame and would skip past the pre-step. + if ( m_subStepOnCreate ) + { + AdvanceOne( true ); + } + else + { + b3RecPlayer_SeekFrame( m_player, frame + 1 ); + m_replayWorldId = b3RecPlayer_GetWorldId( m_player ); + } m_frameAccumulator = 0.0f; m_context->pause = true; } @@ -759,8 +777,10 @@ public: ImGui::TextColored( PanelColor( b3_colorRed ), "****DIVERGED****" ); } - ImGui::TextDisabled( "Frame %d / %d%s", b3RecPlayer_GetFrame( m_player ), m_info.frameCount, - b3RecPlayer_IsAtEnd( m_player ) ? " (end)" : "" ); + const char* phaseTag = b3RecPlayer_IsAtEnd( m_player ) ? " (end)" + : b3RecPlayer_IsAtPreStep( m_player ) ? " (pre-step)" + : ""; + ImGui::TextDisabled( "Frame %d / %d%s", b3RecPlayer_GetFrame( m_player ), m_info.frameCount, phaseTag ); // Selection detail lives here in the info panel, not the Outline window, so the scene tree gets // the full left column. The child takes the remaining panel height and scrolls a long detail. @@ -1609,6 +1629,11 @@ public: ImGui::Checkbox( "Loop", &m_loop ); ImGui::SameLine(); + // Single-step parks at a frame's pre-integration pose when it spawns bodies, so a new body + // shows at its creation transform before the solver moves it. Forward single-step only. + ImGui::Checkbox( "Sub-step spawns", &m_subStepOnCreate ); + 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 ); @@ -1698,6 +1723,7 @@ public: float m_speed; float m_frameAccumulator; bool m_loop; + bool m_subStepOnCreate; // single-step parks at a frame's pre-integration pose when it spawns bodies bool m_selectTimelineTab; // one-shot: focus the Timeline tab on the next draw bool m_prevShowMetrics; // restore the drawer state on exit diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 95b0d8b..f48f70c 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -198,7 +198,8 @@ elseif (APPLE) target_compile_options(box3d PRIVATE -Wmissing-prototypes -Wall -Wextra -pedantic) elseif (EMSCRIPTEN) message(STATUS "Box3D on Emscripten") - target_compile_options(box3d PRIVATE -msimd128 -msse2) + # SSE2/wasm SIMD flags are set directory-wide in the top-level CMakeLists so the + # tests, which include simd.h, get them too. elseif (UNIX) message(STATUS "Box3D using Unix") target_compile_options(box3d PRIVATE -Wmissing-prototypes -Wall -Wextra -pedantic -Wno-unused-value) diff --git a/src/body.c b/src/body.c index aa4e91e..94ef43d 100644 --- a/src/body.c +++ b/src/body.c @@ -72,7 +72,7 @@ b3BodyState* b3GetBodyState( b3World* world, b3Body* body ) return NULL; } -static void b3SyncBodyFlags( b3World* world, b3Body* body ) +void b3SyncBodyFlags( b3World* world, b3Body* body ) { // Never sync transient flags uint32_t flags = body->flags & ~b3_bodyTransientFlags; @@ -801,6 +801,10 @@ void b3UpdateBodyMassData( b3World* world, b3Body* body ) { b3BodySim* bodySim = b3GetBodySim( world, body ); + // Mass is no longer dirty + body->flags &= ~b3_dirtyMass; + b3SyncBodyFlags( world, body ); + // Compute mass data from shapes. Each shape has its own density. body->mass = 0.0f; body->inertia = b3Mat3_zero; @@ -888,7 +892,7 @@ void b3UpdateBodyMassData( b3World* world, b3Body* body ) // Shift to center of mass. This is safe because it can only increase. b3Vec3 offset = b3Sub( localCenter, massData.center ); b3Matrix3 inertia = b3AddMM( massData.inertia, b3Steiner( massData.mass, offset ) ); - body->inertia = b3AddMM(body->inertia, inertia); + body->inertia = b3AddMM( body->inertia, inertia ); } b3StackFree( &world->stack, masses ); @@ -1829,6 +1833,10 @@ void b3Body_SetMassData( b3BodyId bodyId, b3MassData massData ) b3Body* body = b3GetBodyFullId( world, bodyId ); b3BodySim* bodySim = b3GetBodySim( world, body ); + // Mass is no longer dirty + body->flags &= ~b3_dirtyMass; + b3SyncBodyFlags( world, body ); + body->mass = massData.mass; body->inertia = massData.inertia; bodySim->localCenter = massData.center; @@ -1836,9 +1844,45 @@ void b3Body_SetMassData( b3BodyId bodyId, b3MassData massData ) b3Pos center = b3TransformWorldPoint( bodySim->transform, massData.center ); bodySim->center = center; bodySim->center0 = center; - bodySim->invMass = body->mass > 0.0f ? 1.0f / body->mass : 0.0f; - bodySim->invInertiaLocal = b3Det( body->inertia ) > 0.0f ? b3InvertT( body->inertia ) : b3Mat3_zero; + + float det = b3Det( body->inertia ); + B3_ASSERT( det >= 0.0f ); + + if ( det > 0.0f ) + { + // This call is faster than b3Invert + bodySim->invInertiaLocal = b3InvertT( body->inertia ); + + b3Matrix3 rotationMatrix = b3MakeMatrixFromQuat( bodySim->transform.q ); + bodySim->invInertiaWorld = b3MulMM( b3MulMM( rotationMatrix, bodySim->invInertiaLocal ), b3Transpose( rotationMatrix ) ); + } + else + { + bodySim->invInertiaLocal = b3Mat3_zero; + bodySim->invInertiaWorld = b3Mat3_zero; + } + + // Apply fixed rotation + if ( ( bodySim->flags & b3_fixedRotation ) == b3_fixedRotation ) + { + body->inertia = b3Mat3_zero; + bodySim->invInertiaLocal = b3Mat3_zero; + bodySim->invInertiaWorld = b3Mat3_zero; + } + + // Update extents using supplied mass center. + bodySim->minExtent = B3_HUGE; + bodySim->maxExtent = b3Vec3_zero; + int shapeId = body->headShapeId; + while ( shapeId != B3_NULL_INDEX ) + { + const b3Shape* s = b3Array_Get( world->shapes, shapeId ); + b3ShapeExtent extent = b3ComputeShapeExtent( s, massData.center ); + bodySim->minExtent = b3MinFloat( bodySim->minExtent, extent.minExtent ); + bodySim->maxExtent = b3Max( bodySim->maxExtent, extent.maxExtent ); + shapeId = s->nextShapeId; + } } b3MassData b3Body_GetMassData( b3BodyId bodyId ) diff --git a/src/body.h b/src/body.h index bcba5b7..f376192 100644 --- a/src/body.h +++ b/src/body.h @@ -57,6 +57,10 @@ enum b3BodyFlags b3_bodyEnableContactRecycling = 0x00004000, + // The user deferred mass computation via the updateBodyMass shape option and mass + // data still hasn't been set. + b3_dirtyMass = 0x00008000, + // All lock flags b3_allLocks = b3_lockLinearX | b3_lockLinearY | b3_lockLinearZ | b3_lockAngularX | b3_lockAngularY | b3_lockAngularZ, @@ -237,6 +241,7 @@ bool b3WakeBody( b3World* world, b3Body* body ); bool b3WakeBodyWithLock( b3World* world, b3Body* body ); void b3UpdateBodyMassData( b3World* world, b3Body* body ); +void b3SyncBodyFlags( b3World* world, b3Body* body ); void b3DumpBody( b3World* world, b3Body* body ); // Make a sweep relative to a base position to keep TOI in float precision far from the origin. diff --git a/src/recording_replay.c b/src/recording_replay.c index 16b2ba6..228e67c 100644 --- a/src/recording_replay.c +++ b/src/recording_replay.c @@ -2088,6 +2088,7 @@ static int b3RecDispatchOne( b3RecReader* rdr ) { return -1; } + int payloadStart = rdr->cursor; switch ( opcode ) @@ -2651,6 +2652,7 @@ static void b3RecPlayerRestoreKeyframe( b3RecPlayer* player, const b3RecKeyframe player->frame = kf->frame; player->divergeFrame = kf->divergeFrame; player->atEnd = false; + player->atPreStep = false; // Restore the outliner list verbatim so ordinals match this frame. b3RecGrow( (void**)&player->bodyIds, &player->bodyIdCap, kf->bodyIdCount, 0, (int)sizeof( b3BodyId ) ); @@ -2750,6 +2752,7 @@ b3RecPlayer* b3RecPlayer_Create( const void* data, int size, int workerCount ) player->recordedSubStepCount = 0; player->recordedWorkerCount = workerCount; player->atEnd = false; + player->atPreStep = false; player->divergeFrame = -1; player->keyframeMinInterval = B3_REC_KEYFRAME_INTERVAL_DEFAULT; player->keyframeInterval = B3_REC_KEYFRAME_INTERVAL_DEFAULT; @@ -2914,6 +2917,9 @@ void b3RecPlayer_Destroy( b3RecPlayer* player ) bool b3RecPlayer_StepFrame( b3RecPlayer* player ) { + // This is never true when full stepping + player->atPreStep = false; + if ( player->atEnd ) { return false; @@ -2975,6 +2981,91 @@ bool b3RecPlayer_StepFrame( b3RecPlayer* player ) } } +void b3RecPlayer_SubStepFrame( b3RecPlayer* player ) +{ + if ( player->atEnd ) + { + return; + } + + // Reset the per-frame query store before this frame's records are dispatched. + if ( player->atPreStep == false ) + { + player->frameQueryCount = 0; + player->frameHitCount = 0; + } + + // A frame is its leading inputs (queries and between-step mutators), one Step, and the Step's + // trailing StateHash. Queries are recorded before the Step they belong to, so they stash here + // against the world state they were computed for. + bool stepped = false; + bool haveCreateBodyOp = false; + for ( ;; ) + { + if ( player->rdr.cursor >= player->registryEnd || !player->rdr.ok ) + { + player->atEnd = true; + player->atPreStep = false; + return; + } + + // Once stepped, the StateHash is the only record still belonging to this frame. Anything else + // begins the next frame, so stop and let the next StepFrame consume it. Capture a keyframe at + // the boundary. + uint8_t currentOpCode = player->rdr.data[player->rdr.cursor]; + if ( stepped && currentOpCode != b3_recOpStateHash ) + { + if ( player->frame > player->lastKeyframeFrame && player->frame % player->keyframeInterval == 0 ) + { + b3RecCaptureKeyframe( player ); + } + return; + } + + if ( player->atPreStep == false && haveCreateBodyOp == true && currentOpCode == b3_recOpStep ) + { + player->atPreStep = true; + return; + } + + int op = b3RecDispatchOne( &player->rdr ); + if ( op < 0 ) + { + player->atEnd = true; + player->atPreStep = false; + return; + } + if ( op == b3_recOpDestroyWorld ) // end of recording + { + player->atEnd = true; + player->atPreStep = false; + return; + } + + if ( op == b3_recOpCreateBody ) + { + B3_ASSERT( player->atPreStep == false ); + haveCreateBodyOp = true; + } + + if ( op == b3_recOpStep ) + { + player->atPreStep = false; + player->frame += 1; + stepped = true; + } + else if ( op == b3_recOpStateHash ) // trailing record of the frame just stepped + { + // Latch the first frame whose state hash diverged. The hash belongs to the frame Step just + // advanced, so latch against the current frame, not the next Step which would be one late. + if ( player->divergeFrame < 0 && player->rdr.diverged ) + { + player->divergeFrame = player->frame; + } + } + } +} + void b3RecPlayer_Restart( b3RecPlayer* player ) { // Restore the frame-0 image in place so the replay world id stays stable across a restart or @@ -2991,6 +3082,7 @@ void b3RecPlayer_Restart( b3RecPlayer* player ) player->frame = 0; player->divergeFrame = -1; player->atEnd = false; + player->atPreStep = false; // Frame 0 is the pre-step snapshot with no recorded queries, so clear the per-frame store. This // keeps the last stepped frame's queries from lingering on a restart or a backward scrub to 0. @@ -3008,6 +3100,8 @@ void b3RecPlayer_Restart( b3RecPlayer* player ) void b3RecPlayer_SeekFrame( b3RecPlayer* player, int targetFrame ) { + player->atPreStep = false; + if ( player == NULL ) { return; @@ -3071,6 +3165,11 @@ bool b3RecPlayer_IsAtEnd( const b3RecPlayer* player ) return player != NULL ? player->atEnd : true; } +bool b3RecPlayer_IsAtPreStep( const b3RecPlayer* player ) +{ + return player != NULL ? player->atPreStep : false; +} + bool b3RecPlayer_HasDiverged( const b3RecPlayer* player ) { return player != NULL ? player->rdr.diverged : false; diff --git a/src/recording_replay.h b/src/recording_replay.h index e343d2b..f088991 100644 --- a/src/recording_replay.h +++ b/src/recording_replay.h @@ -149,6 +149,9 @@ struct b3RecPlayer int recordedWorkerCount; // worker count requested for the replay world b3AABB bounds; // accumulated world bounds, decoded from the trailing record bool atEnd; + // Indicates all ops for the step have been consumed up to the world step op. The next sub-step + // will clear this and perform the world step. + bool atPreStep; int divergeFrame; // first frame that diverged, -1 until then // Outliner body list, indexed by creation ordinal. Holes (null ids) mark destroyed bodies so diff --git a/src/shape.c b/src/shape.c index 14464f5..fb2d72c 100644 --- a/src/shape.c +++ b/src/shape.c @@ -297,6 +297,11 @@ static b3ShapeId b3CreateShape( b3BodyId bodyId, const b3ShapeDef* def, const vo { b3UpdateBodyMassData( world, body ); } + else if ( ( body->flags & b3_dirtyMass ) == 0 ) + { + body->flags |= b3_dirtyMass; + b3SyncBodyFlags( world, body ); + } b3ValidateSolverSets( world ); diff --git a/src/solver.c b/src/solver.c index 31afb52..6806c35 100644 --- a/src/solver.c +++ b/src/solver.c @@ -733,6 +733,10 @@ static void b3FinalizeBodiesTask( int startIndex, int endIndex, int workerIndex, sim->force = b3Vec3_zero; sim->torque = b3Vec3_zero; + // If you hit this then it means you deferred mass computation but never called b3Body_ApplyMassFromShapes + // or b3Body_SetMassData. + B3_ASSERT( ( body->flags & b3_dirtyMass ) == 0 ); + body->flags &= ~b3_bodyTransientFlags; body->flags |= ( sim->flags & ( b3_isSpeedCapped | b3_hadTimeOfImpact ) ); body->flags |= ( state->flags & ( b3_isSpeedCapped | b3_hadTimeOfImpact ) ); diff --git a/test/test_body.c b/test/test_body.c index 10e7853..c93ab47 100644 --- a/test/test_body.c +++ b/test/test_body.c @@ -7,6 +7,10 @@ #include "box3d/collision.h" #include "box3d/math_functions.h" +// Reach into internals to observe body extents and the dirty mass flag. +#include "body.h" +#include "physics_world.h" + #include // b3UpdateBodyMassData shifts each shape's inertia to the body center of mass with the parallel @@ -117,9 +121,239 @@ static int FarCubeSphereMass( void ) return 0; } +// Shapes added with updateBodyMass = false defer the mass update, which is also the only place +// body extents are computed. A body that reaches the solver with minExtent == B3_HUGE never passes +// the continuous collision gate. The dirty mass flag must track the deferral, and both +// ApplyMassFromShapes and SetMassData must leave finite extents behind. +static int DeferredMassExtents( void ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + b3WorldId worldId = b3CreateWorld( &worldDef ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.density = 1.0f; + shapeDef.updateBodyMass = false; + + b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, 0.5f }; + + // Deferred create leaves mass and extents untouched but marks the body dirty. + b3BodyId applyId = b3CreateBody( worldId, &bodyDef ); + b3CreateSphereShape( applyId, &shapeDef, &sphere ); + + b3World* world = b3GetWorld( applyId.world0 ); + b3Body* applyBody = b3GetBodyFullId( world, applyId ); + b3BodySim* applySim = b3GetBodySim( world, applyBody ); + + ENSURE( ( applyBody->flags & b3_dirtyMass ) != 0 ); + ENSURE( applySim->minExtent == B3_HUGE ); + + // ApplyMassFromShapes computes extents and clears the flag. + b3Body_ApplyMassFromShapes( applyId ); + ENSURE( ( applyBody->flags & b3_dirtyMass ) == 0 ); + ENSURE( applySim->minExtent < B3_HUGE ); + + // SetMassData alone must also produce finite extents and clear the flag (the issue #35 repro). + b3BodyId massId = b3CreateBody( worldId, &bodyDef ); + b3CreateSphereShape( massId, &shapeDef, &sphere ); + + b3Body* massBody = b3GetBodyFullId( world, massId ); + b3BodySim* massSim = b3GetBodySim( world, massBody ); + ENSURE( ( massBody->flags & b3_dirtyMass ) != 0 ); + + b3Matrix3 inertia = { { 0.2f, 0.0f, 0.0f }, { 0.0f, 0.2f, 0.0f }, { 0.0f, 0.0f, 0.2f } }; + b3MassData massData = { 2.0f, { 0.0f, 0.0f, 0.0f }, inertia }; + b3Body_SetMassData( massId, massData ); + + ENSURE( ( massBody->flags & b3_dirtyMass ) == 0 ); + ENSURE( massSim->minExtent < B3_HUGE ); + + b3DestroyWorld( worldId ); + return 0; +} + +// b3Body_SetMassData overrides the mass properties directly, bypassing the shapes. It must derive +// everything the solver reads from the supplied tensor: the inverse mass, the local inverse inertia, +// and the world inverse inertia rotated by the body orientation. Fixed rotation zeros the angular part. +// These tests drive it through the public getters, no shapes required. + +// Diagonal inertia with inverses that are exact in float, so tolerances stay tight. +static const b3Matrix3 kDiagInertia = { { 2.0f, 0.0f, 0.0f }, { 0.0f, 4.0f, 0.0f }, { 0.0f, 0.0f, 8.0f } }; + +static int SetMassDataRoundTrip( void ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + b3WorldId worldId = b3CreateWorld( &worldDef ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = (b3Pos){ 5.0f, -3.0f, 2.0f }; + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + + b3Vec3 center = { 0.1f, 0.2f, 0.3f }; + b3MassData massData = { 3.0f, center, kDiagInertia }; + b3Body_SetMassData( bodyId, massData ); + + ENSURE_SMALL( b3Body_GetMass( bodyId ) - 3.0f, 1e-6f ); + ENSURE_SMALL( b3Body_GetInverseMass( bodyId ) - 1.0f / 3.0f, 1e-6f ); + + b3MassData md = b3Body_GetMassData( bodyId ); + ENSURE_SMALL( md.mass - 3.0f, 1e-6f ); + ENSURE_SMALL( md.center.x - center.x, 1e-6f ); + ENSURE_SMALL( md.center.y - center.y, 1e-6f ); + ENSURE_SMALL( md.center.z - center.z, 1e-6f ); + ENSURE_SMALL( md.inertia.cx.x - 2.0f, 1e-6f ); + ENSURE_SMALL( md.inertia.cy.y - 4.0f, 1e-6f ); + ENSURE_SMALL( md.inertia.cz.z - 8.0f, 1e-6f ); + + b3Vec3 localCenter = b3Body_GetLocalCenterOfMass( bodyId ); + ENSURE_SMALL( localCenter.x - center.x, 1e-6f ); + ENSURE_SMALL( localCenter.y - center.y, 1e-6f ); + ENSURE_SMALL( localCenter.z - center.z, 1e-6f ); + + b3Matrix3 localInertia = b3Body_GetLocalRotationalInertia( bodyId ); + ENSURE_SMALL( localInertia.cx.x - 2.0f, 1e-6f ); + ENSURE_SMALL( localInertia.cy.y - 4.0f, 1e-6f ); + ENSURE_SMALL( localInertia.cz.z - 8.0f, 1e-6f ); + + // Identity rotation, so the world inverse inertia is just the local inverse: diag(1/2, 1/4, 1/8). + b3Matrix3 invWorld = b3Body_GetWorldInverseRotationalInertia( bodyId ); + ENSURE_SMALL( invWorld.cx.x - 0.5f, 1e-5f ); + ENSURE_SMALL( invWorld.cy.y - 0.25f, 1e-5f ); + ENSURE_SMALL( invWorld.cz.z - 0.125f, 1e-5f ); + ENSURE_SMALL( invWorld.cy.x, 1e-5f ); + ENSURE_SMALL( invWorld.cz.x, 1e-5f ); + ENSURE_SMALL( invWorld.cx.y, 1e-5f ); + ENSURE_SMALL( invWorld.cz.y, 1e-5f ); + ENSURE_SMALL( invWorld.cx.z, 1e-5f ); + ENSURE_SMALL( invWorld.cy.z, 1e-5f ); + + // World center of mass is the body origin plus the local center under identity rotation. + b3Pos worldCenter = b3Body_GetWorldCenterOfMass( bodyId ); + ENSURE_SMALL( worldCenter.x - ( 5.0f + center.x ), 1e-5f ); + ENSURE_SMALL( worldCenter.y - ( -3.0f + center.y ), 1e-5f ); + ENSURE_SMALL( worldCenter.z - ( 2.0f + center.z ), 1e-5f ); + + b3DestroyWorld( worldId ); + return 0; +} + +// The world inverse inertia must be the local inverse rotated into world space. A 90 degree turn about +// z swaps the x and y principal moments, so diag(1/2, 1/4, 1/8) becomes diag(1/4, 1/2, 1/8). This is the +// regression guard: before SetMassData rotated the tensor it left the world inverse inertia stale. +static int SetMassDataWorldInertiaRotated( void ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + b3WorldId worldId = b3CreateWorld( &worldDef ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, 0.5f * B3_PI ); + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + + b3MassData massData = { 1.0f, { 0.0f, 0.0f, 0.0f }, kDiagInertia }; + b3Body_SetMassData( bodyId, massData ); + + // The local inertia is stored untouched by the world transform. + b3Matrix3 localInertia = b3Body_GetLocalRotationalInertia( bodyId ); + ENSURE_SMALL( localInertia.cx.x - 2.0f, 1e-6f ); + ENSURE_SMALL( localInertia.cy.y - 4.0f, 1e-6f ); + ENSURE_SMALL( localInertia.cz.z - 8.0f, 1e-6f ); + + b3Matrix3 invWorld = b3Body_GetWorldInverseRotationalInertia( bodyId ); + ENSURE_SMALL( invWorld.cx.x - 0.25f, 1e-4f ); + ENSURE_SMALL( invWorld.cy.y - 0.5f, 1e-4f ); + ENSURE_SMALL( invWorld.cz.z - 0.125f, 1e-4f ); + ENSURE_SMALL( invWorld.cy.x, 1e-4f ); + ENSURE_SMALL( invWorld.cz.x, 1e-4f ); + ENSURE_SMALL( invWorld.cx.y, 1e-4f ); + ENSURE_SMALL( invWorld.cz.y, 1e-4f ); + ENSURE_SMALL( invWorld.cx.z, 1e-4f ); + ENSURE_SMALL( invWorld.cy.z, 1e-4f ); + + b3DestroyWorld( worldId ); + return 0; +} + +// Fixed rotation must leave the mass intact but drive the whole angular inertia to zero, even when the +// caller hands in a real tensor. +static int SetMassDataFixedRotation( void ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + b3WorldId worldId = b3CreateWorld( &worldDef ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.motionLocks.angularX = true; + bodyDef.motionLocks.angularY = true; + bodyDef.motionLocks.angularZ = true; + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + + b3MassData massData = { 5.0f, { 0.0f, 0.0f, 0.0f }, kDiagInertia }; + b3Body_SetMassData( bodyId, massData ); + + ENSURE_SMALL( b3Body_GetMass( bodyId ) - 5.0f, 1e-6f ); + ENSURE_SMALL( b3Body_GetInverseMass( bodyId ) - 0.2f, 1e-6f ); + + b3Matrix3 localInertia = b3Body_GetLocalRotationalInertia( bodyId ); + ENSURE_SMALL( localInertia.cx.x, 1e-6f ); + ENSURE_SMALL( localInertia.cy.y, 1e-6f ); + ENSURE_SMALL( localInertia.cz.z, 1e-6f ); + + b3Matrix3 invWorld = b3Body_GetWorldInverseRotationalInertia( bodyId ); + ENSURE_SMALL( invWorld.cx.x, 1e-6f ); + ENSURE_SMALL( invWorld.cy.y, 1e-6f ); + ENSURE_SMALL( invWorld.cz.z, 1e-6f ); + + b3MassData md = b3Body_GetMassData( bodyId ); + ENSURE_SMALL( md.inertia.cx.x, 1e-6f ); + ENSURE_SMALL( md.inertia.cy.y, 1e-6f ); + ENSURE_SMALL( md.inertia.cz.z, 1e-6f ); + + b3DestroyWorld( worldId ); + return 0; +} + +// Zero mass and a zero tensor have zero determinant, so the inverses must collapse to zero rather than +// divide by it. +static int SetMassDataZeroMass( void ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + b3WorldId worldId = b3CreateWorld( &worldDef ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + + b3MassData massData = { 0.0f, { 0.0f, 0.0f, 0.0f }, b3Mat3_zero }; + b3Body_SetMassData( bodyId, massData ); + + ENSURE_SMALL( b3Body_GetInverseMass( bodyId ), 1e-6f ); + + b3Matrix3 localInertia = b3Body_GetLocalRotationalInertia( bodyId ); + ENSURE_SMALL( localInertia.cx.x, 1e-6f ); + ENSURE_SMALL( localInertia.cy.y, 1e-6f ); + ENSURE_SMALL( localInertia.cz.z, 1e-6f ); + + b3Matrix3 invWorld = b3Body_GetWorldInverseRotationalInertia( bodyId ); + ENSURE_SMALL( invWorld.cx.x, 1e-6f ); + ENSURE_SMALL( invWorld.cy.y, 1e-6f ); + ENSURE_SMALL( invWorld.cz.z, 1e-6f ); + + b3DestroyWorld( worldId ); + return 0; +} + int BodyTest( void ) { RUN_SUBTEST( FarSingleSphereMass ); RUN_SUBTEST( FarCubeSphereMass ); + RUN_SUBTEST( DeferredMassExtents ); + RUN_SUBTEST( SetMassDataRoundTrip ); + RUN_SUBTEST( SetMassDataWorldInertiaRotated ); + RUN_SUBTEST( SetMassDataFixedRotation ); + RUN_SUBTEST( SetMassDataZeroMass ); return 0; } diff --git a/test/test_recording.c b/test/test_recording.c index ba068e5..da0d074 100644 --- a/test/test_recording.c +++ b/test/test_recording.c @@ -1729,6 +1729,126 @@ static int GeometryHashCollision( void ) return 0; } +// Staged stepping must reveal a mid-stream body at its creation transform. A body created and given an +// impulse in one recorded step is first placed by CreateBody, then displaced by the following Step. Atomic +// replay fuses the two, so the body is only ever seen already moved. Staged replay parks between them so +// the pre-integration pose is drawable. Verify the parked pose is the creation transform, that atomic +// replay does not show it, and that the extra park does not perturb the end state. +static int StagedStepCreationPose( 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 ); + + float timeStep = 1.0f / 60.0f; + int subStepCount = 4; + + // A few empty steps so the creation lands inside the stream, not at frame 0. + const int leadFrames = 3; + for ( int i = 0; i < leadFrames; ++i ) + { + b3World_Step( worldId, timeStep, subStepCount ); + } + + // The creation transform under test. No ground, so the body is the only create and stays ballistic. + // Components are exact in float so the round-trip pose compares tight. + const b3Pos spawn = { 1.0, 20.0, -2.0 }; + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = spawn; + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + + b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, 0.5f }; + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.density = 1.0f; + b3CreateSphereShape( bodyId, &shapeDef, &sphere ); + + // Impulse along +x so the first integrated step moves the body a visible distance off the spawn. + b3Body_ApplyLinearImpulseToCenter( bodyId, (b3Vec3){ 5.0f, 0.0f, 0.0f }, true ); + + const int creationFrame = leadFrames + 1; + b3World_Step( worldId, timeStep, subStepCount ); // advances to creationFrame + + const int totalFrames = creationFrame + 3; + for ( int i = creationFrame; 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 ); + + // Atomic replay fuses the create and its step, so at the creation frame the body is already + // integrated and displaced along +x. Capture that pose and the final state hash. + b3RecPlayer* atomic = b3RecPlayer_Create( data, sz, 1 ); + ENSURE( atomic != NULL ); + b3Pos atomicPose = { 0.0, 0.0, 0.0 }; + while ( !b3RecPlayer_IsAtEnd( atomic ) ) + { + b3RecPlayer_StepFrame( atomic ); + if ( b3RecPlayer_GetFrame( atomic ) == creationFrame ) + { + b3BodyId id = b3RecPlayer_GetBodyId( atomic, 0 ); + ENSURE( b3Body_IsValid( id ) ); + atomicPose = b3Body_GetPosition( id ); + } + } + ENSURE( b3RecPlayer_GetFrame( atomic ) == totalFrames ); + ENSURE( !b3RecPlayer_HasDiverged( atomic ) ); + ENSURE( atomicPose.x - spawn.x > 0.01 ); // the impulse moved it before it was ever seen + uint64_t atomicHash = b3HashWorldState( b3GetWorldFromId( b3RecPlayer_GetWorldId( atomic ) ) ); + b3RecPlayer_Destroy( atomic ); + + // Staged replay: step forward until the first pre-step park. It must sit at the creation frame's + // pre-integration state with the new body at exactly its spawn transform. + b3RecPlayer* staged = b3RecPlayer_Create( data, sz, 1 ); + ENSURE( staged != NULL ); + while ( !b3RecPlayer_IsAtEnd( staged ) ) + { + b3RecPlayer_SubStepFrame( staged ); + if ( b3RecPlayer_IsAtPreStep( staged ) ) + { + break; + } + } + ENSURE( b3RecPlayer_IsAtPreStep( staged ) ); + ENSURE( b3RecPlayer_GetFrame( staged ) == creationFrame - 1 ); // parked before the step, frame not advanced + + b3BodyId stagedId = b3RecPlayer_GetBodyId( staged, 0 ); + ENSURE( b3Body_IsValid( stagedId ) ); + b3Pos parkPose = b3Body_GetPosition( stagedId ); + ENSURE_SMALL( parkPose.x - spawn.x, 1.0e-4 ); + ENSURE_SMALL( parkPose.y - spawn.y, 1.0e-4 ); + ENSURE_SMALL( parkPose.z - spawn.z, 1.0e-4 ); + + // Finishing the frame integrates the body, so it leaves the spawn pose on the next advance. + b3RecPlayer_SubStepFrame( staged ); + ENSURE( b3RecPlayer_GetFrame( staged ) == creationFrame ); + ENSURE( !b3RecPlayer_IsAtPreStep( staged ) ); + + // Run staged to the end: the same op stream, so it must land on the atomic end state bit for bit. + while ( !b3RecPlayer_IsAtEnd( staged ) ) + { + b3RecPlayer_SubStepFrame( staged ); + } + ENSURE( b3RecPlayer_GetFrame( staged ) == totalFrames ); + ENSURE( !b3RecPlayer_HasDiverged( staged ) ); + uint64_t stagedHash = b3HashWorldState( b3GetWorldFromId( b3RecPlayer_GetWorldId( staged ) ) ); + ENSURE( stagedHash == atomicHash ); + b3RecPlayer_Destroy( staged ); + + b3DestroyRecording( rec ); + return 0; +} + int RecordingTest( void ) { RUN_SUBTEST( GeometryHashCollision ); @@ -1737,6 +1857,7 @@ int RecordingTest( void ) RUN_SUBTEST( HullDedup ); RUN_SUBTEST( MidStreamNoContacts ); RUN_SUBTEST( MidStreamContacts ); + RUN_SUBTEST( StagedStepCreationPose ); RUN_SUBTEST( ScrubBackward ); RUN_SUBTEST( SeekWithHull ); RUN_SUBTEST( DebugShapeCallbacks );