Fixes 08 (#98)

- fix hull builder face and edge leak
- fix #95
- samples app will no longer crash if data folder is not found
This commit is contained in:
Erin Catto 2026-07-22 15:55:02 -07:00 • committed by GitHub
commit c52908c9a9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 307 additions and 153 deletions

View file

@ -96,13 +96,14 @@ static const b3JointId b3_nullJointId = B3_NULL_ID;
static const b3ContactId b3_nullContactId = B3_NULL_ID;
/// Macro to determine if any id is null.
#define B3_IS_NULL( id ) ( id.index1 == 0 )
#define B3_IS_NULL( id ) ( ( id ).index1 == 0 )
/// Macro to determine if any id is non-null.
#define B3_IS_NON_NULL( id ) ( id.index1 != 0 )
#define B3_IS_NON_NULL( id ) ( ( id ).index1 != 0 )
/// Compare two ids for equality. Doesn't work for b3WorldId. Don't mix types.
#define B3_ID_EQUALS( id1, id2 ) ( id1.index1 == id2.index1 && id1.world0 == id2.world0 && id1.generation == id2.generation )
#define B3_ID_EQUALS( id1, id2 ) \
( ( id1 ).index1 == ( id2 ).index1 && ( id1 ).world0 == ( id2 ).world0 && ( id1 ).generation == ( id2 ).generation )
/// Store a world id into a uint32_t.
B3_ID_INLINE uint32_t b3StoreWorldId( b3WorldId id )

View file

@ -10,40 +10,52 @@
#define TINYOBJLOADER_USE_MAPBOX_EARCUT
#include "tiny_obj_loader.h"
#include <iostream>
#include <stdio.h>
// Load a wavefront obj file using tiny obj loader and earcut for triangulation.
void LoadTempMesh( const char* path, TempMesh* tempMesh, float scale, bool zUp )
// A missing obj is refused rather than fatal, so the samples still run from a
// directory with no data beside them.
static bool ParseObjFile( tinyobj::ObjReader& reader, const char* path )
{
std::string inputFile = path;
tinyobj::ObjReaderConfig readerConfig;
readerConfig.triangulate = true;
readerConfig.mtl_search_path = "./"; // Path to material files
tinyobj::ObjReader reader;
if ( !reader.ParseFromFile( inputFile, readerConfig ) )
if ( reader.ParseFromFile( path, readerConfig ) == false )
{
if ( !reader.Error().empty() )
fprintf( stderr, "Failed to load mesh '%s'", path );
if ( reader.Error().empty() == false )
{
std::cerr << "TinyObjReader: " << reader.Error();
fprintf( stderr, ": %s", reader.Error().c_str() );
}
exit( 1 );
fprintf( stderr, "\n" );
return false;
}
if ( !reader.Warning().empty() )
if ( reader.Warning().empty() == false )
{
std::cout << "TinyObjReader: " << reader.Warning();
fprintf( stderr, "TinyObjReader: %s\n", reader.Warning().c_str() );
}
return true;
}
// Load a wavefront obj file using tiny obj loader and earcut for triangulation.
bool LoadTempMesh( const char* path, TempMesh* tempMesh, float scale, bool zUp )
{
tempMesh->vertices.clear();
tempMesh->indices.clear();
tempMesh->materialIndices.clear();
tinyobj::ObjReader reader;
if ( ParseObjFile( reader, path ) == false )
{
return false;
}
const tinyobj::attrib_t& attrib = reader.GetAttrib();
const std::vector<tinyobj::shape_t>& shapes = reader.GetShapes();
// const std::vector<tinyobj::material_t>& objMaterials = reader.GetMaterials();
tempMesh->vertices.clear();
tempMesh->indices.clear();
tempMesh->materialIndices.clear();
int vertexCount = int( attrib.vertices.size() / 3 );
for ( int i = 0; i < vertexCount; i++ )
{
@ -84,29 +96,16 @@ void LoadTempMesh( const char* path, TempMesh* tempMesh, float scale, bool zUp )
baseIndex += faceVertexCount;
}
}
return true;
}
b3MeshData* CreateMeshData( const char* path, float scale, bool zUp, bool useMedianSplit, bool identifyConvexEdges, bool weldVertices )
{
std::string inputFile = path;
tinyobj::ObjReaderConfig readerConfig;
readerConfig.triangulate = true;
readerConfig.mtl_search_path = "./"; // Path to material files
tinyobj::ObjReader reader;
if ( !reader.ParseFromFile( inputFile, readerConfig ) )
if ( ParseObjFile( reader, path ) == false )
{
if ( !reader.Error().empty() )
{
std::cerr << "TinyObjReader: " << reader.Error();
}
exit( 1 );
}
if ( !reader.Warning().empty() )
{
std::cout << "TinyObjReader: " << reader.Warning();
return nullptr;
}
const tinyobj::attrib_t& attrib = reader.GetAttrib();
@ -168,5 +167,18 @@ b3MeshData* CreateMeshData( const char* path, float scale, bool zUp, bool useMed
def.weldTolerance = 0.002f;
b3MeshData* meshData = b3CreateMesh( &def, nullptr, 0 );
if ( meshData == nullptr )
{
fprintf( stderr, "Mesh '%s' has no usable triangles\n", path );
}
return meshData;
}
void DestroyMeshData( b3MeshData* meshData )
{
if ( meshData != nullptr )
{
b3DestroyMesh( meshData );
}
}

View file

@ -8,9 +8,14 @@
#include <vector>
struct b3MeshData;
// Returns null if the mesh cannot be created.
b3MeshData* CreateMeshData( const char* path, float scale, bool zUp, bool useMedianSplit, bool identifyConvexEdges,
bool weldVertices );
// Null tolerant.
void DestroyMeshData( b3MeshData* meshData );
struct TempMesh
{
std::vector<b3Vec3> vertices;
@ -18,4 +23,4 @@ struct TempMesh
std::vector<uint8_t> materialIndices;
};
void LoadTempMesh( const char* path, TempMesh* tempMesh, float scale, bool zUp );
bool LoadTempMesh( const char* path, TempMesh* tempMesh, float scale, bool zUp );

View file

@ -44,18 +44,34 @@ static char* ReadFile( int& size, const char* filename )
}
fseek( file, 0, SEEK_END );
size = static_cast<int>( ftell( file ) );
long length = ftell( file );
fseek( file, 0, SEEK_SET );
if ( size == 0 )
if ( length <= 0 )
{
fclose( file );
return nullptr;
}
size = static_cast<int>( length );
char* data = (char*)malloc( size + 1 );
fread( data, size, 1, file );
if ( data == nullptr )
{
fclose( file );
return nullptr;
}
// Short read means a truncated or racing file, so treat it as no file at all
size_t read = fread( data, 1, size, file );
fclose( file );
if ( read != (size_t)size )
{
free( data );
return nullptr;
}
data[size] = 0;
return data;
@ -355,7 +371,13 @@ void Sample::FinishRecording()
}
b3World_StopRecording( m_worldId );
b3SaveRecordingToFile( m_recording, m_context->recordingFile );
// The buffer is freed either way, so a failed write has to be said out loud
if ( b3SaveRecordingToFile( m_recording, m_context->recordingFile ) == false )
{
fprintf( stderr, "Failed to write recording '%s'\n", m_context->recordingFile );
}
b3DestroyRecording( m_recording );
m_recording = nullptr;
}
@ -1349,13 +1371,20 @@ void OpenReplayFileDialog( SampleContext* context )
return;
}
NFD_Init();
if ( NFD_Init() != NFD_OKAY )
{
return;
}
nfdu8char_t* outPath = nullptr;
nfdu8filteritem_t filter[1] = { { "Box3D recording", "b3rec" } };
// Start in the working directory, where recordings are saved by default.
std::u8string cwd = std::filesystem::current_path().u8string();
const nfdu8char_t* defaultPath = reinterpret_cast<const nfdu8char_t*>( cwd.c_str() );
// Start in the working directory, where recordings are saved by default. A
// deleted or unreadable working directory just means no starting point.
std::error_code ec;
std::u8string cwd = std::filesystem::current_path( ec ).u8string();
const nfdu8char_t* defaultPath = ec ? nullptr : reinterpret_cast<const nfdu8char_t*>( cwd.c_str() );
if ( NFD_OpenDialogU8( &outPath, filter, 1, defaultPath ) == NFD_OKAY )
{
snprintf( context->replayFile, sizeof( context->replayFile ), "%s", outPath );

View file

@ -340,7 +340,10 @@ public:
shapeDef.materials = materials;
shapeDef.materialCount = 3;
b3CreateMeshShape( body, &shapeDef, m_levelMesh, b3Vec3_one );
if ( m_levelMesh != nullptr )
{
b3CreateMeshShape( body, &shapeDef, m_levelMesh, b3Vec3_one );
}
// b3Transform transform = { { 0.0f, 1.0f, 14.0f }, b3MakeQuatFromAxisAngle( b3Vec3_axisY, 0.75f * B3_PI ) };
// b3BoxHull box = b3MakeTransformedBoxHull( 5.0f, 1.0f, 0.5f, transform );
@ -371,7 +374,10 @@ public:
b3ShapeDef shapeDef = b3DefaultShapeDef();
b3BodyId body = b3CreateBody( m_worldId, &bodyDef );
b3CreateMeshShape( body, &shapeDef, m_stairs, { 0.75f, 0.75f, -1.5f } );
if ( m_stairs != nullptr )
{
b3CreateMeshShape( body, &shapeDef, m_stairs, { 0.75f, 0.75f, -1.5f } );
}
}
{
@ -530,9 +536,9 @@ public:
{
m_camera->m_thirdPerson = false;
sapp_lock_mouse( false );
b3DestroyMesh( m_levelMesh );
b3DestroyMesh( m_stairs );
b3DestroyMesh( m_torus );
DestroyMeshData( m_levelMesh );
DestroyMeshData( m_stairs );
DestroyMeshData( m_torus );
b3DestroyHeightField( m_heightField );
}
@ -1340,7 +1346,10 @@ public:
shapeDef.materials = materials;
shapeDef.materialCount = 3;
b3CreateMeshShape( body, &shapeDef, m_levelMesh, b3Vec3_one );
if ( m_levelMesh != nullptr )
{
b3CreateMeshShape( body, &shapeDef, m_levelMesh, b3Vec3_one );
}
}
// --- Stairs mesh ---
@ -1351,7 +1360,10 @@ public:
b3BodyId body = b3CreateBody( m_worldId, &bodyDef );
b3ShapeDef shapeDef = b3DefaultShapeDef();
b3CreateMeshShape( body, &shapeDef, m_stairs, { 0.75f, 0.75f, -1.5f } );
if ( m_stairs != nullptr )
{
b3CreateMeshShape( body, &shapeDef, m_stairs, { 0.75f, 0.75f, -1.5f } );
}
}
// --- High-poly building mesh ---
@ -1362,7 +1374,10 @@ public:
b3BodyId body = b3CreateBody( m_worldId, &bodyDef );
b3ShapeDef shapeDef = b3DefaultShapeDef();
b3CreateMeshShape( body, &shapeDef, m_building, b3Vec3_one );
if ( m_building != nullptr )
{
b3CreateMeshShape( body, &shapeDef, m_building, b3Vec3_one );
}
}
// --- Voxel meshes (dense tri terrain) ---
@ -1373,7 +1388,10 @@ public:
b3BodyId body = b3CreateBody( m_worldId, &bodyDef );
b3ShapeDef shapeDef = b3DefaultShapeDef();
b3CreateMeshShape( body, &shapeDef, m_voxel01, b3Vec3_one );
if ( m_voxel01 != nullptr )
{
b3CreateMeshShape( body, &shapeDef, m_voxel01, b3Vec3_one );
}
}
{
m_voxel02 = CreateMeshData( "data/meshes/voxel_mesh_02.obj", 1.0f, false, false, true, true );
@ -1382,7 +1400,10 @@ public:
b3BodyId body = b3CreateBody( m_worldId, &bodyDef );
b3ShapeDef shapeDef = b3DefaultShapeDef();
b3CreateMeshShape( body, &shapeDef, m_voxel02, b3Vec3_one );
if ( m_voxel02 != nullptr )
{
b3CreateMeshShape( body, &shapeDef, m_voxel02, b3Vec3_one );
}
}
// --- Height field terrain ---
@ -1494,11 +1515,11 @@ public:
{
m_camera->m_thirdPerson = false;
sapp_lock_mouse( false );
b3DestroyMesh( m_levelMesh );
b3DestroyMesh( m_stairs );
b3DestroyMesh( m_building );
b3DestroyMesh( m_voxel01 );
b3DestroyMesh( m_voxel02 );
DestroyMeshData( m_levelMesh );
DestroyMeshData( m_stairs );
DestroyMeshData( m_building );
DestroyMeshData( m_voxel01 );
DestroyMeshData( m_voxel02 );
b3DestroyHeightField( m_heightField );
}

