From 781673be801569a94be7942848755fc0baad3653 Mon Sep 17 00:00:00 2001 From: Erin Catto Date: Fri, 24 Jul 2026 21:48:23 -0700 Subject: [PATCH] Fixes 09 (#104) - #86 - #88 - #87 - #89 --- CMakeLists.txt | 3 + CMakePresets.json | 42 ++++++++- include/box3d/base.h | 9 +- samples/earcut.h | 3 - samples/gfx/draw.h | 1 + samples/gfx/text.c | 4 + samples/gfx/text.h | 2 + samples/sample.h | 6 +- samples/sample_benchmark.cpp | 4 +- samples/sample_character.cpp | 26 ------ samples/sample_collision.cpp | 2 +- samples/sample_compound.cpp | 6 +- samples/sample_events.cpp | 3 +- samples/sample_mesh.cpp | 2 +- samples/sample_ragdoll.cpp | 16 +--- samples/sample_tree.cpp | 3 - src/CMakeLists.txt | 1 + src/compound.c | 2 +- src/convex_manifold.c | 28 ++---- src/core.h | 1 + src/hull.c | 7 +- src/{hull_map.h => hull.h} | 4 +- src/physics_world.c | 15 +-- src/physics_world.h | 2 +- src/recording.c | 56 +++++------ src/recording.h | 15 +-- src/recording_ops.inl | 6 +- src/recording_replay.c | 40 +++++++- src/shape.c | 17 ++++ src/triangle_manifold.c | 16 ++-- test/test_body_query.c | 110 ++++++++++++++++++++++ test/test_hull.c | 102 ++++++++++++++++++++ test/test_manifold.c | 129 ++++++++++++++++++++++++++ test/test_recording.c | 174 +++++++++++++++++++++++++++++++++-- 34 files changed, 705 insertions(+), 152 deletions(-) rename src/{hull_map.h => hull.h} (77%) diff --git a/CMakeLists.txt b/CMakeLists.txt index 2c4d9aa..f53af49 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -78,6 +78,9 @@ endif() # https://box2d.org/posts/2024/08/determinism/ if (MINGW OR APPLE OR UNIX) add_compile_options(-ffp-contract=off) +elseif (MSVC AND CMAKE_C_COMPILER_ID STREQUAL "Clang") + # clang-cl defaults to contraction on and silently drops the GNU spelling + add_compile_options(/clang:-ffp-contract=off) endif() option(BOX3D_DISABLE_SIMD "Disable SIMD math (slower)" OFF) diff --git a/CMakePresets.json b/CMakePresets.json index e387835..95a5d2c 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -54,6 +54,42 @@ "CMAKE_CXX_COMPILER": "g++", "FETCHCONTENT_BASE_DIR": "${sourceDir}/.fetchcontent-cache/mingw" } + }, + { + "name": "windows-clang-cl", + "displayName": "Windows clang-cl (Visual Studio solution, ClangCL toolset)", + "toolset": "ClangCL", + "condition": { "type": "equals", "lhs": "${hostSystemName}", "rhs": "Windows" }, + "binaryDir": "${sourceDir}/build/clang-cl-vs", + "cacheVariables": { + "FETCHCONTENT_BASE_DIR": "${sourceDir}/.fetchcontent-cache/clang-cl-vs" + } + }, + { + "name": "clang-cl-debug", + "displayName": "Windows clang-cl Debug (Ninja, needs LLVM on PATH)", + "generator": "Ninja", + "condition": { "type": "equals", "lhs": "${hostSystemName}", "rhs": "Windows" }, + "binaryDir": "${sourceDir}/build/clang-cl", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Debug", + "CMAKE_C_COMPILER": "clang-cl", + "CMAKE_CXX_COMPILER": "clang-cl", + "FETCHCONTENT_BASE_DIR": "${sourceDir}/.fetchcontent-cache/clang-cl" + } + }, + { + "name": "clang-cl-release", + "displayName": "Windows clang-cl Release (Ninja, needs LLVM on PATH)", + "generator": "Ninja", + "condition": { "type": "equals", "lhs": "${hostSystemName}", "rhs": "Windows" }, + "binaryDir": "${sourceDir}/build/clang-cl", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Release", + "CMAKE_C_COMPILER": "clang-cl", + "CMAKE_CXX_COMPILER": "clang-cl", + "FETCHCONTENT_BASE_DIR": "${sourceDir}/.fetchcontent-cache/clang-cl" + } } ], "buildPresets": [ @@ -64,6 +100,10 @@ { "name": "macos-debug", "configurePreset": "macos", "configuration": "Debug" }, { "name": "macos-release", "configurePreset": "macos", "configuration": "Release" }, { "name": "mingw-debug", "configurePreset": "mingw-debug" }, - { "name": "mingw-release", "configurePreset": "mingw-release" } + { "name": "mingw-release", "configurePreset": "mingw-release" }, + { "name": "windows-clang-cl-debug", "configurePreset": "windows-clang-cl", "configuration": "Debug" }, + { "name": "windows-clang-cl-release", "configurePreset": "windows-clang-cl", "configuration": "Release" }, + { "name": "clang-cl-debug", "configurePreset": "clang-cl-debug" }, + { "name": "clang-cl-release", "configurePreset": "clang-cl-release" } ] } diff --git a/include/box3d/base.h b/include/box3d/base.h index 6878cb6..30cee46 100644 --- a/include/box3d/base.h +++ b/include/box3d/base.h @@ -68,6 +68,13 @@ #endif // clang-format on +// This is used to validate arguments for functions similar to printf. +#if defined( __GNUC__ ) || defined( __clang__ ) +#define B3_PRINTF_FORMAT( INDEX1, INDEX2 ) __attribute__( ( format( printf, INDEX1, INDEX2 ) ) ) +#else +#define B3_PRINTF_FORMAT( INDEX1, INDEX2 ) +#endif + #if defined( BOX3D_VALIDATE ) && !defined( NDEBUG ) #define B3_ENABLE_VALIDATION 1 #else @@ -125,7 +132,7 @@ B3_API void b3SetAssertFcn( b3AssertFcn* assertFcn ); /// Internal assertion handler. Allows for host intervention. B3_API int b3InternalAssert( const char* condition, const char* fileName, int lineNumber ); /// Assert that a condition is true. -#define B3_ASSERT( condition ) \ +#define B3_ASSERT( condition ) \ ( (void)( ( !!( condition ) ) || ( b3InternalAssert( #condition, __FILE__, (int)( __LINE__ ) ), 0 ) ) ) #else #define B3_ASSERT( ... ) ( (void)0 ) diff --git a/samples/earcut.h b/samples/earcut.h index 31c50e4..c414181 100644 --- a/samples/earcut.h +++ b/samples/earcut.h @@ -262,11 +262,8 @@ void Earcut::earcutLinked(Node* ear, int pass) { Node* prev; Node* next; - int iterations = 0; - // iterate through ears, slicing them one by one while (ear->prev != ear->next) { - iterations++; prev = ear->prev; next = ear->next; diff --git a/samples/gfx/draw.h b/samples/gfx/draw.h index 6d3def5..de5fec8 100644 --- a/samples/gfx/draw.h +++ b/samples/gfx/draw.h @@ -121,6 +121,7 @@ void DrawWireSphere( b3WorldTransform transform, const b3Sphere* sphere, int seg void DrawWireCapsule( b3WorldTransform transform, const b3Capsule* capsule, int segments, Vec4 color ); // printf-style positioned text label. The renderer projects with its latched camera. +B3_PRINTF_FORMAT(3, 4) void DrawString3D( b3Pos point, Vec4 color, const char* format, ... ); #ifdef __cplusplus diff --git a/samples/gfx/text.c b/samples/gfx/text.c index 3bf0a9d..8417a9c 100644 --- a/samples/gfx/text.c +++ b/samples/gfx/text.c @@ -1,6 +1,10 @@ // 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 "gfx/text.h" #include diff --git a/samples/gfx/text.h b/samples/gfx/text.h index 636541d..d127c89 100644 --- a/samples/gfx/text.h +++ b/samples/gfx/text.h @@ -52,6 +52,8 @@ void DrawString( b3Vec3 worldPos, Vec4 color, const char* text ); // Submit a UTF-8 string at a screen-pixel position (origin top-left, Y down, // framebuffer pixels). Same copy/truncation/overflow rules as DrawString. void DrawScreenString( int x, int y, Vec4 color, const char* text ); + +B3_PRINTF_FORMAT( 4, 5 ) void DrawScreenStringFormat( int x, int y, Vec4 color, const char* fmt, ... ); // Iteration surface for the GUI shell. Pointers/strings are valid until diff --git a/samples/sample.h b/samples/sample.h index d460308..ff8735b 100644 --- a/samples/sample.h +++ b/samples/sample.h @@ -119,7 +119,9 @@ public: // Update and render are split to support pausing the simulation virtual void Step(); - virtual void Render() {} + virtual void Render() + { + } // Draw sample controls into the shared info panel. Return true if any widget // was drawn so the panel can add a separator. @@ -180,6 +182,8 @@ public: virtual void MouseMove( b3Vec2 p ); void ToggleThirdPerson(); + + B3_PRINTF_FORMAT( 2, 3 ) void DrawTextLine( const char* text, ... ); void ResetProfile(); diff --git a/samples/sample_benchmark.cpp b/samples/sample_benchmark.cpp index c2b0584..ae5e3cf 100644 --- a/samples/sample_benchmark.cpp +++ b/samples/sample_benchmark.cpp @@ -632,13 +632,13 @@ public: } float milliseconds = b3GetMilliseconds( startTick ); - uint64_t tickCount = b3GetTicks() - startTick; + int tickCount = (int)(b3GetTicks() - startTick); float aveIterations = float( iterationCount ) / float( castCount ); float aveInner = float( innerIterationCount ) / float( castCount ); float aveCastTime = 1000.0f * milliseconds / float( castCount ); - DrawTextLine( "count = %d, hit count = %d, iterations = %d, inner = %d, ticks = %ld", castCount, hitCount, iterationCount, + DrawTextLine( "count = %d, hit count = %d, iterations = %d, inner = %d, ticks = %d", castCount, hitCount, iterationCount, innerIterationCount, tickCount ); DrawTextLine( "ave iterations = %.1f, ave inner = %.1f, ave cast us %.3f", aveIterations, aveInner, aveCastTime ); diff --git a/samples/sample_character.cpp b/samples/sample_character.cpp index 4903d55..cbe2cbc 100644 --- a/samples/sample_character.cpp +++ b/samples/sample_character.cpp @@ -333,12 +333,6 @@ public: b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); b3ShapeDef shapeDef = b3DefaultShapeDef(); - b3SurfaceMaterial materials[3]; - materials[0] = { 0.6f, 0.0f, 0 }; - materials[1] = { 0.6f, 1.0f, 1 }; - materials[2] = { 0.1f, 0.0f, 2 }; - shapeDef.materials = materials; - shapeDef.materialCount = 3; if ( m_levelMesh != nullptr ) { @@ -399,13 +393,6 @@ public: m_heightField = b3CreateWave( 50.0f, 50.0f, b3Vec3_one, 0.02f, 0.04f, true ); b3ShapeDef shapeDef = b3DefaultShapeDef(); - b3SurfaceMaterial materials[3]; - materials[0] = { 0.6f, 0.0f, 0 }; - materials[1] = { 0.6f, 1.0f, 1 }; - materials[2] = { 0.1f, 0.0f, 2 }; - shapeDef.materials = materials; - shapeDef.materialCount = 3; - b3CreateHeightFieldShape( body, &shapeDef, m_heightField ); } @@ -1339,12 +1326,6 @@ public: b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); b3ShapeDef shapeDef = b3DefaultShapeDef(); - b3SurfaceMaterial materials[3]; - materials[0] = { 0.6f, 0.0f, 0 }; - materials[1] = { 0.6f, 1.0f, 1 }; - materials[2] = { 0.1f, 0.0f, 2 }; - shapeDef.materials = materials; - shapeDef.materialCount = 3; if ( m_levelMesh != nullptr ) { @@ -1414,13 +1395,6 @@ public: m_heightField = b3CreateWave( 50.0f, 50.0f, b3Vec3_one, 0.02f, 0.04f, true ); b3ShapeDef shapeDef = b3DefaultShapeDef(); - b3SurfaceMaterial materials[3]; - materials[0] = { 0.6f, 0.0f, 0 }; - materials[1] = { 0.6f, 1.0f, 1 }; - materials[2] = { 0.1f, 0.0f, 2 }; - shapeDef.materials = materials; - shapeDef.materialCount = 3; - b3CreateHeightFieldShape( body, &shapeDef, m_heightField ); } diff --git a/samples/sample_collision.cpp b/samples/sample_collision.cpp index 86e015e..e6dc8e0 100644 --- a/samples/sample_collision.cpp +++ b/samples/sample_collision.cpp @@ -735,7 +735,7 @@ public: for ( int i = 0; i < m_castContext.count; ++i ) { - DrawTextLine( "material = %d, triangle = %d", m_castContext.materialIds[i], m_castContext.triangleIndices[i] ); + DrawTextLine( "material = %d, triangle = %d", (int)m_castContext.materialIds[i], m_castContext.triangleIndices[i] ); } DrawGroundGrid( 10 ); diff --git a/samples/sample_compound.cpp b/samples/sample_compound.cpp index 83eea93..636d378 100644 --- a/samples/sample_compound.cpp +++ b/samples/sample_compound.cpp @@ -692,7 +692,7 @@ public: b3Transform transform = { { 0.0f, 0.01f, 0.0f }, b3Quat_identity }; DrawAxes( b3MakeWorldTransform( transform ), 4.0f ); - DrawTextLine( "surface type = %d", m_userMaterialId ); + DrawTextLine( "surface type = %d", (int)m_userMaterialId ); DrawTextLine( "compound capsules/hulls/meshes/sphere = %d / %d / %d / %d", m_compound->capsuleCount, m_compound->hullCount, m_compound->meshCount, m_compound->sphereCount ); DrawTextLine( "compound byte count = %d", m_compound->byteCount ); @@ -726,7 +726,7 @@ public: DrawLine( p1, p2, MakeColor( b3_colorYellow ) ); DrawPoint( p1, 8.0f, MakeColor( b3_colorLightCoral ) ); DrawTextLine( "ray hit triangle/child/material = %d / %d / %d", context.triangleIndex, context.childIndex, - context.materialId ); + (int)context.materialId ); } else { @@ -751,7 +751,7 @@ public: b3Sphere sphere = { b3Vec3_zero, 0.25f }; DrawSolidSphere( { position, b3Quat_identity }, sphere, MakeColor( b3_colorOrchid ) ); DrawTextLine( "shape hit triangle/child/material = %d / %d / %d", context.triangleIndex, context.childIndex, - context.materialId ); + (int)context.materialId ); } else { diff --git a/samples/sample_events.cpp b/samples/sample_events.cpp index ace7823..ac2c0ab 100644 --- a/samples/sample_events.cpp +++ b/samples/sample_events.cpp @@ -218,7 +218,8 @@ public: DrawPoint( p1, 10.0f, MakeColor( b3_colorYellow ) ); DrawLine( p1, p2, MakeColor( b3_colorYellow ) ); - DrawString3D( p1, MakeColor( b3_colorWhite ), "%.1f, %d", m_events[i].approachSpeed, m_events[i].userMaterialIdA ); + DrawString3D( p1, MakeColor( b3_colorWhite ), "%.1f, %d", m_events[i].approachSpeed, + (int)m_events[i].userMaterialIdA ); } DrawTextLine( "event count = %d", m_eventCount ); diff --git a/samples/sample_mesh.cpp b/samples/sample_mesh.cpp index 6ea9f65..9438735 100644 --- a/samples/sample_mesh.cpp +++ b/samples/sample_mesh.cpp @@ -727,7 +727,7 @@ public: void Render() override { DrawTextLine( "scale = (%.2g, %.2g, %.2g)", m_scale.x, m_scale.y, m_scale.z ); - DrawTextLine( "surface type = %d", m_userMaterialId ); + DrawTextLine( "surface type = %d", (int)m_userMaterialId ); Sample::Render(); } diff --git a/samples/sample_ragdoll.cpp b/samples/sample_ragdoll.cpp index 9d32a46..1e4ce51 100644 --- a/samples/sample_ragdoll.cpp +++ b/samples/sample_ragdoll.cpp @@ -208,15 +208,6 @@ static int sampleRagdollMesh = RegisterSample( "Ragdoll", "Mesh", RagdollOnMesh: class RagdollPile : public Sample { public: - enum - { -#ifdef NDEBUG - e_count = 20 -#else - e_count = 8 -#endif - }; - explicit RagdollPile( SampleContext* context ) : Sample( context ) { @@ -234,10 +225,10 @@ public: b3CreateMeshShape( groundId, &shapeDef, m_groundMesh, b3Vec3_one ); g_randomSeed = 42; - float a = 0.1f * e_count; + float a = 0.1f * m_count; b3Vec3 lower = { -a, -a, -a }; b3Vec3 upper = { a, a, a }; - for ( int i = 0; i < e_count; ++i ) + for ( int i = 0; i < m_count; ++i ) { b3Vec3 offset = RandomVec3( lower, upper ); b3Pos position = { offset.x, 2.0f, offset.z }; @@ -261,8 +252,9 @@ public: return new RagdollPile( context ); } + static constexpr int m_count = m_isDebug ? 8 : 20; b3MeshData* m_groundMesh; - Human m_humans[e_count] = {}; + Human m_humans[m_count] = {}; }; static int sampleRagdollPile = RegisterSample( "Ragdoll", "Pile", RagdollPile::Create ); diff --git a/samples/sample_tree.cpp b/samples/sample_tree.cpp index 109d179..9a760c0 100644 --- a/samples/sample_tree.cpp +++ b/samples/sample_tree.cpp @@ -281,9 +281,6 @@ public: return; } - constexpr int bufferSize = 512; - char buffer[bufferSize]; - int maxArea = 0.0f; int maxAreaIndex = -1; diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 61da44a..3f43e7d 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -33,6 +33,7 @@ set(BOX3D_SOURCE_FILES dynamic_tree.c height_field.c hull.c + hull.h id_pool.c id_pool.h island.c diff --git a/src/compound.c b/src/compound.c index c1af61c..1df1f1e 100644 --- a/src/compound.c +++ b/src/compound.c @@ -3,7 +3,7 @@ #include "compound.h" -#include "hull_map.h" +#include "hull.h" #include "math_internal.h" #include "shape.h" diff --git a/src/convex_manifold.c b/src/convex_manifold.c index dd53247..d3b998a 100644 --- a/src/convex_manifold.c +++ b/src/convex_manifold.c @@ -758,19 +758,6 @@ static bool b3BuildHullFaceAndCapsuleContact( b3LocalManifold* manifold, const b return false; } -static inline float b3DeepestPointSeparation( const b3LocalManifold* manifold ) -{ - // Deepest point - float minSeparation = FLT_MAX; - int pointCount = manifold->pointCount; - for ( int i = 0; i < pointCount; ++i ) - { - minSeparation = b3MinFloat( minSeparation, manifold->points[i].separation ); - } - - return minSeparation; -} - static bool b3BuildHullAndCapsuleEdgeContact( b3LocalManifold* manifold, int capacity, const b3HullData* hullA, const b3Capsule* capsuleB, b3Transform transformBtoA, b3SeparatingAxis query ) { @@ -934,14 +921,12 @@ void b3CollideHullAndCapsule( b3LocalManifold* manifold, int capacity, const b3H // Create face contact float faceSeparation = faceQuery.separation - capsuleB->radius; b3BuildHullFaceAndCapsuleContact( manifold, hullA, capsuleB, transformBtoA, faceQuery ); - if ( manifold->pointCount > 1 ) + B3_VALIDATE( manifold->pointCount == 0 || manifold->pointCount == 2 ); + if ( manifold->pointCount == 2 ) { - // If ( Out.PointCount <= 1 ) -> Compare with unclipped separation - // If ( Out.PointCount > 1 ) -> Be aggressive and compare with clipped separation - // Face contact can be empty if it does not realize the axis of minimum penetration - faceSeparation = b3DeepestPointSeparation( manifold ); + // This becomes the clipped separation. + faceSeparation = b3MinFloat( manifold->points[0].separation, manifold->points[1].separation ); } - B3_VALIDATE( faceSeparation <= 0.0f ); // Is there a valid edge-edge axis? if ( edgeQuery.indexA == B3_NULL_INDEX ) @@ -951,10 +936,9 @@ void b3CollideHullAndCapsule( b3LocalManifold* manifold, int capacity, const b3H // Face contact can be empty if it does not realize the axis of minimum penetration. // Create edge contact if face contact fails or edge contact is significantly better! - const float kRelEdgeTolerance = 0.90f; - const float kAbsTolerance = 0.5f * B3_LINEAR_SLOP; + float linearSlop = B3_LINEAR_SLOP; float edgeSeparation = edgeQuery.separation - capsuleB->radius; - if ( manifold->pointCount == 0 || edgeSeparation > kRelEdgeTolerance * faceSeparation + kAbsTolerance ) + if ( manifold->pointCount == 0 || edgeSeparation > faceSeparation + linearSlop ) { // Edge contact b3BuildHullAndCapsuleEdgeContact( manifold, capacity, hullA, capsuleB, transformBtoA, edgeQuery ); diff --git a/src/core.h b/src/core.h index d4fdeb8..005e2d6 100644 --- a/src/core.h +++ b/src/core.h @@ -137,6 +137,7 @@ void* b3AllocZeroed( size_t size ); void b3Free( void* mem, size_t size ); void* b3GrowAlloc( void* oldMem, int oldSize, int newSize ); +B3_PRINTF_FORMAT( 1, 2 ) void b3Log( const char* format, ... ); // Geometry content hashes reserve zero to mean unhashed diff --git a/src/hull.c b/src/hull.c index 0d63071..ea3ed75 100644 --- a/src/hull.c +++ b/src/hull.c @@ -4,7 +4,7 @@ // Dirk Gregorius contributed portions of this code #include "algorithm.h" -#include "hull_map.h" +#include "hull.h" #include "math_internal.h" #include "shape.h" @@ -2303,6 +2303,7 @@ bool b3CompareHullData( const b3HullData* hull1, const b3HullData* hull2 ) _Static_assert( sizeof( b3HullData ) == 144, "unexpected hull data size" ); _Static_assert( sizeof( b3BoxHull ) == 648, "unexpected box hull size" ); +// Implement b3HullMap. #define NAME b3HullMap #define KEY_TY const b3HullData* #define VAL_TY int @@ -2772,6 +2773,8 @@ static const b3BoxHull s_boxHull = { b3BoxHull b3MakeTransformedBoxHull( float hx, float hy, float hz, b3Transform transform ) { + B3_ASSERT( b3IsValidTransform( transform ) ); + b3BoxHull boxHull = s_boxHull; float minH = 0.2f * B3_LINEAR_SLOP; @@ -2934,6 +2937,8 @@ void b3ScaleBox( b3Vec3* halfWidths, b3Transform* transform, b3Vec3 postScale, f // todo use new hull scaling technique b3BoxHull b3MakeScaledBoxHull( b3Vec3 halfWidths, b3Transform transform, b3Vec3 postScale ) { + B3_ASSERT( b3IsValidTransform( transform ) ); + b3Vec3 h = halfWidths; b3Transform xf = transform; b3ScaleBox( &h, &xf, postScale, 4.0f * B3_LINEAR_SLOP ); diff --git a/src/hull_map.h b/src/hull.h similarity index 77% rename from src/hull_map.h rename to src/hull.h index 5b50c56..a1077bb 100644 --- a/src/hull_map.h +++ b/src/hull.h @@ -12,8 +12,8 @@ uint64_t b3HashHullData( const b3HullData* hull ); bool b3CompareHullData( const b3HullData* hull1, const b3HullData* hull2 ); -// Map keyed by hull content. The world hull database stores a reference count, -// compound baking stores a byte offset. Implementation lives in hull.c. +// Map keyed by hull content. The world hull database uses the value as a reference count, +// while compound baking stores uses the value as a byte offset. Implementation is in hull.c. #define NAME b3HullMap #define KEY_TY const b3HullData* #define VAL_TY int diff --git a/src/physics_world.c b/src/physics_world.c index 50ffefe..6bd7cb0 100644 --- a/src/physics_world.c +++ b/src/physics_world.c @@ -11,7 +11,7 @@ #include "contact.h" #include "core.h" #include "ctz.h" -#include "hull_map.h" +#include "hull.h" #include "island.h" #include "joint.h" #include "parallel_for.h" @@ -41,18 +41,21 @@ const b3HullData* b3AddHullToDatabase( b3World* world, const b3HullData* src ) { b3HullMap* database = world->hullDatabase; - // Compare by content so an unowned query hull finds the shared copy. + // Compare by content to de-duplicate. Not trusting the hash. b3HullMap_itr itr = b3HullMap_get( database, src ); if ( b3HullMap_is_end( itr ) == false ) { + // Bump reference count. itr.data->val += 1; return itr.data->key; } - b3HullData* owned = b3CloneHull( src ); - B3_ASSERT( owned != NULL ); - b3HullMap_insert( database, owned, 1 ); - return owned; + b3HullData* clone = b3CloneHull( src ); + B3_ASSERT( clone != NULL ); + + // Start with reference count of 1. + b3HullMap_insert( database, clone, 1 ); + return clone; } const b3HullData* b3AddOwnedHullToDatabase( b3World* world, b3HullData* owned ) diff --git a/src/physics_world.h b/src/physics_world.h index 12f1695..8bd3df8 100644 --- a/src/physics_world.h +++ b/src/physics_world.h @@ -178,7 +178,7 @@ typedef struct b3World b3Array( b3Shape ) shapes; // Reference counted store of shared hull data keyed by content. Shapes hold a - // pointer to the owned copy here. Opaque to avoid leaking the verstable map + // pointer to the hull stored in the db. Type erased to avoid leaking the verstable map // type into this header. void* hullDatabase; diff --git a/src/recording.c b/src/recording.c index 4d5c599..341ddbf 100644 --- a/src/recording.c +++ b/src/recording.c @@ -799,23 +799,15 @@ uint64_t b3Hash64Blob( const uint8_t* bytes, int n ) static uint32_t b3RegistryPush( b3GeometryRegistry* reg, b3GeometryHashMap* map, b3GeometryHashMap_itr itr, bool hashPresent, b3GeometryKind kind, uint64_t contentHash, uint8_t* bytes, int byteCount ) { - 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; + uint32_t id = (uint32_t)reg->entries.count; + b3GeometryEntry* entry = b3Array_Emplace( reg->entries ); entry->contentHash = contentHash; entry->id = id; entry->kind = kind; entry->byteCount = byteCount; - entry->bytes = bytes; // take ownership + // Take ownership. + entry->bytes = bytes; entry->hashNext = hashPresent ? (int)itr.data->val : B3_NULL_INDEX; - reg->count++; if ( hashPresent ) { @@ -832,11 +824,11 @@ static b3GeometryHashMap* b3RegistryMap( b3GeometryRegistry* reg ) { if ( reg->dedupMap == NULL ) { - b3GeometryHashMap* fresh = (b3GeometryHashMap*)b3Alloc( sizeof( b3GeometryHashMap ) ); + b3GeometryHashMap* fresh = b3Alloc( sizeof( b3GeometryHashMap ) ); b3GeometryHashMap_init( fresh ); reg->dedupMap = fresh; } - return (b3GeometryHashMap*)reg->dedupMap; + return reg->dedupMap; } uint32_t b3InternGeometry( b3GeometryRegistry* reg, b3GeometryKind kind, uint64_t contentHash, uint8_t* bytes, int byteCount ) @@ -848,12 +840,12 @@ uint32_t b3InternGeometry( b3GeometryRegistry* reg, b3GeometryKind kind, uint64_ if ( hashPresent ) { // Walk every entry sharing this hash so a collision still finds the identical blob. - for ( int idx = (int)itr.data->val; idx != B3_NULL_INDEX; idx = reg->entries[idx].hashNext ) + for ( int index = (int)itr.data->val; index != B3_NULL_INDEX; index = reg->entries.data[index].hashNext ) { - b3GeometryEntry* e = reg->entries + idx; + b3GeometryEntry* e = reg->entries.data + index; if ( e->byteCount == byteCount && memcmp( e->bytes, bytes, (size_t)byteCount ) == 0 ) { - // Duplicate: the caller transferred ownership; return existing id + // Duplicate. Free bytes because the caller transferred ownership. Return existing id. b3Free( bytes, (size_t)byteCount ); return e->id; } @@ -873,22 +865,18 @@ uint32_t b3AppendGeometry( b3GeometryRegistry* reg, b3GeometryKind kind, uint64_ void b3FreeRegistry( b3GeometryRegistry* reg ) { - for ( int i = 0; i < reg->count; ++i ) + for ( int i = 0; i < reg->entries.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 ) ) ); + b3Free( reg->entries.data[i].bytes, (size_t)reg->entries.data[i].byteCount ); } + + b3Array_Destroy( reg->entries ); + 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; } @@ -955,10 +943,10 @@ void b3RecInternTag( b3Recording* rec, uint64_t key, uint64_t id, const char* na // the tag table stops after the geometry entries and ignores the trailing tag bytes. void b3RecWriteRegistry( b3Recording* rec ) { - b3RecW_U32( &rec->buffer, (uint32_t)rec->registry.count ); - for ( int i = 0; i < rec->registry.count; ++i ) + b3RecW_U32( &rec->buffer, (uint32_t)rec->registry.entries.count ); + for ( int i = 0; i < rec->registry.entries.count; ++i ) { - b3GeometryEntry* e = rec->registry.entries + i; + b3GeometryEntry* e = rec->registry.entries.data + i; b3RecW_U8( &rec->buffer, (uint8_t)e->kind ); b3RecW_U32( &rec->buffer, (uint32_t)e->byteCount ); b3RecBufAppend( &rec->buffer, e->bytes, e->byteCount ); @@ -977,7 +965,7 @@ void b3RecWriteRegistry( b3Recording* rec ) b3Recording* b3CreateRecording( int byteCapacity ) { - b3Recording* rec = (b3Recording*)b3Alloc( sizeof( b3Recording ) ); + b3Recording* rec = b3Alloc( sizeof( b3Recording ) ); *rec = (b3Recording){ 0 }; int initCap = byteCapacity > 0 ? byteCapacity : 65536; @@ -1196,7 +1184,7 @@ b3Recording* b3LoadRecordingFromFile( const char* path ) uint32_t b3RecInternHull( b3Recording* rec, const b3HullData* hull ) { int byteCount = hull->byteCount; - uint8_t* bytes = (uint8_t*)b3Alloc( (size_t)byteCount ); + uint8_t* bytes = 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 ); @@ -1205,7 +1193,7 @@ uint32_t b3RecInternHull( b3Recording* rec, const b3HullData* hull ) uint32_t b3RecInternMesh( b3Recording* rec, const b3MeshData* mesh ) { int byteCount = mesh->byteCount; - uint8_t* bytes = (uint8_t*)b3Alloc( (size_t)byteCount ); + uint8_t* bytes = 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 ); @@ -1214,7 +1202,7 @@ uint32_t b3RecInternMesh( b3Recording* rec, const b3MeshData* mesh ) uint32_t b3RecInternHeightField( b3Recording* rec, const b3HeightFieldData* hf ) { int byteCount = hf->byteCount; - uint8_t* bytes = (uint8_t*)b3Alloc( (size_t)byteCount ); + uint8_t* bytes = 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 ); @@ -1223,7 +1211,7 @@ uint32_t b3RecInternHeightField( b3Recording* rec, const b3HeightFieldData* hf ) uint32_t b3RecInternCompound( b3Recording* rec, const b3CompoundData* compound ) { int byteCount = compound->byteCount; - uint8_t* bytes = (uint8_t*)b3Alloc( (size_t)byteCount ); + uint8_t* bytes = 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. diff --git a/src/recording.h b/src/recording.h index 3ba2fd3..19a96c5 100644 --- a/src/recording.h +++ b/src/recording.h @@ -3,6 +3,7 @@ #pragma once +#include "container.h" #include "core.h" #include "box3d/id.h" @@ -50,10 +51,10 @@ typedef struct b3World b3World; #define B3_REC_VERSION_MAJOR 4 // Minor tracks op-stream additions that keep the 48 byte header shape. -// Minor version 3 added name cache. -#define B3_REC_VERSION_MINOR 3 +// Minor version 4 added b3Shape_SetMeshMaterial, b3Shape_SetHull, b3Shape_SetMesh +#define B3_REC_VERSION_MINOR 4 -// File header, fixed 48 bytes, little-endian. Contains the registry locator so the player +// File header, fixed 48 bytes. Contains the registry locator so the player // can load geometry before replaying any ops. typedef struct b3RecHeader { @@ -106,13 +107,13 @@ typedef struct b3GeometryEntry int hashNext; } b3GeometryEntry; +b3DeclareArray( 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; + b3Array( b3GeometryEntry ) entries; void* dedupMap; } b3GeometryRegistry; @@ -126,7 +127,7 @@ typedef struct b3GeometryRegistry typedef struct b3RecTag { // hash of (id, queryName) - uint64_t key; + uint64_t key; uint64_t id; char queryName[B3_MAX_QUERY_NAME_LENGTH + 1]; } b3RecTag; diff --git a/src/recording_ops.inl b/src/recording_ops.inl index 88acf0a..3f0cf42 100644 --- a/src/recording_ops.inl +++ b/src/recording_ops.inl @@ -91,9 +91,11 @@ B3_REC_OP( 0x57, ShapeEnablePreSolveEvents, RET_NONE, ARG( SHAPEID, shape ) ARG( 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 ) ) +B3_REC_OP( 0x5B, ShapeApplyWind, RET_NONE, ARG( SHAPEID, shape ) ARG( VEC3, wind ) ARG( F32, drag ) ARG( F32, lift ) ARG( F32, maxSpeed ) ARG( BOOL, wake ) ) B3_REC_OP( 0x5C, ShapeSetName, RET_NONE, ARG( SHAPEID, shape ) ARG( STR, name ) ) +B3_REC_OP( 0x5D, ShapeSetMeshMaterial, RET_NONE, ARG( SHAPEID, shape ) ARG( MATERIAL, material ) ARG( I32, index ) ) +B3_REC_OP( 0x5E, ShapeSetHull, RET_NONE, ARG( SHAPEID, shape ) ARG( GEOMID, geometryId ) ) +B3_REC_OP( 0x5F, ShapeSetMesh, RET_NONE, ARG( SHAPEID, shape ) ARG( GEOMID, geometryId ) ARG( VEC3, scale ) ) // Joint create and destroy B3_REC_OP( 0x90, CreateParallelJoint, RET_JOINTID, ARG( WORLDID, world ) ARG( PARALLELJOINTDEF, def ) ) diff --git a/src/recording_replay.c b/src/recording_replay.c index c3cc491..f2f578d 100644 --- a/src/recording_replay.c +++ b/src/recording_replay.c @@ -1024,7 +1024,7 @@ static void b3RecDispatch_CreateMeshShape( const b3RecArgs_CreateMeshShape* a, b return; } b3RegistrySlot* slot = rdr->slots + id; - const b3MeshData* mesh = (const b3MeshData*)b3RecGetLiveMesh( slot ); + const b3MeshData* mesh = b3RecGetLiveMesh( slot ); b3BodyId bodyId = b3RecMakeBodyId( rdr, a->body ); b3ShapeId gotId = b3CreateMeshShape( bodyId, &a->def, mesh, a->scale ); b3RecCheckShapeId( rdr, gotId, recId ); @@ -1110,6 +1110,11 @@ static void b3RecDispatch_ShapeSetSurfaceMaterial( const b3RecArgs_ShapeSetSurfa b3Shape_SetSurfaceMaterial( b3RecMakeShapeId( rdr, a->shape ), a->material ); } +static void b3RecDispatch_ShapeSetMeshMaterial( const b3RecArgs_ShapeSetMeshMaterial* a, b3RecReader* rdr ) +{ + b3Shape_SetMeshMaterial( b3RecMakeShapeId( rdr, a->shape ), a->material, a->index ); +} + static void b3RecDispatch_ShapeSetFilter( const b3RecArgs_ShapeSetFilter* a, b3RecReader* rdr ) { b3Shape_SetFilter( b3RecMakeShapeId( rdr, a->shape ), a->filter, a->invokeContacts ); @@ -1145,6 +1150,35 @@ static void b3RecDispatch_ShapeSetCapsule( const b3RecArgs_ShapeSetCapsule* a, b b3Shape_SetCapsule( b3RecMakeShapeId( rdr, a->shape ), &a->capsule ); } +static void b3RecDispatch_ShapeSetHull( const b3RecArgs_ShapeSetHull* a, b3RecReader* rdr ) +{ + 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; + b3ShapeId shapeId = b3RecMakeShapeId( rdr, a->shape ); + b3Shape_SetHull( shapeId, (const b3HullData*)slot->bytes ); +} + +static void b3RecDispatch_ShapeSetMesh( const b3RecArgs_ShapeSetMesh* a, b3RecReader* rdr ) +{ + 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; + b3ShapeId shapeId = b3RecMakeShapeId( rdr, a->shape ); + const b3MeshData* mesh = b3RecGetLiveMesh( slot ); + b3Shape_SetMesh( shapeId, mesh, a->scale ); +} + 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 ); @@ -2581,12 +2615,12 @@ static void b3RecCaptureKeyframe( b3RecPlayer* player ) b3World* world = b3GetWorldFromId( player->rdr.replayWorldId ); b3RecBuffer buf = { 0 }; - int regCountBefore = player->keyframeRec->registry.count; + int regCountBefore = player->keyframeRec->registry.entries.count; B3_UNUSED( regCountBefore ); b3SerializeWorld( world, &buf, player->keyframeRec ); // Registry must not grow: all geometry was pre-seeded and the registry dedups exactly. - B3_ASSERT( player->keyframeRec->registry.count == regCountBefore ); + B3_ASSERT( player->keyframeRec->registry.entries.count == regCountBefore ); size_t bodyBytes = (size_t)player->bodyIdCount * sizeof( b3BodyId ); size_t newBytes = (size_t)buf.capacity + bodyBytes; diff --git a/src/shape.c b/src/shape.c index 61c14d1..eabc1eb 100644 --- a/src/shape.c +++ b/src/shape.c @@ -1295,6 +1295,8 @@ void b3Shape_SetMeshMaterial( b3ShapeId shapeId, b3SurfaceMaterial surfaceMateri B3_ASSERT( 0 <= index && index < shape->materialCount ); B3_ASSERT( shape->type != b3_compoundShape ); + + B3_REC( world, ShapeSetMeshMaterial, shapeId, surfaceMaterial, index ); b3GetShapeMaterials( shape )[index] = surfaceMaterial; } @@ -1613,6 +1615,14 @@ void b3Shape_SetHull( b3ShapeId shapeId, const b3HullData* hull ) return; } + if ( world->recording != NULL ) + { + // Intern the shared hull. + uint32_t geometryId = b3RecInternHull( world->recording, data ); + b3RecArgs_ShapeSetHull setArgs = { shapeId, geometryId }; + b3RecWrite_ShapeSetHull( world->recording, &setArgs ); + } + b3DestroyShapeAllocationForShapeChange( world, shape ); shape->hull = data; @@ -1640,6 +1650,13 @@ void b3Shape_SetMesh( b3ShapeId shapeId, const b3MeshData* meshData, b3Vec3 scal world->locked = true; + if ( world->recording != NULL ) + { + uint32_t geometryId = b3RecInternMesh( world->recording, meshData ); + b3RecArgs_ShapeSetMesh setArgs = { shapeId, geometryId, scale }; + b3RecWrite_ShapeSetMesh( world->recording, &setArgs ); + } + b3Shape* shape = b3GetShape( world, shapeId ); b3DestroyShapeAllocationForShapeChange( world, shape ); diff --git a/src/triangle_manifold.c b/src/triangle_manifold.c index c702540..3de7fee 100644 --- a/src/triangle_manifold.c +++ b/src/triangle_manifold.c @@ -390,9 +390,9 @@ void b3CollideTriangleAndCapsule( b3LocalManifold* manifold, int capacity, const distanceInput.useRadii = false; b3DistanceOutput distanceOutput = b3ShapeDistance( &distanceInput, cache, NULL, 0 ); - + float speculativeDistance = B3_SPECULATIVE_DISTANCE; float radius = capsuleB->radius; - if ( distanceOutput.distance > radius + B3_SPECULATIVE_DISTANCE ) + if ( distanceOutput.distance > radius + speculativeDistance ) { // Shapes are separated, persist the cache return; @@ -468,32 +468,32 @@ void b3CollideTriangleAndCapsule( b3LocalManifold* manifold, int capacity, const b3SeparatingAxis faceQuery = b3QueryTriangleFaceAndCapsule( plane, capsuleB ); if ( faceQuery.separation > radius ) { - // Shapes are separated + // Shapes are separated. Should be impossible for a reasonable capsule radius. return; } b3SeparatingAxis edgeQuery = b3QueryTriangleAndCapsuleEdges( triangleA, plane, capsuleB ); if ( edgeQuery.separation > radius ) { - // Shapes are separated + // Shapes are separated. Should be impossible for a reasonable capsule radius. return; } // Create face contact float faceSeparation = faceQuery.separation - radius; b3BuildTriangleAndCapsuleFaceContact( manifold, triangleA, plane, capsuleB ); + B3_VALIDATE( manifold->pointCount == 0 || manifold->pointCount == 2 ); if ( manifold->pointCount == 2 ) { + // This becomes the clipped separation. faceSeparation = b3MinFloat( manifold->points[0].separation, manifold->points[1].separation ); } - B3_VALIDATE( faceSeparation <= 0.0f ); // Face contact can be empty if it does not realize the axis of minimum penetration. // Create edge contact if face contact fails or edge contact is significantly better! - const float kRelEdgeTolerance = 0.50f; - const float kAbsTolerance = 1.0f * B3_LINEAR_SLOP; + float linearSlop = B3_LINEAR_SLOP; float edgeSeparation = edgeQuery.separation - radius; - if ( manifold->pointCount == 0 || edgeSeparation > kRelEdgeTolerance * faceSeparation + kAbsTolerance ) + if ( manifold->pointCount == 0 || edgeSeparation > faceSeparation + linearSlop ) { // Edge contact b3BuildTriangleAndCapsuleEdgeContact( manifold, triangleA, plane, capsuleB, edgeQuery ); diff --git a/test/test_body_query.c b/test/test_body_query.c index a2939cb..8ea43d9 100644 --- a/test/test_body_query.c +++ b/test/test_body_query.c @@ -355,6 +355,114 @@ static int OverlapFilter( void ) return 0; } +static bool CountOverlapCallback( b3ShapeId shapeId, void* context ) +{ + (void)shapeId; + *(int*)context += 1; + return true; +} + +// A box hull proxy built around a world target with a zero origin must hit the same shapes as the +// same box built at the local origin and queried with the target as origin. This is the origin +// relative equivalence the world query promises, and the pattern users reach for when they bake a +// query box with b3MakeTransformedBoxHull. +static int OverlapHullProxyEquivalence( void ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + b3WorldId worldId = b3CreateWorld( &worldDef ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_staticBody; + bodyDef.position = (b3Pos){ 10.0f, 0.0f, 0.0f }; + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + b3BoxHull box = b3MakeBoxHull( 1.0f, 1.0f, 1.0f ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + + b3World_Step( worldId, 1.0f / 60.0f, 1 ); + + b3QueryFilter filter = b3DefaultQueryFilter(); + + // Overlapping target: a 10 wide query box centered on the body. + { + b3Vec3 offset = { 10.0f, 0.0f, 0.0f }; + + b3BoxHull baked = b3MakeTransformedBoxHull( 5.0f, 5.0f, 5.0f, (b3Transform){ offset, b3Quat_identity } ); + b3ShapeProxy bakedProxy = { baked.boxPoints, baked.base.vertexCount, 0.0f }; + int bakedHits = 0; + b3World_OverlapShape( worldId, b3Pos_zero, &bakedProxy, filter, CountOverlapCallback, &bakedHits ); + + b3Pos origin = b3OffsetPos( b3Pos_zero, offset ); + b3BoxHull local = b3MakeBoxHull( 5.0f, 5.0f, 5.0f ); + b3ShapeProxy localProxy = { local.boxPoints, local.base.vertexCount, 0.0f }; + int localHits = 0; + b3World_OverlapShape( worldId, origin, &localProxy, filter, CountOverlapCallback, &localHits ); + + ENSURE( bakedHits == 1 ); + ENSURE( localHits == bakedHits ); + } + + // Clearing target: same box far from the body, both formulations agree on the miss. + { + b3Vec3 offset = { 100.0f, 0.0f, 0.0f }; + + b3BoxHull baked = b3MakeTransformedBoxHull( 5.0f, 5.0f, 5.0f, (b3Transform){ offset, b3Quat_identity } ); + b3ShapeProxy bakedProxy = { baked.boxPoints, baked.base.vertexCount, 0.0f }; + int bakedHits = 0; + b3World_OverlapShape( worldId, b3Pos_zero, &bakedProxy, filter, CountOverlapCallback, &bakedHits ); + + b3Pos origin = b3OffsetPos( b3Pos_zero, offset ); + b3BoxHull local = b3MakeBoxHull( 5.0f, 5.0f, 5.0f ); + b3ShapeProxy localProxy = { local.boxPoints, local.base.vertexCount, 0.0f }; + int localHits = 0; + b3World_OverlapShape( worldId, origin, &localProxy, filter, CountOverlapCallback, &localHits ); + + ENSURE( bakedHits == 0 ); + ENSURE( localHits == bakedHits ); + } + + b3DestroyWorld( worldId ); + return 0; +} + +// A quarter turn baked into the query hull must reach the overlap test. A long thin bar hits a body +// off the origin when aligned along X and clears it once rotated to lie along Z. +static int OverlapHullProxyRotation( void ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + b3WorldId worldId = b3CreateWorld( &worldDef ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_staticBody; + bodyDef.position = (b3Pos){ 3.0f, 0.0f, 0.0f }; + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + + b3World_Step( worldId, 1.0f / 60.0f, 1 ); + + b3QueryFilter filter = b3DefaultQueryFilter(); + + // Bar long in local X, centered at the origin, reaches the body at x = 3. + b3BoxHull aligned = b3MakeTransformedBoxHull( 4.0f, 0.3f, 0.3f, b3Transform_identity ); + b3ShapeProxy alignedProxy = { aligned.boxPoints, aligned.base.vertexCount, 0.0f }; + int alignedHits = 0; + b3World_OverlapShape( worldId, b3Pos_zero, &alignedProxy, filter, CountOverlapCallback, &alignedHits ); + ENSURE( alignedHits == 1 ); + + // Rotated a quarter turn about Y the long axis points along Z, so the bar no longer reaches x = 3. + b3Quat q = b3MakeQuatFromAxisAngle( (b3Vec3){ 0.0f, 1.0f, 0.0f }, 0.5f * B3_PI ); + b3BoxHull turned = b3MakeTransformedBoxHull( 4.0f, 0.3f, 0.3f, (b3Transform){ b3Vec3_zero, q } ); + b3ShapeProxy turnedProxy = { turned.boxPoints, turned.base.vertexCount, 0.0f }; + int turnedHits = 0; + b3World_OverlapShape( worldId, b3Pos_zero, &turnedProxy, filter, CountOverlapCallback, &turnedHits ); + ENSURE( turnedHits == 0 ); + + b3DestroyWorld( worldId ); + return 0; +} + // CollideMover ----------------------------------------------------------------------------- static int MoverTouchesBox( void ) @@ -474,6 +582,8 @@ int BodyQueryTest( void ) RUN_SUBTEST( OverlapFalse ); RUN_SUBTEST( OverlapRespectsBodyTransform ); RUN_SUBTEST( OverlapFilter ); + RUN_SUBTEST( OverlapHullProxyEquivalence ); + RUN_SUBTEST( OverlapHullProxyRotation ); RUN_SUBTEST( MoverTouchesBox ); RUN_SUBTEST( MoverSeparated ); diff --git a/test/test_hull.c b/test/test_hull.c index 9860d97..e4f2458 100644 --- a/test/test_hull.c +++ b/test/test_hull.c @@ -409,6 +409,107 @@ static int CreateHullMergeChurnStressTest( void ) return 0; } +// b3ComputeCosSin is a coarse approximation, so build rotations from libm to keep the +// analytic corner and plane positions exact. +static b3Quat ExactQuat( b3Vec3 axis, float radians ) +{ + float half = 0.5f * radians; + float s = sinf( half ); + return (b3Quat){ { s * axis.x, s * axis.y, s * axis.z }, cosf( half ) }; +} + +// Corner sign pattern baked by b3MakeTransformedBoxHull, in order. +static const b3Vec3 s_boxCornerSigns[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 }, +}; + +// The baked box hull is only exercised elsewhere through mass properties, which are analytic +// and never read boxPoints or boxPlanes. Pin the geometry itself against the transform so an +// axis swap in the point or plane bake cannot pass silently. +static int CheckTransformedBox( b3Vec3 h, b3Transform xf ) +{ + b3BoxHull box = b3MakeTransformedBoxHull( h.x, h.y, h.z, xf ); + + const float tol = 1e-5f; + + // Each corner is the transform of the signed half extent. + for ( int i = 0; i < 8; ++i ) + { + b3Vec3 local = { s_boxCornerSigns[i].x * h.x, s_boxCornerSigns[i].y * h.y, s_boxCornerSigns[i].z * h.z }; + b3Vec3 expected = b3TransformPoint( xf, local ); + ENSURE_SMALL( box.boxPoints[i].x - expected.x, tol ); + ENSURE_SMALL( box.boxPoints[i].y - expected.y, tol ); + ENSURE_SMALL( box.boxPoints[i].z - expected.z, tol ); + } + + // Face normals rotate with the box, offsets carry the rotated normal through the translation. + b3Vec3 localNormals[6] = { + b3Neg( b3Vec3_axisX ), b3Vec3_axisX, b3Neg( b3Vec3_axisY ), b3Vec3_axisY, b3Neg( b3Vec3_axisZ ), b3Vec3_axisZ, + }; + float localOffsets[6] = { h.x, h.x, h.y, h.y, h.z, h.z }; + for ( int i = 0; i < 6; ++i ) + { + b3Vec3 n = b3RotateVector( xf.q, localNormals[i] ); + float offset = localOffsets[i] + b3Dot( n, xf.p ); + ENSURE_SMALL( box.boxPlanes[i].normal.x - n.x, tol ); + ENSURE_SMALL( box.boxPlanes[i].normal.y - n.y, tol ); + ENSURE_SMALL( box.boxPlanes[i].normal.z - n.z, tol ); + ENSURE_SMALL( box.boxPlanes[i].offset - offset, tol ); + } + + // SoA vertex mirrors match the AoS points on all eight lanes. + for ( int i = 0; i < 8; ++i ) + { + ENSURE_SMALL( box.vx[i] - box.boxPoints[i].x, tol ); + ENSURE_SMALL( box.vy[i] - box.boxPoints[i].y, tol ); + ENSURE_SMALL( box.vz[i] - box.boxPoints[i].z, tol ); + } + + // SoA normal mirrors carry the six real faces and zero the two pad lanes. + for ( int i = 0; i < 6; ++i ) + { + ENSURE_SMALL( box.nx[i] - box.boxPlanes[i].normal.x, tol ); + ENSURE_SMALL( box.ny[i] - box.boxPlanes[i].normal.y, tol ); + ENSURE_SMALL( box.nz[i] - box.boxPlanes[i].normal.z, tol ); + } + ENSURE( box.nx[6] == 0.0f && box.nx[7] == 0.0f ); + ENSURE( box.ny[6] == 0.0f && box.ny[7] == 0.0f ); + ENSURE( box.nz[6] == 0.0f && box.nz[7] == 0.0f ); + + // The stored AABB bounds every baked corner. + b3AABB pointBox = b3MakeAABB( box.boxPoints, 8, 0.0f ); + ENSURE( b3AABB_Contains( box.base.aabb, pointBox ) ); + + return 0; +} + +static int TransformedBoxHullTest( void ) +{ + b3Vec3 h = { 0.25f, 0.5f, 0.3f }; + + // Identity. + if ( CheckTransformedBox( h, b3Transform_identity ) ) + return 1; + + // Translation only. + b3Transform translated = { { 0.4f, -0.7f, 0.1f }, b3Quat_identity }; + if ( CheckTransformedBox( h, translated ) ) + return 1; + + // Rotation only. A quarter turn about Y swaps the world X and Z extents. + b3Transform rotated = { b3Vec3_zero, ExactQuat( b3Vec3_axisY, 0.25f * B3_PI ) }; + if ( CheckTransformedBox( h, rotated ) ) + return 1; + + // Translation and rotation together. + b3Transform transformed = { { 3.0f, -2.0f, 1.5f }, ExactQuat( b3Vec3_axisZ, 0.25f * B3_PI ) }; + if ( CheckTransformedBox( h, transformed ) ) + return 1; + + return 0; +} + static int CreateHullDegenerateTest( void ) { // Real (non-null) buffer; pointCount < 4 cases are guarded inside Construct(). @@ -456,6 +557,7 @@ int HullTest( void ) RUN_SUBTEST( CreateHullSphereStressTest ); RUN_SUBTEST( CreateHullMergeChurnStressTest ); RUN_SUBTEST( CreateHullDegenerateTest ); + RUN_SUBTEST( TransformedBoxHullTest ); return 0; } diff --git a/test/test_manifold.c b/test/test_manifold.c index b178b9a..117af56 100644 --- a/test/test_manifold.c +++ b/test/test_manifold.c @@ -1117,6 +1117,133 @@ static int CapsuleHullSeamTest( void ) return 0; } +// A capsule core straddling a triangle face inside the interior. The core pierces the plane so the +// deep path runs, and with the tilt kept small the face stays the axis of minimum penetration, so the +// clip must return two points on the triangle face. This is the branch that had no coverage. +static int CapsuleTriangleFaceDeepTest( void ) +{ + // Triangle in the y = 0 plane, normal +y, centroid at the origin + b3Vec3 v1 = { -3.0f, 0.0f, -2.0f }; + b3Vec3 v2 = { 0.0f, 0.0f, 4.0f }; + b3Vec3 v3 = { 3.0f, 0.0f, -2.0f }; + b3Vec3 triangle[] = { v1, v2, v3 }; + + float yaws[] = { 0.0f, 0.6f, 1.2f, 1.8f, 2.4f }; + float tilts[] = { 0.06f, 0.1f, 0.15f }; + float radii[] = { 0.05f, 0.1f, 0.2f }; + + // Bias the center just above the plane so the back side cull passes while the lower endpoint dips through + float bias = 0.01f; + float halfLength = 1.0f; + + int faceContacts = 0; + + for ( int i = 0; i < ARRAY_COUNT( yaws ); ++i ) + { + for ( int j = 0; j < ARRAY_COUNT( tilts ); ++j ) + { + for ( int r = 0; r < ARRAY_COUNT( radii ); ++r ) + { + // Axis is the in-plane heading tipped up so the segment straddles the plane + b3Vec3 axis = { cosf( tilts[j] ) * cosf( yaws[i] ), sinf( tilts[j] ), cosf( tilts[j] ) * sinf( yaws[i] ) }; + b3Vec3 center = { 0.0f, bias, 0.0f }; + b3Vec3 c1 = b3MulAdd( center, -halfLength, axis ); + b3Vec3 c2 = b3MulAdd( center, halfLength, axis ); + b3Capsule capsule = { c1, c2, radii[r] }; + + b3LocalManifoldPoint points[8]; + b3LocalManifold manifold = { 0 }; + manifold.points = points; + b3SimplexCache cache = { 0 }; + b3CollideTriangleAndCapsule( &manifold, 8, triangle, &capsule, &cache ); + + // Two points on the triangle face with the plane normal + ENSURE( manifold.pointCount == 2 ); + ENSURE( manifold.feature == b3_featureTriangleFace ); + ENSURE_SMALL( manifold.normal.x, 1e-5f ); + ENSURE_SMALL( manifold.normal.y - 1.0f, 1e-5f ); + ENSURE_SMALL( manifold.normal.z, 1e-5f ); + + // Separations are the endpoint heights pulled in by the radius. The lower endpoint is below + // the plane, so the deepest separation is negative. + float lower = b3MinFloat( c1.y, c2.y ) - radii[r]; + float upper = b3MaxFloat( c1.y, c2.y ) - radii[r]; + float minSep = b3MinFloat( manifold.points[0].separation, manifold.points[1].separation ); + float maxSep = b3MaxFloat( manifold.points[0].separation, manifold.points[1].separation ); + ENSURE_SMALL( minSep - lower, 1e-5f ); + ENSURE_SMALL( maxSep - upper, 1e-5f ); + ENSURE( minSep < 0.0f ); + + ++faceContacts; + } + } + } + + // Every configuration must reach the face path + ENSURE( faceContacts == ARRAY_COUNT( yaws ) * ARRAY_COUNT( tilts ) * ARRAY_COUNT( radii ) ); + + return 0; +} + +// A capsule laid flat with its core below a box top face. The core sits inside the box so the deep +// path runs, and across a sweep of depths, headings and radii the face clip must return two points. +static int HullCapsuleFaceDeepTest( void ) +{ + b3BoxHull hull = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + + float depths[] = { 0.1f, 0.2f, 0.3f, 0.4f, 0.45f }; + float yaws[] = { 0.0f, 0.4f, 0.8f, 1.2f }; + float radii[] = { 0.1f, 0.15f, 0.2f }; + float offsets[] = { -0.1f, 0.0f, 0.1f }; + float halfLength = 0.3f; + + int faceContacts = 0; + + for ( int i = 0; i < ARRAY_COUNT( depths ); ++i ) + { + for ( int j = 0; j < ARRAY_COUNT( yaws ); ++j ) + { + for ( int r = 0; r < ARRAY_COUNT( radii ); ++r ) + { + for ( int o = 0; o < ARRAY_COUNT( offsets ); ++o ) + { + float y = depths[i]; + b3Vec3 dir = { cosf( yaws[j] ), 0.0f, sinf( yaws[j] ) }; + b3Vec3 center = { offsets[o], y, 0.0f }; + b3Vec3 c1 = b3MulAdd( center, -halfLength, dir ); + b3Vec3 c2 = b3MulAdd( center, halfLength, dir ); + b3Capsule capsule = { c1, c2, radii[r] }; + + b3LocalManifoldPoint points[8]; + b3LocalManifold manifold = { 0 }; + manifold.points = points; + b3SimplexCache cache = { 0 }; + b3CollideHullAndCapsule( &manifold, 8, &hull.base, &capsule, b3Transform_identity, &cache ); + + // Two points on the top face. The hull path does not tag a feature, so the face is + // identified by the normal and the point count. + ENSURE( manifold.pointCount == 2 ); + ENSURE_SMALL( manifold.normal.x, 1e-5f ); + ENSURE_SMALL( manifold.normal.y - 1.0f, 1e-5f ); + ENSURE_SMALL( manifold.normal.z, 1e-5f ); + + // Flat capsule, so both points sit at the same analytic gap + float expected = ( y - 0.5f ) - radii[r]; + ENSURE_SMALL( manifold.points[0].separation - expected, 1e-5f ); + ENSURE_SMALL( manifold.points[1].separation - expected, 1e-5f ); + ENSURE( expected < 0.0f ); + + ++faceContacts; + } + } + } + } + + ENSURE( faceContacts == ARRAY_COUNT( depths ) * ARRAY_COUNT( yaws ) * ARRAY_COUNT( radii ) * ARRAY_COUNT( offsets ) ); + + return 0; +} + int ManifoldTest( void ) { RUN_SUBTEST( CrossedEdgeTest ); @@ -1134,6 +1261,8 @@ int ManifoldTest( void ) RUN_SUBTEST( HullCapsuleEdgeDeepTest ); RUN_SUBTEST( TriangleHullEdgeSweepTest ); RUN_SUBTEST( CapsuleTriangleEdgeDeepTest ); + RUN_SUBTEST( CapsuleTriangleFaceDeepTest ); + RUN_SUBTEST( HullCapsuleFaceDeepTest ); RUN_SUBTEST( SphereHullSeamTest ); RUN_SUBTEST( CapsuleHullSeamTest ); diff --git a/test/test_recording.c b/test/test_recording.c index 9307e55..0101a91 100644 --- a/test/test_recording.c +++ b/test/test_recording.c @@ -1117,8 +1117,11 @@ static int AllOps( void ) b3BodyId meshBodyId = b3CreateBody( worldId, &meshBodyDef ); b3MeshData* meshData = b3CreateGridMesh( 3, 3, 2.0f, 0, false ); ENSURE( meshData != NULL ); + b3MeshData* swapMeshData = b3CreateGridMesh( 4, 4, 1.5f, 0, false ); + ENSURE( swapMeshData != NULL ); b3ShapeDef meshShapeDef = b3DefaultShapeDef(); - b3CreateMeshShape( meshBodyId, &meshShapeDef, meshData, (b3Vec3){ 1.0f, 1.0f, 1.0f } ); + b3ShapeId meshShapeId = b3CreateMeshShape( meshBodyId, &meshShapeDef, meshData, (b3Vec3){ 1.0f, 1.0f, 1.0f } ); + ENSURE( b3Shape_IsValid( meshShapeId ) ); b3BodyDef hfBodyDef = b3DefaultBodyDef(); hfBodyDef.type = b3_staticBody; @@ -1150,9 +1153,9 @@ static int AllOps( void ) b3ShapeId tmpShapeId = b3CreateSphereShape( capsuleBodyId, &capsuleShapeDef, &tmpSphere ); b3DestroyShape( tmpShapeId, true ); - // Shape mutators: SetFriction, SetRestitution, SetDensity, SetSurfaceMaterial, SetFilter, - // EnableSensorEvents, EnableContactEvents, EnableHitEvents, EnablePreSolveEvents, ApplyWind, - // SetSphere, SetCapsule, SetName + // Shape mutators: SetFriction, SetRestitution, SetDensity, SetSurfaceMaterial, SetMeshMaterial, + // SetFilter, EnableSensorEvents, EnableContactEvents, EnableHitEvents, EnablePreSolveEvents, + // ApplyWind, SetSphere, SetCapsule, SetHull, SetMesh, SetName b3Shape_SetFriction( boxShapeId, 0.3f ); b3Shape_SetRestitution( capsuleShapeId, 0.5f ); b3Shape_SetDensity( boxShapeId, 3.0f, true ); @@ -1174,6 +1177,14 @@ static int AllOps( void ) b3Shape_SetCapsule( capsuleShapeId, &newCapsule ); b3Shape_SetName( boxShapeId, "box" ); + // Geometry swaps intern into the registry at the record site. The repeated SetHull takes the + // shared hull short circuit, which changes nothing and so must leave the stream alone. + b3BoxHull swapHull = b3MakeBoxHull( 0.3f, 0.7f, 0.4f ); + b3Shape_SetHull( boxShapeId, &swapHull.base ); + b3Shape_SetHull( boxShapeId, &swapHull.base ); + b3Shape_SetMesh( meshShapeId, swapMeshData, (b3Vec3){ 1.0f, 1.0f, 1.0f } ); + b3Shape_SetMeshMaterial( meshShapeId, surfMat, 0 ); + // Body mutators: SetTransform, SetLinearVelocity/AngularVelocity (Vec3), SetName, // damping, gravity scale, sleep threshold, SetAwake, EnableSleep, SetBullet, SetMotionLocks, // SetMassData, ApplyMassFromShapes, SetType, SetTargetTransform, Disable/Enable, EnableContactRecycling, @@ -1453,6 +1464,7 @@ static int AllOps( void ) // Free geometry allocated for this subtest b3DestroyHull( customHull ); b3DestroyMesh( meshData ); + b3DestroyMesh( swapMeshData ); b3DestroyHeightField( hf ); b3DestroyCompound( compound ); @@ -1679,7 +1691,7 @@ static int GeometryHashCollision( void ) uint32_t idA = b3InternGeometry( ®, b3_geometryHull, sharedHash, blobA, n ); uint32_t idB = b3InternGeometry( ®, b3_geometryHull, sharedHash, blobB, n ); ENSURE( idA != idB ); - ENSURE( reg.count == 2 ); + ENSURE( reg.entries.count == 2 ); // Re-interning either blob must find it through the hash chain and never grow the registry, // including the one shadowed behind the bucket head. The old single-entry lookup missed the @@ -1687,12 +1699,12 @@ static int GeometryHashCollision( void ) uint8_t* blobA2 = (uint8_t*)b3Alloc( (size_t)n ); memset( blobA2, 0xAA, (size_t)n ); ENSURE( b3InternGeometry( ®, b3_geometryHull, sharedHash, blobA2, n ) == idA ); - ENSURE( reg.count == 2 ); + ENSURE( reg.entries.count == 2 ); uint8_t* blobB2 = (uint8_t*)b3Alloc( (size_t)n ); memset( blobB2, 0xBB, (size_t)n ); ENSURE( b3InternGeometry( ®, b3_geometryHull, sharedHash, blobB2, n ) == idB ); - ENSURE( reg.count == 2 ); + ENSURE( reg.entries.count == 2 ); b3FreeRegistry( ® ); @@ -1712,10 +1724,10 @@ static int GeometryHashCollision( void ) uint8_t* live = (uint8_t*)b3Alloc( (size_t)n ); memset( live, 0xAA, (size_t)n ); uint32_t resolved = b3InternGeometry( &seeded, b3_geometryHull, sharedHash, live, n ); - ENSURE( seeded.count == 3 ); // no growth + ENSURE( seeded.entries.count == 3 ); // no growth ENSURE( resolved == 0 || resolved == 2 ); // a valid slot index for that content - ENSURE( seeded.entries[resolved].byteCount == n ); - ENSURE( memcmp( seeded.entries[resolved].bytes, slot0, (size_t)n ) == 0 ); + ENSURE( seeded.entries.data[resolved].byteCount == n ); + ENSURE( memcmp( seeded.entries.data[resolved].bytes, slot0, (size_t)n ) == 0 ); b3FreeRegistry( &seeded ); return 0; @@ -1924,6 +1936,147 @@ static int ShapeNameReplay( void ) return 0; } +// A box sliding across a mesh floor, with the option to swap both geometries and retune a +// per-triangle material part way through. Returns the final state hash so the caller can prove the +// mutations move the simulation. Recording is optional so the same scene serves as the control. +static uint64_t RunGeometryMutatorScene( b3Recording* rec, bool mutate, const b3MeshData* meshA, const b3MeshData* meshB, + const b3HullData* swapHull, float swapFriction ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + worldDef.workerCount = 1; + b3WorldId worldId = b3CreateWorld( &worldDef ); + + if ( rec != NULL ) + { + b3World_StartRecording( worldId, rec ); + } + + // The mesh body is created first so its ordinal is stable for the read back after replay. + b3SurfaceMaterial meshMaterials[2] = { b3DefaultSurfaceMaterial(), b3DefaultSurfaceMaterial() }; + meshMaterials[1].friction = 0.05f; + + b3BodyDef meshBodyDef = b3DefaultBodyDef(); + meshBodyDef.type = b3_staticBody; + b3BodyId meshBodyId = b3CreateBody( worldId, &meshBodyDef ); + + b3ShapeDef meshShapeDef = b3DefaultShapeDef(); + meshShapeDef.materials = meshMaterials; + meshShapeDef.materialCount = 2; + b3ShapeId meshShapeId = b3CreateMeshShape( meshBodyId, &meshShapeDef, meshA, (b3Vec3){ 1.0f, 1.0f, 1.0f } ); + + b3BodyDef boxBodyDef = b3DefaultBodyDef(); + boxBodyDef.type = b3_dynamicBody; + boxBodyDef.position = (b3Pos){ -2.0f, 2.0f, 0.0f }; + boxBodyDef.linearVelocity = (b3Vec3){ 4.0f, 0.0f, 0.0f }; + b3BodyId boxBodyId = b3CreateBody( worldId, &boxBodyDef ); + + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + b3ShapeDef boxShapeDef = b3DefaultShapeDef(); + boxShapeDef.density = 1.0f; + b3ShapeId boxShapeId = b3CreateHullShape( boxBodyId, &boxShapeDef, &box.base ); + + float timeStep = 1.0f / 60.0f; + for ( int i = 0; i < 10; ++i ) + { + b3World_Step( worldId, timeStep, 4 ); + } + + if ( mutate ) + { + b3Shape_SetHull( boxShapeId, swapHull ); + b3Shape_SetMesh( meshShapeId, meshB, (b3Vec3){ 1.0f, 1.0f, 1.0f } ); + + b3SurfaceMaterial grippy = b3DefaultSurfaceMaterial(); + grippy.friction = swapFriction; + b3Shape_SetMeshMaterial( meshShapeId, grippy, 1 ); + } + + for ( int i = 0; i < 30; ++i ) + { + b3World_Step( worldId, timeStep, 4 ); + } + + uint64_t hash = b3HashWorldState( b3GetWorldFromId( worldId ) ); + + if ( rec != NULL ) + { + b3World_StopRecording( worldId ); + } + b3DestroyWorld( worldId ); + + return hash; +} + +// Swapping a shape's hull or mesh, or retuning one of its per-triangle materials, is a world +// mutation like any other and has to ride the stream. The geometry pair interns into the registry +// at the record site so replay rebuilds the same shape instead of running on the geometry it was +// created with. The control run proves the mutations move the simulation, so the state hash gate +// has teeth, and the read back covers each op on its own where dynamics alone would not. +static int GeometryMutatorReplay( void ) +{ + // Two flat floors with different triangulations, both carrying two material slots so the + // material index stays live across the swap. + b3MeshData* meshA = b3CreateGridMesh( 8, 8, 2.0f, 2, false ); + ENSURE( meshA != NULL ); + b3MeshData* meshB = b3CreateGridMesh( 12, 12, 1.5f, 2, false ); + ENSURE( meshB != NULL ); + ENSURE( meshA->triangleCount != meshB->triangleCount ); + + b3BoxHull swapHull = b3MakeBoxHull( 0.25f, 1.5f, 0.25f ); + const float swapFriction = 0.95f; + + uint64_t controlHash = RunGeometryMutatorScene( NULL, false, meshA, meshB, &swapHull.base, swapFriction ); + + b3Recording* rec = b3CreateRecording( 0 ); + ENSURE( rec != NULL ); + uint64_t mutatedHash = RunGeometryMutatorScene( rec, true, meshA, meshB, &swapHull.base, swapFriction ); + + // Without this the replay gate below could pass on a recording that never carried the ops. + ENSURE( mutatedHash != controlHash ); + + const uint8_t* data = b3Recording_GetData( rec ); + int size = b3Recording_GetSize( rec ); + ENSURE( size > 0 ); + + ENSURE( b3ValidateReplay( data, size, 1 ) ); + ENSURE( b3ValidateReplay( data, size, 4 ) ); + + b3RecPlayer* player = b3RecPlayer_Create( data, size, 1 ); + ENSURE( player != NULL ); + while ( b3RecPlayer_StepFrame( player ) ) + { + } + ENSURE( b3RecPlayer_HasDiverged( player ) == false ); + + // Body ordinals follow creation order in the replayed world. + b3BodyId replayMeshBody = b3RecPlayer_GetBodyId( player, 0 ); + b3BodyId replayBoxBody = b3RecPlayer_GetBodyId( player, 1 ); + ENSURE( b3Body_IsValid( replayMeshBody ) && b3Body_IsValid( replayBoxBody ) ); + + b3ShapeId replayMeshShape; + ENSURE( b3Body_GetShapes( replayMeshBody, &replayMeshShape, 1 ) == 1 ); + b3ShapeId replayBoxShape; + ENSURE( b3Body_GetShapes( replayBoxBody, &replayBoxShape, 1 ) == 1 ); + + const b3HullData* replayHull = b3Shape_GetHull( replayBoxShape ); + ENSURE( replayHull != NULL ); + ENSURE( replayHull->hash == swapHull.base.hash ); + + b3Mesh replayMesh = b3Shape_GetMesh( replayMeshShape ); + ENSURE( replayMesh.data != NULL ); + ENSURE( replayMesh.data->hash == meshB->hash ); + ENSURE( replayMesh.data->triangleCount == meshB->triangleCount ); + + b3SurfaceMaterial replayMaterial = b3Shape_GetMeshSurfaceMaterial( replayMeshShape, 1 ); + ENSURE( replayMaterial.friction == swapFriction ); + + b3RecPlayer_Destroy( player ); + b3DestroyRecording( rec ); + b3DestroyMesh( meshA ); + b3DestroyMesh( meshB ); + return 0; +} + int RecordingTest( void ) { RUN_SUBTEST( GeometryHashCollision ); @@ -1942,6 +2095,7 @@ int RecordingTest( void ) RUN_SUBTEST( QueryReplay ); RUN_SUBTEST( TaggedQuery ); RUN_SUBTEST( TransformedHullRoundTrip ); + RUN_SUBTEST( GeometryMutatorReplay ); RUN_SUBTEST( AllOps ); RUN_SUBTEST( ReservedHeaderBytes ); return 0;