Hull sharing (#13)

Save memory when there are many duplicate hulls. Can improve performance
in some cases.

For consistency with b3MeshData, b3Hull is renamed to b3HullData.
This commit is contained in:
Erin Catto 2026-06-11 22:39:26 -07:00 • committed by GitHub
commit a252f03b19
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
66 changed files with 881 additions and 549 deletions

View file

@ -38,9 +38,9 @@ std::vector<b3JointId> joints;
vs[5] = {-0.5, 0.5, -0.5};
vs[6] = {-0.5, -0.5, -0.5};
vs[7] = {0.5, -0.5, -0.5};
b3Hull* hull = b3CreateHull(vs, 8, 8);
b3CreateHullShape(bodyId, &sd, hull);
b3DestroyHull(hull);
b3HullData* hullData = b3CreateHull(vs, 8, 8);
b3CreateHullShape(bodyId, &sd, hullData);
b3DestroyHull(hullData);
}
}
{
@ -78,8 +78,8 @@ std::vector<b3JointId> joints;
vs[5] = {-15, 1, -15};
vs[6] = {-15, -1, -15};
vs[7] = {15, -1, -15};
b3Hull* hull = b3CreateHull(vs, 8, 8);
b3CreateHullShape(bodyId, &sd, hull);
b3DestroyHull(hull);
b3HullData* hullData = b3CreateHull(vs, 8, 8);
b3CreateHullShape(bodyId, &sd, hullData);
b3DestroyHull(hullData);
}
}

View file

@ -63,8 +63,10 @@ capsule.radius = 0.25f;
### Convex Hulls
Box3D convex hulls are solid convex polyhedra represented by the `b3Hull` type. A shape is
convex when all line segments connecting two interior points remain inside the shape.
Box3D convex hulls are solid convex polyhedra. The geometry lives in a heavy, immutable
`b3HullData` object. The world shares identical hull data through a reference counted
database, so many shapes built from the same data hold one copy. A shape is convex when
all line segments connecting two interior points remain inside the shape.
<!-- TODO: 3D diagram needed -->
@ -77,7 +79,11 @@ b3BoxHull cube = b3MakeCubeHull(0.5f); // uniform half-width
```
`b3BoxHull` stores everything inline — do not call `b3DestroyHull` on one.
Its `.base` member is a `b3Hull` that you pass to shape creation functions.
Its `.base` member is the `b3HullData` that you pass to shape creation:
```c
b3CreateHullShape(bodyId, &shapeDef, &box.base);
```
For a box that is offset or rotated from the body origin:
@ -89,13 +95,14 @@ b3BoxHull rotatedBox = b3MakeTransformedBoxHull(0.5f, 1.0f, 0.5f, localTransform
For arbitrary convex geometry, provide a point cloud and let Box3D compute the hull:
```c
b3Hull* hull = b3CreateHull(points, pointCount, maxVertexCount);
if (hull == NULL)
b3HullData* data = b3CreateHull(points, pointCount, maxVertexCount);
if (data == NULL)
{
// degenerate input: coincident or coplanar points, or insufficient volume
}
// ... use hull ...
b3DestroyHull(hull);
b3CreateHullShape(bodyId, &shapeDef, data);
// The world keeps its own copy, so you may free yours immediately
b3DestroyHull(data);
```
`maxVertexCount` limits the output complexity; pass the same value as `pointCount`
@ -105,8 +112,8 @@ than four non-coplanar points, or nearly-zero volume). Always check before using
Box3D also provides helpers to create cylindrical and conical hulls:
```c
b3Hull* cylinder = b3CreateCylinder(height, radius, yOffset, sides);
b3Hull* cone = b3CreateCone(height, radius1, radius2, slices);
b3HullData* cylinder = b3CreateCylinder(height, radius, yOffset, sides);
b3HullData* cone = b3CreateCone(height, radius1, radius2, slices);
b3DestroyHull(cylinder);
b3DestroyHull(cone);
```

View file

@ -73,9 +73,9 @@ b3ShapeDef groundShapeDef = b3DefaultShapeDef();
b3CreateHullShape(groundId, &groundShapeDef, &groundBox.base);
```
The `.base` field holds the `b3Hull` that `b3CreateHullShape` expects. Box3D copies the
hull data into its internal structures, so `groundBox` does not need to outlive the
call. Do not call `b3DestroyHull` on a `b3BoxHull`; it is stack-allocated.
The `.base` field holds the `b3HullData` that `b3CreateHullShape` expects. Box3D copies
the hull data into a shared internal database, so `groundBox` does not need to outlive
the call. Do not call `b3DestroyHull` on a `b3BoxHull`; it is stack-allocated.
Box3D is tuned for meters, kilograms, and seconds, so the extents above are in meters.
The engine works best when objects are sized like real-world objects (a barrel is roughly

View file

@ -222,7 +222,7 @@ B3_API void b3World_SetWorkerCount( b3WorldId worldId, int count );
/// Get the worker count.
B3_API int b3World_GetWorkerCount( b3WorldId worldId );
/// Dump memory stats to box3d_memory.txt
/// Dump memory stats to log.
B3_API void b3World_DumpMemoryStats( b3WorldId worldId );
/// Dump shape bounds to box3d_bounds.txt
@ -558,15 +558,16 @@ B3_API b3ShapeId b3CreateSphereShape( b3BodyId bodyId, const b3ShapeDef* def, co
/// @return the shape id for accessing the shape
B3_API b3ShapeId b3CreateCapsuleShape( b3BodyId bodyId, const b3ShapeDef* def, const b3Capsule* capsule );
/// Create a convex hull shape and attach it to a body. The hull is cloned.
/// The shape definition and geometry are fully cloned. Contacts are not created until the next time step.
/// Create a convex hull shape and attach it to a body. The shape definition is fully cloned. Contacts are not created
/// until the next time step.
/// @return the shape id for accessing the shape
B3_API b3ShapeId b3CreateHullShape( b3BodyId bodyId, const b3ShapeDef* def, const b3Hull* hull );
B3_API b3ShapeId b3CreateHullShape( b3BodyId bodyId, const b3ShapeDef* def, const b3HullData* hull );
/// Create a convex hull shape and attach it to a body. The hull is cloned then transformed with scale applied first.
/// The shape definition and geometry are fully cloned. Contacts are not created until the next time step.
/// Use this for non-uniform or mirrored scale or a baked local transform. The baked result is shared through the
/// world hull database. The shape definition and geometry are fully cloned. Contacts are not created until the next time step.
/// @return the shape id for accessing the shape
B3_API b3ShapeId b3CreateTransformedHullShape( b3BodyId bodyId, const b3ShapeDef* def, const b3Hull* hull, b3Transform transform,
B3_API b3ShapeId b3CreateTransformedHullShape( b3BodyId bodyId, const b3ShapeDef* def, const b3HullData* hull, b3Transform transform,
b3Vec3 scale );
/// Create a mesh hull shape and attach it to a body. The shape definition is fully cloned but the mesh is not.
@ -703,7 +704,7 @@ B3_API b3Sphere b3Shape_GetSphere( b3ShapeId shapeId );
B3_API b3Capsule b3Shape_GetCapsule( b3ShapeId shapeId );
/// Get the shape's convex hull. Asserts the type is correct.
B3_API const b3Hull* b3Shape_GetHull( b3ShapeId shapeId );
B3_API const b3HullData* b3Shape_GetHull( b3ShapeId shapeId );
/// Get the shape's mesh. Asserts the type is correct.
B3_API b3Mesh b3Shape_GetMesh( b3ShapeId shapeId );
@ -724,7 +725,7 @@ B3_API void b3Shape_SetCapsule( b3ShapeId shapeId, const b3Capsule* capsule );
/// Allows you to change a shape to be a hull or update the current hull.
/// This does not modify the mass properties.
/// @see b3Body_ApplyMassFromShapes
B3_API void b3Shape_SetHull( b3ShapeId shapeId, const b3Hull* hull );
B3_API void b3Shape_SetHull( b3ShapeId shapeId, const b3HullData* hull );
/// Allows you to change a shape to be a mesh or update the current mesh.
/// This does not modify the mass properties.

View file

@ -143,7 +143,7 @@ B3_INLINE b3AABB b3DynamicTree_GetAABB( const b3DynamicTree* tree, int proxyId )
*/
/// Get read only hull vertices.
B3_INLINE const b3HullVertex* b3GetHullVertices( const b3Hull* hull )
B3_INLINE const b3HullVertex* b3GetHullVertices( const b3HullData* hull )
{
if ( hull->vertexOffset == 0 )
{
@ -154,7 +154,7 @@ B3_INLINE const b3HullVertex* b3GetHullVertices( const b3Hull* hull )
}
/// Get read only hull points.
B3_INLINE const b3Vec3* b3GetHullPoints( const b3Hull* hull )
B3_INLINE const b3Vec3* b3GetHullPoints( const b3HullData* hull )
{
if ( hull->pointOffset == 0 )
{
@ -165,7 +165,7 @@ B3_INLINE const b3Vec3* b3GetHullPoints( const b3Hull* hull )
}
/// Get read only hull half edges.
B3_INLINE const b3HullHalfEdge* b3GetHullEdges( const b3Hull* hull )
B3_INLINE const b3HullHalfEdge* b3GetHullEdges( const b3HullData* hull )
{
if ( hull->edgeOffset == 0 )
{
@ -176,7 +176,7 @@ B3_INLINE const b3HullHalfEdge* b3GetHullEdges( const b3Hull* hull )
}
/// Get read only hull faces.
B3_INLINE const b3HullFace* b3GetHullFaces( const b3Hull* hull )
B3_INLINE const b3HullFace* b3GetHullFaces( const b3HullData* hull )
{
if ( hull->faceOffset == 0 )
{
@ -187,7 +187,7 @@ B3_INLINE const b3HullFace* b3GetHullFaces( const b3Hull* hull )
}
/// Get read only hull planes.
B3_INLINE const b3Plane* b3GetHullPlanes( const b3Hull* hull )
B3_INLINE const b3Plane* b3GetHullPlanes( const b3HullData* hull )
{
if ( hull->planeOffset == 0 )
{
@ -198,22 +198,22 @@ B3_INLINE const b3Plane* b3GetHullPlanes( const b3Hull* hull )
}
/// Create a tessellated cylinder as a hull.
B3_API b3Hull* b3CreateCylinder( float height, float radius, float yOffset, int sides );
B3_API b3HullData* b3CreateCylinder( float height, float radius, float yOffset, int sides );
/// Create a tessellated cone as a hull.
B3_API b3Hull* b3CreateCone( float height, float radius1, float radius2, int slices );
B3_API b3HullData* b3CreateCone( float height, float radius1, float radius2, int slices );
/// Create a generic convex hull.
B3_API b3Hull* b3CreateHull( const b3Vec3* points, int pointCount, int maxVertexCount );
B3_API b3HullData* b3CreateHull( const b3Vec3* points, int pointCount, int maxVertexCount );
/// Deep clone a hull.
B3_API b3Hull* b3CloneHull( const b3Hull* hull );
B3_API b3HullData* b3CloneHull( const b3HullData* hull );
/// Clone and transform a hull. Supports non-uniform and mirroring scale.
B3_API b3Hull* b3CloneAndTransformHull( const b3Hull* original, b3Transform transform, b3Vec3 scale );
B3_API b3HullData* b3CloneAndTransformHull( const b3HullData* original, b3Transform transform, b3Vec3 scale );
/// Destroy a hull.
B3_API void b3DestroyHull( b3Hull* hull );
B3_API void b3DestroyHull( b3HullData* hull );
/// Make a cube as a hull. Do not call b3DestroyHull on this.
B3_API b3BoxHull b3MakeCubeHull( float halfWidth );
@ -426,7 +426,7 @@ B3_API b3MassData b3ComputeSphereMass( const b3Sphere* shape, float density );
B3_API b3MassData b3ComputeCapsuleMass( const b3Capsule* shape, float density );
/// Compute mass properties of a hull
B3_API b3MassData b3ComputeHullMass( const b3Hull* shape, float density );
B3_API b3MassData b3ComputeHullMass( const b3HullData* shape, float density );
/// Compute the bounding box of a transformed sphere
B3_API b3AABB b3ComputeSphereAABB( const b3Sphere* shape, b3Transform transform );
@ -435,7 +435,7 @@ B3_API b3AABB b3ComputeSphereAABB( const b3Sphere* shape, b3Transform transform
B3_API b3AABB b3ComputeCapsuleAABB( const b3Capsule* shape, b3Transform transform );
/// Compute the bounding box of a transformed hull
B3_API b3AABB b3ComputeHullAABB( const b3Hull* shape, b3Transform transform );
B3_API b3AABB b3ComputeHullAABB( const b3HullData* shape, b3Transform transform );
/// Compute the bounding box of a transformed mesh. Scale may be non-uniform and have negative components.
B3_API b3AABB b3ComputeMeshAABB( const b3MeshData* shape, b3Transform transform, b3Vec3 scale );
@ -466,7 +466,7 @@ B3_API bool b3OverlapCompound( const b3Compound* shape, b3Transform shapeTransfo
B3_API bool b3OverlapHeightField( const b3HeightField* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy );
/// Overlap shape versus hull
B3_API bool b3OverlapHull( const b3Hull* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy );
B3_API bool b3OverlapHull( const b3HullData* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy );
/// Overlap shape versus mesh
B3_API bool b3OverlapMesh( const b3Mesh* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy );
@ -487,7 +487,7 @@ B3_API b3CastOutput b3RayCastCapsule( const b3Capsule* shape, const b3RayCastInp
B3_API b3CastOutput b3RayCastCompound( const b3Compound* shape, const b3RayCastInput* input );
/// Ray cast versus hull shape in local space. Initial overlap is treated as a miss.
B3_API b3CastOutput b3RayCastHull( const b3Hull* shape, const b3RayCastInput* input );
B3_API b3CastOutput b3RayCastHull( const b3HullData* shape, const b3RayCastInput* input );
/// Ray cast versus mesh in local space.
B3_API b3CastOutput b3RayCastMesh( const b3Mesh* shape, const b3RayCastInput* input );
@ -505,7 +505,7 @@ B3_API b3CastOutput b3ShapeCastCapsule( const b3Capsule* shape, const b3ShapeCas
B3_API b3CastOutput b3ShapeCastCompound( const b3Compound* shape, const b3ShapeCastInput* input );
/// Shape cast versus a hull. Initial overlap is treated as a miss.
B3_API b3CastOutput b3ShapeCastHull( const b3Hull* shape, const b3ShapeCastInput* input );
B3_API b3CastOutput b3ShapeCastHull( const b3HullData* shape, const b3ShapeCastInput* input );
/// Shape cast versus a mesh. Initial overlap is treated as a miss.
B3_API b3CastOutput b3ShapeCastMesh( const b3Mesh* shape, const b3ShapeCastInput* input );
@ -564,7 +564,7 @@ B3_API void b3CollideCapsuleAndSphere( b3LocalManifold* manifold, int capacity,
const b3Sphere* sphereB, b3Transform transformBtoA );
/// Collide a hull and a sphere.
B3_API void b3CollideHullAndSphere( b3LocalManifold* manifold, int capacity, const b3Hull* hullA, const b3Sphere* sphereB,
B3_API void b3CollideHullAndSphere( b3LocalManifold* manifold, int capacity, const b3HullData* hullA, const b3Sphere* sphereB,
b3Transform transformBtoA, b3SimplexCache* cache );
/// Collide two capsules.
@ -572,11 +572,11 @@ B3_API void b3CollideCapsules( b3LocalManifold* manifold, int capacity, const b3
b3Transform transformBtoA );
/// Collide a hull and a capsule.
B3_API void b3CollideHullAndCapsule( b3LocalManifold* manifold, int capacity, const b3Hull* hullA, const b3Capsule* capsuleB,
B3_API void b3CollideHullAndCapsule( b3LocalManifold* manifold, int capacity, const b3HullData* hullA, const b3Capsule* capsuleB,
b3Transform transformBtoA, b3SimplexCache* cache );
/// Collide two hulls.
B3_API void b3CollideHulls( b3LocalManifold* manifold, int capacity, const b3Hull* hullA, const b3Hull* hullB,
B3_API void b3CollideHulls( b3LocalManifold* manifold, int capacity, const b3HullData* hullA, const b3HullData* hullB,
b3Transform transformBtoA, b3SATCache* cache );
/// Collide a capsule and a triangle.
@ -584,7 +584,7 @@ B3_API void b3CollideCapsuleAndTriangle( b3LocalManifold* manifold, int capacity
const b3Vec3* triangleB, b3SimplexCache* cache );
/// Collide a hull and a triangle.
B3_API void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3Hull* hullA, b3Vec3 v1, b3Vec3 v2,
B3_API void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3HullData* hullA, b3Vec3 v1, b3Vec3 v2,
b3Vec3 v3, int triangleFlags, b3SATCache* cache );
/// Collide a sphere and a triangle.

View file

@ -1937,7 +1937,7 @@ typedef struct b3HullFace
/// A convex hull.
/// @note This data structure has data hanging off the end and cannot be directly copied.
typedef struct b3Hull
typedef struct b3HullData
{
/// Version must be first and match B3_HULL_VERSION
uint64_t version;
@ -1989,17 +1989,22 @@ typedef struct b3Hull
/// Offset of the face plane array in bytes from the struct address.
int planeOffset;
} b3Hull;
/// Explicit padding. Hull identity is a content hash and memcmp over raw bytes,
/// so there must be no unnamed padding for struct copies to scramble.
int padding;
} b3HullData;
/// Efficient box hull
typedef struct b3BoxHull
{
/// The embedded hull. So the offsets index into the arrays that follow.
b3Hull base;
b3HullData base;
b3HullVertex boxVertices[8]; ///< Box vertices.
b3Vec3 boxPoints[8]; ///< Box points.
b3HullHalfEdge boxEdges[24]; ///< Box half-edges.
b3HullFace boxFaces[6]; ///< Box faces.
uint8_t padding[2]; ///< Explicit padding, see b3HullData::padding.
b3Plane boxPlanes[6]; ///< Box face planes.
} b3BoxHull;
@ -2293,7 +2298,7 @@ typedef struct b3CompoundCapsuleDef
typedef struct b3CompoundHullDef
{
/// Shared hull.
const b3Hull* hull;
const b3HullData* hull;
/// Transform of the shared hull into compound local space.
b3Transform transform;
@ -2438,7 +2443,7 @@ typedef struct b3CompoundCapsule
typedef struct b3CompoundHull
{
/// Pointer to the unique shared hull.
const b3Hull* hull;
const b3HullData* hull;
/// The transform of this hull instance.
b3Transform transform;
@ -2483,7 +2488,7 @@ typedef struct b3ChildShape
union
{
b3Capsule capsule; ///< Capsule.
const b3Hull* hull; ///< Hull.
const b3HullData* hull; ///< Hull.
b3Mesh mesh; ///< Mesh.
b3Sphere sphere; ///< Sphere.
};
@ -2898,7 +2903,7 @@ typedef struct b3DebugShape
const b3Capsule* capsule; ///< Capsule shape.
const b3Compound* compound; ///< Compound shape.
const b3HeightField* heightField; ///< Height-field shape.
const b3Hull* hull; ///< Convex hull shape.
const b3HullData* hull; ///< Convex hull shape.
const b3Mesh* mesh; ///< Mesh shape with scale.
const b3Sphere* sphere; ///< Sphere shape.
};

View file

@ -513,7 +513,7 @@ static void* AdapterCreateDebugShape( const b3DebugShape* debugShape, void* cont
if ( debugShape->type == b3_hullShape )
{
const b3Hull* hull = debugShape->hull;
const b3HullData* hull = debugShape->hull;
MeshHandle handle = FindOrAddHull( hull );
if ( !IsMeshHandleValid( handle ) )
{

View file

@ -293,7 +293,7 @@ static b3Vec3 TriangleNormal( b3Vec3 a, b3Vec3 b, b3Vec3 c )
return n;
}
static MeshHandle BuildHull( const b3Hull* hull )
static MeshHandle BuildHull( const b3HullData* hull )
{
const b3Vec3* points = b3GetHullPoints( hull );
const b3HullHalfEdge* edges = b3GetHullEdges( hull );
@ -789,7 +789,7 @@ static MeshHandle BuildHeightField( const b3HeightField* hf )
return h;
}
MeshHandle FindOrAddHull( const b3Hull* hull )
MeshHandle FindOrAddHull( const b3HullData* hull )
{
if ( !hull || hull->hash == 0u )
{

View file

@ -32,7 +32,7 @@ extern "C"
// Acquire a registry handle for the given Box3D hull. Returns an invalid
// handle on registry-full or zero hash. The caller owns one refcount. Pair
// each Acquire with a single ReleaseMeshReference when the consumer goes away.
MeshHandle FindOrAddHull( const b3Hull* hull );
MeshHandle FindOrAddHull( const b3HullData* hull );
// Acquire for b3MeshData. The b3Mesh struct's per-instance `scale` is NOT
// part of the geometry, callers pass it as the per-instance scale at

View file

@ -67,7 +67,7 @@ void DrawSolidCapsule( b3Transform transform, b3Capsule capsule, Vec4 color )
DrawCapsule( world, 0.5f * length, capsule.radius, color );
}
void DrawHull( b3Transform transform, const b3Hull* hull, Vec4 color )
void DrawHull( b3Transform transform, const b3HullData* hull, Vec4 color )
{
const b3Vec3* points = b3GetHullPoints( hull );
const b3HullHalfEdge* edges = b3GetHullEdges( hull );

View file

@ -52,7 +52,7 @@ void DrawSolidSphere( b3Transform transform, b3Sphere sphere, Vec4 color );
void DrawSolidCapsule( b3Transform transform, b3Capsule capsule, Vec4 color );
// Convex hull wireframe. Each undirected edge once, in world space.
void DrawHull( b3Transform transform, const b3Hull* hull, Vec4 color );
void DrawHull( b3Transform transform, const b3HullData* hull, Vec4 color );
// Plane as a unit wireframe quad through the point, plus a short normal and a dot.
void DrawPlane( b3Vec3 normal, b3Vec3 point, Vec4 color );

View file

@ -4,7 +4,7 @@
// Ref-counted GPU buffer store for triangle geometries (convex hulls,
// triangle meshes, heightfields). Owned by the renderer
// Keyed by uint32_t content hash for Box3D shapes we
// pass through b3Hull.hash / b3MeshData.hash / b3HeightField.hash
// pass through b3HullData.hash / b3MeshData.hash / b3HeightField.hash
//
// Lifecycle:
//

View file

@ -1119,7 +1119,7 @@ void Sample::MouseDown( b3Vec2 p, int button, int modifiers )
bodyDef.linearVelocity = ( 10.0f * m_launchSpeedScale ) * direction;
b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef );
b3Hull* hull = b3CreateCylinder( 2.0f, 0.15f, 0.0f, 6 );
b3HullData* hull = b3CreateCylinder( 2.0f, 0.15f, 0.0f, 6 );
b3CreateHullShape( bodyId, &shapeDef, hull );
b3DestroyHull( hull );
}
@ -1465,13 +1465,9 @@ static void DrawMenuBar( SampleContext* context )
{
context->sample->ResetProfile();
}
if ( ImGui::MenuItem( "Dump" ) )
if ( ImGui::MenuItem( "Dump Mem Stats" ) )
{
b3World_Dump( context->sample->m_worldId );
}
if ( ImGui::MenuItem( "Dump Awake" ) )
{
b3World_DumpAwake( context->sample->m_worldId );
b3World_DumpMemoryStats( context->sample->m_worldId );
}
ImGui::Separator();
if ( ImGui::MenuItem( "Quit", "Esc" ) )

View file

@ -334,7 +334,7 @@ public:
b3DestroyHull( m_convex );
}
b3Hull* CreateConvex( float radius1, float height1, float radius2, float height2 ) const
b3HullData* CreateConvex( float radius1, float height1, float radius2, float height2 ) const
{
constexpr int sideCount = 8;
const float deltaAlpha = 2.0f * B3_PI / sideCount;
@ -365,7 +365,7 @@ public:
return new CandyCups( context );
}
b3Hull* m_convex;
b3HullData* m_convex;
};
static int sampleSmallConvexes = RegisterSample( "Benchmark", "Candy Cups", CandyCups::Create );
@ -486,7 +486,7 @@ public:
}
b3MeshData* m_gridMesh;
b3Hull* m_cylinder;
b3HullData* m_cylinder;
float m_impulse;
};
@ -1076,7 +1076,7 @@ public:
for ( int i = 0; i < trials; ++i )
{
b3Hull* hull = b3CreateHull( m_points, m_count, m_count );
b3HullData* hull = b3CreateHull( m_points, m_count, m_count );
area += hull->surfaceArea;
b3DestroyHull( hull );
}
@ -1086,7 +1086,7 @@ public:
float scaledArea = 0.0f;
for ( int i = 0; i < trials; ++i )
{
b3Hull* hull = b3CloneAndTransformHull( m_hull, b3Transform_identity, m_scale );
b3HullData* hull = b3CloneAndTransformHull( m_hull, b3Transform_identity, m_scale );
scaledArea += hull->surfaceArea;
b3DestroyHull( hull );
}
@ -1106,8 +1106,8 @@ public:
}
static constexpr int m_capacity = 64;
b3Hull* m_hull;
b3Hull* m_transformedHull;
b3HullData* m_hull;
b3HullData* m_transformedHull;
b3Vec3 m_scale;
b3Vec3 m_points[m_capacity];
int m_count;

View file

@ -340,7 +340,7 @@ public:
b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef );
b3ShapeDef shapeDef = b3DefaultShapeDef();
b3Hull* cylinder = b3CreateCylinder( 0.6f, 0.15f, 0.0f, 32 );
b3HullData* cylinder = b3CreateCylinder( 0.6f, 0.15f, 0.0f, 32 );
b3BoxHull box = b3MakeBoxHull( 1.0f, 0.05f, 0.1f );
b3CreateHullShape( bodyId, &shapeDef, cylinder );
b3CreateHullShape( bodyId, &shapeDef, &box.base );
@ -727,7 +727,7 @@ public:
return new BodyCast( context );
}
b3Hull* m_cylinder;
b3HullData* m_cylinder;
b3BodyId m_bodyId;
b3Transform m_transform;

View file

@ -1549,7 +1549,7 @@ public:
b3Transform m_transform;
b3Vec3 m_translation;
b3Capsule m_capsule;
b3Hull* m_box;
b3HullData* m_box;
b3Vec3 m_points[8];
b3Vec3 m_triangle[3];
};
@ -1796,7 +1796,7 @@ public:
}
b3Transform m_transformB;
b3Hull* m_box;
b3HullData* m_box;
b3BoxHull m_boxA;
b3BoxHull m_boxB;
b3Vec3 m_points[8];

View file

@ -384,7 +384,7 @@ public:
b3MeshData* m_needle2;
b3MeshData* m_needle3;
b3MeshData* m_needle4;
b3Hull* mConvex;
b3HullData* mConvex;
};
static int sampleNeedleMesh = RegisterSample( "Continuous", "Needle Mesh", NeedleMesh::Create );
@ -734,7 +734,7 @@ public:
b3MeshData* m_groundMesh;
float m_groundAmplitude;
b3BodyId m_groundId;
b3Hull* m_cylinder;
b3HullData* m_cylinder;
b3BodyId* m_bodies;
ShapeType m_shapeType;
int m_runCount;

View file

@ -130,7 +130,7 @@ public:
b3Transform m_transform;
b3Vec3 m_postScale;
b3BoxHull m_box;
b3Hull* m_hull;
b3HullData* m_hull;
};
static int sampleBoxHull = RegisterSample( "Geometry", "Box Hull", BoxHull::Create );
@ -223,7 +223,7 @@ public:
}
static constexpr int m_capacity = 64;
b3Hull* m_hull;
b3HullData* m_hull;
b3Vec3 m_points[m_capacity];
int m_count;
};
@ -352,17 +352,17 @@ public:
static constexpr int m_capacity = 128;
Type m_type;
b3Hull* m_hull;
b3HullData* m_hull;
b3Vec3 m_points[m_capacity];
int m_count;
};
static int sampleHullReduction = RegisterSample( "Geometry", "Hull Reduction", HullReduction::Create );
class HullScale : public Sample
class HullTransform : public Sample
{
public:
explicit HullScale( SampleContext* context )
explicit HullTransform( SampleContext* context )
: Sample( context )
{
if ( m_context->restart == false )
@ -379,7 +379,7 @@ public:
m_hull = b3CloneAndTransformHull( m_original, b3Transform_identity, m_scale );
}
~HullScale() override
~HullTransform() override
{
if ( m_original != &m_box.base )
{
@ -474,18 +474,18 @@ public:
static Sample* Create( SampleContext* sampleContext )
{
return new HullScale( sampleContext );
return new HullTransform( sampleContext );
}
b3BoxHull m_box;
b3Hull* m_original;
b3Hull* m_hull;
b3HullData* m_original;
b3HullData* m_hull;
b3Vec3 m_angles;
b3Vec3 m_scale;
b3Vec3 m_offset;
};
static int sampleHullScale = RegisterSample( "Geometry", "Hull Scale", HullScale::Create );
static int sampleHullTransform = RegisterSample( "Geometry", "Hull Transform", HullTransform::Create );
class CapsuleMass : public Sample
{
@ -639,7 +639,7 @@ public:
static constexpr int m_maxSides = 6;
b3Capsule m_capsule;
b3BoxHull m_box;
b3Hull* m_hull;
b3HullData* m_hull;
float m_radius;
float m_length;
int m_sides;

View file

@ -265,7 +265,7 @@ public:
}
static constexpr int m_capacity = 64;
b3Hull* m_hull;
b3HullData* m_hull;
b3Vec3 m_points[m_capacity];
int m_count;
};
@ -322,7 +322,7 @@ public:
points[i] = { s * p.x, s * p.z, s * p.y };
}
b3Hull* hull = b3CreateHull( points, count, count );
b3HullData* hull = b3CreateHull( points, count, count );
b3CreateHullShape( bodyId, &shapeDef, hull );
b3DestroyHull( hull );
@ -367,7 +367,7 @@ public:
points[i] = { s * p.x, s * p.z, s * p.y };
}
b3Hull* hull = b3CreateHull( points, count, count );
b3HullData* hull = b3CreateHull( points, count, count );
b3CreateHullShape( bodyId, &shapeDef, hull );
b3DestroyHull( hull );

View file

@ -1332,7 +1332,7 @@ public:
b3ShapeDef shapeDef = b3DefaultShapeDef();
b3Hull* hull = b3CreateCylinder( 0.25f, 0.4f, 0.0f, 12 );
b3HullData* hull = b3CreateCylinder( 0.25f, 0.4f, 0.0f, 12 );
// b3BoxHull box = b3MakeBoxHull( 0.5f, 1.5f, 0.25f );
b3CreateHullShape( m_bodyId, &shapeDef, hull );
b3DestroyHull( hull );
@ -2310,7 +2310,7 @@ public:
bodyDef.allowFastRotation = true;
bodyDef.rotation = b3ComputeQuatBetweenUnitVectors( b3Vec3_axisY, b3Vec3_axisZ );
// b3Hull* hull = b3CreateCylinder( 0.25f, 0.4f, 0.0f, 16 );
// b3HullData* hull = b3CreateCylinder( 0.25f, 0.4f, 0.0f, 16 );
b3WheelJointDef jointDef = b3DefaultWheelJointDef();
jointDef.base.bodyIdA = m_chassisId;

View file

@ -746,7 +746,7 @@ public:
}
}
b3Hull* CreateConvex( float radius1, float height1, float radius2, float height2 ) const
b3HullData* CreateConvex( float radius1, float height1, float radius2, float height2 ) const
{
constexpr int sideCount = 32;
const float deltaAlpha = 2.0f * B3_PI / sideCount;
@ -815,8 +815,8 @@ public:
b3BoxHull m_boxA;
b3BoxHull m_boxB;
b3Hull* m_hullA;
b3Hull* m_hullB;
b3HullData* m_hullA;
b3HullData* m_hullB;
};
static int sampleCollideHulls = RegisterSample( "Manifold", "Hull vs Hull", HullAndHull::Create );
@ -931,8 +931,8 @@ public:
int m_flags;
b3BoxHull m_boxHull;
b3Hull* m_cylinder;
b3Hull* m_hull;
b3HullData* m_cylinder;
b3HullData* m_hull;
};
static int sampleHullAndTriangle = RegisterSample( "Manifold", "Triangle vs Hull", TriangleAndHull::Create );