View file

@ -574,9 +574,11 @@ public:
constexpr int materialCapacity = 5;
b3SurfaceMaterial meshMaterials[materialCapacity];
// Without the building mesh the village still stands, just with no buildings
b3MeshData* buildingMesh = CreateMeshData( "data/meshes/building.obj", 1.0f, false, false, true, true );
int materialCount = buildingMesh->materialCount;
int materialCount = buildingMesh != nullptr ? buildingMesh->materialCount : 0;
assert( materialCount <= materialCapacity );
for ( int i = 0; i < materialCount; ++i )
@ -593,11 +595,11 @@ public:
meshMaterials[i].userMaterialId = i + 42;
}
b3CompoundMeshDef* meshes = new b3CompoundMeshDef[meshCount];
b3CompoundMeshDef* meshes = buildingMesh != nullptr ? new b3CompoundMeshDef[meshCount] : nullptr;
transform = b3Transform_identity;
int meshIndex = 0;
for ( int i = 0; i < meshGridCount; ++i )
for ( int i = 0; meshes != nullptr && i < meshGridCount; ++i )
{
transform.p.x = ( 2.0f * i - meshGridCount ) * b + 0.5f * b;
@ -630,7 +632,7 @@ public:
}
}
assert( meshIndex == meshCount );
assert( meshes == nullptr || meshIndex == meshCount );
b3CompoundDef def = {};
def.capsules = capsules;
@ -639,7 +641,7 @@ public:
def.hulls = hulls;
def.hullCount = hullCount;
def.meshes = meshes;
def.meshCount = meshCount;
def.meshCount = meshIndex;
def.spheres = spheres;
def.sphereCount = sphereIndex;
@ -665,7 +667,7 @@ public:
delete[] spheres;
spheres = nullptr;
b3DestroyMesh( buildingMesh );
DestroyMeshData( buildingMesh );
}
m_rayOrigin = { -0.45f * m_worldWidth, 20.0f, -0.45f * m_worldWidth };

