From 146966401f61d6b3387689124dd105806967d051 Mon Sep 17 00:00:00 2001 From: Erin Catto Date: Tue, 17 Nov 2026 10:00:53 -0800 Subject: [PATCH] manifold cap --- benchmark/mesh_soak.c | 92 ++++++++++--- benchmark/soak_baseline.csv | 4 + include/box3d/constants.h | 28 ++-- samples/sample.cpp | 8 +- samples/sample_continuous.cpp | 41 +++++- samples/sample_mesh.cpp | 246 ++++++++++++++++++++++++++++++++++ shared/mesh_drop.c | 92 +++++++++---- shared/mesh_drop.h | 25 +++- src/constraint_graph.c | 2 +- src/mesh_contact.c | 98 +++++++++++++- src/physics_world.c | 28 +--- src/physics_world.h | 16 +-- src/world_snapshot.c | 3 +- 13 files changed, 564 insertions(+), 119 deletions(-) diff --git a/benchmark/mesh_soak.c b/benchmark/mesh_soak.c index f696682..3727c9d 100644 --- a/benchmark/mesh_soak.c +++ b/benchmark/mesh_soak.c @@ -6,7 +6,8 @@ // or the pile is still awake at the step limit. Tunnels are rare, so the soak also counts bodies that // sink into the wave past a few depth levels and can compare those counts against a baseline. // Generations run in parallel, one single threaded world per thread. The printed seed reproduces a -// generation in the sample. +// generation in the sample. The rough wave has bumps smaller than the bodies, so mesh contacts reach +// the manifold cap. It is far slower per generation, so run it with fewer of them. #define _CRT_SECURE_NO_WARNINGS @@ -77,6 +78,10 @@ typedef struct Soak int failureCount; long long totalSteps; int maxSteps; + + // Mesh contact updates by manifold count, rough wave only + long long manifoldCounts[B3_CONTACT_MANIFOLD_COUNT_BUCKETS]; + ShapeStats stats[e_meshDropShapeCount]; Failure failures[MAX_REPORTED_FAILURES]; } Soak; @@ -100,7 +105,7 @@ static void RecordFailure( Soak* soak, const Failure* failure ) // Mirrors MeshDrop::Generate and the auto generate step loop. Returns the step count. static int RunGeneration( Soak* soak, int generation, uint32_t seed, MeshDropShape shape, b3BodyId* bodies, - MeshDropDepth* depth, int* failureKind ) + MeshDropDepth* depth, int* failureKind, long long* manifoldCounts ) { b3WorldDef worldDef = b3DefaultWorldDef(); worldDef.workerCount = 1; @@ -115,7 +120,7 @@ static int RunGeneration( Soak* soak, int generation, uint32_t seed, MeshDropSha b3World_SetContactRecycleDistance( worldId, 0.0f ); } - CreateMeshDropGround( worldId, soak->groundMesh ); + CreateMeshDropGround( worldId, soak->groundMesh, soak->settings ); MeshDropSettings settings = soak->settings; settings.shape = shape; @@ -135,6 +140,16 @@ static int RunGeneration( Soak* soak, int generation, uint32_t seed, MeshDropSha UpdateMeshDropDepth( worldId, depth ); step += 1; + // Counters walk the world, so only pay for them where the cap matters + if ( soak->settings.rough ) + { + b3Counters counters = b3World_GetCounters( worldId ); + for ( int i = 0; i < B3_CONTACT_MANIFOLD_COUNT_BUCKETS; ++i ) + { + manifoldCounts[i] += counters.manifoldCounts[i]; + } + } + for ( int i = 0; i < MESH_DROP_BODY_COUNT; ++i ) { b3Pos center = b3Body_GetWorldCenter( bodies[i] ); @@ -203,7 +218,8 @@ static void SoakWorker( void* context ) soak->shapeFilter >= 0 ? (MeshDropShape)soak->shapeFilter : (MeshDropShape)( generation % e_meshDropShapeCount ); int failureKind = -1; - int steps = RunGeneration( soak, generation, seed, shape, bodies, depth, &failureKind ); + long long manifoldCounts[B3_CONTACT_MANIFOLD_COUNT_BUCKETS] = { 0 }; + int steps = RunGeneration( soak, generation, seed, shape, bodies, depth, &failureKind, manifoldCounts ); int depthCounts[MESH_DROP_DEPTH_LEVEL_COUNT]; GetMeshDropDepthCounts( depth, depthCounts ); @@ -212,6 +228,10 @@ static void SoakWorker( void* context ) soak->completedCount += 1; soak->totalSteps += steps; soak->maxSteps = b3MaxInt( soak->maxSteps, steps ); + for ( int i = 0; i < B3_CONTACT_MANIFOLD_COUNT_BUCKETS; ++i ) + { + soak->manifoldCounts[i] += manifoldCounts[i]; + } ShapeStats* stats = soak->stats + shape; stats->generationCount += 1; @@ -247,15 +267,24 @@ static void SoakWorker( void* context ) free( bodies ); } -static const char* GetFilterName( int shapeFilter ) +// The rough wave gets its own names so its baseline rows never match a run on the broad wave +static const char* GetFilterName( int shapeFilter, bool rough ) { - return shapeFilter >= 0 ? g_meshDropShapeNames[shapeFilter] : "all"; + static const char* roughNames[e_meshDropShapeCount] = { "rough_box", "rough_capsule", "rough_cylinder", "rough_sphere" }; + + if ( shapeFilter < 0 ) + { + return rough ? "rough_all" : "all"; + } + + return rough ? roughNames[shapeFilter] : g_meshDropShapeNames[shapeFilter]; } // A baseline row starts with the run that made it, so one file can hold several runs static void GetBaselineKey( const Soak* soak, char* key, int size ) { - snprintf( key, size, "%s,%u,%d,", GetFilterName( soak->shapeFilter ), soak->baseSeed, soak->generationCount ); + snprintf( key, size, "%s,%u,%d,", GetFilterName( soak->shapeFilter, soak->settings.rough ), soak->baseSeed, + soak->generationCount ); } // Replaces the rows of this run and keeps the rest @@ -327,8 +356,8 @@ static void WriteBaseline( const Soak* soak, const char* path ) continue; } - fprintf( file, "%s,%u,%d,%s,%d,%d", GetFilterName( soak->shapeFilter ), soak->baseSeed, soak->generationCount, - g_meshDropShapeNames[shape], stats->tunnelCount, stats->awakeCount ); + fprintf( file, "%s,%u,%d,%s,%d,%d", GetFilterName( soak->shapeFilter, soak->settings.rough ), soak->baseSeed, + soak->generationCount, g_meshDropShapeNames[shape], stats->tunnelCount, stats->awakeCount ); for ( int i = 0; i < MESH_DROP_DEPTH_LEVEL_COUNT; ++i ) { fprintf( file, ",%d", stats->depthCounts[i] ); @@ -378,7 +407,7 @@ static int CompareBaseline( const Soak* soak, const char* path ) continue; } - if ( strcmp( filter, GetFilterName( soak->shapeFilter ) ) != 0 || base != soak->baseSeed || + if ( strcmp( filter, GetFilterName( soak->shapeFilter, soak->settings.rough ) ) != 0 || base != soak->baseSeed || generations != soak->generationCount ) { continue; @@ -440,8 +469,8 @@ static int CompareBaseline( const Soak* soak, const char* path ) if ( matchedCount == 0 ) { - printf( "%s has no rows for -s=%s -b=%u -g=%d\n", path, GetFilterName( soak->shapeFilter ), soak->baseSeed, - soak->generationCount ); + printf( "%s has no rows for %s-s=%s -b=%u -g=%d\n", path, soak->settings.rough ? "--rough " : "", + GetFilterName( soak->shapeFilter, false ), soak->baseSeed, soak->generationCount ); return 2; } @@ -474,6 +503,7 @@ int main( int argc, char** argv ) uint32_t seed = (uint32_t)b3GetTicks(); bool fixedSeed = false; bool recycling = true; + bool amplitudeSet = false; const char* writePath = NULL; const char* comparePath = NULL; MeshDropSettings settings = GetDefaultMeshDropSettings(); @@ -525,6 +555,11 @@ int main( int argc, char** argv ) else if ( ( value = MatchValue( arg, "-a=", "--amplitude=" ) ) != NULL ) { settings.amplitude = (float)atof( value ); + amplitudeSet = true; + } + else if ( strcmp( arg, "--rough" ) == 0 ) + { + settings.rough = true; } else if ( ( value = MatchValue( arg, "-w=", "--write=" ) ) != NULL ) { @@ -549,9 +584,10 @@ int main( int argc, char** argv ) " -s, --shape= box, capsule, cylinder, sphere or all (default box)\n" " -b, --base-seed= base seed, each generation hashes its own seed from it (default random)\n" " --seed= run every generation with this exact seed (replay)\n" - " -a, --amplitude= wave amplitude (default 0.5)\n" + " -a, --amplitude= wave amplitude (default 0.5, rough 0.015)\n" + " --rough fine bumps smaller than the bodies, reaches the manifold cap\n" " -w, --write= write the counts as a baseline, replacing only the rows of this run\n" - " -c, --compare= compare the counts with the baseline rows from the same -s, -b and -g\n" + " -c, --compare= compare the counts with the baseline rows from the same wave, -s, -b and -g\n" " --no-recycling disable contact recycling\n" "Exit code is 0 when every generation passes and no count grew past noise, 1 otherwise,\n" "2 for bad arguments or a baseline from a different run.\n", @@ -560,6 +596,11 @@ int main( int argc, char** argv ) } } + if ( settings.rough && amplitudeSet == false ) + { + settings.amplitude = GetMeshDropDefaultAmplitude( true ); + } + if ( fixedSeed && ( writePath != NULL || comparePath != NULL ) ) { printf( "a baseline needs a base seed, not --seed\n" ); @@ -570,7 +611,7 @@ int main( int argc, char** argv ) soak.mutex = b3CreateMutex(); soak.settings = settings; soak.recycling = recycling; - soak.groundMesh = CreateMeshDropMesh( settings.amplitude ); + soak.groundMesh = CreateMeshDropMesh( settings ); soak.cylinder = CreateMeshDropCylinder(); soak.baseSeed = seed; soak.fixedSeed = fixedSeed; @@ -583,8 +624,8 @@ int main( int argc, char** argv ) soak.stats[i].maxGeneration = INT32_MAX; } - printf( "mesh soak: %d generations, %d threads, shape %s, %s seed %u\n", generationCount, threadCount, - GetFilterName( shapeFilter ), fixedSeed ? "fixed" : "base", seed ); + printf( "mesh soak: %d generations, %d threads, %sshape %s, %s seed %u\n", generationCount, threadCount, + settings.rough ? "rough wave, " : "", GetFilterName( shapeFilter, false ), fixedSeed ? "fixed" : "base", seed ); fflush( stdout ); uint64_t ticks = b3GetTicks(); @@ -641,6 +682,23 @@ int main( int argc, char** argv ) printf( "\nsteps to sleep: average %.0f, max %d, time %.1f s\n", averageSteps, soak.maxSteps, seconds ); + if ( settings.rough ) + { + long long total = 0; + for ( int i = 0; i < B3_CONTACT_MANIFOLD_COUNT_BUCKETS; ++i ) + { + total += soak.manifoldCounts[i]; + } + + // The last bucket is the cap, so it holds every contact that was reduced + printf( "contact updates by manifold count:" ); + for ( int i = 0; i < B3_CONTACT_MANIFOLD_COUNT_BUCKETS; ++i ) + { + printf( " %d: %.1f%%", i + 1, total > 0 ? 100.0 * soak.manifoldCounts[i] / total : 0.0 ); + } + printf( "\n" ); + } + int reported = b3MinInt( soak.failureCount, MAX_REPORTED_FAILURES ); for ( int i = 0; i < reported; ++i ) { diff --git a/benchmark/soak_baseline.csv b/benchmark/soak_baseline.csv index ab4be06..f364117 100644 --- a/benchmark/soak_baseline.csv +++ b/benchmark/soak_baseline.csv @@ -7,3 +7,7 @@ all,12345,1000,box,0,0,1503,218,3,0 all,12345,1000,capsule,0,0,14507,3488,28,0 all,12345,1000,cylinder,0,0,10859,2193,36,0 all,12345,1000,sphere,0,0,56,0,0,0 +rough_all,12345,1000,box,0,0,2107,535,6,0 +rough_all,12345,1000,capsule,0,0,3603,177,1,0 +rough_all,12345,1000,cylinder,0,0,3239,726,21,0 +rough_all,12345,1000,sphere,0,0,0,0,0,0 diff --git a/include/box3d/constants.h b/include/box3d/constants.h index 8e8c3e3..2c8eb16 100644 --- a/include/box3d/constants.h +++ b/include/box3d/constants.h @@ -14,9 +14,9 @@ B3_API void b3SetLengthUnitsPerMeter( float lengthUnits ); /// Get the current length units per meter. B3_API float b3GetLengthUnitsPerMeter( void ); -// Used to detect bad values. In float mode positions greater than about 16km have precision -// problems, so 100km is a safe limit. Large world mode keeps coordinates accurate much farther -// from the origin, so the sanity limit widens to keep valid far-field positions from tripping it. +/// Used to detect bad values. In float mode positions greater than about 16km have precision +/// problems, so 100km is a safe limit. Large world mode keeps coordinates accurate much farther +/// from the origin, so the sanity limit widens to keep valid far-field positions from tripping it. #if defined( BOX3D_DOUBLE_PRECISION ) #define B3_HUGE ( 1.0e9f * b3GetLengthUnitsPerMeter() ) #else @@ -32,18 +32,22 @@ B3_API float b3GetLengthUnitsPerMeter( void ); /// size array for Box3D task, which may help with creating stable user task pointers. #define B3_MAX_TASKS 256 -// Maximum number of colors in the constraint graph. Constraints that cannot -// find a color are added to the overflow set which are solved single-threaded. -// The compound barrel benchmark has minor overflow with 24 colors +/// Maximum number of colors in the constraint graph. Constraints that cannot +/// find a color are added to the overflow set which are solved single-threaded. +/// The compound barrel benchmark has minor overflow with 24 colors #define B3_GRAPH_COLOR_COUNT 24 -// Number of contact point buckets for counting the number of contact points per -// shape contact pair. This is just for reporting and doesn't affect simulation. -#define B3_CONTACT_MANIFOLD_COUNT_BUCKETS 8 +/// The maximum number of contact manifolds between shape pairs. Extra manifolds are +/// dropped using heuristics until this number is reached. +#define B3_MAX_MANIFOLDS 8 -// A small length used as a collision and constraint tolerance. Usually it is -// chosen to be numerically significant, but visually insignificant. In meters. -// @warning modifying this can have a significant impact on stability +/// Number of contact point buckets for counting the number of contact points per +/// shape contact pair. This is just for reporting and doesn't affect simulation. +#define B3_CONTACT_MANIFOLD_COUNT_BUCKETS B3_MAX_MANIFOLDS + +/// A small length used as a collision and constraint tolerance. Usually it is +/// chosen to be numerically significant, but visually insignificant. In meters. +/// @warning modifying this can have a significant impact on stability #define B3_LINEAR_SLOP ( 0.005f * b3GetLengthUnitsPerMeter() ) /// The minimum length of a capsules. Very short capsules should be created as spheres diff --git a/samples/sample.cpp b/samples/sample.cpp index cff7428..0d16f9a 100644 --- a/samples/sample.cpp +++ b/samples/sample.cpp @@ -1088,9 +1088,8 @@ void Sample::DrawMetrics() ImGui::Text( "toi %d / %d / %d", s.distanceIterations, s.pushBackIterations, s.rootIterations ); ImGui::SetItemTooltip( "TOI distance / push back / root iterations" ); - // The world clamps into the second to last bucket, so the last is always empty and the - // second to last means that many or more - constexpr int manifoldBarCount = manifoldBucketCount - 1; + // One bucket per manifold count, up to the cap + constexpr int manifoldBarCount = manifoldBucketCount; int totalManifolds = 0; int maxManifolds = 0; ImU32 manifoldColors[manifoldBarCount]; @@ -1107,8 +1106,7 @@ void Sample::DrawMetrics() DrawBarChart( "##manifolds", s.manifoldCounts, manifoldColors, manifoldBarCount, maxManifolds, manifoldSize ); if ( hoveredBucket >= 0 ) { - const char* plus = hoveredBucket == manifoldBarCount - 1 ? "+" : ""; - ImGui::SetTooltip( "%d%s manifolds: %d of %d pairs", hoveredBucket + 1, plus, s.manifoldCounts[hoveredBucket], + ImGui::SetTooltip( "%d manifolds: %d of %d pairs", hoveredBucket + 1, s.manifoldCounts[hoveredBucket], totalManifolds ); } diff --git a/samples/sample_continuous.cpp b/samples/sample_continuous.cpp index fc4d506..6397573 100644 --- a/samples/sample_continuous.cpp +++ b/samples/sample_continuous.cpp @@ -388,19 +388,23 @@ public: static int sampleNeedleMesh = RegisterSample( "Continuous", "Needle Mesh", NeedleMesh::Create ); +// The rough wave has bumps smaller than the bodies, so a mesh contact reaches the manifold cap. Registered +// a second time as Rough Mesh Drop with that wave on. class MeshDrop : public Sample { public: - explicit MeshDrop( SampleContext* context ) + MeshDrop( SampleContext* context, bool rough ) : Sample( context ) { if ( context->restart == false ) { - m_camera->SetView( 0.0f, 30.0f, 20.0f, b3Pos_zero ); + m_camera->SetView( 0.0f, 30.0f, rough ? 12.0f : 20.0f, b3Pos_zero ); GetGuiDraw()->forceScale = 0.1f; } m_settings = GetDefaultMeshDropSettings(); + m_settings.rough = rough; + m_settings.amplitude = GetMeshDropDefaultAmplitude( rough ); m_groundId = b3_nullBodyId; m_groundMesh = nullptr; CreateGround(); @@ -440,8 +444,8 @@ public: m_groundMesh = nullptr; } - m_groundMesh = CreateMeshDropMesh( m_settings.amplitude ); - m_groundId = CreateMeshDropGround( m_worldId, m_groundMesh ); + m_groundMesh = CreateMeshDropMesh( m_settings ); + m_groundId = CreateMeshDropGround( m_worldId, m_groundMesh, m_settings ); } void Generate() @@ -484,7 +488,17 @@ public: Generate(); } - if ( ImGui::SliderFloat( "Amplitude", &m_settings.amplitude, 0.0f, 1.0f ) ) + if ( ImGui::Checkbox( "Rough", &m_settings.rough ) ) + { + m_settings.amplitude = GetMeshDropDefaultAmplitude( m_settings.rough ); + CreateGround(); + Generate(); + } + + // The rough mesh is slow to build, so wait for the slider to settle + float maxAmplitude = m_settings.rough ? 0.05f : 1.0f; + bool amplitudeChanged = ImGui::SliderFloat( "Amplitude", &m_settings.amplitude, 0.0f, maxAmplitude, "%.3f" ); + if ( m_settings.rough ? ImGui::IsItemDeactivatedAfterEdit() : amplitudeChanged ) { CreateGround(); Generate(); @@ -546,6 +560,15 @@ public: DrawTextLine( "seed %u", m_seed ); + // The last bucket is the cap, so it holds every contact that was reduced + b3Counters counters = b3World_GetCounters( m_worldId ); + int contactCount = 0; + for ( int i = 0; i < B3_CONTACT_MANIFOLD_COUNT_BUCKETS; ++i ) + { + contactCount += counters.manifoldCounts[i]; + } + DrawTextLine( "contacts at the manifold cap: %d of %d", counters.manifoldCounts[B3_MAX_MANIFOLDS - 1], contactCount ); + if ( m_depth.maxIndex >= 0 ) { int index = m_depth.maxIndex; @@ -612,7 +635,12 @@ public: static Sample* Create( SampleContext* context ) { - return new MeshDrop( context ); + return new MeshDrop( context, false ); + } + + static Sample* CreateRough( SampleContext* context ) + { + return new MeshDrop( context, true ); } MeshDropSettings m_settings; @@ -630,6 +658,7 @@ public: }; static int sampleMeshDrop = RegisterSample( "Continuous", "Mesh Drop", MeshDrop::Create ); +static int sampleRoughMeshDrop = RegisterSample( "Continuous", "Rough Mesh Drop", MeshDrop::CreateRough ); // This sample shows that clustering based on the manifold normal can lead to clipping and/or tunneling. class HumpMesh : public Sample diff --git a/samples/sample_mesh.cpp b/samples/sample_mesh.cpp index 983d802..38f5c67 100644 --- a/samples/sample_mesh.cpp +++ b/samples/sample_mesh.cpp @@ -1626,3 +1626,249 @@ public: static int sampleHollowBox = RegisterSample( "Mesh", "Hollow Box", HollowBox::Create ); +// A sphere fitted inside an inward facing sphere mesh. Every triangle is in range and every contact +// normal is different, so the manifolds cannot be merged. From a voxel cavity filled with wedged debris. +// The sphere should stay inside and go to sleep. +class WedgedSphere : public Sample +{ +public: + explicit WedgedSphere( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 45.0f, 20.0f, 4.0f, b3Pos_zero ); + } + + m_mesh = nullptr; + m_groundId = b3_nullBodyId; + m_bodyId = b3_nullBodyId; + m_subdivisions = 3; + m_fit = 5.0f; + + Build(); + } + + ~WedgedSphere() override + { + b3DestroyMesh( m_mesh ); + } + + static void Subdivide( std::vector& vertices, b3Vec3 a, b3Vec3 b, b3Vec3 c, int depth ) + { + if ( depth == 0 ) + { + vertices.push_back( a ); + vertices.push_back( b ); + vertices.push_back( c ); + return; + } + + b3Vec3 ab = b3Normalize( b3Add( a, b ) ); + b3Vec3 bc = b3Normalize( b3Add( b, c ) ); + b3Vec3 ca = b3Normalize( b3Add( c, a ) ); + Subdivide( vertices, a, ab, ca, depth - 1 ); + Subdivide( vertices, ab, b, bc, depth - 1 ); + Subdivide( vertices, ca, bc, c, depth - 1 ); + Subdivide( vertices, ab, bc, ca, depth - 1 ); + } + + void Build() + { + if ( B3_IS_NON_NULL( m_bodyId ) ) + { + b3DestroyBody( m_bodyId ); + b3DestroyBody( m_groundId ); + b3DestroyMesh( m_mesh ); + } + + // Unit icosphere as a triangle soup, welded by the mesh builder + float t = 0.5f * ( 1.0f + sqrtf( 5.0f ) ); + b3Vec3 corners[12] = { + { -1.0f, t, 0.0f }, { 1.0f, t, 0.0f }, { -1.0f, -t, 0.0f }, { 1.0f, -t, 0.0f }, + { 0.0f, -1.0f, t }, { 0.0f, 1.0f, t }, { 0.0f, -1.0f, -t }, { 0.0f, 1.0f, -t }, + { t, 0.0f, -1.0f }, { t, 0.0f, 1.0f }, { -t, 0.0f, -1.0f }, { -t, 0.0f, 1.0f }, + }; + + int faces[20][3] = { + { 0, 11, 5 }, { 0, 5, 1 }, { 0, 1, 7 }, { 0, 7, 10 }, { 0, 10, 11 }, { 1, 5, 9 }, { 5, 11, 4 }, + { 11, 10, 2 }, { 10, 7, 6 }, { 7, 1, 8 }, { 3, 9, 4 }, { 3, 4, 2 }, { 3, 2, 6 }, { 3, 6, 8 }, + { 3, 8, 9 }, { 4, 9, 5 }, { 2, 4, 11 }, { 6, 2, 10 }, { 8, 6, 7 }, { 9, 8, 1 }, + }; + + std::vector vertices; + for ( int i = 0; i < 20; ++i ) + { + Subdivide( vertices, b3Normalize( corners[faces[i][0]] ), b3Normalize( corners[faces[i][1]] ), + b3Normalize( corners[faces[i][2]] ), m_subdivisions ); + } + + m_triangleCount = (int)vertices.size() / 3; + + // The flat faces sit inside the unit sphere. The closest one bounds the largest sphere that fits. + m_inscribedRadius = 1.0f; + std::vector indices( vertices.size() ); + for ( int i = 0; i < m_triangleCount; ++i ) + { + b3Vec3 a = vertices[3 * i + 0]; + b3Vec3 b = vertices[3 * i + 1]; + b3Vec3 c = vertices[3 * i + 2]; + b3Vec3 normal = b3Normalize( b3Cross( b3Sub( b, a ), b3Sub( c, a ) ) ); + m_inscribedRadius = b3MinFloat( m_inscribedRadius, b3AbsFloat( b3Dot( normal, a ) ) ); + + // Reverse the winding so the triangles face the center + indices[3 * i + 0] = 3 * i + 0; + indices[3 * i + 1] = 3 * i + 2; + indices[3 * i + 2] = 3 * i + 1; + } + + b3MeshDef meshDef = {}; + meshDef.vertices = vertices.data(); + meshDef.indices = indices.data(); + meshDef.vertexCount = (int)vertices.size(); + meshDef.triangleCount = m_triangleCount; + meshDef.weldVertices = true; + meshDef.weldTolerance = 1.0e-4f; + meshDef.identifyEdges = true; + m_mesh = b3CreateMesh( &meshDef, nullptr, 0 ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + m_groundId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateMeshShape( m_groundId, &shapeDef, m_mesh, b3Vec3_one ); + + bodyDef.type = b3_dynamicBody; + m_bodyId = b3CreateBody( m_worldId, &bodyDef ); + + m_radius = m_inscribedRadius + 0.001f * m_fit; + b3Sphere sphere = { b3Vec3_zero, m_radius }; + b3CreateSphereShape( m_bodyId, &shapeDef, &sphere ); + + m_buildStep = m_stepCount; + m_sleepStep = -1; + m_maxManifoldCount = 0; + m_maxOffset = 0.0f; + m_maxSpeed = 0.0f; + } + + bool DrawControls() override + { + bool rebuild = false; + + if ( ImGui::RadioButton( "320 triangles", m_subdivisions == 2 ) ) + { + m_subdivisions = 2; + rebuild = true; + } + + if ( ImGui::RadioButton( "1280 triangles", m_subdivisions == 3 ) ) + { + m_subdivisions = 3; + rebuild = true; + } + + if ( ImGui::RadioButton( "5120 triangles", m_subdivisions == 4 ) ) + { + m_subdivisions = 4; + rebuild = true; + } + + // Positive is a sphere larger than the cavity + ImGui::SliderFloat( "Fit (mm)", &m_fit, -20.0f, 20.0f, "%.0f" ); + rebuild = rebuild || ImGui::IsItemDeactivatedAfterEdit(); + + if ( ImGui::Button( "Reset" ) ) + { + rebuild = true; + } + + if ( rebuild ) + { + Build(); + } + + if ( ImGui::Button( "Kick" ) ) + { + b3Body_SetLinearVelocity( m_bodyId, { 6.0f, 7.0f, 3.9f } ); + b3Body_SetAwake( m_bodyId, true ); + m_sleepStep = -1; + } + + return true; + } + + void Step() override + { + Sample::Step(); + + int manifoldCount = 0; + b3ContactData contactData; + if ( b3Body_GetContactData( m_bodyId, &contactData, 1 ) == 1 ) + { + manifoldCount = contactData.manifoldCount; + } + + // Surface speed counts spin + b3Vec3 v = b3Body_GetLinearVelocity( m_bodyId ); + b3Vec3 w = b3Body_GetAngularVelocity( m_bodyId ); + float speed = b3Length( v ) + m_radius * b3Length( w ); + float offset = b3Length( b3SubPos( b3Body_GetPosition( m_bodyId ), b3Pos_zero ) ); + bool awake = b3Body_IsAwake( m_bodyId ); + + m_maxManifoldCount = b3MaxInt( m_maxManifoldCount, manifoldCount ); + m_maxOffset = b3MaxFloat( m_maxOffset, offset ); + m_maxSpeed = b3MaxFloat( m_maxSpeed, speed ); + + if ( awake ) + { + m_sleepStep = -1; + } + else if ( m_sleepStep < 0 ) + { + m_sleepStep = m_stepCount - m_buildStep; + } + + DrawTextLine( "triangles = %d, sphere radius = %.4f m, cavity radius = %.4f m", m_triangleCount, m_radius, + m_inscribedRadius ); + DrawTextLine( "manifolds = %d, max %d", manifoldCount, m_maxManifoldCount ); + DrawTextLine( "speed = %.3f m/s, max %.3f", speed, m_maxSpeed ); + DrawTextLine( "center offset = %.1f mm, max %.1f", 1000.0f * offset, 1000.0f * m_maxOffset ); + + if ( awake ) + { + DrawTextLine( "awake for %d steps", m_stepCount - m_buildStep ); + } + else + { + DrawTextLine( "asleep after %d steps", m_sleepStep ); + } + + // The center cannot leave the cavity unless the sphere tunnels + if ( m_maxOffset > m_inscribedRadius ) + { + DrawTextLine( "FAIL: tunneled" ); + } + } + + static Sample* Create( SampleContext* context ) + { + return new WedgedSphere( context ); + } + + b3MeshData* m_mesh; + b3BodyId m_groundId; + b3BodyId m_bodyId; + int m_subdivisions; + int m_triangleCount; + int m_buildStep; + int m_sleepStep; + int m_maxManifoldCount; + float m_fit; + float m_radius; + float m_inscribedRadius; + float m_maxOffset; + float m_maxSpeed; +}; + +static int sampleWedgedSphere = RegisterSample( "Mesh", "Wedged Sphere", WedgedSphere::Create ); diff --git a/shared/mesh_drop.c b/shared/mesh_drop.c index bf5df6e..0abdc7b 100644 --- a/shared/mesh_drop.c +++ b/shared/mesh_drop.c @@ -8,9 +8,19 @@ #include #include +#define WAVE_COUNT 40 #define WAVE_CELL_WIDTH 1.0f #define WAVE_ROW_FREQUENCY 0.1f #define WAVE_COLUMN_FREQUENCY 0.2f +#define WAVE_AMPLITUDE 0.5f + +// Bumps about 20 cm across, close to the curvature of the bodies, on cells a few times smaller. The cell +// width is a power of two so the mesh builder steps to the same vertices the depth tracker computes. +#define ROUGH_WAVE_COUNT 640 +#define ROUGH_CELL_WIDTH 0.03125f +#define ROUGH_ROW_FREQUENCY 4.7f +#define ROUGH_COLUMN_FREQUENCY 5.9f +#define ROUGH_AMPLITUDE 0.015f #define DROP_SPACING 0.5f #define DROP_HEIGHT 5.0f #define BODY_RADIUS 0.05f @@ -53,6 +63,27 @@ static uint32_t HashSeed( uint32_t x ) return x != 0 ? x : 1; } +typedef struct WaveGrid +{ + int count; + float cellWidth; + float rowFrequency; + float columnFrequency; +} WaveGrid; + +static WaveGrid GetWaveGrid( bool rough ) +{ + _Static_assert( ROUGH_WAVE_COUNT <= MESH_DROP_MAX_WAVE_COUNT && WAVE_COUNT <= MESH_DROP_MAX_WAVE_COUNT, + "wave count exceeds the depth tracker tables" ); + + if ( rough ) + { + return (WaveGrid){ ROUGH_WAVE_COUNT, ROUGH_CELL_WIDTH, ROUGH_ROW_FREQUENCY, ROUGH_COLUMN_FREQUENCY }; + } + + return (WaveGrid){ WAVE_COUNT, WAVE_CELL_WIDTH, WAVE_ROW_FREQUENCY, WAVE_COLUMN_FREQUENCY }; +} + static b3BoxHull MakeDropBox( void ) { // The soft contact solver cannot always resolve a smaller box at 4 sub-steps, and its size gets @@ -64,13 +95,19 @@ MeshDropSettings GetDefaultMeshDropSettings( void ) { MeshDropSettings settings = { .shape = e_meshDropBox, - .amplitude = 0.5f, + .amplitude = WAVE_AMPLITUDE, + .rough = false, .collide = false, .soloIndex = -1, }; return settings; } +float GetMeshDropDefaultAmplitude( bool rough ) +{ + return rough ? ROUGH_AMPLITUDE : WAVE_AMPLITUDE; +} + uint32_t GetMeshDropSeed( uint32_t baseSeed, int generation ) { return HashSeed( HashSeed( baseSeed ) + (uint32_t)generation ); @@ -86,10 +123,11 @@ float GetMeshDropTunnelHeight( void ) return -2.0f; } -b3MeshData* CreateMeshDropMesh( float amplitude ) +b3MeshData* CreateMeshDropMesh( MeshDropSettings settings ) { - return b3CreateWaveMesh( MESH_DROP_WAVE_COUNT, MESH_DROP_WAVE_COUNT, WAVE_CELL_WIDTH, amplitude, WAVE_ROW_FREQUENCY, - WAVE_COLUMN_FREQUENCY ); + WaveGrid grid = GetWaveGrid( settings.rough ); + return b3CreateWaveMesh( grid.count, grid.count, grid.cellWidth, settings.amplitude, grid.rowFrequency, + grid.columnFrequency ); } b3HullData* CreateMeshDropCylinder( void ) @@ -97,7 +135,7 @@ b3HullData* CreateMeshDropCylinder( void ) return b3CreateCylinder( 0.4f, BODY_RADIUS, 0.0f, 6 ); } -b3BodyId CreateMeshDropGround( b3WorldId worldId, const b3MeshData* mesh ) +b3BodyId CreateMeshDropGround( b3WorldId worldId, const b3MeshData* mesh, MeshDropSettings settings ) { b3BodyDef bodyDef = b3DefaultBodyDef(); b3BodyId groundId = b3CreateBody( worldId, &bodyDef ); @@ -106,7 +144,8 @@ b3BodyId CreateMeshDropGround( b3WorldId worldId, const b3MeshData* mesh ) shapeDef.filter.categoryBits = 1; b3CreateMeshShape( groundId, &shapeDef, mesh, b3Vec3_one ); - float extent = 0.5f * MESH_DROP_WAVE_COUNT * WAVE_CELL_WIDTH; + WaveGrid grid = GetWaveGrid( settings.rough ); + float extent = 0.5f * grid.count * grid.cellWidth; float halfHeight = 1.0f; b3Transform transforms[4] = { @@ -202,19 +241,18 @@ int GetMeshDropBodyIndex( void* userData ) void ResetMeshDropDepth( MeshDropDepth* depth, MeshDropSettings settings, const b3HullData* cylinder ) { // Same heights as b3CreateWaveMesh - float omegaZ = 2.0f * B3_PI * WAVE_ROW_FREQUENCY * WAVE_CELL_WIDTH; - float omegaX = 2.0f * B3_PI * WAVE_COLUMN_FREQUENCY * WAVE_CELL_WIDTH; - int index = 0; - for ( int ix = 0; ix <= MESH_DROP_WAVE_COUNT; ++ix ) + WaveGrid grid = GetWaveGrid( settings.rough ); + float omegaZ = 2.0f * B3_PI * grid.rowFrequency * grid.cellWidth; + float omegaX = 2.0f * B3_PI * grid.columnFrequency * grid.cellWidth; + for ( int i = 0; i <= grid.count; ++i ) { - float rowHeight = b3ComputeCosSin( omegaX * ix ).sine; - for ( int iz = 0; iz <= MESH_DROP_WAVE_COUNT; ++iz ) - { - float columnHeight = b3ComputeCosSin( omegaZ * iz ).sine; - depth->heights[index++] = settings.amplitude * rowHeight * columnHeight; - } + depth->rowHeights[i] = b3ComputeCosSin( omegaX * i ).sine; + depth->columnHeights[i] = b3ComputeCosSin( omegaZ * i ).sine; } + depth->waveCount = grid.count; + depth->cellWidth = grid.cellWidth; + depth->waveAmplitude = settings.amplitude; depth->amplitude = fabsf( settings.amplitude ); depth->probeCount = 0; depth->radius = 0.0f; @@ -272,20 +310,20 @@ void ResetMeshDropDepth( MeshDropDepth* depth, MeshDropSettings settings, const // it reads a little deep on a crest and shallow in a valley. static float GetWaveDistance( const MeshDropDepth* depth, b3Vec3 p ) { - float origin = -0.5f * MESH_DROP_WAVE_COUNT * WAVE_CELL_WIDTH; - float u = ( p.x - origin ) / WAVE_CELL_WIDTH; - float v = ( p.z - origin ) / WAVE_CELL_WIDTH; - int ix = b3ClampInt( (int)floorf( u ), 0, MESH_DROP_WAVE_COUNT - 1 ); - int iz = b3ClampInt( (int)floorf( v ), 0, MESH_DROP_WAVE_COUNT - 1 ); + float w = depth->cellWidth; + float origin = -0.5f * depth->waveCount * w; + float u = ( p.x - origin ) / w; + float v = ( p.z - origin ) / w; + int ix = b3ClampInt( (int)floorf( u ), 0, depth->waveCount - 1 ); + int iz = b3ClampInt( (int)floorf( v ), 0, depth->waveCount - 1 ); - int stride = MESH_DROP_WAVE_COUNT + 1; - float ha = depth->heights[ix * stride + iz]; - float hb = depth->heights[ix * stride + iz + 1]; - float hc = depth->heights[( ix + 1 ) * stride + iz + 1]; - float hd = depth->heights[( ix + 1 ) * stride + iz]; + float amplitude = depth->waveAmplitude; + float ha = amplitude * depth->rowHeights[ix] * depth->columnHeights[iz]; + float hb = amplitude * depth->rowHeights[ix] * depth->columnHeights[iz + 1]; + float hc = amplitude * depth->rowHeights[ix + 1] * depth->columnHeights[iz + 1]; + float hd = amplitude * depth->rowHeights[ix + 1] * depth->columnHeights[iz]; // The cell diagonal runs from a to c, matching b3CreateWaveMesh - float w = WAVE_CELL_WIDTH; b3Vec3 a = { origin + ix * w, ha, origin + iz * w }; b3Vec3 ac = { w, hc - ha, w }; b3Vec3 side = v - iz >= u - ix ? (b3Vec3){ 0.0f, hb - ha, w } : (b3Vec3){ w, hd - ha, 0.0f }; diff --git a/shared/mesh_drop.h b/shared/mesh_drop.h index 9c19dc0..621cb47 100644 --- a/shared/mesh_drop.h +++ b/shared/mesh_drop.h @@ -17,7 +17,8 @@ extern "C" // Mesh Drop scene, shared by the Continuous / Mesh Drop sample and the headless mesh soak. A generation // drops a grid of small bodies with random velocities on a wave mesh and steps until they sleep. A body // that falls out of the world tunneled. The depth tracker measures how far each body sinks into the -// wave, which flags contact trouble far more often than tunnels do. +// wave, which flags contact trouble far more often than tunnels do. The rough wave has bumps smaller than +// the bodies, so a body touches many triangles with different normals. typedef enum MeshDropShape { @@ -32,8 +33,8 @@ typedef enum MeshDropShape #define MESH_DROP_BODY_COUNT ( MESH_DROP_GRID_COUNT * MESH_DROP_GRID_COUNT ) #define MESH_DROP_DEPTH_LEVEL_COUNT 4 -// Wave mesh cells along x and z -#define MESH_DROP_WAVE_COUNT 40 +// Most wave mesh cells along x and z, reached by the rough wave +#define MESH_DROP_MAX_WAVE_COUNT 640 // Enough for the cylinder hull #define MESH_DROP_MAX_PROBES 16 @@ -48,6 +49,9 @@ typedef struct MeshDropSettings MeshDropShape shape; float amplitude; + // Fine bumps instead of the broad wave. The amplitude should be a few centimeters. + bool rough; + // Let the bodies collide with each other. Off isolates mesh collision. bool collide; @@ -57,6 +61,8 @@ typedef struct MeshDropSettings MeshDropSettings GetDefaultMeshDropSettings( void ); +float GetMeshDropDefaultAmplitude( bool rough ); + // Hashes the base before adding the generation, so nearby base seeds share no generations uint32_t GetMeshDropSeed( uint32_t baseSeed, int generation ); @@ -66,11 +72,11 @@ int GetMeshDropStepLimit( MeshDropShape shape ); // A body below this height tunneled float GetMeshDropTunnelHeight( void ); -b3MeshData* CreateMeshDropMesh( float amplitude ); +b3MeshData* CreateMeshDropMesh( MeshDropSettings settings ); b3HullData* CreateMeshDropCylinder( void ); // Creates a static body with the wave mesh and four walls -b3BodyId CreateMeshDropGround( b3WorldId worldId, const b3MeshData* mesh ); +b3BodyId CreateMeshDropGround( b3WorldId worldId, const b3MeshData* mesh, MeshDropSettings settings ); // Creates the bodies of one generation in grid order. Bodies left out by the solo index are null. The // body user data encodes the grid index, see GetMeshDropBodyIndex. @@ -82,8 +88,13 @@ int GetMeshDropBodyIndex( void* userData ); typedef struct MeshDropDepth { - // Wave heights at the mesh vertices - float heights[( MESH_DROP_WAVE_COUNT + 1 ) * ( MESH_DROP_WAVE_COUNT + 1 )]; + // Wave height factors at the mesh vertices along x and z. A vertex height is their product times + // the wave amplitude. + float rowHeights[MESH_DROP_MAX_WAVE_COUNT + 1]; + float columnHeights[MESH_DROP_MAX_WAVE_COUNT + 1]; + int waveCount; + float cellWidth; + float waveAmplitude; // Collision points in the body frame, rounded by the radius b3Vec3 probes[MESH_DROP_MAX_PROBES]; diff --git a/src/constraint_graph.c b/src/constraint_graph.c index c5e3d3e..749d0f4 100644 --- a/src/constraint_graph.c +++ b/src/constraint_graph.c @@ -154,7 +154,7 @@ void b3AddContactToGraph( b3World* world, b3Contact* contact ) if ( isScalar ) { - B3_ASSERT( contact->manifoldCount < UINT16_MAX ); + B3_ASSERT( contact->manifoldCount <= B3_MAX_MANIFOLDS ); b3ContactSpec spec = { .contactId = contact->contactId, .manifoldStart = 0, diff --git a/src/mesh_contact.c b/src/mesh_contact.c index c7437e5..5bcd149 100644 --- a/src/mesh_contact.c +++ b/src/mesh_contact.c @@ -1154,8 +1154,8 @@ static void b3CollideBoundaryEdge( b3LocalManifold* manifold, const b3Shape* sha static int b3CollideMeshTriangles( b3Cluster** clustersOut, const b3Shape* shapeA, const b3Shape* shapeB, b3Transform transformAtoB, b3TriangleCache* triangleCaches, int triangleCount, - bool enableSpeculative, bool handleGhosts, bool isFast, b3TaskContext* context, - b3Arena* arena ) + bool enableSpeculative, bool handleGhosts, bool isFast, int manifoldCapacity, + b3TaskContext* context, b3Arena* arena ) { *clustersOut = NULL; @@ -1647,6 +1647,93 @@ static int b3CollideMeshTriangles( b3Cluster** clustersOut, const b3Shape* shape return 0; } + if ( clusterCount > manifoldCapacity ) + { + float* clusterDepths = b3Bump( arena, clusterCount * sizeof( float ) ); + int* clusterRemap = b3Bump( arena, clusterCount * sizeof( int ) ); + for ( int i = 0; i < clusterCount; ++i ) + { + clusterDepths[i] = FLT_MAX; + clusterRemap[i] = B3_NULL_INDEX; + } + + for ( int i = 0; i < acceptedManifoldCount; ++i ) + { + const b3LocalManifold* manifold = acceptedManifolds[i]; + int clusterIndex = clusterMemberships[i]; + for ( int j = 0; j < manifold->pointCount; ++j ) + { + clusterDepths[clusterIndex] = b3MinFloat( clusterDepths[clusterIndex], manifold->points[j].separation ); + } + } + + int keptCount = 0; + + if ( manifoldCapacity >= 8 ) + { + int octantClusters[8] = { B3_NULL_INDEX, B3_NULL_INDEX, B3_NULL_INDEX, B3_NULL_INDEX, + B3_NULL_INDEX, B3_NULL_INDEX, B3_NULL_INDEX, B3_NULL_INDEX }; + for ( int i = 0; i < clusterCount; ++i ) + { + b3Vec3 normal = b3InvRotateVector( transformAtoB.q, clusters[i].manifoldNormal ); + int octant = ( normal.x > 0.0f ? 1 : 0 ) | ( normal.y > 0.0f ? 2 : 0 ) | ( normal.z > 0.0f ? 4 : 0 ); + int best = octantClusters[octant]; + if ( best == B3_NULL_INDEX || clusterDepths[i] < clusterDepths[best] ) + { + octantClusters[octant] = i; + } + } + + for ( int i = 0; i < 8; ++i ) + { + if ( octantClusters[i] != B3_NULL_INDEX ) + { + clusterRemap[octantClusters[i]] = 0; + keptCount += 1; + } + } + } + + while ( keptCount < manifoldCapacity ) + { + int best = B3_NULL_INDEX; + for ( int i = 0; i < clusterCount; ++i ) + { + if ( clusterRemap[i] != B3_NULL_INDEX ) + { + continue; + } + + if ( best == B3_NULL_INDEX || clusterDepths[i] < clusterDepths[best] ) + { + best = i; + } + } + + B3_ASSERT( best != B3_NULL_INDEX ); + clusterRemap[best] = 0; + keptCount += 1; + } + + keptCount = 0; + for ( int i = 0; i < clusterCount; ++i ) + { + if ( clusterRemap[i] != B3_NULL_INDEX ) + { + clusters[keptCount] = clusters[i]; + clusterRemap[i] = keptCount; + keptCount += 1; + } + } + + for ( int i = 0; i < acceptedManifoldCount; ++i ) + { + clusterMemberships[i] = clusterRemap[clusterMemberships[i]]; + } + + clusterCount = keptCount; + } + // Setup clusters b3LocalManifoldPoint* clusterPoints = b3Bump( arena, clusterPointCount * sizeof( b3LocalManifoldPoint ) ); int pointOffset = 0; @@ -1718,7 +1805,8 @@ bool b3ComputeMeshManifolds( b3World* world, int workerIndex, b3Contact* contact b3Cluster* clusters; int clusterCount = b3CollideMeshTriangles( &clusters, shapeA, shapeB, transformAtoB, meshContact->triangleCache.data, meshContact->triangleCache.count, - enableSpeculative, handleGhosts, isFast, context, &arena ); + enableSpeculative, handleGhosts, isFast, B3_MAX_MANIFOLDS, context, + &arena ); if ( clusterCount == 0 ) { @@ -1985,8 +2073,10 @@ static int b3CollideMeshAndShape( b3Manifold* manifolds, int capacity, const b3M b3Transform transformAtoB = b3InvertTransform( transformBtoA ); b3Cluster* clusters; + int manifoldCapacity = b3MinInt( capacity, B3_MAX_MANIFOLDS ); int clusterCount = b3CollideMeshTriangles( &clusters, &meshShape, shapeB, transformAtoB, triangleCaches, - triangleCount, enableSpeculative, handleGhosts, false, NULL, &arena ); + triangleCount, enableSpeculative, handleGhosts, false, manifoldCapacity, + NULL, &arena ); int count = b3MinInt( clusterCount, capacity ); b3Matrix3 matrixB = b3MakeMatrixFromQuat( transformBtoA.q ); diff --git a/src/physics_world.c b/src/physics_world.c index 2ec1812..a252b2d 100644 --- a/src/physics_world.c +++ b/src/physics_world.c @@ -488,18 +488,6 @@ void b3DestroyWorld( b3WorldId worldId ) b3DestroyNameCache( &world->names ); - // Pooled manifold arrays go with their block allocators below; directly allocated ones are freed here. - for ( int i = 0; i < world->contacts.count; ++i ) - { - b3Contact* contact = world->contacts.data + i; - if ( contact->contactId != B3_NULL_INDEX && contact->manifoldCount > B3_POOLED_MANIFOLD_COUNT ) - { - b3FreeManifolds( world, contact->manifolds, contact->manifoldCount ); - contact->manifolds = NULL; - contact->manifoldCount = 0; - } - } - b3Array_Destroy( world->shapes ); b3Array_Destroy( world->fatAABBs ); b3Array_Destroy( world->contacts ); @@ -736,7 +724,7 @@ static void b3CollideTask( int startIndex, int endIndex, int workerIndex, void* // Diagnostics taskContext->recycledContactCount += 1; - int bucketIndex = b3MinInt( manifoldCount, B3_CONTACT_MANIFOLD_COUNT_BUCKETS - 1 ); + int bucketIndex = b3MinInt( manifoldCount, B3_CONTACT_MANIFOLD_COUNT_BUCKETS ); if ( bucketIndex > 0 ) { taskContext->manifoldCounts[bucketIndex - 1] += 1; @@ -760,7 +748,7 @@ static void b3CollideTask( int startIndex, int endIndex, int workerIndex, void* transformA, shapeB, bodySimB->localCenter, transformB, isFast, taskContext->arena ); - int bucketIndex = b3MinInt( contact->manifoldCount, B3_CONTACT_MANIFOLD_COUNT_BUCKETS - 1 ); + int bucketIndex = b3MinInt( contact->manifoldCount, B3_CONTACT_MANIFOLD_COUNT_BUCKETS ); if ( bucketIndex > 0 ) { taskContext->manifoldCounts[bucketIndex - 1] += 1; @@ -2479,23 +2467,13 @@ static uint64_t b3GetWorldByteCount( b3World* world, bool log ) manifoldBlockBytes += b3Array_ByteCount( allocator->blocks ); manifoldBlockBytes += allocator->blocks.count * B3_BLOCK_SIZE * allocator->elementSize; } - int64_t manifoldDirectBytes = 0; - for ( int i = 0; i < world->contacts.count; ++i ) - { - const b3Contact* contact = world->contacts.data + i; - if ( contact->contactId != B3_NULL_INDEX && contact->manifoldCount > B3_POOLED_MANIFOLD_COUNT ) - { - manifoldDirectBytes += (int64_t)contact->manifoldCount * sizeof( b3Manifold ); - } - } - total += (uint64_t)manifoldArrayBytes + manifoldBlockBytes + (uint64_t)manifoldDirectBytes; + total += (uint64_t)manifoldArrayBytes + manifoldBlockBytes; if ( log ) { b3Log( "manifold allocators" ); b3Log( "allocator array: %d", manifoldArrayBytes ); b3Log( "blocks: %d", manifoldBlockBytes ); - b3Log( "direct arrays: %" PRId64, manifoldDirectBytes ); } // solver sets diff --git a/src/physics_world.h b/src/physics_world.h index 0a571ce..e3bfed6 100644 --- a/src/physics_world.h +++ b/src/physics_world.h @@ -346,11 +346,6 @@ const b3HullData* b3AddOwnedHullToDatabase( b3World* world, b3HullData* owned ); // Release a reference to a shared hull. The owned copy is freed when the count reaches zero. void b3RemoveHullFromDatabase( b3World* world, const b3HullData* data ); -// Manifold arrays up to this count come from per-count block allocators, which the world keeps until it is destroyed. -// Larger arrays are rare (a dynamic shape on a finely cut triangle mesh), and a block allocator per count up to one -// of them would hold memory quadratic in the largest count ever seen, so they are allocated and freed directly. -#define B3_POOLED_MANIFOLD_COUNT 8 - static inline b3Manifold* b3AllocateManifolds( b3World* world, int count ) { if ( count == 0 ) @@ -358,10 +353,7 @@ static inline b3Manifold* b3AllocateManifolds( b3World* world, int count ) return NULL; } - if ( count > B3_POOLED_MANIFOLD_COUNT ) - { - return (b3Manifold*)b3AllocZero( count * sizeof( b3Manifold ) ); - } + B3_ASSERT( count <= B3_MAX_MANIFOLDS ); int index = count - 1; @@ -388,11 +380,7 @@ static inline void b3FreeManifolds( b3World* world, b3Manifold* manifolds, int c return; } - if ( count > B3_POOLED_MANIFOLD_COUNT ) - { - b3Free( manifolds, count * sizeof( b3Manifold ) ); - return; - } + B3_ASSERT( count <= B3_MAX_MANIFOLDS ); int index = count - 1; b3LockMutex( world->manifoldAllocatorMutex ); diff --git a/src/world_snapshot.c b/src/world_snapshot.c index 4ce5240..1faf2d1 100644 --- a/src/world_snapshot.c +++ b/src/world_snapshot.c @@ -925,7 +925,8 @@ static void b3DesContacts( b3SnapReader* r, b3World* world ) if ( isLive && manifoldCount > 0 ) { - if ( b3SnapCheckCount( r, manifoldCount, (int)sizeof( b3Manifold ), (int)sizeof( b3Manifold ) ) == false ) + if ( manifoldCount > B3_MAX_MANIFOLDS || + b3SnapCheckCount( r, manifoldCount, (int)sizeof( b3Manifold ), (int)sizeof( b3Manifold ) ) == false ) { r->ok = false; break;