View file

@ -197,7 +197,7 @@ public:
return new GridMesh( context );
}
b3Hull* m_cylinderHull;
b3HullData* m_cylinderHull;
ShapeType m_shapeType;
b3BodyId m_bodyId;
b3MeshData* m_gridMesh;
@ -371,7 +371,7 @@ public:
return new BigBoxMesh( context );
}
b3Hull* m_cylinderHull;
b3HullData* m_cylinderHull;
ShapeType m_shapeType;
b3BodyId m_bodyId;
b3MeshData* m_boxMesh;
@ -543,7 +543,7 @@ public:
ShapeType m_shapeType;
b3BodyId m_bodyId;
b3MeshData* m_boxMesh;
b3Hull* m_cylinderHull;
b3HullData* m_cylinderHull;
b3ShapeId m_boxShapeId;
b3Vec3 m_scale;
};
@ -1443,7 +1443,7 @@ public:
points[i] = b3MulSV( 0.01f, b3Vec3{ p.y, p.z, p.x } );
}
b3Hull* hull = b3CreateHull( points, 16, 16 );
b3HullData* hull = b3CreateHull( points, 16, 16 );
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.name = "cylinder";
bodyDef.type = b3_dynamicBody;
@ -1516,7 +1516,7 @@ public:
b3ShapeDef shapeDef = b3DefaultShapeDef();
{
b3Hull* cylinderHull = b3CreateCylinder( 1.0f, 0.25f, 0.0f, 8 );
b3HullData* cylinderHull = b3CreateCylinder( 1.0f, 0.25f, 0.0f, 8 );
b3Vec3 positions[6] = {
{ 0.0f, -10.2f, 0.0f }, { 0.0f, 9.2f, 0.0f }, { -9.8f, 0.0f, 0.0f },

View file

@ -362,7 +362,7 @@ public:
b3ShapeDef shapeDef = b3DefaultShapeDef();
groundId->AddMesh( &shapeDef, m_ground );
b3Hull* Hull = b3CreateOffsetBox( { { -3.0f, 0.5f, 0.0f }, b3Quat_identity }, { 0.25f, 0.5f, 3.0f } );
b3HullData* Hull = b3CreateOffsetBox( { { -3.0f, 0.5f, 0.0f }, b3Quat_identity }, { 0.25f, 0.5f, 3.0f } );
groundId->AddHull( &shapeDef, Hull );
b3DestroyHull( Hull );
@ -377,7 +377,7 @@ public:
m_time = 0.0f;
{
b3Hull* Cylinder = b3CreateCylinder( 0.5f, 0.5f, 0.0f, 16 );
b3HullData* Cylinder = b3CreateCylinder( 0.5f, 0.5f, 0.0f, 16 );
bodyDef.type = b3_dynamicBody;
bodyDef.position = { 3.0f, 0.5f, 0.0f };
bodyDef.rotation = b3MakeQuatFromAxisAngle( B3_VEC3_AXIS_Z, 0.5f * B3_PI );

View file

@ -669,7 +669,7 @@ public:
b3Transform m_meshTransform;
b3MeshData* m_meshData;
b3Hull* m_cylinderHull;
b3HullData* m_cylinderHull;
b3Vec3 m_velocities[7];
};

View file

@ -358,7 +358,7 @@ public:
return new Cylinder( context );
}
b3Hull* m_hull;
b3HullData* m_hull;
};
static int sampleCylinder = RegisterSample( "Stacking", "Cylinder", Cylinder::Create );
@ -416,7 +416,7 @@ public:
return new CylinderStack( context );
}
b3Hull* m_hull;
b3HullData* m_hull;
};
static int sampleCylinderStack = RegisterSample( "Stacking", "Cylinder Stack", CylinderStack::Create );
@ -671,7 +671,7 @@ public:
b3DestroyHull( m_wedgeHull );
}
b3Hull* m_wedgeHull;
b3HullData* m_wedgeHull;
};
static int sampleWedge = RegisterSample( "Stacking", "Wedge", Wedge::Create );
@ -784,7 +784,7 @@ public:
{ ps1[i].x, ps1[i].y, halfDepth }, { ps2[i].x, ps2[i].y, halfDepth },
{ ps2[i + 1].x, ps2[i + 1].y, halfDepth }, { ps1[i + 1].x, ps1[i + 1].y, halfDepth },
};
b3Hull* hull = b3CreateHull( ps, 8, 8 );
b3HullData* hull = b3CreateHull( ps, 8, 8 );
b3CreateHullShape( bodyId, &shapeDef, hull );
b3DestroyHull( hull );
}
@ -798,7 +798,7 @@ public:
{ -ps2[i].x, ps2[i].y, halfDepth }, { -ps1[i].x, ps1[i].y, halfDepth },
{ -ps1[i + 1].x, ps1[i + 1].y, halfDepth }, { -ps2[i + 1].x, ps2[i + 1].y, halfDepth },
};
b3Hull* hull = b3CreateHull( ps, 8, 8 );
b3HullData* hull = b3CreateHull( ps, 8, 8 );
b3CreateHullShape( bodyId, &shapeDef, hull );
b3DestroyHull( hull );
}
@ -810,7 +810,7 @@ public:
{ -ps1[8].x, ps1[8].y, -halfDepth }, { ps1[8].x, ps1[8].y, halfDepth }, { ps2[8].x, ps2[8].y, halfDepth },
{ -ps2[8].x, ps2[8].y, halfDepth }, { -ps1[8].x, ps1[8].y, halfDepth },
};
b3Hull* hull = b3CreateHull( ps, 8, 8 );
b3HullData* hull = b3CreateHull( ps, 8, 8 );
b3CreateHullShape( bodyId, &shapeDef, hull );
b3DestroyHull( hull );
}

View file