View file

@ -1,10 +1,10 @@
// SPDX-FileCopyrightText: 2025 Erin Catto
// SPDX-License-Identifier: MIT
#include "gfx/draw.h"
#include "imgui.h"
#include "mesh_loader.h"
#include "sample.h"
#include "gfx/draw.h"
#include "box3d/box3d.h"
@ -242,7 +242,6 @@ public:
if ( context->restart == false )
{
m_camera->SetView( 0.0f, 15.0f, 10.0f, { 0.0f, 2.0f, 0.0f } );
}
AddGroundBox( 10.0f );
@ -361,11 +360,11 @@ public:
b3ShapeDef shapeDef = b3DefaultShapeDef();
m_heightField = b3CreateGrid( 40, 40, { 0.5f, 1.0f, 0.5f }, false );
//m_heightField = b3CreateWave( 40, 40, {1.0f, 2.0f, 1.0f}, 0.02f, 0.04f, false );
// m_heightField = b3CreateWave( 40, 40, {1.0f, 2.0f, 1.0f}, 0.02f, 0.04f, false );
b3CreateHeightFieldShape( groundId, &shapeDef, m_heightField );
m_gridMesh = b3CreateGridMesh( 40, 40, 0.5f, 1, true );
//b3CreateMeshShape( groundId, &shapeDef, m_gridMesh, b3Vec3_one );
// b3CreateMeshShape( groundId, &shapeDef, m_gridMesh, b3Vec3_one );
}
{
@ -444,6 +443,7 @@ public:
// --- Building mesh on top of ground ---
m_building = CreateMeshData( "data/meshes/building.obj", 1.0f, false, false, true, true );
if ( m_building != nullptr )
{
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.position = { 0.0f, 0.1f, 0.0f };
@ -492,7 +492,6 @@ public:
static int sampleIndex = RegisterSample( "Issues", "Capsule Mesh", CapsuleMeshBug::Create );
// Reproduces s&box rigid body character ghost collisions on a FLAT floor.
//
// The s&box player is a fixed rotation dynamic body (zero radius box hull) moved by setting
@ -564,7 +563,7 @@ public:
b3ShapeDef shapeDef = b3DefaultShapeDef();
shapeDef.baseMaterial.friction = 0.0f;
shapeDef.baseMaterial.restitution = 0.0f;
//shapeDef.baseMaterial.customColor = b3_colorLimeGreen;
// shapeDef.baseMaterial.customColor = b3_colorLimeGreen;
float volume = 8.0f * m_bodyHalfWidth * m_bodyHalfHeight * m_bodyHalfWidth;
shapeDef.density = m_characterMass / volume;
@ -828,7 +827,7 @@ public:
}
else if ( position.z < -m_walkRangeZ )
{
m_walkDirectionZ= 1.0f;
m_walkDirectionZ = 1.0f;
}
b3Vec3 velocity = b3Body_GetLinearVelocity( m_characterId );
@ -1096,11 +1095,11 @@ public:
bodyDef.position = { 0.0f, startY + i * spacing, 0.0f };
b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef );
//for ( int h = 0; h < s_metalWheel1HullCount; ++h )
// for ( int h = 0; h < s_metalWheel1HullCount; ++h )
//{
// b3CreateHullShape( bodyId, &shapeDef, m_hulls[h] );
//}
// }
// Using a single hull improves the simulation.
b3CreateHullShape( bodyId, &shapeDef, wheelHull );
}
@ -1286,7 +1285,7 @@ public:
bodyDef.type = b3_dynamicBody;
bodyDef.position = { -boxOffset.x, 5.0f - boxOffset.y, -boxOffset.z };
bodyDef.rotation = orientation;
//bodyDef.angularVelocity = 25.0f * b3RotateVector( orientation, b3Vec3_axisY );
// bodyDef.angularVelocity = 25.0f * b3RotateVector( orientation, b3Vec3_axisY );
b3BodyId boxBody = b3CreateBody( m_worldId, &bodyDef );
b3BoxHull mBox = b3MakeOffsetBoxHull( 1.0f, 0.5f, 1.0f, boxLocalCenter );
shapeDef.baseMaterial.friction = 0.3f;

View file

@ -599,12 +599,17 @@ public:
bodyDef.position = { -10.0f, 0.0f, 0.0f };
b3BodyId body = b3CreateBody( m_worldId, &bodyDef );
b3CreateMeshShape( body, &meshShapeDef, m_buildingMesh, b3Vec3_one );
m_scale = { -1.0f, 1.0f, 1.0f };
bodyDef.position = { 10.0f, 0.0f, 0.0f };
m_meshBodyId = b3CreateBody( m_worldId, &bodyDef );
m_meshShapeId = b3CreateMeshShape( m_meshBodyId, &meshShapeDef, m_buildingMesh, m_scale );
m_meshShapeId = b3_nullShapeId;
if ( m_buildingMesh != nullptr )
{
b3CreateMeshShape( body, &meshShapeDef, m_buildingMesh, b3Vec3_one );
m_meshShapeId = b3CreateMeshShape( m_meshBodyId, &meshShapeDef, m_buildingMesh, m_scale );
}
}
bodyDef.type = b3_dynamicBody;
@ -652,7 +657,7 @@ public:
~MeshReflection() override
{
b3DestroyMesh( m_gridMesh );
b3DestroyMesh( m_buildingMesh );
DestroyMeshData( m_buildingMesh );
for ( int i = 0; i < e_humanCount; ++i )
{
@ -710,7 +715,10 @@ public:
{
m_scale = scale;
b3Shape_SetMesh( m_meshShapeId, m_buildingMesh, m_scale );
if ( m_buildingMesh != nullptr )
{
b3Shape_SetMesh( m_meshShapeId, m_buildingMesh, m_scale );
}
}
return true;
@ -1047,7 +1055,7 @@ public:
~MeshViewer() override
{
b3DestroyMesh( m_mesh );
DestroyMeshData( m_mesh );
}
void LoadMesh()
@ -1078,7 +1086,14 @@ public:
char buffer[64] = {};
snprintf( buffer, 64, "data/meshes/%s", filesNames[m_meshIndex] );
LoadTempMesh( buffer, &m_tempMesh, scale, true );
if ( LoadTempMesh( buffer, &m_tempMesh, scale, true ) == false )
{
m_buildTime = 0.0f;
m_area = 0.0f;
m_height = 0;
m_drawLevel = -1;
return;
}
b3MeshDef def = {};
def.vertices = m_tempMesh.vertices.data();
@ -1095,6 +1110,14 @@ public:
m_mesh = b3CreateMesh( &def, m_degenerateTriangles, m_degenerateCapacity );
m_buildTime = b3GetMilliseconds( startTicks );
if ( m_mesh == nullptr )
{
m_area = 0.0f;
m_height = 0;
m_drawLevel = -1;
return;
}
b3ShapeDef shapeDef = b3DefaultShapeDef();
b3CreateMeshShape( m_bodyId, &shapeDef, m_mesh, b3Vec3_one );
@ -1231,6 +1254,12 @@ public:
Sample::Render();
DrawAxes( b3WorldTransform_identity, 1.0f );
if ( m_mesh == nullptr )
{
DrawTextLine( "mesh failed to load" );
return;
}
DrawTextLine( "triangle count = %d", m_mesh->triangleCount );
DrawTextLine( "vertex count = %d", m_mesh->vertexCount );
DrawTextLine( "degenerate count = %d", m_mesh->degenerateCount );
@ -1347,6 +1376,11 @@ public:
def.weldTolerance = 0.0015f;
b3MeshData* meshData = b3CreateMesh( &def, nullptr, 0 );
if ( meshData == nullptr )
{
continue;
}
triangleCount += i == 0 ? meshData->triangleCount : 0;
if ( computeArea && i == 0 )
@ -1420,8 +1454,11 @@ public:
m_meshData = b3CreateMesh( &def, nullptr, 0 );
b3ShapeDef shapeDef = b3DefaultShapeDef();
b3CreateMeshShape( groundId, &shapeDef, m_meshData, b3Vec3_one );
if ( m_meshData != nullptr )
{
b3ShapeDef shapeDef = b3DefaultShapeDef();
b3CreateMeshShape( groundId, &shapeDef, m_meshData, b3Vec3_one );
}
}
{
@ -1475,7 +1512,7 @@ public:
~VoxelMesh() override
{
b3DestroyMesh( m_meshData );
DestroyMeshData( m_meshData );
}
void Step() override

View file

@ -499,9 +499,10 @@ public:
AddGroundBox( 20.0f );
// Mesh
{
m_meshData = CreateMeshData( "data/meshes/conveyor.obj", 1.0f, false, true, true, true );
m_meshData = CreateMeshData( "data/meshes/conveyor.obj", 1.0f, false, true, true, true );
if ( m_meshData != nullptr )
{
int triangleCount = m_meshData->triangleCount;
uint8_t* materialIndices = (uint8_t*)( (intptr_t)m_meshData + m_meshData->materialOffset );
@ -620,7 +621,7 @@ public:
~ConveyorMesh() override
{
b3DestroyMesh( m_meshData );
DestroyMeshData( m_meshData );
b3DestroyHull( m_cylinderHull );
}
@ -628,6 +629,11 @@ public:
{
Sample::Render();
if ( m_meshData == nullptr )
{
return;
}
int triangleCount = m_meshData->triangleCount;
const b3MeshTriangle* triangles = b3GetMeshTriangles( m_meshData );
const b3Vec3* vertices = b3GetMeshVertices( m_meshData );

View file

@ -5,10 +5,10 @@
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "imgui.h"
#include "utils.h"
#include "sample.h"
#include "gfx/draw.h"
#include "imgui.h"
#include "sample.h"
#include "utils.h"
#include "box3d/box3d.h"
@ -63,6 +63,7 @@ public:
m_closestPoint = b3Pos_zero;
m_timeStamp = 1;
m_drawLevel = -1;
m_doOverlap = false;
m_doClosest = false;
m_doRay = false;
@ -91,6 +92,11 @@ public:
{
m_depths.resize( m_tree.nodeCapacity, 0 );
if ( m_tree.nodes == nullptr || m_tree.nodeCount == 0 || m_tree.root == B3_NULL_INDEX )
{
return 0;
}
int* queue = (int*)malloc( m_tree.nodeCount * sizeof( int ) );
int front = 0;
int back = 0;
@ -149,6 +155,7 @@ public:
FILE* file = fopen( filePath, "r" );
if ( file == nullptr )
{
fprintf( stderr, "Failed to open '%s'\n", filePath );
return;
}
@ -217,6 +224,13 @@ public:
// }
}
fclose( file );
if ( m_proxies.empty() )
{
return;
}
printf( "max index = %d\n", maxAreaIndex );
// constexpr int n = m_isDebug ? 1000 : INT_MAX;
@ -252,10 +266,21 @@ public:
m_proxies.clear();
{
//bool zUp = true;
// bool zUp = true;
m_tree = b3DynamicTree_Load( m_saveFileName, m_loadScale );
}
// A missing or stale save file loads as an empty tree, which has no root to walk
if ( m_tree.nodes == nullptr || m_tree.proxyCount == 0 )
{
fprintf( stderr, "Failed to load tree '%s'\n", m_saveFileName );
m_height = 0;
m_drawLevel = -1;
m_buildTime = 0.0f;
m_areaRatio = 0.0f;
return;
}
constexpr int bufferSize = 512;
char buffer[bufferSize];
@ -406,6 +431,11 @@ public:
bool DrawControls() override
{
if ( m_tree.proxyCount == 0 )
{
return false;
}
DrawTextLine( "leaves = %d, height = %d, area = %g", m_tree.proxyCount, m_height, m_areaRatio );
DrawTextLine( "build time = %g ms", m_buildTime );
DrawTextLine( "total: ray = %g ms, overlap = %g ms, closest = %g ms", m_rayTime, m_overlapTime, m_closestTime );
@ -463,6 +493,11 @@ public:
DrawAxes( b3WorldTransform_identity, 2.0f );
if ( m_tree.proxyCount == 0 )
{
return;
}
b3Pos cp = m_camera->DrawOrigin();
b3TreeNode* nodes = m_tree.nodes;
float distSquared = m_drawDistance * m_drawDistance * 1000.0f * 1000.0f;
@ -550,8 +585,14 @@ public:
void Step() override
{
Sample::Step();
if ( m_tree.proxyCount == 0 )
{
return;
}
++m_timeStamp;
if ( m_doRay )
{
Ray ray = m_rays[m_testIndex];
@ -599,9 +640,11 @@ public:
std::unordered_map<uint64_t, Proxy> m_proxies;
std::vector<uint16_t> m_depths;
b3DynamicTree m_tree;
Ray m_rays[m_testCount];
b3AABB m_overlapQueries[m_testCount];
b3Sphere m_closestPointQueries[m_testCount];
// Zeroed because the queries are only generated once a tree loads
Ray m_rays[m_testCount] = {};
b3AABB m_overlapQueries[m_testCount] = {};
b3Sphere m_closestPointQueries[m_testCount] = {};
b3Pos m_closestPoint;
float m_areaRatio;
float m_rayTime;

View file

@ -26,8 +26,8 @@
#define B3_MARK_VISIBLE 0
#define B3_MARK_DELETE 1
// Final hull is index-encoded with uint8_t, so vertex/edge/face counts are capped at UINT8_MAX.
#define B3_HULL_LIMIT UINT8_MAX
// Final hull is index-encoded with uint8_t, so vertex/edge/face counts are capped at 256.
#define B3_HULL_MAX_COUNT ( UINT8_MAX + 1 )
typedef struct b3QHListNode
{
@ -120,12 +120,16 @@ typedef struct b3HullBuilder
b3QHHalfEdge* edgeBase;
int edgeCapacity;
int edgeCount;
b3QHHalfEdge* edgeFreeHead; // LIFO free list; overlays edge->next
// LIFO free list. Built with edge->next.
b3QHHalfEdge* edgeFreeHead;
b3QHFace* faceBase;
int faceCapacity;
int faceCount;
b3QHFace* faceFreeHead; // LIFO free list; overlays face->link.next
// LIFO free list. Built with face->link.next.
b3QHFace* faceFreeHead;
// Reusable scratch buffers.
b3QHHalfEdge** horizon;
@ -145,7 +149,6 @@ typedef struct b3HullBuilder
int horizonStackCapacity;
// Final counts of the constructed hull (vertexList / faceList / half-edges around faces).
// Populated by CleanHull; zero until then.
int finalVertexCount;
int finalHalfEdgeCount;
int finalFaceCount;
@ -300,17 +303,18 @@ static b3QHFace* b3HullBuilder_NewFace( b3HullBuilder* b, b3QHVertex* v1, b3QHVe
return face;
}
// Remove face from faceList if still linked, clear its edge pointer, then push onto faceFreeHead.
// Uses face->link.next as the free-list next pointer (link.prev stays NULL, so b3QHList_Contains
// returns false on a free slot, as required by the retire-guard in ResolveFaces).
// Remove face and add to free list.
static void b3HullBuilder_RetireFace( b3HullBuilder* b, b3QHFace* face )
{
// Sometimes a cone face gets merged and never added to the list.
if ( b3QHList_Contains( &face->link ) )
{
b3QHList_Remove( &face->link );
}
face->edge = NULL;
// link.prev is already NULL after Remove (or was never set). link.next holds free-list ptr.
// link.prev is already NULL after Remove (or was never set).
B3_VALIDATE( face->link.prev == NULL );
face->link.next = (b3QHListNode*)b->faceFreeHead;
b->faceFreeHead = face;
}
@ -1232,7 +1236,7 @@ static void b3HullBuilder_ResolveVertices( b3HullBuilder* b )
static void b3HullBuilder_ResolveFaces( b3HullBuilder* b )
{
// Splice deleted faces out of the face list. Faces already retired by AbsorbFaces are no
// longer on faceList, so we guard with b3QHList_Contains before removing.
// longer on faceList, so guard with b3QHList_Contains before removing.
b3QHListNode* node = b->faceList.link.next;
while ( node != &b->faceList.link )
{
@ -1242,7 +1246,21 @@ static void b3HullBuilder_ResolveFaces( b3HullBuilder* b )
if ( face->mark == B3_MARK_DELETE && b3QHList_Contains( &face->link ) )
{
B3_ASSERT( B3_LIST_EMPTY( &face->conflictListHead.link ) );
b3QHList_Remove( &face->link );
// Each half-edge is owned by exactly one face, so ring walks over the
// dead region retire every interior edge exactly once. Merge deleted
// faces are already off the face list.
b3QHHalfEdge* start = face->edge;
b3QHHalfEdge* edge = start;
do
{
b3QHHalfEdge* next = edge->next;
b3HullBuilder_RetireEdge( b, edge );
edge = next;
}
while ( edge != start );
b3HullBuilder_RetireFace( b, face );
}
}
@ -1427,7 +1445,7 @@ static bool b3HullBuilder_Construct( b3HullBuilder* b, const b3Vec3* points, int
return false;
}
int budget = b3ClampInt( maxVertexCount - 4, 0, B3_HULL_LIMIT - 4 );
int budget = b3ClampInt( maxVertexCount - 4, 0, B3_HULL_MAX_COUNT - 4 );
b3QHVertex* vertex = b3HullBuilder_NextConflictVertex( b );
while ( vertex && budget > 0 )
@ -1448,8 +1466,10 @@ static bool b3HullBuilder_Construct( b3HullBuilder* b, const b3Vec3* points, int
typedef struct b3HullWorkSizes
{
int N; // pointCount
int M; // clamped maxVertexCount, in [4, B3_HULL_LIMIT]
// Input point count
int N;
// Output point limit
int M;
int vertexCapacity;
int edgeCapacity;
int faceCapacity;
@ -1479,39 +1499,19 @@ static b3HullWorkSizes b3ComputeHullWorkSizes( int pointCount, int clampedMaxCou
s.vertexCapacity = pointCount + 4;
// Edges and faces use free-list recycling; capacity is proportional to live hull size.
// edgeCapacity: peak is ~twice live edges plus cone edges; floor 48.
s.edgeCapacity = 24 * s.M - 48;
if ( s.edgeCapacity < 48 )
{
s.edgeCapacity = 48;
}
// edgeCapacity: peak is ~twice live edges plus cone edges. Minimum 48.
s.edgeCapacity = b3MaxInt( 48, 24 * s.M - 48 );
// faceCapacity: peak intermediate state live faces (<=2*M-4) plus full cone (<=3*M-6); floor 16.
s.faceCapacity = 5 * s.M - 10;
if ( s.faceCapacity < 16 )
{
s.faceCapacity = 16;
}
// faceCapacity: peak intermediate state live faces (<=2*M-4) plus full cone (<=3*M-6). Minimum 16.
s.faceCapacity = b3MaxInt( 16, 5 * s.M - 10 );
// Horizon/cone bounded by current half-edge count; mergedFaces by face count.
s.horizonCapacity = 3 * s.M - 6;
if ( s.horizonCapacity < 6 )
{
s.horizonCapacity = 6;
}
// Horizon/cone bounded by current half-edge count. Merged faces by face count.
s.horizonCapacity = b3MaxInt( 6, 3 * s.M - 6 );
s.coneCapacity = s.horizonCapacity;
s.mergedFacesCapacity = 2 * s.M - 4;
if ( s.mergedFacesCapacity < 4 )
{
s.mergedFacesCapacity = 4;
}
s.mergedFacesCapacity = b3MaxInt( 4, 2 * s.M - 4 );
// Horizon DFS depth is bounded by the number of live faces (Euler: <=2*M-4).
s.horizonStackCapacity = 2 * s.M - 4;
if ( s.horizonStackCapacity < 4 )
{
s.horizonStackCapacity = 4;
}
s.horizonStackCapacity = b3MaxInt( 4, 2 * s.M - 4 );
size_t offset = 0;
@ -2065,14 +2065,14 @@ b3HullData* b3CreateHull( const b3Vec3* points, int pointCount, int maxVertexCou
return NULL;
}
if ( builder.finalVertexCount >= B3_MAX_HULL_VERTICES )
if ( builder.finalVertexCount > B3_MAX_HULL_VERTICES )
{
b3Log( "hull final vertex count of %d exceeds limit of %d", builder.finalVertexCount, B3_MAX_HULL_VERTICES );
b3Free( work, sizes.totalBytes );
return NULL;
}
if ( builder.finalFaceCount >= B3_MAX_HULL_FACES )
if ( builder.finalFaceCount > B3_MAX_HULL_FACES )
{
b3Log( "hull final face count of %d exceeds limit of %d", builder.finalFaceCount, B3_MAX_HULL_FACES );
b3Free( work, sizes.totalBytes );
@ -2080,20 +2080,20 @@ b3HullData* b3CreateHull( const b3Vec3* points, int pointCount, int maxVertexCou
}
int maxHalfEdgeCount = 2 * B3_MAX_HULL_EDGES;
if ( builder.finalHalfEdgeCount >= maxHalfEdgeCount )
if ( builder.finalHalfEdgeCount > maxHalfEdgeCount )
{
b3Log( "hull final half edge count of %d exceeds limit of %d", builder.finalHalfEdgeCount, maxHalfEdgeCount );
b3Free( work, sizes.totalBytes );
return NULL;
}
// Walk lists into temp arrays bounded by B3_HULL_LIMIT, stamping finalIndex on each node so
// Walk lists into temp arrays bounded by B3_HULL_MAX_COUNT, stamping finalIndex on each node so
// the resolution pass below is O(E + F) instead of O(E^2 + F^2).
const b3QHVertex* tempVertices[B3_HULL_LIMIT];
const b3QHVertex* tempVertices[B3_HULL_MAX_COUNT];
int vertexCount = 0;
for ( b3QHListNode* node = builder.vertexList.link.next; node != &builder.vertexList.link; node = node->next )
{
B3_ASSERT( vertexCount <= B3_HULL_LIMIT - 1 );
B3_ASSERT( vertexCount < B3_HULL_MAX_COUNT );
b3QHVertex* vertex = (b3QHVertex*)node;
vertex->finalIndex = vertexCount;
@ -2101,15 +2101,14 @@ b3HullData* b3CreateHull( const b3Vec3* points, int pointCount, int maxVertexCou
}
// Collect edges in twin-paired order (i, i+1) by stamping each pair as we discover it.
// Replaces b3SortEdges' O(E^2) twin pairing.
const b3QHFace* tempFaces[B3_HULL_LIMIT];
const b3QHHalfEdge* tempEdges[B3_HULL_LIMIT];
const b3QHFace* tempFaces[B3_HULL_MAX_COUNT];
const b3QHHalfEdge* tempEdges[B3_HULL_MAX_COUNT];
int faceCount = 0;
int edgeCount = 0;
for ( b3QHListNode* faceNode = builder.faceList.link.next; faceNode != &builder.faceList.link; faceNode = faceNode->next )
{
B3_ASSERT( faceCount <= B3_HULL_LIMIT - 1 );
B3_ASSERT( faceCount < B3_HULL_MAX_COUNT );
b3QHFace* face = (b3QHFace*)faceNode;
face->finalIndex = faceCount;
@ -2120,7 +2119,7 @@ b3HullData* b3CreateHull( const b3Vec3* points, int pointCount, int maxVertexCou
{
if ( edge->finalIndex < 0 )
{
B3_ASSERT( edgeCount + 1 <= B3_HULL_LIMIT - 1 );
B3_ASSERT( edgeCount + 1 < B3_HULL_MAX_COUNT );
edge->finalIndex = edgeCount;
tempEdges[edgeCount++] = edge;
@ -2349,9 +2348,9 @@ b3HullData* b3CloneAndTransformHull( const b3HullData* original, b3Transform tra
{
const b3HullFace* face = faces + i;
uint8_t startEdgeIndex = face->edge;
uint8_t currentEdgeIndex = startEdgeIndex;
uint8_t prevEdgeIndex = UINT8_MAX;
int startEdgeIndex = face->edge;
int currentEdgeIndex = startEdgeIndex;
int prevEdgeIndex = B3_NULL_INDEX;
do
{
@ -2367,7 +2366,7 @@ b3HullData* b3CloneAndTransformHull( const b3HullData* original, b3Transform tra
}
while ( currentEdgeIndex != startEdgeIndex );
B3_ASSERT( prevEdgeIndex != UINT8_MAX );
B3_ASSERT( prevEdgeIndex != B3_NULL_INDEX );
currentEdgeIndex = startEdgeIndex;
@ -2375,7 +2374,7 @@ b3HullData* b3CloneAndTransformHull( const b3HullData* original, b3Transform tra
{
b3HullHalfEdge* edge = edges + currentEdgeIndex;
uint8_t nextIndex = edge->next;
edge->next = prevEdgeIndex;
edge->next = (uint8_t)prevEdgeIndex;
if ( currentEdgeIndex < edge->twin )
{