@ -603,7 +603,7 @@ void CreateWasher( b3WorldId worldId )
b3Vec3 p8 = b3MulAdd( pd, r2, a2 );
b3Vec3 points[8] = { p1, p2, p3, p4, p5, p6, p7, p8 };
b3Hull* hull = b3CreateHull( points, 8, 8 );
b3HullData* hull = b3CreateHull( points, 8, 8 );
b3CreateHullShape( bodyId, &shapeDef, hull );
b3DestroyHull( hull );
}
@ -620,7 +620,7 @@ void CreateWasher( b3WorldId worldId )
b3Vec3 p8 = b3MulAdd( pd, r1, u2 );
b3Vec3 points[8] = { p1, p2, p3, p4, p5, p6, p7, p8 };
b3Hull* hull = b3CreateHull( points, 8, 8 );
b3HullData* hull = b3CreateHull( points, 8, 8 );
b3CreateHullShape( bodyId, &shapeDef, hull );
b3DestroyHull( hull );
}
@ -714,7 +714,7 @@ static void CreateTrees( b3WorldId worldId, int scale )
shapeDef.density = 1.0f;
int hullCount = 22;
b3Hull* hulls[22] = { 0 };
b3HullData* hulls[22] = { 0 };
float y = 1.0f;
float r = 0.75f;
@ -830,7 +830,7 @@ void CreateJunkyard( b3WorldId worldId )
}
}
{
b3Hull* hull;
b3HullData* hull;
{
float radius = 1.5f;
int pointCount = 10;
@ -880,7 +880,7 @@ void CreateJunkyard( b3WorldId worldId )
g_junkyardData.radius = 35.0f;
float mHeight = 24.0f;
b3Hull* hull = b3CreateCylinder( mHeight, 4.0f, 0.0f, 16 );
b3HullData* hull = b3CreateCylinder( mHeight, 4.0f, 0.0f, 16 );
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_kinematicBody;
bodyDef.position = (b3Vec3){ g_junkyardData.radius, 0.0f, 0.0f };

View file

@ -51,7 +51,7 @@ b3DeclareArray( b3OverflowBlock );
// across copies -- hence this pointer-shared block.
typedef struct b3ArenaSharedState
{
b3ArrayC( b3OverflowBlock ) overflows;
b3Array( b3OverflowBlock ) overflows;
int maxIndex; // high water mark of the bump pointer this step
int overflowBytes; // total bytes in overflow blocks this step
int peakDemand; // all-time peak of (maxIndex + overflowBytes), survives sync

View file

@ -19,7 +19,7 @@ b3DeclareArray( b3Block );
typedef struct b3BlockAllocator
{
b3ArrayC( b3Block ) blocks;
b3Array( b3Block ) blocks;
void* freeList;
int elementSize;
int nextIndex;

View file

@ -31,7 +31,7 @@ typedef struct b3BroadPhase
// Per body-type bit sets indexed by proxyId, marking proxies moved this step.
// Paired with moveArray which preserves deterministic insertion order for pair queries.
b3BitSet movedProxies[b3_bodyTypeCount];
b3ArrayC( int ) moveArray;
b3Array( int ) moveArray;
// These are the results from the pair query and are used to create new contacts
// in deterministic order.

View file

@ -269,8 +269,8 @@ int b3CollideMoverAndCapsule( b3PlaneResult* result, const b3Capsule* shape, con
{
float totalRadius = mover->radius + shape->radius;
b3ClosestApproachResult approach =
b3ClosestApproachSegments( shape->center1, shape->center2, mover->center1, mover->center2 );
b3SegmentDistanceResult approach =
b3SegmentDistance( shape->center1, shape->center2, mover->center1, mover->center2 );
// The normal points from the shape toward the mover.
float distance;

View file

@ -3,6 +3,7 @@
#include "compound.h"
#include "hull_map.h"
#include "math_internal.h"
#include "shape.h"
@ -16,7 +17,7 @@
typedef struct b3SharedHull
{
const b3Hull* hull;
const b3HullData* hull;
int hullOffset;
} b3SharedHull;
@ -88,7 +89,7 @@ b3CompoundHull b3GetCompoundHull( const b3Compound* compound, int index )
const b3HullInstance* hullInstances = (const b3HullInstance*)( (intptr_t)compound + compound->hullOffset );
uint32_t hullOffset = hullInstances[index].hullOffset;
B3_ASSERT( hullOffset >= compound->hullOffset + compound->hullCount * sizeof( b3HullInstance ) );
result.hull = (const b3Hull*)( (intptr_t)compound + hullOffset );
result.hull = (const b3HullData*)( (intptr_t)compound + hullOffset );
result.transform = hullInstances[index].transform;
result.materialIndex = hullInstances[index].materialIndex;
return result;
@ -195,36 +196,6 @@ b3ChildShape b3GetCompoundChild( const b3Compound* compound, int childIndex )
static inline size_t vt_wyhash( const void* key, size_t len );
static inline uint64_t b3HashHull( const b3Hull* hull )
{
return vt_wyhash( hull, hull->byteCount );
}
static bool b3CompareHulls( const b3Hull* hull1, const b3Hull* hull2 )
{
if ( hull1 == hull2 )
{
return true;
}
if ( hull1->byteCount != hull2->byteCount )
{
return false;
}
int result = memcmp( hull1, hull2, hull1->byteCount );
return result == 0;
}
#define NAME b3HullMap
#define KEY_TY const b3Hull*
#define VAL_TY int
#define HASH_FN b3HashHull
#define CMPR_FN b3CompareHulls
#define MALLOC_FN b3Alloc
#define FREE_FN b3Free
#include "verstable.h"
static inline uint64_t b3HashMesh( const b3MeshData* mesh )
{
return vt_wyhash( mesh, mesh->byteCount );
@ -357,7 +328,7 @@ b3Compound* b3CreateCompound( const b3CompoundDef* def )
for ( int i = 0; i < hullCount; ++i )
{
const b3CompoundHullDef* hullDef = def->hulls + i;
const b3Hull* hull = hullDef->hull;
const b3HullData* hull = hullDef->hull;
b3AABB aabb = b3ComputeHullAABB( hull, hullDef->transform );
b3DynamicTree_CreateProxy( &tree, aabb, ~0ull, childIndex );
childIndex += 1;
@ -607,7 +578,7 @@ b3Compound* b3CreateCompound( const b3CompoundDef* def )
for ( int i = 0; i < sharedHullCount; ++i )
{
int offset = sharedHulls[i].hullOffset;
b3Hull* destinationHull = (b3Hull*)( (intptr_t)compound + offset );
b3HullData* destinationHull = (b3HullData*)( (intptr_t)compound + offset );
memcpy( destinationHull, sharedHulls[i].hull, sharedHulls[i].hull->byteCount );
}

View file

@ -44,10 +44,10 @@ typedef struct b3GraphColor
b3BitSet bodySet;
// cache friendly arrays
b3ArrayC( b3JointSim ) jointSims;
b3Array( b3JointSim ) jointSims;
b3ArrayC( int ) convexContacts;
b3ArrayC( b3ContactSpec ) contacts;
b3Array( int ) convexContacts;
b3Array( b3ContactSpec ) contacts;
// These are used for convex contacts
struct b3ContactConstraintWide* wideConstraints;

View file

@ -83,8 +83,7 @@ typedef struct b3ContactEdge
typedef struct b3MeshContact
{
// todo use block allocator for this for faster shutdown
b3ArrayC( b3TriangleCache ) triangleCache;
b3Array( b3TriangleCache ) triangleCache;
b3AABB queryBounds;
} b3MeshContact;

View file

@ -12,12 +12,12 @@
#define b3DeclareArray( T ) \
typedef struct b3DynamicArray_##T \
{ \
struct T* data; \
struct T* data; \
int count; \
int capacity; \
} b3DynamicArray_##T
#define b3DeclareArrayNative( T ) \
#define b3DeclareArrayNative( T ) \
typedef struct b3DynamicArray_##T \
{ \
T* data; \
@ -27,8 +27,8 @@
// Define an array.
// It may be zero initialized:
// b3ArrayC(int) myArray = { 0 };
#define b3ArrayC( T ) b3DynamicArray_##T
// b3Array(int) myArray = { 0 };
#define b3Array( T ) b3DynamicArray_##T
// Alternative to zero initialization
#define b3Array_Create( a ) \
@ -110,22 +110,22 @@
#define b3Array_AddIndex( a ) \
( b3EmplaceHelper( (void**)&( a ).data, &( a ).count, &( a ).capacity, sizeof( *( a ).data ) ), ( a ).count - 1 )
// Append a contiguous run of values.
// Append a contiguous run of values. _n is used to cache the input count while avoiding naming conflicts.
#define b3Array_Append( a, src, n ) \
do \
{ \
int b3_n = ( n ); \
if ( ( a ).count + b3_n > ( a ).capacity ) \
int _n = ( n ); \
if ( ( a ).count + _n > ( a ).capacity ) \
{ \
int req = ( a ).count + b3_n; \
int req = ( a ).count + _n; \
int newCapacity = req > 2 ? req + ( req >> 1 ) : 8; \
int oldSize = ( a ).capacity * sizeof( *( a ).data ); \
int newSize = newCapacity * sizeof( *( a ).data ); \
( a ).data = (B3_TYPE_OF( ( a ).data ))b3GrowAlloc( ( a ).data, oldSize, newSize ); \
( a ).capacity = newCapacity; \
} \
memcpy( ( a ).data + ( a ).count, ( src ), b3_n * sizeof( *( a ).data ) ); \
( a ).count += b3_n; \
memcpy( ( a ).data + ( a ).count, ( src ), _n * sizeof( *( a ).data ) ); \
( a ).count += _n; \
} \
while ( 0 )

View file

@ -69,7 +69,7 @@ static int b3ClipSegment( b3ClipVertex segment[2], b3Plane plane )
return vertexCount;
}
static int b3ClipSegmentToHullFace( b3ClipVertex segment[2], const b3Hull* hull, int refFace )
static int b3ClipSegmentToHullFace( b3ClipVertex segment[2], const b3HullData* hull, int refFace )
{
const b3HullFace* faces = b3GetHullFaces( hull );
const b3Plane* planes = b3GetHullPlanes( hull );
@ -106,7 +106,7 @@ static int b3ClipSegmentToHullFace( b3ClipVertex segment[2], const b3Hull* hull,
return 2;
}
static b3FaceQuery b3QueryFaceDirectionHullAndCapsule( const b3Hull* hull, const b3Capsule* capsule,
static b3FaceQuery b3QueryFaceDirectionHullAndCapsule( const b3HullData* hull, const b3Capsule* capsule,
b3Transform capsuleTransform )
{
int maxFaceIndex = -1;
@ -141,7 +141,7 @@ static b3FaceQuery b3QueryFaceDirectionHullAndCapsule( const b3Hull* hull, const
};
}
static b3FaceQuery b3QueryFaceDirections( const b3Hull* hullA, const b3Hull* hullB, b3Transform relativeTransform )
static b3FaceQuery b3QueryFaceDirections( const b3HullData* hullA, const b3HullData* hullB, b3Transform relativeTransform )
{
// We perform all computations in local space of the second hull
b3Transform transform = b3InvertTransform( relativeTransform );
@ -174,7 +174,7 @@ static b3FaceQuery b3QueryFaceDirections( const b3Hull* hullA, const b3Hull* hul
};
}
static b3EdgeQuery b3QueryEdgeDirectionHullAndCapsule( const b3Hull* hull, const b3Capsule* capsule,
static b3EdgeQuery b3QueryEdgeDirectionHullAndCapsule( const b3HullData* hull, const b3Capsule* capsule,
b3Transform capsuleTransform )
{
// Find axis of minimum penetration
@ -230,7 +230,7 @@ static b3EdgeQuery b3QueryEdgeDirectionHullAndCapsule( const b3Hull* hull, const
};
}
static b3EdgeQuery b3QueryEdgeDirections( const b3Hull* hullA, const b3Hull* hullB, b3Transform transformBtoA )
static b3EdgeQuery b3QueryEdgeDirections( const b3HullData* hullA, const b3HullData* hullB, b3Transform transformBtoA )
{
// Find axis of minimum penetration
float maxSeparation = -FLT_MAX;
@ -535,7 +535,7 @@ void b3CollideCapsuleAndSphere( b3LocalManifold* manifold, int capacity, const b
float totalRadius = sphereB->radius + capsuleA->radius;
b3Vec3 closestPoint = b3ClosestPointOnSegment( center1, center2, center );
b3Vec3 closestPoint = b3PointToSegmentDistance( center1, center2, center );
b3Vec3 offset = b3Sub( center, closestPoint );
float distanceSq = b3LengthSquared( offset );
@ -567,7 +567,7 @@ void b3CollideCapsuleAndSphere( b3LocalManifold* manifold, int capacity, const b
pt->pair = b3FeaturePair_single;
}
void b3CollideHullAndSphere( b3LocalManifold* manifold, int capacity, const b3Hull* hullA, const b3Sphere* sphereB,
void b3CollideHullAndSphere( b3LocalManifold* manifold, int capacity, const b3HullData* hullA, const b3Sphere* sphereB,
b3Transform transformBtoA, b3SimplexCache* cache )
{
manifold->pointCount = 0;
@ -685,7 +685,7 @@ void b3CollideCapsules( b3LocalManifold* manifold, int capacity, const b3Capsule
float radius = capsuleA->radius + capsuleB->radius;
float maxDistance = radius + B3_SPECULATIVE_DISTANCE;
b3ClosestApproachResult result = b3ClosestApproachSegments( centerA1, centerA2, centerB1, centerB2 );
b3SegmentDistanceResult result = b3SegmentDistance( centerA1, centerA2, centerB1, centerB2 );
b3Vec3 offset = b3Sub( result.point2, result.point1 );
float distanceSquared = b3LengthSquared( offset );
float linearSlop = B3_LINEAR_SLOP;
@ -748,8 +748,8 @@ void b3CollideCapsules( b3LocalManifold* manifold, int capacity, const b3Capsule
if ( pointCount == 2 )
{
// Closest points on A to the clipped points on B.
b3Vec3 closestPoint1 = b3ClosestPointOnSegment( centerA1, centerA2, verticesB[0].position );
b3Vec3 closestPoint2 = b3ClosestPointOnSegment( centerA1, centerA2, verticesB[1].position );
b3Vec3 closestPoint1 = b3PointToSegmentDistance( centerA1, centerA2, verticesB[0].position );
b3Vec3 closestPoint2 = b3PointToSegmentDistance( centerA1, centerA2, verticesB[1].position );
float distance1 = b3Distance( closestPoint1, verticesB[0].position );
float distance2 = b3Distance( closestPoint2, verticesB[1].position );
@ -810,7 +810,7 @@ void b3CollideCapsules( b3LocalManifold* manifold, int capacity, const b3Capsule
pt->pair = b3FeaturePair_single;
}
static bool b3BuildHullFaceAndCapsuleContact( b3LocalManifold* manifold, const b3Hull* hullA, const b3Capsule* capsuleB,
static bool b3BuildHullFaceAndCapsuleContact( b3LocalManifold* manifold, const b3HullData* hullA, const b3Capsule* capsuleB,
b3Transform transformBtoA, b3FaceQuery query )
{
// Work in shapeA coordinates
@ -877,7 +877,7 @@ static inline float b3DeepestPointSeparation( const b3LocalManifold* manifold )
return minSeparation;
}
static bool b3BuildHullAndCapsuleEdgeContact( b3LocalManifold* manifold, int capacity, const b3Hull* hullA,
static bool b3BuildHullAndCapsuleEdgeContact( b3LocalManifold* manifold, int capacity, const b3HullData* hullA,
const b3Capsule* capsuleB, b3Transform transformBtoA, b3EdgeQuery query )
{
if ( capacity < 1 )
@ -910,7 +910,7 @@ static bool b3BuildHullAndCapsuleEdgeContact( b3LocalManifold* manifold, int cap
normal = b3Neg( normal );
}
b3ClosestApproachResult result = b3ClosestApproachLines( ph, eh, pc, ec );
b3SegmentDistanceResult result = b3LineDistance( ph, eh, pc, ec );
if ( b3IsWithinSegments( &result ) == false )
{
@ -934,7 +934,7 @@ static bool b3BuildHullAndCapsuleEdgeContact( b3LocalManifold* manifold, int cap
return true;
}
void b3CollideHullAndCapsule( b3LocalManifold* manifold, int capacity, const b3Hull* hullA, const b3Capsule* capsuleB,
void b3CollideHullAndCapsule( b3LocalManifold* manifold, int capacity, const b3HullData* hullA, const b3Capsule* capsuleB,
b3Transform transformBtoA, b3SimplexCache* cache )
{
manifold->pointCount = 0;
@ -1071,7 +1071,7 @@ void b3CollideHullAndCapsule( b3LocalManifold* manifold, int capacity, const b3H
}
}
static int b3BuildPolygon( b3ClipVertex* out, b3Transform transform, const b3Hull* hull, int incFace, b3Plane refPlane )
static int b3BuildPolygon( b3ClipVertex* out, b3Transform transform, const b3HullData* hull, int incFace, b3Plane refPlane )
{
const b3HullFace* faces = b3GetHullFaces( hull );
const b3HullHalfEdge* edges = b3GetHullEdges( hull );
@ -1109,7 +1109,7 @@ static int b3BuildPolygon( b3ClipVertex* out, b3Transform transform, const b3Hul
return outCount;
}
static bool b3BuildFaceAContact( b3LocalManifold* manifold, int capacity, const b3Hull* hullA, const b3Hull* hullB,
static bool b3BuildFaceAContact( b3LocalManifold* manifold, int capacity, const b3HullData* hullA, const b3HullData* hullB,
b3Transform transformBtoA, b3FaceQuery query, b3SATCache* cache )
{
const b3HullFace* facesA = b3GetHullFaces( hullA );
@ -1206,7 +1206,7 @@ static bool b3BuildFaceAContact( b3LocalManifold* manifold, int capacity, const
return true;
}
static bool b3BuildFaceBContact( b3LocalManifold* manifold, int capacity, const b3Hull* hullA, const b3Hull* hullB,
static bool b3BuildFaceBContact( b3LocalManifold* manifold, int capacity, const b3HullData* hullA, const b3HullData* hullB,
b3Transform transformBtoA, b3FaceQuery query, b3SATCache* cache )
{
b3Transform transformAtoB = b3InvertTransform( transformBtoA );
@ -1237,7 +1237,7 @@ static bool b3BuildFaceBContact( b3LocalManifold* manifold, int capacity, const
return true;
}
static bool b3BuildEdgeContact( b3LocalManifold* manifold, const b3Hull* hullA, const b3Hull* hullB, b3Transform transformBtoA,
static bool b3BuildEdgeContact( b3LocalManifold* manifold, const b3HullData* hullA, const b3HullData* hullB, b3Transform transformBtoA,
b3EdgeQuery query, b3SATCache* cache )
{
// Work in shapeA coordinates
@ -1270,7 +1270,7 @@ static bool b3BuildEdgeContact( b3LocalManifold* manifold, const b3Hull* hullA,
normal = b3Neg( normal );
}
b3ClosestApproachResult result = b3ClosestApproachLines( pA, eA, pB, eB );
b3SegmentDistanceResult result = b3LineDistance( pA, eA, pB, eB );
if ( b3IsWithinSegments( &result ) == false )
{
@ -1304,7 +1304,7 @@ static bool b3BuildEdgeContact( b3LocalManifold* manifold, const b3Hull* hullA,
return true;
}
void b3CollideHulls( b3LocalManifold* manifold, int capacity, const b3Hull* hullA, const b3Hull* hullB, b3Transform transformBtoA,
void b3CollideHulls( b3LocalManifold* manifold, int capacity, const b3HullData* hullA, const b3HullData* hullB, b3Transform transformBtoA,
b3SATCache* cache )
{
manifold->pointCount = 0;

View file

@ -131,6 +131,12 @@ void* b3GrowAlloc( void* oldMem, int oldSize, int newSize );
void b3Log( const char* format, ... );
// Geometry content hashes reserve zero to mean unhashed
static inline uint32_t b3NonZeroHash( uint32_t hash )
{
return hash != 0 ? hash : 1;
}
typedef struct b3Mutex b3Mutex;
b3Mutex* b3CreateMutex( void );
void b3DestroyMutex( b3Mutex* m );

View file

@ -3,6 +3,9 @@
#pragma once
#include "box3d/base.h"
#include <stdbool.h>
#include <stdint.h>
#if defined( _MSC_VER ) && !defined( __clang__ )
@ -11,7 +14,7 @@
// https://en.wikipedia.org/wiki/Find_first_set
B3_INLINE uint32_t b3CTZ32( uint32_t block )
static inline uint32_t b3CTZ32( uint32_t block )
{
unsigned long index;
_BitScanForward( &index, block );
@ -19,7 +22,7 @@ B3_INLINE uint32_t b3CTZ32( uint32_t block )
}
// This function doesn't need to be fast, so using the Ivy Bridge fallback.
B3_INLINE uint32_t b3CLZ32( uint32_t value )
static inline uint32_t b3CLZ32( uint32_t value )
{
#if 0
@ -45,7 +48,7 @@ B3_INLINE uint32_t b3CLZ32( uint32_t value )
#endif
}
B3_INLINE uint32_t b3CTZ64( uint64_t block )
static inline uint32_t b3CTZ64( uint64_t block )
{
unsigned long index;
@ -67,41 +70,41 @@ B3_INLINE uint32_t b3CTZ64( uint64_t block )
return index;
}
B3_INLINE int b3PopCount64( uint64_t block )
static inline int b3PopCount64( uint64_t block )
{
return (int)__popcnt64( block );
}
#else
B3_INLINE uint32_t b3CTZ32( uint32_t block )
static inline uint32_t b3CTZ32( uint32_t block )
{
return __builtin_ctz( block );
}
B3_INLINE uint32_t b3CLZ32( uint32_t value )
static inline uint32_t b3CLZ32( uint32_t value )
{
return __builtin_clz( value );
}
B3_INLINE uint32_t b3CTZ64( uint64_t block )
static inline uint32_t b3CTZ64( uint64_t block )
{
return __builtin_ctzll( block );
}
B3_INLINE int b3PopCount64( uint64_t block )
static inline int b3PopCount64( uint64_t block )
{
return __builtin_popcountll( block );
}
#endif
B3_INLINE bool b3IsPowerOf2( int x )
static inline bool b3IsPowerOf2( int x )
{
return ( x & ( x - 1 ) ) == 0;
}
B3_INLINE int b3BoundingPowerOf2( int x )
static inline int b3BoundingPowerOf2( int x )
{
if ( x <= 1 )
{
@ -111,7 +114,7 @@ B3_INLINE int b3BoundingPowerOf2( int x )
return 32 - (int)b3CLZ32( (uint32_t)x - 1 );
}
B3_INLINE int b3RoundUpPowerOf2( int x )
static inline int b3RoundUpPowerOf2( int x )
{
if ( x <= 1 )
{
@ -121,7 +124,7 @@ B3_INLINE int b3RoundUpPowerOf2( int x )
return 1 << ( 32 - (int)b3CLZ32( (uint32_t)x - 1 ) );
}
B3_INLINE int b3LowerPowerOf2Exponent( int x )
static inline int b3LowerPowerOf2Exponent( int x )
{
B3_ASSERT( x > 0 );
int clz = (int)b3CLZ32( (uint32_t)x );

View file

@ -465,7 +465,7 @@ b3HeightField* b3CreateHeightField( const b3HeightFieldDef* data )
h = b3Hash( h, (const uint8_t*)hf->materialIndices, cellCount * (int)sizeof( uint8_t ) );
h = b3Hash( h, (const uint8_t*)hf->flags, triangleCount * (int)sizeof( uint8_t ) );
h = b3Hash( h, (const uint8_t*)&hf->aabb, (int)( sizeof( b3HeightField ) - offsetof( b3HeightField, aabb ) ) );
hf->hash = h;
hf->hash = b3NonZeroHash( h );
return hf;
}

View file

@ -4,6 +4,7 @@
// Dirk Gregorius contributed portions of this code
#include "algorithm.h"
#include "hull_map.h"
#include "math_internal.h"
#include "shape.h"
@ -1570,7 +1571,7 @@ static void b3HullBuilder_Init( b3HullBuilder* b, char* mem, const b3HullWorkSiz
b->horizonStackCapacity = s->horizonStackCapacity;
}
static b3Vec3* b3GetHullPointsWrite( b3Hull* hull )
static b3Vec3* b3GetHullPointsWrite( b3HullData* hull )
{
if ( hull->pointOffset == 0 )
{
@ -1579,7 +1580,7 @@ static b3Vec3* b3GetHullPointsWrite( b3Hull* hull )
return (b3Vec3*)( (intptr_t)hull + hull->pointOffset );
}
static b3Plane* b3GetHullPlanesWrite( b3Hull* hull )
static b3Plane* b3GetHullPlanesWrite( b3HullData* hull )
{
if ( hull->planeOffset == 0 )
{
@ -1588,7 +1589,7 @@ static b3Plane* b3GetHullPlanesWrite( b3Hull* hull )
return (b3Plane*)( (intptr_t)hull + hull->planeOffset );
}
static b3HullVertex* b3GetHullVerticesWrite( b3Hull* hull )
static b3HullVertex* b3GetHullVerticesWrite( b3HullData* hull )
{
if ( hull->vertexOffset == 0 )
{
@ -1597,7 +1598,7 @@ static b3HullVertex* b3GetHullVerticesWrite( b3Hull* hull )
return (b3HullVertex*)( (intptr_t)hull + hull->vertexOffset );
}
static b3HullHalfEdge* b3GetHullEdgesWrite( b3Hull* hull )
static b3HullHalfEdge* b3GetHullEdgesWrite( b3HullData* hull )
{
if ( hull->edgeOffset == 0 )
{
@ -1606,7 +1607,7 @@ static b3HullHalfEdge* b3GetHullEdgesWrite( b3Hull* hull )
return (b3HullHalfEdge*)( (intptr_t)hull + hull->edgeOffset );
}
int b3FindHullSupportVertex( const b3Hull* hull, b3Vec3 direction )
int b3FindHullSupportVertex( const b3HullData* hull, b3Vec3 direction )
{
int bestIndex = B3_NULL_INDEX;
float bestDot = -FLT_MAX;
@ -1628,7 +1629,7 @@ int b3FindHullSupportVertex( const b3Hull* hull, b3Vec3 direction )
return bestIndex;
}
int b3FindHullSupportFace( const b3Hull* hull, b3Vec3 direction )
int b3FindHullSupportFace( const b3HullData* hull, b3Vec3 direction )
{
int bestIndex = B3_NULL_INDEX;
float bestDot = -FLT_MAX;
@ -1652,7 +1653,7 @@ int b3FindHullSupportFace( const b3Hull* hull, b3Vec3 direction )
#if B3_ENABLE_VALIDATION
bool b3IsValidHull( const b3Hull* hull )
bool b3IsValidHull( const b3HullData* hull )
{
if ( hull->version != B3_HULL_VERSION )
{
@ -1759,7 +1760,7 @@ bool b3IsValidHull( const b3Hull* hull )
#else
bool b3IsValidHull( const b3Hull* hull )
bool b3IsValidHull( const b3HullData* hull )
{
B3_UNUSED( hull );
return true;
@ -1767,7 +1768,7 @@ bool b3IsValidHull( const b3Hull* hull )
#endif
b3Hull* b3CreateCylinder( float height, float radius, float yOffset, int sides )
b3HullData* b3CreateCylinder( float height, float radius, float yOffset, int sides )
{
B3_ASSERT( height > 0.0f );
B3_ASSERT( radius > 0.0f );
@ -1791,7 +1792,7 @@ b3Hull* b3CreateCylinder( float height, float radius, float yOffset, int sides )
alpha += deltaAlpha;
}
b3Hull* hull = b3CreateHull( points, pointCount, pointCount );
b3HullData* hull = b3CreateHull( points, pointCount, pointCount );
B3_ASSERT( hull->vertexCount == pointCount );
B3_ASSERT( hull->edgeCount == 6 * sides );
B3_ASSERT( hull->faceCount == sides + 2 );
@ -1801,7 +1802,7 @@ b3Hull* b3CreateCylinder( float height, float radius, float yOffset, int sides )
return hull;
}
b3Hull* b3CreateCone( float height, float radius1, float radius2, int slices )
b3HullData* b3CreateCone( float height, float radius1, float radius2, int slices )
{
B3_ASSERT( height > 0.0f );
B3_ASSERT( radius1 > 0.0f );
@ -1826,7 +1827,7 @@ b3Hull* b3CreateCone( float height, float radius1, float radius2, int slices )
alpha += deltaAlpha;
}
b3Hull* hull = b3CreateHull( points, pointCount, pointCount );
b3HullData* hull = b3CreateHull( points, pointCount, pointCount );
B3_ASSERT( hull->vertexCount == pointCount );
B3_ASSERT( hull->edgeCount == 6 * slices );
B3_ASSERT( hull->faceCount == slices + 2 );
@ -1836,7 +1837,7 @@ b3Hull* b3CreateCone( float height, float radius1, float radius2, int slices )
return hull;
}
static void b3UpdateHullBounds( b3Hull* hull )
static void b3UpdateHullBounds( b3HullData* hull )
{
const b3Vec3* points = b3GetHullPoints( hull );
int vertexCount = hull->vertexCount;
@ -1857,7 +1858,7 @@ static void b3UpdateHullBounds( b3Hull* hull )
}
// M. Kallay - "Computing the Moment of Inertia of a Solid Defined by a Triangle Mesh"
static bool b3UpdateHullBulkProperties( b3Hull* hull )
static bool b3UpdateHullBulkProperties( b3HullData* hull )
{
const b3Vec3* points = b3GetHullPoints( hull );
const b3HullFace* faces = b3GetHullFaces( hull );
@ -1984,7 +1985,7 @@ static bool b3UpdateHullBulkProperties( b3Hull* hull )
return true;
}
b3Hull* b3CreateHull( const b3Vec3* points, int pointCount, int maxVertexCount )
b3HullData* b3CreateHull( const b3Vec3* points, int pointCount, int maxVertexCount )
{
if ( pointCount < 4 )
{
@ -2077,7 +2078,7 @@ b3Hull* b3CreateHull( const b3Vec3* points, int pointCount, int maxVertexCount )
}
// Allocate the hull. Arrays hang off the end.
size_t byteCount = b3AlignUp8( sizeof( b3Hull ) );
size_t byteCount = b3AlignUp8( sizeof( b3HullData ) );
int vertexOffset = (int)byteCount;
byteCount += b3AlignUp8( vertexCount * (int)sizeof( b3HullVertex ) );
int pointOffset = (int)byteCount;
@ -2089,7 +2090,7 @@ b3Hull* b3CreateHull( const b3Vec3* points, int pointCount, int maxVertexCount )
int planeOffset = (int)byteCount;
byteCount += b3AlignUp8( faceCount * (int)sizeof( b3Plane ) );
b3Hull* hull = b3Alloc( byteCount );
b3HullData* hull = b3Alloc( byteCount );
memset( hull, 0, byteCount );
hull->version = B3_HULL_VERSION;
@ -2160,32 +2161,80 @@ b3Hull* b3CreateHull( const b3Vec3* points, int pointCount, int maxVertexCount )
}
hull->hash = 0;
hull->hash = b3Hash( B3_HASH_INIT, (uint8_t*)hull, hull->byteCount );
hull->hash = b3NonZeroHash( b3Hash( B3_HASH_INIT, (uint8_t*)hull, hull->byteCount ) );
return hull;
}
b3Hull* b3CloneHull( const b3Hull* hull )
b3HullData* b3CloneHull( const b3HullData* hull )
{
if ( hull == NULL || b3IsValidHull( hull ) == false )
{
return NULL;
}
b3Hull* clone = (b3Hull*)b3Alloc( hull->byteCount );
b3HullData* clone = (b3HullData*)b3Alloc( hull->byteCount );
memcpy( clone, hull, hull->byteCount );
return clone;
}
b3Hull* b3CloneAndTransformHull( const b3Hull* original, b3Transform transform, b3Vec3 scale )
uint64_t b3HashHullData( const b3HullData* hull )
{
// The baked content hash already covers byteCount. Spread the 32 bits across 64 so the table
// can use the high bits for its fast reject fragment.
return (uint64_t)hull->hash * 0x9E3779B97F4A7C15ull;
}
bool b3CompareHullData( const b3HullData* hull1, const b3HullData* hull2 )
{
if ( hull1 == hull2 )
{
return true;
}
if ( hull1->byteCount != hull2->byteCount )
{
return false;
}
return memcmp( hull1, hull2, hull1->byteCount ) == 0;
}
// Hull identity covers every byte, so the structs carry explicit padding. These lock
// the layout, re-audit padding if a size changes.
_Static_assert( sizeof( b3HullData ) == 136, "unexpected hull data size" );
_Static_assert( sizeof( b3BoxHull ) == 440, "unexpected box hull size" );
#define NAME b3HullMap
#define KEY_TY const b3HullData*
#define VAL_TY int
#define HASH_FN b3HashHullData
#define CMPR_FN b3CompareHullData
#define MALLOC_FN b3Alloc
#define FREE_FN b3Free
#define IMPLEMENTATION_MODE
#include "verstable.h"
size_t b3HullMapByteCount( b3HullMap* map )
{
// The map owns a combined bucket and metadata allocation, valid only when buckets exist
size_t byteCount = sizeof( b3HullMap );
if ( b3HullMap_bucket_count( map ) > 0 )
{
byteCount += b3HullMap_total_alloc_size( map );
}
return byteCount;
}
b3HullData* b3CloneAndTransformHull( const b3HullData* original, b3Transform transform, b3Vec3 scale )
{
if ( original == NULL || b3IsValidHull( original ) == false )
{
return NULL;
}
b3Hull* hull = (b3Hull*)b3Alloc( original->byteCount );
b3HullData* hull = (b3HullData*)b3Alloc( original->byteCount );
memcpy( hull, original, original->byteCount );
b3Vec3 safeScale = b3SafeScale( scale );
@ -2317,19 +2366,19 @@ b3Hull* b3CloneAndTransformHull( const b3Hull* original, b3Transform transform,
}
hull->hash = 0;
hull->hash = b3Hash( B3_HASH_INIT, (uint8_t*)hull, hull->byteCount );
hull->hash = b3NonZeroHash( b3Hash( B3_HASH_INIT, (uint8_t*)hull, hull->byteCount ) );
B3_VALIDATE( b3IsValidHull( hull ) );
return hull;
}
void b3DestroyHull( b3Hull* hull )
void b3DestroyHull( b3HullData* hull )
{
b3Free( hull, hull->byteCount );
}
b3MassData b3ComputeHullMass( const b3Hull* shape, float density )
b3MassData b3ComputeHullMass( const b3HullData* shape, float density )
{
b3MassData out;
out.mass = density * shape->volume;
@ -2340,19 +2389,19 @@ b3MassData b3ComputeHullMass( const b3Hull* shape, float density )
return out;
}
b3AABB b3ComputeHullAABB( const b3Hull* shape, b3Transform transform )
b3AABB b3ComputeHullAABB( const b3HullData* shape, b3Transform transform )
{
return b3AABB_Transform( transform, shape->aabb );
}
b3AABB b3ComputeSweptHullAABB( const b3Hull* shape, b3Transform xf1, b3Transform xf2 )
b3AABB b3ComputeSweptHullAABB( const b3HullData* shape, b3Transform xf1, b3Transform xf2 )
{
b3AABB aabb1 = b3AABB_Transform( xf1, shape->aabb );
b3AABB aabb2 = b3AABB_Transform( xf2, shape->aabb );
return b3AABB_Union( aabb1, aabb2 );
}
bool b3OverlapHull( const b3Hull* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy )
bool b3OverlapHull( const b3HullData* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy )
{
const b3Vec3* points = b3GetHullPoints( shape );
@ -2368,7 +2417,7 @@ bool b3OverlapHull( const b3Hull* shape, b3Transform shapeTransform, const b3Sha
return output.distance < B3_OVERLAP_SLOP;
}
b3CastOutput b3RayCastHull( const b3Hull* shape, const b3RayCastInput* input )
b3CastOutput b3RayCastHull( const b3HullData* shape, const b3RayCastInput* input )
{
B3_ASSERT( b3IsValidRay( input ) );
b3CastOutput output = { 0 };
@ -2436,7 +2485,7 @@ b3CastOutput b3RayCastHull( const b3Hull* shape, const b3RayCastInput* input )
return output;
}
b3CastOutput b3ShapeCastHull( const b3Hull* shape, const b3ShapeCastInput* input )
b3CastOutput b3ShapeCastHull( const b3HullData* shape, const b3ShapeCastInput* input )
{
const b3Vec3* points = b3GetHullPoints( shape );
@ -2453,7 +2502,7 @@ b3CastOutput b3ShapeCastHull( const b3Hull* shape, const b3ShapeCastInput* input
return output;
}
int b3CollideMoverAndHull( b3PlaneResult* result, const b3Hull* shape, const b3Capsule* mover )
int b3CollideMoverAndHull( b3PlaneResult* result, const b3HullData* shape, const b3Capsule* mover )
{
const b3Vec3* points = b3GetHullPoints( shape );
b3DistanceInput distanceInput;
@ -2487,7 +2536,7 @@ int b3CollideMoverAndHull( b3PlaneResult* result, const b3Hull* shape, const b3C
return 0;
}
b3ShapeExtent b3ComputeHullExtent( const b3Hull* hull, b3Vec3 origin )
b3ShapeExtent b3ComputeHullExtent( const b3HullData* hull, b3Vec3 origin )
{
const b3Vec3* points = b3GetHullPoints( hull );
@ -2503,7 +2552,7 @@ b3ShapeExtent b3ComputeHullExtent( const b3Hull* hull, b3Vec3 origin )
return extent;
}
float b3ComputeHullProjectedArea( const b3Hull* hull, b3Vec3 direction )
float b3ComputeHullProjectedArea( const b3HullData* hull, b3Vec3 direction )
{
float area = 0.0f;
@ -2630,7 +2679,7 @@ b3BoxHull b3MakeTransformedBoxHull( float hx, float hy, float hz, b3Transform tr
boxHull.boxPoints[7] = b3TransformPoint( transform, (b3Vec3){ h.x, -h.y, -h.z } );
boxHull.base.hash = 0;
boxHull.base.hash = b3Hash( B3_HASH_INIT, (uint8_t*)&boxHull, sizeof( b3BoxHull ) );
boxHull.base.hash = b3NonZeroHash( b3Hash( B3_HASH_INIT, (uint8_t*)&boxHull, sizeof( b3BoxHull ) ) );
return boxHull;
}

24
src/hull_map.h Normal file
View file

@ -0,0 +1,24 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
#pragma once
#include "box3d/types.h"
#include <stddef.h>
// Content hash and equality over the whole baked hull. Shared by every hull
// de-duplication map so they agree on identity.
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.
#define NAME b3HullMap
#define KEY_TY const b3HullData*
#define VAL_TY int
#define HEADER_MODE
#include "verstable.h"
// Total map allocation in bytes, excluding the stored hull data
size_t b3HullMapByteCount( b3HullMap* map );

View file

@ -7,7 +7,7 @@
typedef struct b3IdPool
{
b3ArrayC( int ) freeArray;
b3Array( int ) freeArray;
int nextIndex;
} b3IdPool;

View file

@ -63,14 +63,14 @@ typedef struct b3Island
// I tried using a stack array for this but the data pointer goes out of
// sync when the world island array grows.
b3ArrayC( int ) bodies;
b3Array( int ) bodies;
// Contacts and joints that belong to this island. May connect to static
// bodies not in the island.
// Each link has the two body ids so that b3SplitIsland's union-find pass
// never needs to touch b3Contact/b3Joint.
b3ArrayC( b3ContactLink ) contacts;
b3ArrayC( b3JointLink ) joints;
b3Array( b3ContactLink ) contacts;
b3Array( b3JointLink ) joints;
} b3Island;

View file

@ -67,7 +67,7 @@ float b3EdgeEdgeSeparation( b3Vec3 p1, b3Vec3 e1, b3Vec3 c1, b3Vec3 p2, b3Vec3 e
// Then we look for all edges coming out of that vertex and look for the edge that is
// most perpendicular to the reference normal.
// Then from that edge, we select the adjacent face that is most anti-parallel to the reference normal.
int b3FindIncidentFace( const b3Hull* hull, b3Vec3 refNormal, int vertexIndex )
int b3FindIncidentFace( const b3HullData* hull, b3Vec3 refNormal, int vertexIndex )
{
const b3HullVertex* vertices = b3GetHullVertices( hull );
const b3HullHalfEdge* edges = b3GetHullEdges( hull );

View file

@ -36,7 +36,7 @@ typedef enum b3FeatureOwner
} b3FeatureOwner;
float b3EdgeEdgeSeparation( b3Vec3 p1, b3Vec3 e1, b3Vec3 c1, b3Vec3 p2, b3Vec3 e2, b3Vec3 c2 );
int b3FindIncidentFace( const b3Hull* hull, b3Vec3 refNormal, int vertexIndex );
int b3FindIncidentFace( const b3HullData* hull, b3Vec3 refNormal, int vertexIndex );
b3FeaturePair b3MakeFeaturePair( b3FeatureOwner owner1, int index1, b3FeatureOwner owner2, int index2 );
b3FeaturePair b3FlipPair( b3FeaturePair pair );

View file

@ -315,9 +315,9 @@ b3Quat b3ComputeQuatBetweenUnitVectors( b3Vec3 v1, b3Vec3 v2 )
//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
b3ClosestApproachResult b3ClosestApproachLines( b3Vec3 p1, b3Vec3 d1, b3Vec3 p2, b3Vec3 d2 )
b3SegmentDistanceResult b3LineDistance( b3Vec3 p1, b3Vec3 d1, b3Vec3 p2, b3Vec3 d2 )
{
b3ClosestApproachResult result;
b3SegmentDistanceResult result;
// Solve A*x = b
float a11 = b3Dot( d1, d1 );
@ -355,9 +355,9 @@ b3ClosestApproachResult b3ClosestApproachLines( b3Vec3 p1, b3Vec3 d1, b3Vec3 p2,
}
//--------------------------------------------------------------------------------------------------
b3ClosestApproachResult b3ClosestApproachSegments( b3Vec3 p1, b3Vec3 q1, b3Vec3 p2, b3Vec3 q2 )
b3SegmentDistanceResult b3SegmentDistance( b3Vec3 p1, b3Vec3 q1, b3Vec3 p2, b3Vec3 q2 )
{
b3ClosestApproachResult result;
b3SegmentDistanceResult result;
b3Vec3 d1 = b3Sub( q1, p1 );
b3Vec3 d2 = b3Sub( q2, p2 );
@ -432,7 +432,7 @@ b3ClosestApproachResult b3ClosestApproachSegments( b3Vec3 p1, b3Vec3 q1, b3Vec3
return result;
}
b3Vec3 b3ClosestPointOnSegment( b3Vec3 a, b3Vec3 b, b3Vec3 q )
b3Vec3 b3PointToSegmentDistance( b3Vec3 a, b3Vec3 b, b3Vec3 q )
{
b3Vec3 ab = b3Sub( b, a );
b3Vec3 aq = b3Sub( q, a );

View file

@ -31,7 +31,7 @@ typedef struct b3Triangle
int flags;
} b3Triangle;
typedef struct
typedef struct b3TrianglePoint
{
b3Vec3 point;
b3TriangleFeature feature;
@ -46,22 +46,22 @@ typedef struct b3ShapeExtent
b3TrianglePoint b3ClosestPointOnTriangle( b3Vec3 a, b3Vec3 b, b3Vec3 c, b3Vec3 q );
// The closest points between to segments or infinite lines.
typedef struct b3ClosestApproachResult
typedef struct b3SegmentDistanceResult
{
b3Vec3 point1;
float fraction1;
b3Vec3 point2;
float fraction2;
} b3ClosestApproachResult;
} b3SegmentDistanceResult;
// Compute the closest point on the segment a-b to the target q
b3Vec3 b3ClosestPointOnSegment( b3Vec3 a, b3Vec3 b, b3Vec3 q );
b3Vec3 b3PointToSegmentDistance( b3Vec3 a, b3Vec3 b, b3Vec3 q );
// Compute the closest points on two infinite lines
b3ClosestApproachResult b3ClosestApproachLines( b3Vec3 p1, b3Vec3 d1, b3Vec3 p2, b3Vec3 d2 );
b3SegmentDistanceResult b3LineDistance( b3Vec3 p1, b3Vec3 d1, b3Vec3 p2, b3Vec3 d2 );
// Compute the closest points on two line segments
b3ClosestApproachResult b3ClosestApproachSegments( b3Vec3 p1, b3Vec3 q1, b3Vec3 p2, b3Vec3 q2 );
b3SegmentDistanceResult b3SegmentDistance( b3Vec3 p1, b3Vec3 q1, b3Vec3 p2, b3Vec3 q2 );
float b3IntersectSegmentTriangle( b3Vec3 p, b3Vec3 q, b3Vec3 a, b3Vec3 b, b3Vec3 c );
float b3IntersectSegmentSphere( b3Vec3 p, b3Vec3 q, b3Vec3 c, float r );
@ -470,7 +470,7 @@ static inline float b3SignedVolume( b3Vec3 v1, b3Vec3 v2, b3Vec3 v3, b3Vec3 p )
}
// todo eliminate this
static inline bool b3IsWithinSegments( const b3ClosestApproachResult* result )
static inline bool b3IsWithinSegments( const b3SegmentDistanceResult* result )
{
return ( 0.0f <= result->fraction1 && result->fraction1 <= 1.0f ) &&
( 0.0f <= result->fraction2 && result->fraction2 <= 1.0f );

View file

@ -347,7 +347,7 @@ typedef struct b3VertexNode
typedef struct b3SpatialHash
{
b3ArrayC( b3VertexNode ) nodes;
b3Array( b3VertexNode ) nodes;
const b3Vec3* vertices;
int vertexCount;
b3VertexMap vertexMap;
@ -491,7 +491,7 @@ static int b3WeldVertices( b3WeldData* data, float tolerance )
// Create spatial hash and find duplicates
b3SpatialHash spatialHash;
b3SpatialHash_Create( &spatialHash, data->srcVertices, vertexCount, tolerance );
b3ArrayC( int ) vertexMapping = { 0 };
b3Array( int ) vertexMapping = { 0 };
b3Array_Resize( vertexMapping, vertexCount );
for ( int i = 0; i < vertexCount; ++i )
@ -870,7 +870,7 @@ static bool b3ValidateSplit( int count, b3Primitive* primitives, const b3Split*
#endif
static int b3BuildRecursive( b3ArrayC( b3MeshNode ) * nodes, int count, b3Primitive* primitives, b3Primitive* base,
static int b3BuildRecursive( b3Array( b3MeshNode ) * nodes, int count, b3Primitive* primitives, b3Primitive* base,
bool useMedianSplit, int* height )
{
if ( count > B3_DESIRED_TRIANGLES_PER_LEAF )
@ -955,10 +955,10 @@ static bool b3SortMeshTriangles( b3MeshData* mesh )
// Sort triangles in depth-first-order
int offset = 0;
b3ArrayC( b3MeshTriangle ) tempTriangles;
b3Array( b3MeshTriangle ) tempTriangles;
b3Array_CreateN( tempTriangles, mesh->triangleCount );
b3ArrayC( uint8_t ) tempMaterialIndices;
b3Array( uint8_t ) tempMaterialIndices;
b3Array_CreateN( tempMaterialIndices, mesh->triangleCount );
int count = 0;
@ -1220,7 +1220,7 @@ b3MeshData* b3CreateGridMesh( int xCount, int zCount, float cellWidth, int mater
// Create vertices
int vertexCount = ( xCount + 1 ) * ( zCount + 1 );
b3ArrayC( b3Vec3 ) vertices = { 0 };
b3Array( b3Vec3 ) vertices = { 0 };
b3Array_Resize( vertices, vertexCount );
int index = 0;
@ -1244,10 +1244,10 @@ b3MeshData* b3CreateGridMesh( int xCount, int zCount, float cellWidth, int mater
// Triangles
int triangleCount = 2 * xCount * zCount;
b3ArrayC( int ) indices = { 0 };
b3Array( int ) indices = { 0 };
b3Array_Resize( indices, 3 * triangleCount );
b3ArrayC( uint8_t ) materialIndices = { 0 };
b3Array( uint8_t ) materialIndices = { 0 };
b3Array_Resize( materialIndices, triangleCount );
int materialIndex = 0;
@ -1310,7 +1310,7 @@ b3MeshData* b3CreateWaveMesh( int xCount, int zCount, float cellWidth, float amp
// Create vertices
int vertexCount = ( xCount + 1 ) * ( zCount + 1 );
b3ArrayC( b3Vec3 ) vertices = { 0 };
b3Array( b3Vec3 ) vertices = { 0 };
b3Array_Resize( vertices, vertexCount );
int index = 0;
@ -1342,7 +1342,7 @@ b3MeshData* b3CreateWaveMesh( int xCount, int zCount, float cellWidth, float amp
// Triangles
int triangleCount = 2 * xCount * zCount;
b3ArrayC( int ) indices = { 0 };
b3Array( int ) indices = { 0 };
b3Array_Resize( indices, 3 * triangleCount );
index = 0;
@ -1392,7 +1392,7 @@ b3MeshData* b3CreateWaveMesh( int xCount, int zCount, float cellWidth, float amp
b3MeshData* b3CreateTorusMesh( int radialResolution, int tubularResolution, float radius, float thickness )
{
// Create vertices
b3ArrayC( b3Vec3 ) vertices = { 0 };
b3Array( b3Vec3 ) vertices = { 0 };
for ( int radialIndex = 0; radialIndex < radialResolution; radialIndex++ )
{
@ -1411,7 +1411,7 @@ b3MeshData* b3CreateTorusMesh( int radialResolution, int tubularResolution, floa
}
// Triangles
b3ArrayC( int ) indices = { 0 };
b3Array( int ) indices = { 0 };
for ( int radialIndex1 = 0; radialIndex1 < radialResolution; radialIndex1++ )
{
int radialIndex2 = ( radialIndex1 + 1 ) % radialResolution;
@ -1570,10 +1570,10 @@ b3MeshData* b3CreateMesh( const b3MeshDef* def, int* degenerateTriangleIndices,
b3AABB meshBounds = B3_BOUNDS3_EMPTY;
// Clone indices and vertices to support welding
b3ArrayC( int ) indices;
b3Array( int ) indices;
b3Array_CreateN( indices, 3 * triangleCount );
b3ArrayC( b3Vec3 ) vertices;
b3Array( b3Vec3 ) vertices;
b3Array_CreateN( vertices, vertexCount );
if ( def->weldVertices && def->weldTolerance > 0.0f )
@ -1598,7 +1598,7 @@ b3MeshData* b3CreateMesh( const b3MeshDef* def, int* degenerateTriangleIndices,
b3Array_Append( indices, def->indices, 3 * triangleCount );
}
b3ArrayC( b3Primitive ) primitives;
b3Array( b3Primitive ) primitives;
b3Array_CreateN( primitives, triangleCount );
int degenerateCount = 0;
float minArea = 0.01f * B3_LINEAR_SLOP * B3_LINEAR_SLOP;
@ -1668,7 +1668,7 @@ b3MeshData* b3CreateMesh( const b3MeshDef* def, int* degenerateTriangleIndices,
}
// Build the tree (this reorders the builder triangles)
b3ArrayC( b3MeshNode ) tempNodes;
b3Array( b3MeshNode ) tempNodes;
b3Array_CreateN( tempNodes, 2 * triangleCount - 1 );
int treeHeight = 0;
@ -1758,7 +1758,7 @@ b3MeshData* b3CreateMesh( const b3MeshDef* def, int* degenerateTriangleIndices,
b3Array_Destroy( vertices );
mesh->hash = 0;
mesh->hash = b3Hash( B3_HASH_INIT, (uint8_t*)mesh, mesh->byteCount );
mesh->hash = b3NonZeroHash( b3Hash( B3_HASH_INIT, (uint8_t*)mesh, mesh->byteCount ) );
return mesh;
}

View file

@ -571,6 +571,8 @@ bool b3ComputeMeshManifolds( b3World* world, int workerIndex, b3Contact* contact
b3TriangleCache* triangleCaches = meshContact->triangleCache.data;
const b3HullData* hullB = shapeB->type == b3_hullShape ? shapeB->hull : NULL;
for ( int index = 0; index < triangleCount && totalPointCount + 3 < pointBufferCapacity; ++index )
{
int triangleIndex = triangleCaches[index].triangleIndex;
@ -614,7 +616,7 @@ bool b3ComputeMeshManifolds( b3World* world, int workerIndex, b3Contact* contact
cache->satCache = (b3SATCache){ 0 };
}
b3CollideHullAndTriangle( manifold, pointCapacity, shapeB->hull, vertices[0], vertices[1], vertices[2],
b3CollideHullAndTriangle( manifold, pointCapacity, hullB, vertices[0], vertices[1], vertices[2],
triangle.flags, &cache->satCache );
context->satCallCount += 1;
context->satCacheHitCount += cache->satCache.hit;

View file

@ -12,6 +12,7 @@
#include "contact.h"
#include "core.h"
#include "ctz.h"
#include "hull_map.h"
#include "island.h"
#include "joint.h"
#include "parallel_for.h"
@ -35,6 +36,57 @@ b3World b3_worlds[B3_MAX_WORLDS];
b3AtomicInt b3_worldCount;
int b3_maxWorldCount;
const b3HullData* b3AddHullToDatabase( b3World* world, const b3HullData* src )
{
b3HullMap* database = world->hullDatabase;
// Compare by content so an unowned query hull finds the shared copy.
b3HullMap_itr itr = b3HullMap_get( database, src );
if ( b3HullMap_is_end( itr ) == false )
{
itr.data->val += 1;
return itr.data->key;
}
b3HullData* owned = b3CloneHull( src );
B3_ASSERT( owned != NULL );
b3HullMap_insert( database, owned, 1 );
return owned;
}
const b3HullData* b3AddOwnedHullToDatabase( b3World* world, b3HullData* owned )
{
b3HullMap* database = world->hullDatabase;
b3HullMap_itr itr = b3HullMap_get( database, owned );
if ( b3HullMap_is_end( itr ) == false )
{
itr.data->val += 1;
b3DestroyHull( owned );
return itr.data->key;
}
// Take ownership of input hull.
b3HullMap_insert( database, owned, 1 );
return owned;
}
void b3RemoveHullFromDatabase( b3World* world, const b3HullData* data )
{
b3HullMap* database = world->hullDatabase;
b3HullMap_itr itr = b3HullMap_get( database, data );
B3_ASSERT( b3HullMap_is_end( itr ) == false );
if ( --itr.data->val == 0 )
{
// Erase through the iterator we already have so the lookup runs once.
b3HullData* owned = (b3HullData*)itr.data->key;
b3HullMap_erase_itr( database, itr );
b3DestroyHull( owned );
}
}
b3World* b3GetUnlockedWorldFromId( b3WorldId id )
{
B3_ASSERT( 1 <= id.index1 && id.index1 <= B3_MAX_WORLDS );
@ -235,6 +287,9 @@ b3WorldId b3CreateWorld( const b3WorldDef* def )
int shapeCapacity = b3MaxInt( 16, def->capacity.staticShapeCount + def->capacity.dynamicShapeCount );
b3Array_Reserve( world->shapes, shapeCapacity );
world->hullDatabase = b3Alloc( sizeof( b3HullMap ) );
b3HullMap_init( world->hullDatabase );
world->contactIdPool = b3CreateIdPool();
b3Array_Reserve( world->contacts, b3MaxInt( 16, def->capacity.contactCount ) );
@ -409,6 +464,12 @@ void b3DestroyWorld( b3WorldId worldId )
}
}
// Destroying every shape above released all hull references, so the database is empty.
B3_ASSERT( b3HullMap_size( (b3HullMap*)world->hullDatabase ) == 0 );
b3HullMap_cleanup( world->hullDatabase );
b3Free( world->hullDatabase, sizeof( b3HullMap ) );
world->hullDatabase = NULL;
b3Array_Destroy( world->shapes );
b3Array_Destroy( world->contacts );
b3Array_Destroy( world->joints );
@ -2145,47 +2206,125 @@ void b3World_DumpMemoryStats( b3WorldId worldId )
return;
}
FILE* file = b3OpenFile( "box3d_memory.txt" );
if ( file == NULL )
{
return;
}
// Large worlds can exceed 2GB, sum in 64 bits
uint64_t total = 0;
// id pools
fprintf( file, "id pools\n" );
fprintf( file, "body ids: %d\n", b3GetIdBytes( &world->bodyIdPool ) );
fprintf( file, "solver set ids: %d\n", b3GetIdBytes( &world->solverSetIdPool ) );
fprintf( file, "joint ids: %d\n", b3GetIdBytes( &world->jointIdPool ) );
fprintf( file, "contact ids: %d\n", b3GetIdBytes( &world->contactIdPool ) );
fprintf( file, "island ids: %d\n", b3GetIdBytes( &world->islandIdPool ) );
fprintf( file, "shape ids: %d\n", b3GetIdBytes( &world->shapeIdPool ) );
fprintf( file, "\n" );
int bodyIdBytes = b3GetIdBytes( &world->bodyIdPool );
int solverSetIdBytes = b3GetIdBytes( &world->solverSetIdPool );
int jointIdBytes = b3GetIdBytes( &world->jointIdPool );
int contactIdBytes = b3GetIdBytes( &world->contactIdPool );
int islandIdBytes = b3GetIdBytes( &world->islandIdPool );
int shapeIdBytes = b3GetIdBytes( &world->shapeIdPool );
total += (uint64_t)bodyIdBytes + solverSetIdBytes + jointIdBytes + contactIdBytes + islandIdBytes + shapeIdBytes;
b3Log( "id pools" );
b3Log( "body ids: %d", bodyIdBytes );
b3Log( "solver set ids: %d", solverSetIdBytes );
b3Log( "joint ids: %d", jointIdBytes );
b3Log( "contact ids: %d", contactIdBytes );
b3Log( "island ids: %d", islandIdBytes );
b3Log( "shape ids: %d", shapeIdBytes );
// Islands own per-island body/contact/joint link arrays
int islandLinkBytes = 0;
for ( int i = 0; i < world->islands.count; ++i )
{
b3Island* island = world->islands.data + i;
islandLinkBytes += b3Array_ByteCount( island->bodies );
islandLinkBytes += b3Array_ByteCount( island->contacts );
islandLinkBytes += b3Array_ByteCount( island->joints );
}
// world arrays
fprintf( file, "world arrays\n" );
fprintf( file, "bodies: %d\n", b3Array_ByteCount( world->bodies ) );
fprintf( file, "solver sets: %d\n", b3Array_ByteCount( world->solverSets ) );
fprintf( file, "joints: %d\n", b3Array_ByteCount( world->joints ) );
fprintf( file, "contacts: %d\n", b3Array_ByteCount( world->contacts ) );
fprintf( file, "islands: %d\n", b3Array_ByteCount( world->islands ) );
fprintf( file, "shapes: %d\n", b3Array_ByteCount( world->shapes ) );
fprintf( file, "\n" );
int bodyArrayBytes = b3Array_ByteCount( world->bodies );
int solverSetArrayBytes = b3Array_ByteCount( world->solverSets );
int jointArrayBytes = b3Array_ByteCount( world->joints );
int contactArrayBytes = b3Array_ByteCount( world->contacts );
int islandArrayBytes = b3Array_ByteCount( world->islands );
int shapeArrayBytes = b3Array_ByteCount( world->shapes );
int sensorArrayBytes = b3Array_ByteCount( world->sensors );
total += (uint64_t)bodyArrayBytes + solverSetArrayBytes + jointArrayBytes + contactArrayBytes + islandArrayBytes +
islandLinkBytes + shapeArrayBytes + sensorArrayBytes;
b3Log( "world arrays" );
b3Log( "bodies: %d", bodyArrayBytes );
b3Log( "solver sets: %d", solverSetArrayBytes );
b3Log( "joints: %d", jointArrayBytes );
b3Log( "contacts: %d", contactArrayBytes );
b3Log( "islands: %d", islandArrayBytes );
b3Log( "island links: %d", islandLinkBytes );
b3Log( "shapes: %d", shapeArrayBytes );
b3Log( "sensors: %d", sensorArrayBytes );
// Sensors own overlap tracking arrays. The sensor array is dense.
int sensorOverlapBytes = 0;
for ( int i = 0; i < world->sensors.count; ++i )
{
b3Sensor* sensor = world->sensors.data + i;
sensorOverlapBytes += b3Array_ByteCount( sensor->hits );
sensorOverlapBytes += b3Array_ByteCount( sensor->overlaps1 );
sensorOverlapBytes += b3Array_ByteCount( sensor->overlaps2 );
}
total += sensorOverlapBytes;
b3Log( "owned arrays" );
b3Log( "sensor overlaps: %d", sensorOverlapBytes );
// Shared hull database. The map owns a combined bucket and metadata allocation
// plus the small map struct. Each stored key is an owned clone sized by byteCount.
b3HullMap* hullDatabase = world->hullDatabase;
int hullCount = (int)b3HullMap_size( hullDatabase );
int hullBucketCount = (int)b3HullMap_bucket_count( hullDatabase );
uint64_t hullMapBytes = b3HullMapByteCount( hullDatabase );
uint64_t hullDataBytes = 0;
for ( b3HullMap_itr itr = b3HullMap_first( hullDatabase ); b3HullMap_is_end( itr ) == false;
itr = b3HullMap_next( itr ) )
{
hullDataBytes += itr.data->key->byteCount;
}
total += hullMapBytes + hullDataBytes;
b3Log( "hulls" );
b3Log( "database: %llu (%d, %d)", (unsigned long long)hullMapBytes, hullCount, hullBucketCount );
b3Log( "hull data: %llu", (unsigned long long)hullDataBytes );
// broad-phase
fprintf( file, "broad-phase\n" );
fprintf( file, "static tree: %d\n", b3DynamicTree_GetByteCount( world->broadPhase.trees + b3_staticBody ) );
fprintf( file, "kinematic tree: %d\n", b3DynamicTree_GetByteCount( world->broadPhase.trees + b3_kinematicBody ) );
fprintf( file, "dynamic tree: %d\n", b3DynamicTree_GetByteCount( world->broadPhase.trees + b3_dynamicBody ) );
int staticTreeBytes = b3DynamicTree_GetByteCount( world->broadPhase.trees + b3_staticBody );
int kinematicTreeBytes = b3DynamicTree_GetByteCount( world->broadPhase.trees + b3_kinematicBody );
int dynamicTreeBytes = b3DynamicTree_GetByteCount( world->broadPhase.trees + b3_dynamicBody );
int movedBytes = 0;
for ( int i = 0; i < b3_bodyTypeCount; ++i )
{
movedBytes += b3GetBitSetBytes( &world->broadPhase.movedProxies[i] );
}
fprintf( file, "movedProxies: %d\n", movedBytes );
fprintf( file, "moveArray: %d\n", b3Array_ByteCount( world->broadPhase.moveArray ) );
int moveArrayBytes = b3Array_ByteCount( world->broadPhase.moveArray );
b3HashSet* pairSet = &world->broadPhase.pairSet;
fprintf( file, "pairSet: %d (%d, %d)\n", b3GetHashSetBytes( pairSet ), pairSet->count, pairSet->capacity );
fprintf( file, "\n" );
int pairSetBytes = b3GetHashSetBytes( pairSet );
total += (uint64_t)staticTreeBytes + kinematicTreeBytes + dynamicTreeBytes + movedBytes + moveArrayBytes + pairSetBytes;
b3Log( "broad-phase" );
b3Log( "static tree: %d", staticTreeBytes );
b3Log( "kinematic tree: %d", kinematicTreeBytes );
b3Log( "dynamic tree: %d", dynamicTreeBytes );
b3Log( "movedProxies: %d", movedBytes );
b3Log( "moveArray: %d", moveArrayBytes );
b3Log( "pairSet: %d (%d, %d)", pairSetBytes, pairSet->count, pairSet->capacity );
// Manifold block allocators, one per manifold point count
int manifoldArrayBytes = b3Array_ByteCount( world->manifoldAllocators );
int manifoldBlockBytes = 0;
for ( int i = 0; i < world->manifoldAllocators.count; ++i )
{
b3BlockAllocator* allocator = world->manifoldAllocators.data + i;
manifoldBlockBytes += b3Array_ByteCount( allocator->blocks );
manifoldBlockBytes += allocator->blocks.count * B3_BLOCK_SIZE * allocator->elementSize;
}
total += (uint64_t)manifoldArrayBytes + manifoldBlockBytes;
b3Log( "manifold allocators" );
b3Log( "allocator array: %d", manifoldArrayBytes );
b3Log( "blocks: %d", manifoldBlockBytes );
// solver sets
int bodySimCapacity = 0;
@ -2209,36 +2348,93 @@ void b3World_DumpMemoryStats( b3WorldId worldId )
islandSimCapacity += set->islandSims.capacity;
}
fprintf( file, "solver sets\n" );
fprintf( file, "body sim: %d\n", bodySimCapacity * (int)sizeof( b3BodySim ) );
fprintf( file, "body state: %d\n", bodyStateCapacity * (int)sizeof( b3BodyState ) );
fprintf( file, "joint sim: %d\n", jointSimCapacity * (int)sizeof( b3JointSim ) );
fprintf( file, "contact sim: %d\n", contactIndexCapacity * (int)sizeof( int ) );
fprintf( file, "island sim: %d\n", islandSimCapacity * (int)sizeof( islandSimCapacity ) );
fprintf( file, "\n" );
int setBodySimBytes = bodySimCapacity * (int)sizeof( b3BodySim );
int setBodyStateBytes = bodyStateCapacity * (int)sizeof( b3BodyState );
int setJointSimBytes = jointSimCapacity * (int)sizeof( b3JointSim );
int setContactSimBytes = contactIndexCapacity * (int)sizeof( int );
int setIslandSimBytes = islandSimCapacity * (int)sizeof( b3IslandSim );
total += (uint64_t)setBodySimBytes + setBodyStateBytes + setJointSimBytes + setContactSimBytes + setIslandSimBytes;
b3Log( "solver sets" );
b3Log( "body sim: %d", setBodySimBytes );
b3Log( "body state: %d", setBodyStateBytes );
b3Log( "joint sim: %d", setJointSimBytes );
b3Log( "contact sim: %d", setContactSimBytes );
b3Log( "island sim: %d", setIslandSimBytes );
// constraint graph
int bodyBitSetBytes = 0;
int contactSpecCapacity = 0;
jointSimCapacity = 0;
int graphContactBytes = 0;
int graphJointSimBytes = 0;
for ( int i = 0; i < B3_GRAPH_COLOR_COUNT; ++i )
{
b3GraphColor* c = world->constraintGraph.colors + i;
bodyBitSetBytes += b3GetBitSetBytes( &c->bodySet );
contactSpecCapacity += c->convexContacts.capacity + c->contacts.capacity;
jointSimCapacity += c->jointSims.capacity;
graphContactBytes += b3Array_ByteCount( c->convexContacts ) + b3Array_ByteCount( c->contacts );
graphJointSimBytes += b3Array_ByteCount( c->jointSims );
}
total += (uint64_t)bodyBitSetBytes + graphJointSimBytes + graphContactBytes;
b3Log( "constraint graph" );
b3Log( "body bit sets: %d", bodyBitSetBytes );
b3Log( "joint sim: %d", graphJointSimBytes );
b3Log( "contact sim: %d", graphContactBytes );
// Per worker task storage and its bit sets
int taskContextBytes = b3Array_ByteCount( world->taskContexts );
for ( int i = 0; i < world->taskContexts.count; ++i )
{
b3TaskContext* taskContext = world->taskContexts.data + i;
taskContextBytes += b3Array_ByteCount( taskContext->sensorHits );
taskContextBytes += b3GetBitSetBytes( &taskContext->contactStateBitSet );
taskContextBytes += b3GetBitSetBytes( &taskContext->jointStateBitSet );
taskContextBytes += b3GetBitSetBytes( &taskContext->hitEventBitSet );
taskContextBytes += b3GetBitSetBytes( &taskContext->enlargedSimBitSet );
taskContextBytes += b3GetBitSetBytes( &taskContext->awakeIslandBitSet );
}
fprintf( file, "constraint graph\n" );
fprintf( file, "body bit sets: %d\n", bodyBitSetBytes );
fprintf( file, "joint sim: %d\n", jointSimCapacity * (int)sizeof( b3JointSim ) );
fprintf( file, "contact sim: %d\n", contactSpecCapacity * (int)sizeof( int ) );
fprintf( file, "\n" );
int sensorTaskContextBytes = b3Array_ByteCount( world->sensorTaskContexts );
for ( int i = 0; i < world->sensorTaskContexts.count; ++i )
{
b3SensorTaskContext* taskContext = world->sensorTaskContexts.data + i;
sensorTaskContextBytes += b3GetBitSetBytes( &taskContext->eventBits );
}
total += (uint64_t)taskContextBytes + sensorTaskContextBytes;
b3Log( "task contexts" );
b3Log( "worker: %d", taskContextBytes );
b3Log( "sensor: %d", sensorTaskContextBytes );
// Double buffered event arrays
int eventBytes = 0;
eventBytes += b3Array_ByteCount( world->bodyMoveEvents );
eventBytes += b3Array_ByteCount( world->sensorBeginEvents );
eventBytes += b3Array_ByteCount( world->contactBeginEvents );
eventBytes += b3Array_ByteCount( world->sensorEndEvents[0] );
eventBytes += b3Array_ByteCount( world->sensorEndEvents[1] );
eventBytes += b3Array_ByteCount( world->contactEndEvents[0] );
eventBytes += b3Array_ByteCount( world->contactEndEvents[1] );
eventBytes += b3Array_ByteCount( world->contactHitEvents );
eventBytes += b3Array_ByteCount( world->jointEvents );
total += eventBytes;
b3Log( "events: %d", eventBytes );
// Debug draw bit sets
int debugBytes = 0;
debugBytes += b3GetBitSetBytes( &world->debugBodySet );
debugBytes += b3GetBitSetBytes( &world->debugJointSet );
debugBytes += b3GetBitSetBytes( &world->debugContactSet );
debugBytes += b3GetBitSetBytes( &world->debugIslandSet );
total += debugBytes;
b3Log( "debug draw: %d", debugBytes );
// stack allocator
fprintf( file, "stack allocator: %d\n\n", world->stack.capacity );
total += world->stack.capacity;
b3Log( "stack allocator: %d", world->stack.capacity );
fclose( file );
b3Log( "total: %llu", (unsigned long long)total );
}
void b3World_DumpShapeBounds( b3WorldId worldId, b3BodyType type )

View file

@ -72,7 +72,7 @@ typedef struct b3TaskContext
b3Arena arena;
// Collect per thread sensor continuous hit events.
b3ArrayC( b3SensorHit ) sensorHits;
b3Array( b3SensorHit ) sensorHits;
// These bits align with the b3ConstraintGraph::contactBlocks and signal a change in contact status
b3BitSet contactStateBitSet;
@ -129,7 +129,7 @@ typedef struct b3World
b3ConstraintGraph constraintGraph;
// Manifold allocators have one allocator for each manifold count.
b3ArrayC( b3BlockAllocator ) manifoldAllocators;
b3Array( b3BlockAllocator ) manifoldAllocators;
b3Mutex* manifoldAllocatorMutex;
// The body id pool is used to allocate and recycle body ids. Body ids
@ -140,7 +140,7 @@ typedef struct b3World
// This is a sparse array that maps body ids to the body data
// stored in solver sets. As sims move within a set or across set.
// Indices come from id pool.
b3ArrayC( b3Body ) bodies;
b3Array( b3Body ) bodies;
// Provides free list for solver sets.
b3IdPool solverSetIdPool;
@ -148,51 +148,56 @@ typedef struct b3World
// Solvers sets allow sims to be stored in contiguous arrays. The first
// set is all static sims. The second set is active sims. The third set is disabled
// sims. The remaining sets are sleeping islands.
b3ArrayC( b3SolverSet ) solverSets;
b3Array( b3SolverSet ) solverSets;
// Used to create stable ids for joints
b3IdPool jointIdPool;
// This is a sparse array that maps joint ids to the joint data stored in the constraint graph
// or in the solver sets.
b3ArrayC( b3Joint ) joints;
b3Array( b3Joint ) joints;
// Used to create stable ids for contacts
b3IdPool contactIdPool;
// This is a sparse array that maps contact ids to the contact data stored in the constraint graph
// or in the solver sets.
b3ArrayC( b3Contact ) contacts;
b3Array( b3Contact ) contacts;
// Used to create stable ids for islands
b3IdPool islandIdPool;
// This is a sparse array that maps island ids to the island data stored in the solver sets.
b3ArrayC( b3Island ) islands;
b3Array( b3Island ) islands;
b3IdPool shapeIdPool;
// These are sparse arrays that point into the pools above
b3ArrayC( b3Shape ) shapes;
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
// type into this header.
void* hullDatabase;
// This is a dense array of sensor data.
b3ArrayC( b3Sensor ) sensors;
b3Array( b3Sensor ) sensors;
// Per thread storage
b3ArrayC( b3TaskContext ) taskContexts;
b3ArrayC( b3SensorTaskContext ) sensorTaskContexts;
b3Array( b3TaskContext ) taskContexts;
b3Array( b3SensorTaskContext ) sensorTaskContexts;
b3ArrayC( b3BodyMoveEvent ) bodyMoveEvents;
b3ArrayC( b3SensorBeginTouchEvent ) sensorBeginEvents;
b3ArrayC( b3ContactBeginTouchEvent ) contactBeginEvents;
b3Array( b3BodyMoveEvent ) bodyMoveEvents;
b3Array( b3SensorBeginTouchEvent ) sensorBeginEvents;
b3Array( b3ContactBeginTouchEvent ) contactBeginEvents;
// End events are double buffered so that the user doesn't need to flush events
b3ArrayC( b3SensorEndTouchEvent ) sensorEndEvents[2];
b3ArrayC( b3ContactEndTouchEvent ) contactEndEvents[2];
b3Array( b3SensorEndTouchEvent ) sensorEndEvents[2];
b3Array( b3ContactEndTouchEvent ) contactEndEvents[2];
int endEventArrayIndex;
b3ArrayC( b3ContactHitEvent ) contactHitEvents;
b3ArrayC( b3JointEvent ) jointEvents;
b3Array( b3ContactHitEvent ) contactHitEvents;
b3Array( b3JointEvent ) jointEvents;
// Used to track debug draw
b3BitSet debugBodySet;
@ -285,6 +290,17 @@ void b3ValidateConnectivity( b3World* world );
void b3ValidateSolverSets( b3World* world );
void b3ValidateContacts( b3World* world );
// Register a hull in the world database, returning the owned shared copy. Identical hulls
// share one copy with a reference count. The input may be freed after this call.
const b3HullData* b3AddHullToDatabase( b3World* world, const b3HullData* src );
// Like b3AddHullToDatabase but takes ownership of a heap hull: inserted directly on a miss,
// freed on a hit. Avoids cloning data the caller already allocated.
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 );
static inline b3Manifold* b3AllocateManifolds( b3World* world, int count )
{
if ( count == 0 )

View file

@ -195,7 +195,7 @@ static void b3SensorTask( int startIndex, int endIndex, int workerIndex, void* c
b3Shape* sensorShape = b3Array_Get( world->shapes, sensor->shapeId );
// Swap overlap arrays
b3ArrayC( b3Visitor ) temp = sensor->overlaps1;
b3Array( b3Visitor ) temp = sensor->overlaps1;
sensor->overlaps1 = sensor->overlaps2;
sensor->overlaps2 = temp;
b3Array_Clear( sensor->overlaps2 );

View file

@ -26,9 +26,9 @@ b3DeclareArray( b3Visitor );
typedef struct b3Sensor
{
b3ArrayC( b3Visitor ) hits;
b3ArrayC( b3Visitor ) overlaps1;
b3ArrayC( b3Visitor ) overlaps2;
b3Array( b3Visitor ) hits;
b3Array( b3Visitor ) overlaps1;
b3Array( b3Visitor ) overlaps2;
int shapeId;
} b3Sensor;

View file

@ -46,7 +46,7 @@ static float b3ComputeShapeMargin( b3Shape* shape )
case b3_hullShape:
{
const b3Hull* hull = shape->hull;
const b3HullData* hull = shape->hull;
const b3Vec3* points = b3GetHullPoints( hull );
float maxExtentSqr = 0.0f;
int count = hull->vertexCount;
@ -143,18 +143,21 @@ static b3Shape* b3CreateShapeInternal( b3World* world, b3Body* body, b3Transform
case b3_hullShape:
if ( haveShapeTransform )
{
shape->hull = b3CloneAndTransformHull( (b3Hull*)geometry, shapeTransform, scale );
if ( shape->hull == NULL )
// The transform and non-uniform scale are baked into fresh data, then shared.
b3HullData* baked = b3CloneAndTransformHull( (b3HullData*)geometry, shapeTransform, scale );
if ( baked == NULL )
{
// This can fail to produce a valid hull in extreme cases
b3FreeId( &world->shapeIdPool, shapeId );
shape->id = B3_NULL_INDEX;
return NULL;
}
shape->hull = b3AddOwnedHullToDatabase( world, baked );
}
else
{
shape->hull = b3CloneHull( (b3Hull*)geometry );
shape->hull = b3AddHullToDatabase( world, (const b3HullData*)geometry );
}
break;
@ -336,14 +339,14 @@ b3ShapeId b3CreateCapsuleShape( b3BodyId bodyId, const b3ShapeDef* def, const b3
return b3CreateShape( bodyId, def, capsule, b3_capsuleShape, b3Transform_identity, b3Vec3_one, false );
}
b3ShapeId b3CreateHullShape( b3BodyId bodyId, const b3ShapeDef* def, const b3Hull* hull )
b3ShapeId b3CreateHullShape( b3BodyId bodyId, const b3ShapeDef* def, const b3HullData* hull )
{
B3_VALIDATE( b3IsValidHull( hull ) );
B3_VALIDATE( hull->hash != 0 );
return b3CreateShape( bodyId, def, hull, b3_hullShape, b3Transform_identity, b3Vec3_one, false );
}
b3ShapeId b3CreateTransformedHullShape( b3BodyId bodyId, const b3ShapeDef* def, const b3Hull* hull, b3Transform transform,
b3ShapeId b3CreateTransformedHullShape( b3BodyId bodyId, const b3ShapeDef* def, const b3HullData* hull, b3Transform transform,
b3Vec3 scale )
{
B3_VALIDATE( b3IsValidHull( hull ) );
@ -918,7 +921,7 @@ static void b3DestroyShapeAllocationForShapeChange( b3World* world, b3Shape* sha
switch ( type )
{
case b3_hullShape:
b3DestroyHull( (b3Hull*)shape->hull );
b3RemoveHullFromDatabase( world, shape->hull );
shape->hull = NULL;
break;
@ -966,8 +969,9 @@ b3ShapeProxy b3MakeShapeProxy( const b3Shape* shape )
case b3_hullShape:
{
const b3Vec3* points = b3GetHullPoints( shape->hull );
return (b3ShapeProxy){ points, shape->hull->vertexCount, 0.0f };
const b3HullData* hull = shape->hull;
const b3Vec3* points = b3GetHullPoints( hull );
return (b3ShapeProxy){ points, hull->vertexCount, 0.0f };
}
default:
@ -1437,7 +1441,7 @@ b3Capsule b3Shape_GetCapsule( b3ShapeId shapeId )
return shape->capsule;
}
const b3Hull* b3Shape_GetHull( b3ShapeId shapeId )
const b3HullData* b3Shape_GetHull( b3ShapeId shapeId )
{
b3World* world = b3GetWorld( shapeId.world0 );
b3Shape* shape = b3GetShape( world, shapeId );
@ -1513,8 +1517,11 @@ void b3Shape_SetCapsule( b3ShapeId shapeId, const b3Capsule* capsule )
world->locked = false;
}
void b3Shape_SetHull( b3ShapeId shapeId, const b3Hull* hull )
void b3Shape_SetHull( b3ShapeId shapeId, const b3HullData* hull )
{
B3_VALIDATE( b3IsValidHull( hull ) );
B3_VALIDATE( hull->hash != 0 );
b3World* world = b3GetUnlockedWorld( shapeId.world0 );
if ( world == NULL )
{
@ -1525,9 +1532,21 @@ void b3Shape_SetHull( b3ShapeId shapeId, const b3Hull* hull )
b3Shape* shape = b3GetShape( world, shapeId );
// Acquire the new hull before releasing the old so the input may safely alias
// the shape's current shared data.
const b3HullData* data = b3AddHullToDatabase( world, hull );
// Same shared hull, avoid destroying contacts and recreating the proxy
if ( shape->type == b3_hullShape && data == shape->hull )
{
b3RemoveHullFromDatabase( world, data );
world->locked = false;
return;
}
b3DestroyShapeAllocationForShapeChange( world, shape );
shape->hull = b3CloneHull( hull );
shape->hull = data;
shape->type = b3_hullShape;
shape->aabbMargin = b3ComputeShapeMargin( shape );
@ -2344,7 +2363,7 @@ void b3DumpShape( b3World* world, int shapeIndex )
case b3_hullShape:
{
const b3Hull* s = shape->hull;
const b3HullData* s = shape->hull;
int vertexCount = s->vertexCount;
const b3Vec3* vs = b3GetHullPoints( s );
b3Dump( " b3Vec3 vs[%d];\n", vertexCount );
@ -2352,9 +2371,9 @@ void b3DumpShape( b3World* world, int shapeIndex )
{
b3Dump( " vs[%d] = {%.9g, %.9g, %.9g};\n", i, vs[i].x, vs[i].y, vs[i].z );
}
b3Dump( " b3Hull* hull = b3CreateHull(vs, %d);\n", vertexCount );
b3Dump( " b3CreateHullShape(bodyId, &sd, hull);\n" );
b3Dump( " b3DestroyHull(hull);\n" );
b3Dump( " b3HullData* hullData = b3CreateHull(vs, %d, %d);\n", vertexCount, vertexCount );
b3Dump( " b3CreateHullShape(bodyId, &sd, hullData);\n" );
b3Dump( " b3DestroyHull(hullData);\n" );
}
break;

View file

@ -49,7 +49,7 @@ typedef struct b3Shape
{
b3Capsule capsule;
b3Sphere sphere;
const b3Hull* hull;
const b3HullData* hull;
b3Mesh mesh;
const b3HeightField* heightField;
const b3Compound* compound;
@ -89,19 +89,19 @@ b3TOIOutput b3ShapeTimeOfImpact( b3Shape* shapeA, b3Shape* shapeB, b3Sweep* swee
int b3CollideMoverAndSphere( b3PlaneResult* result, const b3Sphere* shape, const b3Capsule* mover );
int b3CollideMoverAndCapsule( b3PlaneResult* result, const b3Capsule* shape, const b3Capsule* mover );
int b3CollideMoverAndHull( b3PlaneResult* result, const b3Hull* shape, const b3Capsule* mover );
int b3CollideMoverAndHull( b3PlaneResult* result, const b3HullData* shape, const b3Capsule* mover );
int b3CollideMoverAndMesh( b3PlaneResult* planes, int capacity, const b3Mesh* shape, const b3Capsule* mover );
int b3CollideMoverAndHeightField( b3PlaneResult* results, int capacity, const b3HeightField* shape, const b3Capsule* mover );
int b3CollideMover( b3PlaneResult* planes, int planeCapacity, const b3Shape* shape, b3Transform transform,
const b3Capsule* mover );
// Hull
int b3FindHullSupportVertex( const b3Hull* hull, b3Vec3 direction );
int b3FindHullSupportFace( const b3Hull* hull, b3Vec3 direction );
bool b3IsValidHull( const b3Hull* hull );
b3AABB b3ComputeSweptHullAABB( const b3Hull* shape, b3Transform xf1, b3Transform xf2 );
b3ShapeExtent b3ComputeHullExtent( const b3Hull* hull, b3Vec3 origin );
float b3ComputeHullProjectedArea( const b3Hull* hull, b3Vec3 direction );
int b3FindHullSupportVertex( const b3HullData* hull, b3Vec3 direction );
int b3FindHullSupportFace( const b3HullData* hull, b3Vec3 direction );
bool b3IsValidHull( const b3HullData* hull );
b3AABB b3ComputeSweptHullAABB( const b3HullData* shape, b3Transform xf1, b3Transform xf2 );
b3ShapeExtent b3ComputeHullExtent( const b3HullData* hull, b3Vec3 origin );
float b3ComputeHullProjectedArea( const b3HullData* hull, b3Vec3 direction );
// Height field
b3Triangle b3GetHeightFieldTriangle( const b3HeightField* heightField, int triangleIndex );

View file

@ -30,25 +30,25 @@ b3DeclareArray( b3IslandSim );
typedef struct b3SolverSet
{
// Body array. Empty for unused set.
b3ArrayC( b3BodySim ) bodySims;
b3Array( b3BodySim ) bodySims;
// Body state only exists for active set
b3ArrayC( b3BodyState ) bodyStates;
b3Array( b3BodyState ) bodyStates;
// This holds sleeping/disabled joints. Empty for static/active set.
b3ArrayC( b3JointSim ) jointSims;
b3Array( b3JointSim ) jointSims;
// This holds all contacts for sleeping sets.
// This holds non-touching contacts for the awake set.
// This should be empty for the static and disabled sets.
b3ArrayC( int ) contactIndices;
b3Array( int ) contactIndices;
// The awake set has an array of islands. Sleeping sets normally have a single islands. However, joints
// created between sleeping sets causes the sets to merge, leaving them with multiple islands. These sleeping
// islands will be naturally merged with the set is woken.
// The static and disabled sets have no islands.
// Islands live in the solver sets to limit the number of islands that need to be considered for sleeping.
b3ArrayC( b3IslandSim ) islandSims;
b3Array( b3IslandSim ) islandSims;
// Aligns with b3World::solverSetIdPool. Used to create a stable id for body/contact/joint/islands.
int setIndex;

View file

@ -219,7 +219,7 @@ b3CastOutput b3ShapeCastSphere( const b3Sphere* sphere, const b3ShapeCastInput*
int b3CollideMoverAndSphere( b3PlaneResult* result, const b3Sphere* shape, const b3Capsule* mover )
{
float totalRadius = mover->radius + shape->radius;
b3Vec3 closest = b3ClosestPointOnSegment( mover->center1, mover->center2, shape->center );
b3Vec3 closest = b3PointToSegmentDistance( mover->center1, mover->center2, shape->center );
// The normal points from the sphere toward the mover.
float distance;

View file

@ -297,7 +297,7 @@ static void b3BuildTriangleAndCapsuleEdgeContact( b3LocalManifold* manifold, con
normal = b3Neg( normal );
}
b3ClosestApproachResult result = b3ClosestApproachLines( v1, triangleEdge, p1, capsuleEdge );
b3SegmentDistanceResult result = b3LineDistance( v1, triangleEdge, p1, capsuleEdge );
if ( result.fraction1 < 0.0f || 1.0f < result.fraction1 || result.fraction2 < 0.0f || 1.0f < result.fraction2 )
{
@ -480,7 +480,7 @@ static inline int b3GetTriangleSupport( b3Vec3* points, b3Vec3 direction )
return index;
}
static b3FaceQuery b3QueryTriangleFace( const b3TriangleData* triangle, const b3Hull* hull )
static b3FaceQuery b3QueryTriangleFace( const b3TriangleData* triangle, const b3HullData* hull )
{
const b3Vec3* hullPoints = b3GetHullPoints( hull );
b3Plane plane = triangle->plane;
@ -495,7 +495,7 @@ static b3FaceQuery b3QueryTriangleFace( const b3TriangleData* triangle, const b3
};
}
static b3FaceQuery b3QueryHullFace( const b3TriangleData* triangle, const b3Hull* hull )
static b3FaceQuery b3QueryHullFace( const b3TriangleData* triangle, const b3HullData* hull )
{
const b3Plane* hullPlanes = b3GetHullPlanes( hull );
int faceCount = hull->faceCount;
@ -528,7 +528,7 @@ static b3FaceQuery b3QueryHullFace( const b3TriangleData* triangle, const b3Hull
};
}
static b3EdgeQuery b3TestEdgePairs( const b3TriangleData* triangle, const b3Hull* hull )
static b3EdgeQuery b3TestEdgePairs( const b3TriangleData* triangle, const b3HullData* hull )
{
b3EdgeQuery result = {
.separation = -FLT_MAX,
@ -596,7 +596,7 @@ static b3EdgeQuery b3TestEdgePairs( const b3TriangleData* triangle, const b3Hull
return result;
}
static float b3CollideHullFace( b3LocalManifold* manifold, int pointCapacity, const b3TriangleData* triangle, const b3Hull* hull,
static float b3CollideHullFace( b3LocalManifold* manifold, int pointCapacity, const b3TriangleData* triangle, const b3HullData* hull,
b3FaceQuery query, b3SATCache* cache )
{
manifold->pointCount = 0;
@ -701,7 +701,7 @@ static float b3CollideHullFace( b3LocalManifold* manifold, int pointCapacity, co
}
static float b3CollideTriangleFace( b3LocalManifold* manifold, int pointCapacity, const b3TriangleData* triangle,
const b3Hull* hull, b3FaceQuery query, b3SATCache* cache )
const b3HullData* hull, b3FaceQuery query, b3SATCache* cache )
{
B3_VALIDATE( manifold->pointCount == 0 );
@ -807,7 +807,7 @@ static float b3CollideTriangleFace( b3LocalManifold* manifold, int pointCapacity
}
static void b3CollideHullAndTriangleEdges( b3LocalManifold* manifold, int capacity, b3Vec3 trianglePoint, b3Vec3 triangleEdge,
b3Vec3 triangleCenter, const b3Hull* hull, b3EdgeQuery query, b3SATCache* cache )
b3Vec3 triangleCenter, const b3HullData* hull, b3EdgeQuery query, b3SATCache* cache )
{
B3_VALIDATE( query.separation <= 2.0f * B3_SPECULATIVE_DISTANCE );
B3_ASSERT( query.indexA < 3 );
@ -851,7 +851,7 @@ static void b3CollideHullAndTriangleEdges( b3LocalManifold* manifold, int capaci
}
// Get the closest points between the infinite edge lines
b3ClosestApproachResult result = b3ClosestApproachLines( pA, eA, pB, eB );
b3SegmentDistanceResult result = b3LineDistance( pA, eA, pB, eB );
// Is one of the closest points outside of the associated edge segment?
if ( capacity == 0 || result.fraction1 < 0.0f || 1.0f < result.fraction1 || result.fraction2 < 0.0f || 1.0f < result.fraction2 )
@ -901,7 +901,7 @@ b3AtomicInt b3_triangleConvexCalls;
b3AtomicInt b3_triangleCacheHits;
// Computes the manifold in the local space of the hull
void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3Hull* hullA, b3Vec3 v1, b3Vec3 v2, b3Vec3 v3,
void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3HullData* hullA, b3Vec3 v1, b3Vec3 v2, b3Vec3 v3,
int triangleFlags, b3SATCache* cache )
{
manifold->pointCount = 0;

View file

@ -8,7 +8,7 @@ set(BOX3D_TEST_FILES
test_compound.c
test_container.c
test_determinism.c
#test_distance.c
test_distance.c
test_height_field.c
test_hull.c
test_id.c
@ -16,7 +16,7 @@ set(BOX3D_TEST_FILES
test_math.c
test_mover.c
test_shape.c
#test_table.c
test_table.c
test_world.c
)

View file

@ -31,14 +31,14 @@ extern int CollisionTest( void );
extern int CompoundTest( void );
extern int ContainerTest( void );
extern int DeterminismTest( void );
// extern int DistanceTest( void );
extern int DistanceTest( void );
extern int HeightFieldTest( void );
extern int HullTest( void );
extern int IdTest( void );
extern int MathTest( void );
extern int MoverTest( void );
extern int ShapeTest( void );
// extern int TableTest( void );
extern int TableTest( void );
extern int WorldTest( void );
// Filter-aware test runner: skips tests that don't match the filter
@ -90,17 +90,16 @@ int main( int argc, char** argv )
MAYBE_RUN_TEST( CompoundTest );
MAYBE_RUN_TEST( ContainerTest );
MAYBE_RUN_TEST( DeterminismTest );
MAYBE_RUN_TEST( DistanceTest );
MAYBE_RUN_TEST( HeightFieldTest );
MAYBE_RUN_TEST( HullTest );
MAYBE_RUN_TEST( IdTest );
MAYBE_RUN_TEST( MathTest );
MAYBE_RUN_TEST( MoverTest );
MAYBE_RUN_TEST( ShapeTest );
MAYBE_RUN_TEST( TableTest );
MAYBE_RUN_TEST( WorldTest );
// RUN_TEST( DistanceTest );
// RUN_TEST( TableTest );
printf( "======================================\n" );
printf( "All Box3D tests passed!\n" );

View file

@ -22,10 +22,6 @@ static b3SurfaceMaterial MakeMaterial( float friction, uint64_t userId )
return m;
}
// ---------------------------------------------------------------------------
// Construction & layout
// ---------------------------------------------------------------------------
static int CompoundCreateMixed( void )
{
b3SurfaceMaterial mat = b3DefaultSurfaceMaterial();
@ -56,10 +52,14 @@ static int CompoundCreateMixed( void )
};
b3CompoundDef def = {
.capsules = capsules, .capsuleCount = 1,
.hulls = hulls, .hullCount = 1,
.meshes = meshes, .meshCount = 1,
.spheres = spheres, .sphereCount = 2,
.capsules = capsules,
.capsuleCount = 1,
.hulls = hulls,
.hullCount = 1,
.meshes = meshes,
.meshCount = 1,
.spheres = spheres,
.sphereCount = 2,
};
b3Compound* compound = b3CreateCompound( &def );
@ -136,10 +136,6 @@ static int CompoundCreateSingleType( void )
return 0;
}
// ---------------------------------------------------------------------------
// Material deduplication
// ---------------------------------------------------------------------------
static int CompoundMaterialDedup( void )
{
b3SurfaceMaterial mat = MakeMaterial( 0.4f, 7 );
@ -201,9 +197,12 @@ static int CompoundMaterialCrossShape( void )
b3CompoundSphereDef sph = { .sphere = { { 5, 0, 0 }, 0.5f }, .material = mat };
b3CompoundDef def = {
.capsules = &cap, .capsuleCount = 1,
.hulls = &hull, .hullCount = 1,
.spheres = &sph, .sphereCount = 1,
.capsules = &cap,
.capsuleCount = 1,
.hulls = &hull,
.hullCount = 1,
.spheres = &sph,
.sphereCount = 1,
};
b3Compound* c = b3CreateCompound( &def );
ENSURE( c->materialCount == 1 );
@ -237,8 +236,10 @@ static int CompoundMaterialMeshShared( void )
};
b3CompoundDef def = {
.meshes = &mesh, .meshCount = 1,
.spheres = &sph, .sphereCount = 1,
.meshes = &mesh,
.meshCount = 1,
.spheres = &sph,
.sphereCount = 1,
};
b3Compound* c = b3CreateCompound( &def );
ENSURE( c->materialCount == 1 );
@ -387,10 +388,6 @@ static int CompoundMeshDistinct( void )
return 0;
}
// ---------------------------------------------------------------------------
// Child accessors and dispatch
// ---------------------------------------------------------------------------
static int CompoundChildDispatch( void )
{
b3SurfaceMaterial mat = b3DefaultSurfaceMaterial();
@ -414,10 +411,14 @@ static int CompoundChildDispatch( void )
b3CompoundSphereDef spheres[1] = { { .sphere = { { -5, 0, 0 }, 0.5f }, .material = mat } };
b3CompoundDef def = {
.capsules = caps, .capsuleCount = 2,
.hulls = hulls, .hullCount = 1,
.meshes = meshes, .meshCount = 1,
.spheres = spheres, .sphereCount = 1,
.capsules = caps,
.capsuleCount = 2,
.hulls = hulls,
.hullCount = 1,
.meshes = meshes,
.meshCount = 1,
.spheres = spheres,
.sphereCount = 1,
};
b3Compound* c = b3CreateCompound( &def );
@ -453,10 +454,6 @@ static int CompoundChildDispatch( void )
return 0;
}
// ---------------------------------------------------------------------------
// AABB
// ---------------------------------------------------------------------------
static int CompoundAABBContainsChildren( void )
{
b3SurfaceMaterial mat = b3DefaultSurfaceMaterial();
@ -484,10 +481,6 @@ static int CompoundAABBContainsChildren( void )
return 0;
}
// ---------------------------------------------------------------------------
// Ray cast / shape cast
// ---------------------------------------------------------------------------
static int CompoundRayCastMiss( void )
{
b3SurfaceMaterial mat = b3DefaultSurfaceMaterial();
@ -590,10 +583,6 @@ static int CompoundShapeCastClosest( void )
return 0;
}
// ---------------------------------------------------------------------------
// Overlap
// ---------------------------------------------------------------------------
static int CompoundOverlap( void )
{
b3SurfaceMaterial mat = b3DefaultSurfaceMaterial();
@ -618,11 +607,7 @@ static int CompoundOverlap( void )
return 0;
}
// ---------------------------------------------------------------------------
// Query
// ---------------------------------------------------------------------------
struct QueryAccum
struct QueryAccumulator
{
int childIndices[8];
int count;
@ -632,7 +617,7 @@ struct QueryAccum
static bool QueryCallback( const b3Compound* compound, int childIndex, void* context )
{
(void)compound;
struct QueryAccum* acc = context;
struct QueryAccumulator* acc = context;
if ( acc->count < (int)( sizeof( acc->childIndices ) / sizeof( acc->childIndices[0] ) ) )
{
acc->childIndices[acc->count++] = childIndex;
@ -657,19 +642,19 @@ static int CompoundQuery( void )
// Tight box around the middle sphere — only it should be reported.
b3AABB middle = { { -1, -1, -1 }, { 1, 1, 1 } };
struct QueryAccum acc = { .stopAfter = -1 };
struct QueryAccumulator acc = { .stopAfter = -1 };
b3QueryCompound( c, middle, QueryCallback, &acc );
ENSURE( acc.count == 1 );
ENSURE( acc.childIndices[0] == 1 );
// Wide box overlapping all three; early-exit after the first reported child.
b3AABB wide = { { -20, -1, -1 }, { 20, 1, 1 } };
struct QueryAccum stop = { .stopAfter = 1 };
struct QueryAccumulator stop = { .stopAfter = 1 };
b3QueryCompound( c, wide, QueryCallback, &stop );
ENSURE( stop.count == 1 );
// Without early-exit, all three are visited.
struct QueryAccum all = { .stopAfter = -1 };
struct QueryAccumulator all = { .stopAfter = -1 };
b3QueryCompound( c, wide, QueryCallback, &all );
ENSURE( all.count == 3 );
@ -677,10 +662,6 @@ static int CompoundQuery( void )
return 0;
}
// ---------------------------------------------------------------------------
// Mover
// ---------------------------------------------------------------------------
static int CompoundMover( void )
{
b3SurfaceMaterial mat = b3DefaultSurfaceMaterial();
@ -723,10 +704,6 @@ static int CompoundMover( void )
return 0;
}
// ---------------------------------------------------------------------------
// Serialization round-trip
// ---------------------------------------------------------------------------
static b3Compound* BuildSerializableCompound( b3MeshData* md )
{
b3SurfaceMaterial mat = b3DefaultSurfaceMaterial();
@ -744,10 +721,14 @@ static b3Compound* BuildSerializableCompound( b3MeshData* md )
b3CompoundSphereDef sph = { .sphere = { { -5, 0, 0 }, 0.5f }, .material = mat };
b3CompoundDef def = {
.capsules = &cap, .capsuleCount = 1,
.hulls = &hull, .hullCount = 1,
.meshes = &mesh, .meshCount = 1,
.spheres = &sph, .sphereCount = 1,
.capsules = &cap,
.capsuleCount = 1,
.hulls = &hull,
.hullCount = 1,
.meshes = &mesh,
.meshCount = 1,
.spheres = &sph,
.sphereCount = 1,
};
return b3CreateCompound( &def );
}
@ -806,7 +787,7 @@ static int CompoundSerializeBadVersion( void )
b3DestroyCompound( a );
// Corrupt the version word (first 8 bytes of b3Compound).
((b3Compound*)buffer)->version ^= 0x1ull;
( (b3Compound*)buffer )->version ^= 0x1ull;
b3Compound* b = b3ConvertBytesToCompound( buffer, byteCount );
ENSURE( b == NULL );
@ -835,8 +816,6 @@ static int CompoundSerializeWrongByteCount( void )
return 0;
}
// ---------------------------------------------------------------------------
int CompoundTest( void )
{
RUN_SUBTEST( CompoundCreateMixed );

View file

@ -22,12 +22,12 @@ b3DeclareArray( Foo );
typedef struct Bar
{
b3ArrayC( int ) a;
b3Array( int ) a;
} Bar;
static int TestCreateDestroy( void )
{
b3ArrayC( int ) a;
b3Array( int ) a;
b3Array_Create( a );
b3Array_Destroy( a );
return 0;
@ -35,7 +35,7 @@ static int TestCreateDestroy( void )
static int TestAccess( void )
{
b3ArrayC( int ) a;
b3Array( int ) a;
b3Array_Create( a );
b3Array_Push( a, 42 );
int* element = b3Array_Get( a, 0 );
@ -46,7 +46,7 @@ static int TestAccess( void )
static int TestIteration( void )
{
b3ArrayC( int ) a = { 0 };
b3Array( int ) a = { 0 };
b3Array_Push( a, 1 );
b3Array_Push( a, 2 );
b3Array_Push( a, 3 );
@ -64,7 +64,7 @@ static int TestIteration( void )
static int TestArrayOfStruct( void )
{
b3ArrayC( Foo ) a;
b3Array( Foo ) a;
b3Array_Create( a );
b3Array_Push( a, ( (Foo){ .a = 1, .b = 5.0f } ) );
b3Array_Push( a, ( (Foo){ .a = 2, .b = 6.0f } ) );
@ -107,7 +107,7 @@ static int TestStructWithArray( void )
static int TestArrayEmplace( void )
{
b3ArrayC( int ) a = { 0 };
b3Array( int ) a = { 0 };
int n = 100;
for ( int i = 0; i < n; ++i )
@ -130,7 +130,7 @@ static int TestArrayEmplace( void )
static int TestArrayRemove( void )
{
b3ArrayC( int16_t ) a = { 0 };
b3Array( int16_t ) a = { 0 };
int n = 100;
b3Array_Reserve( a, n );
@ -157,7 +157,7 @@ static int TestArrayRemove( void )
static int TestArrayPop( void )
{
b3ArrayC( int ) a = { 0 };
b3Array( int ) a = { 0 };
int n = 10;
b3Array_Resize( a, n );

View file

@ -1,51 +1,53 @@
// SPDX-FileCopyrightText: 2023 Erin Catto
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
#include "math_internal.h"
#include "test_macros.h"
#include "box2d/collision.h"
#include "box2d/math_functions.h"
#include "box3d/collision.h"
#include "box3d/math_functions.h"
#include <float.h>
static int SegmentDistanceTest( void )
{
b2Vec2 p1 = { -1.0f, -1.0f };
b2Vec2 q1 = { -1.0f, 1.0f };
b2Vec2 p2 = { 2.0f, 0.0f };
b2Vec2 q2 = { 1.0f, 0.0f };
b3Vec3 p1 = { -1.0f, -1.0f };
b3Vec3 q1 = { -1.0f, 1.0f };
b3Vec3 p2 = { 2.0f, 0.0f };
b3Vec3 q2 = { 1.0f, 0.0f };
b2SegmentDistanceResult result = b2SegmentDistance( p1, q1, p2, q2 );
b3SegmentDistanceResult result = b3SegmentDistance( p1, q1, p2, q2 );
ENSURE_SMALL( result.fraction1 - 0.5f, FLT_EPSILON );
ENSURE_SMALL( result.fraction2 - 1.0f, FLT_EPSILON );
ENSURE_SMALL( result.closest1.x + 1.0f, FLT_EPSILON );
ENSURE_SMALL( result.closest1.y, FLT_EPSILON );
ENSURE_SMALL( result.closest2.x - 1.0f, FLT_EPSILON );
ENSURE_SMALL( result.closest2.y, FLT_EPSILON );
ENSURE_SMALL( result.distanceSquared - 4.0f, FLT_EPSILON );
ENSURE_SMALL( result.point1.x + 1.0f, FLT_EPSILON );
ENSURE_SMALL( result.point1.y, FLT_EPSILON );
ENSURE_SMALL( result.point1.z, FLT_EPSILON );
ENSURE_SMALL( result.point2.x - 1.0f, FLT_EPSILON );
ENSURE_SMALL( result.point2.y, FLT_EPSILON );
ENSURE_SMALL( result.point2.z, FLT_EPSILON );
return 0;
}
static int ShapeDistanceTest( void )
{
b2Vec2 vas[] = { ( b2Vec2 ){ -1.0f, -1.0f }, ( b2Vec2 ){ 1.0f, -1.0f }, ( b2Vec2 ){ 1.0f, 1.0f }, ( b2Vec2 ){ -1.0f, 1.0f } };
b3Vec3 vas[] = { (b3Vec3){ -1.0f, -1.0f }, (b3Vec3){ 1.0f, -1.0f }, (b3Vec3){ 1.0f, 1.0f }, (b3Vec3){ -1.0f, 1.0f } };
b2Vec2 vbs[] = {
( b2Vec2 ){ 2.0f, -1.0f },
( b2Vec2 ){ 2.0f, 1.0f },
b3Vec3 vbs[] = {
(b3Vec3){ 2.0f, -1.0f },
(b3Vec3){ 2.0f, 1.0f },
};
b2DistanceInput input;
input.proxyA = b2MakeProxy( vas, ARRAY_COUNT( vas ), 0.0f );
input.proxyB = b2MakeProxy( vbs, ARRAY_COUNT( vbs ), 0.0f );
input.transformA = b2Transform_identity;
input.transformB = b2Transform_identity;
b3DistanceInput input;
input.proxyA = (b3ShapeProxy){ vas, ARRAY_COUNT( vas ), 0.0f };
input.proxyB = (b3ShapeProxy){ vbs, ARRAY_COUNT( vbs ), 0.0f };
input.transformA = b3Transform_identity;
input.transformB = b3Transform_identity;
input.useRadii = false;
b2DistanceCache cache = { 0 };
b2DistanceOutput output = b2ShapeDistance( &cache, &input, NULL, 0 );
b3SimplexCache cache = { 0 };
b3DistanceOutput output = b3ShapeDistance( &input, &cache, NULL, 0 );
ENSURE_SMALL( output.distance - 1.0f, FLT_EPSILON );
@ -54,22 +56,24 @@ static int ShapeDistanceTest( void )
static int ShapeCastTest( void )
{
b2Vec2 vas[] = { ( b2Vec2 ){ -1.0f, -1.0f }, ( b2Vec2 ){ 1.0f, -1.0f }, ( b2Vec2 ){ 1.0f, 1.0f }, ( b2Vec2 ){ -1.0f, 1.0f } };
b3Vec3 vas[] = { (b3Vec3){ -1.0f, -1.0f, 0.0f }, (b3Vec3){ 1.0f, -1.0f, 0.0f }, (b3Vec3){ 1.0f, 1.0f, 0.0f },
(b3Vec3){ -1.0f, 1.0f } };
b2Vec2 vbs[] = {
( b2Vec2 ){ 2.0f, -1.0f },
( b2Vec2 ){ 2.0f, 1.0f },
b3Vec3 vbs[] = {
(b3Vec3){ 2.0f, -1.0f, 0.0f },
(b3Vec3){ 2.0f, 1.0f, 0.0f },
};
b2ShapeCastPairInput input;
input.proxyA = b2MakeProxy( vas, ARRAY_COUNT( vas ), 0.0f );
input.proxyB = b2MakeProxy( vbs, ARRAY_COUNT( vbs ), 0.0f );
input.transformA = b2Transform_identity;
input.transformB = b2Transform_identity;
input.translationB = ( b2Vec2 ){ -2.0f, 0.0f };
b3ShapeCastPairInput input;
input.proxyA = (b3ShapeProxy){ vas, ARRAY_COUNT( vas ), 0.0f };
input.proxyB = (b3ShapeProxy){ vbs, ARRAY_COUNT( vbs ), 0.0f };
input.transformA = b3Transform_identity;
input.transformB = b3Transform_identity;
input.translationB = (b3Vec3){ -2.0f, 0.0f };
input.maxFraction = 1.0f;
input.canEncroach = false;
b2CastOutput output = b2ShapeCast( &input );
b3CastOutput output = b3ShapeCast( &input );
ENSURE( output.hit );
ENSURE_SMALL( output.fraction - 0.5f, 0.005f );
@ -79,24 +83,24 @@ static int ShapeCastTest( void )
static int TimeOfImpactTest( void )
{
b2Vec2 vas[] = { { -1.0f, -1.0f }, { 1.0f, -1.0f }, { 1.0f, 1.0f }, { -1.0f, 1.0f } };
b3Vec3 vas[] = { { -1.0f, -1.0f }, { 1.0f, -1.0f }, { 1.0f, 1.0f }, { -1.0f, 1.0f } };
b2Vec2 vbs[] = {
b3Vec3 vbs[] = {
{ 2.0f, -1.0f },
{ 2.0f, 1.0f },
};
b2TOIInput input;
input.proxyA = b2MakeProxy( vas, ARRAY_COUNT( vas ), 0.0f );
input.proxyB = b2MakeProxy( vbs, ARRAY_COUNT( vbs ), 0.0f );
input.sweepA = ( b2Sweep ){ b2Vec2_zero, b2Vec2_zero, b2Vec2_zero, b2Rot_identity, b2Rot_identity };
input.sweepB = ( b2Sweep ){ b2Vec2_zero, b2Vec2_zero, ( b2Vec2 ){ -2.0f, 0.0f }, b2Rot_identity, b2Rot_identity };
input.tMax = 1.0f;
b3TOIInput input;
input.proxyA = (b3ShapeProxy){ vas, ARRAY_COUNT( vas ), 0.0f };
input.proxyB = (b3ShapeProxy){ vbs, ARRAY_COUNT( vbs ), 0.0f };
input.sweepA = (b3Sweep){ b3Vec3_zero, b3Vec3_zero, b3Vec3_zero, b3Quat_identity, b3Quat_identity };
input.sweepB = (b3Sweep){ b3Vec3_zero, b3Vec3_zero, (b3Vec3){ -2.0f, 0.0f, 0.0f }, b3Quat_identity, b3Quat_identity };
input.maxFraction = 1.0f;
b2TOIOutput output = b2TimeOfImpact( &input );
b3TOIOutput output = b3TimeOfImpact( &input );
ENSURE( output.state == b2_toiStateHit );
ENSURE_SMALL( output.t - 0.5f, 0.005f );
ENSURE( output.state == b3_toiStateHit );
ENSURE_SMALL( output.fraction - 0.5f, 0.005f );
return 0;
}

View file

@ -17,7 +17,7 @@ static const b3Vec3 s_cubeCorners[8] = {
static int CreateHullCubeTest( void )
{
b3Hull* hull = b3CreateHull( s_cubeCorners, 8, 8 );
b3HullData* hull = b3CreateHull( s_cubeCorners, 8, 8 );
ENSURE( hull != NULL );
ENSURE( hull->vertexCount == 8 );
@ -68,7 +68,7 @@ static int CreateHullTetrahedronTest( void )
{ 0.0f, 0.0f, 1.0f },
};
b3Hull* hull = b3CreateHull( points, 4, 4 );
b3HullData* hull = b3CreateHull( points, 4, 4 );
ENSURE( hull != NULL );
ENSURE( hull->vertexCount == 4 );
@ -102,8 +102,8 @@ static int CreateHullTetrahedronTest( void )
static int CreateHullDeterminismTest( void )
{
b3Hull* h1 = b3CreateHull( s_cubeCorners, 8, 8 );
b3Hull* h2 = b3CreateHull( s_cubeCorners, 8, 8 );
b3HullData* h1 = b3CreateHull( s_cubeCorners, 8, 8 );
b3HullData* h2 = b3CreateHull( s_cubeCorners, 8, 8 );
ENSURE( h1 != NULL && h2 != NULL );
ENSURE( h1->byteCount == h2->byteCount );
@ -138,19 +138,19 @@ static int CreateHullMaxVertexTest( void )
int count = SPHERE_N * SPHERE_N;
// maxVertexCount honored as a strict cap.
b3Hull* h1 = b3CreateHull( points, count, 8 );
b3HullData* h1 = b3CreateHull( points, count, 8 );
ENSURE( h1 != NULL );
ENSURE( h1->vertexCount <= 8 );
b3DestroyHull( h1 );
// Below the floor: clamps up to 4.
b3Hull* h2 = b3CreateHull( points, count, 1 );
b3HullData* h2 = b3CreateHull( points, count, 1 );
ENSURE( h2 != NULL );
ENSURE( h2->vertexCount >= 4 && h2->vertexCount <= 255 );
b3DestroyHull( h2 );
// Above the ceiling: clamps down to 255.
b3Hull* h3 = b3CreateHull( points, count, 1000 );
b3HullData* h3 = b3CreateHull( points, count, 1000 );
ENSURE( h3 != NULL );
ENSURE( h3->vertexCount >= 4 && h3->vertexCount <= 255 );
b3DestroyHull( h3 );
@ -184,7 +184,7 @@ static int CreateHullRedundantInputTest( void )
{ 0.5f, 0.5f, 0.5f },
};
b3Hull* hull = b3CreateHull( points, 20, 8 );
b3HullData* hull = b3CreateHull( points, 20, 8 );
ENSURE( hull != NULL );
ENSURE( hull->vertexCount == 8 );
@ -214,10 +214,10 @@ static int CreateHullRedundantInputTest( void )
static int CreateHullCloneTest( void )
{
b3Hull* original = b3CreateHull( s_cubeCorners, 8, 8 );
b3HullData* original = b3CreateHull( s_cubeCorners, 8, 8 );
ENSURE( original != NULL );
b3Hull* clone = b3CloneHull( original );
b3HullData* clone = b3CloneHull( original );
ENSURE( clone != NULL );
ENSURE( clone->byteCount == original->byteCount );
ENSURE( memcmp( clone, original, original->byteCount ) == 0 );
@ -234,7 +234,7 @@ static int CreateHullCylinderTest( void )
const int sides = 8;
const float yOffset = 0.0f;
b3Hull* hull = b3CreateCylinder( height, radius, yOffset, sides );
b3HullData* hull = b3CreateCylinder( height, radius, yOffset, sides );
ENSURE( hull != NULL );
ENSURE( hull->vertexCount == 2 * sides );
@ -306,7 +306,7 @@ static int CreateHullSphereReductionTest( void )
b3Vec3 points[64];
FillSphereSample( points, 64, 12345 ); // RAND_SEED
b3Hull* hull = b3CreateHull( points, 64, 20 );
b3HullData* hull = b3CreateHull( points, 64, 20 );
ENSURE( hull != NULL );
ENSURE( hull->vertexCount >= 4 && hull->vertexCount <= 20 );
ENSURE( hull->vertexCount - hull->edgeCount / 2 + hull->faceCount == 2 );
@ -362,7 +362,7 @@ static int CreateHullSphereStressTest( void )
for ( int m = 0; m < ARRAY_COUNT( M_values ); ++m )
{
int M = M_values[m];
b3Hull* hull = b3CreateHull( points, N, M );
b3HullData* hull = b3CreateHull( points, N, M );
ENSURE( hull != NULL );
ENSURE( hull->vertexCount >= 4 && hull->vertexCount <= M );
ENSURE( hull->vertexCount - hull->edgeCount / 2 + hull->faceCount == 2 );
@ -399,7 +399,7 @@ static int CreateHullMergeChurnStressTest( void )
points[N - 8 + c].z = ( c & 4 ) ? 1.0f : -1.0f;
}
b3Hull* hull = b3CreateHull( points, N, 64 );
b3HullData* hull = b3CreateHull( points, N, 64 );
ENSURE( hull != NULL );
ENSURE( hull->vertexCount == 8 );
ENSURE( hull->edgeCount == 24 );

View file

@ -197,7 +197,7 @@ static int ShapeMassTest( void )
ENSURE( index == 2 * N * N );
b3Hull* hull = b3CreateHull( points, 2 * N * N, 2 * N * N );
b3HullData* hull = b3CreateHull( points, 2 * N * N, 2 * N * N );
b3MassData mdLower = b3ComputeHullMass( hull, 1.0f );
ENSURE( mdLower.mass < md.mass && md.mass < mdUpper.mass );

View file

@ -1,23 +1,23 @@
// SPDX-FileCopyrightText: 2023 Erin Catto
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
#include "core.h"
#include "ctz.h"
#include "platform.h"
#include "table.h"
#include "test_macros.h"
#include "box2d/base.h"
#include <stdatomic.h>
#include "box3d/base.h"
#define SET_SPAN 317
#define ITEM_COUNT ( ( SET_SPAN * SET_SPAN - SET_SPAN ) / 2 )
int TableTest( void )
{
int power = b2BoundingPowerOf2( 3008 );
int power = b3BoundingPowerOf2( 3008 );
ENSURE( power == 12 );
int nextPowerOf2 = b2RoundUpPowerOf2( 3008 );
int nextPowerOf2 = b3RoundUpPowerOf2( 3008 );
ENSURE( nextPowerOf2 == ( 1 << power ) );
const int32_t N = SET_SPAN;
@ -26,15 +26,15 @@ int TableTest( void )
for ( int32_t iter = 0; iter < 1; ++iter )
{
b2HashSet set = b2CreateSet( 16 );
b3HashSet set = b3CreateSet( 16 );
// Fill set
for ( int32_t i = 0; i < N; ++i )
{
for ( int32_t j = i + 1; j < N; ++j )
{
uint64_t key = B2_SHAPE_PAIR_KEY( i, j );
b2AddKey( &set, key );
uint64_t key = b3ShapePairKey( i, j, 0 );
b3AddKey( &set, key );
}
}
@ -49,8 +49,8 @@ int TableTest( void )
{
if ( j == i + 1 )
{
uint64_t key = B2_SHAPE_PAIR_KEY( i, j );
b2RemoveKey( &set, key );
uint64_t key = b3ShapePairKey( i, j, 0 );
b3RemoveKey( &set, key );
removed[k++] = true;
removeCount += 1;
}
@ -64,34 +64,32 @@ int TableTest( void )
ENSURE( set.count == ( itemCount - removeCount ) );
#ifndef NDEBUG
extern _Atomic int g_probeCount;
g_probeCount = 0;
extern b3AtomicInt b3_probeCount;
b3AtomicStoreInt(&b3_probeCount, 0);
#endif
// Test key search
// ~5ns per search on an AMD 7950x
b2Timer timer = b2CreateTimer();
uint64_t ticks = b3GetTicks();
k = 0;
for ( int32_t i = 0; i < N; ++i )
{
for ( int32_t j = i + 1; j < N; ++j )
{
uint64_t key = B2_SHAPE_PAIR_KEY( j, i );
ENSURE( b2ContainsKey( &set, key ) || removed[k] );
uint64_t key = b3ShapePairKey( j, i, 0 );
ENSURE( b3ContainsKey( &set, key ) || removed[k] );
k += 1;
}
}
// uint64_t ticks = b2GetTicks(&timer);
// printf("set ticks = %llu\n", ticks);
float ms = b3GetMilliseconds( ticks );
printf( "set: count = %d, b3ContainsKey = %.5f ms, ave = %.5f us\n", itemCount, ms, 1000.0f * ms / itemCount );
float ms = b2GetMilliseconds( &timer );
printf( "set: count = %d, b2ContainsKey = %.5f ms, ave = %.5f us\n", itemCount, ms, 1000.0f * ms / itemCount );
#if !NDEBUG
float aveProbeCount = (float)g_probeCount / (float)itemCount;
printf( "item count = %d, probe count = %d, ave probe count %.2f\n", itemCount, g_probeCount, aveProbeCount );
#ifndef NDEBUG
int probeCount = b3AtomicLoadInt( &b3_probeCount );
float aveProbeCount = (float)probeCount / (float)itemCount;
printf( "item count = %d, probe count = %d, ave probe count %.2f\n", itemCount, probeCount, aveProbeCount );
#endif
// Remove all keys from set
@ -99,14 +97,14 @@ int TableTest( void )
{
for ( int32_t j = i + 1; j < N; ++j )
{
uint64_t key = B2_SHAPE_PAIR_KEY( i, j );
b2RemoveKey( &set, key );
uint64_t key = b3ShapePairKey( i, j, 0 );
b3RemoveKey( &set, key );
}
}
ENSURE( set.count == 0 );
b2DestroySet( &set );
b3DestroySet( &set );
}
return 0;

View file

@ -878,6 +878,63 @@ static int EnableContactRecyclingTest( void )
return 0;
}
// Identical hull data is shared through a reference counted world database.
static int TestHullDatabase( void )
{
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f );
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
b3BodyId bodyA = b3CreateBody( worldId, &bodyDef );
b3BodyId bodyB = b3CreateBody( worldId, &bodyDef );
b3ShapeDef shapeDef = b3DefaultShapeDef();
// Two shapes built from identical data share one owned copy in the world database.
b3ShapeId shapeA = b3CreateHullShape( bodyA, &shapeDef, &box.base );
b3ShapeId shapeB = b3CreateHullShape( bodyB, &shapeDef, &box.base );
const b3HullData* gotA = b3Shape_GetHull( shapeA );
const b3HullData* gotB = b3Shape_GetHull( shapeB );
// Both shapes point at the single shared copy
ENSURE( gotA == gotB );
// The shared copy is owned by the world, not the caller's stack hull
ENSURE( gotA != &box.base );
// A box built on an independent stack frame must de-duplicate to the same shared copy.
// This holds only if content hashing sees deterministic padding bytes.
b3BoxHull box2 = b3MakeBoxHull( 0.5f, 0.5f, 0.5f );
b3BodyId bodyC = b3CreateBody( worldId, &bodyDef );
b3ShapeId shapeC = b3CreateHullShape( bodyC, &shapeDef, &box2.base );
ENSURE( b3Shape_GetHull( shapeC ) == gotA );
b3DestroyShape( shapeC, true );
// Setting a shape's hull to its own sole shared copy must not free it mid update.
b3BoxHull box3 = b3MakeBoxHull( 0.3f, 0.3f, 0.3f );
b3BodyId bodyD = b3CreateBody( worldId, &bodyDef );
b3ShapeId shapeD = b3CreateHullShape( bodyD, &shapeDef, &box3.base );
const b3HullData* gotD = b3Shape_GetHull( shapeD );
b3Shape_SetHull( shapeD, gotD );
ENSURE( b3Shape_GetHull( shapeD ) == gotD );
b3DestroyShape( shapeD, true );
// Releasing one reference keeps the other alive
b3DestroyShape( shapeA, true );
const b3HullData* stillB = b3Shape_GetHull( shapeB );
ENSURE( stillB == gotB );
b3DestroyShape( shapeB, true );
// World destroy asserts the database drained to zero references
b3DestroyWorld( worldId );
return 0;
}
int WorldTest( void )
{
RUN_SUBTEST( HelloWorld );
@ -897,6 +954,7 @@ int WorldTest( void )
RUN_SUBTEST( EnableSleepNoopUnlockTest );
RUN_SUBTEST( EnableContactRecyclingTest );
RUN_SUBTEST( TestSetWorkerCount );
RUN_SUBTEST( TestHullDatabase );
return 0;
}