initial commit

This commit is contained in:
Erin Catto 2026-05-10 13:36:52 -07:00
commit 573e1a9fa3
220 changed files with 150440 additions and 0 deletions

40
test/CMakeLists.txt Normal file
View file

@ -0,0 +1,40 @@
# Box3D unit test app
set(BOX3D_TEST_FILES
main.c
test_allocator.c
test_bitset.c
test_collision.c
test_compound.c
test_container.c
test_determinism.c
#test_distance.c
test_height_field.c
test_hull.c
test_id.c
test_macros.h
test_math.c
test_mover.c
test_shape.c
#test_table.c
test_world.c
)
add_executable(test ${BOX3D_TEST_FILES})
set_target_properties(test PROPERTIES
C_STANDARD 17
C_STANDARD_REQUIRED YES
C_EXTENSIONS NO
)
# Special access to Box3D internals for testing
target_include_directories(test PRIVATE ${CMAKE_SOURCE_DIR}/src)
if(BOX3D_VALIDATE)
target_compile_definitions(test PRIVATE BOX3D_VALIDATE)
endif()
target_link_libraries(test PRIVATE box3d shared)
source_group(TREE "${CMAKE_CURRENT_SOURCE_DIR}" PREFIX "" FILES ${BOX3D_TEST_FILES})

122
test/main.c Normal file
View file

@ -0,0 +1,122 @@
// SPDX-FileCopyrightText: 2024 Erin Catto
// SPDX-License-Identifier: MIT
#include "test_macros.h"
#include "box3d/base.h"
#include <string.h>
#if defined( _WIN32 )
#include <crtdbg.h>
// int MyAllocHook(int allocType, void* userData, size_t size, int blockType, long requestNumber, const unsigned char* filename,
// int lineNumber)
//{
// if (size == 16416)
// {
// size += 0;
// }
//
// return 1;
// }
#endif
#ifdef TRACY_ENABLE
#include <tracy/TracyC.h>
#endif
extern int AllocatorTest( void );
extern int BitTest( void );
extern int CollisionTest( void );
extern int CompoundTest( void );
extern int ContainerTest( void );
extern int DeterminismTest( 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 WorldTest( void );
// Filter-aware test runner: skips tests that don't match the filter
#define MAYBE_RUN_TEST( T ) \
do \
{ \
if ( filter != NULL && strcmp( filter, #T ) != 0 ) \
{ \
printf( "test skipped: " #T "\n" ); \
break; \
} \
RUN_TEST( T ); \
} \
while ( false )
int main( int argc, char** argv )
{
#if defined( _WIN32 )
// Enable memory-leak reports
//_CrtSetBreakAlloc(196);
_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDERR );
//_CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF | _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG));
//_CrtSetAllocHook(MyAllocHook);
#endif
#ifdef TRACY_ENABLE
___tracy_startup_profiler();
#endif
const char* filter = NULL;
if ( argc > 1 )
{
filter = argv[1];
}
uint64_t ticks = b3GetTicks();
printf( "Starting Box3D unit tests\n" );
if ( filter != NULL )
{
printf( "Filter: %s\n", filter );
}
printf( "======================================\n" );
MAYBE_RUN_TEST( AllocatorTest );
MAYBE_RUN_TEST( BitTest );
MAYBE_RUN_TEST( CollisionTest );
MAYBE_RUN_TEST( CompoundTest );
MAYBE_RUN_TEST( ContainerTest );
MAYBE_RUN_TEST( DeterminismTest );
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( WorldTest );
// RUN_TEST( DistanceTest );
// RUN_TEST( TableTest );
printf( "======================================\n" );
printf( "All Box3D tests passed!\n" );
float duration = b3GetMilliseconds( ticks );
printf( "Test duration = %.2f s\n", 0.001f * duration );
#ifdef TRACY_ENABLE
___tracy_shutdown_profiler();
#endif
#if defined( _WIN32 )
if ( _CrtDumpMemoryLeaks() )
{
return 1;
}
#endif
return 0;
}

49
test/test_allocator.c Normal file
View file

@ -0,0 +1,49 @@
// SPDX-FileCopyrightText: 2025 Erin Catto
// SPDX-License-Identifier: MIT
#include "block_allocator.h"
#include "test_macros.h"
typedef struct
{
int value1;
float value2;
} Foo;
_Static_assert( sizeof( Foo ) >= sizeof( void* ), "too small" );
static int TestBlockAllocate( void )
{
b3BlockAllocator allocator = b3CreateBlockAllocator( (int)sizeof( Foo ), 2 );
Foo* item1 = b3AllocateElement( &allocator );
ENSURE( item1 != NULL );
Foo* item2 = b3AllocateElement( &allocator );
ENSURE( item2 != NULL );
b3DestroyBlockAllocator( &allocator );
return 0;
}
static int TestBlockClear( void )
{
b3BlockAllocator allocator = b3CreateBlockAllocator( (int)sizeof( Foo ), 0 );
Foo* item1 = b3AllocateElement( &allocator );
Foo* item2 = b3AllocateElement( &allocator );
b3FreeElement( &allocator, item1 );
b3FreeElement( &allocator, item2 );
b3DestroyBlockAllocator( &allocator );
return 0;
}
int AllocatorTest( void )
{
RUN_SUBTEST( TestBlockAllocate );
RUN_SUBTEST( TestBlockClear );
return 0;
}

63
test/test_bitset.c Normal file
View file

@ -0,0 +1,63 @@
// SPDX-FileCopyrightText: 2023 Erin Catto
// SPDX-License-Identifier: MIT
#include "bitset.h"
#include "ctz.h"
#include "test_macros.h"
#include <math.h>
#define COUNT 169
int TestBitMath( void )
{
uint32_t r1 = b3CLZ32( 9 );
ENSURE( r1 == 31 - 3 );
for (int i = 1; i < 1000; ++i)
{
int e1 = b3LowerPowerOf2Exponent( i );
int e2 = (int)floorf( log2f( (float)i ) );
ENSURE(e1 == e2);
}
return 0;
}
int TestBitSet( void )
{
struct b3BitSet bitSet = b3CreateBitSet( COUNT );
b3SetBitCountAndClear( &bitSet, COUNT );
bool values[COUNT] = { false };
int32_t i1 = 0, i2 = 1;
b3SetBit( &bitSet, i1 );
values[i1] = true;
while ( i2 < COUNT )
{
b3SetBit( &bitSet, i2 );
values[i2] = true;
int32_t next = i1 + i2;
i1 = i2;
i2 = next;
}
for ( int32_t i = 0; i < COUNT; ++i )
{
bool value = b3GetBit( &bitSet, i );
ENSURE( value == values[i] );
}
b3DestroyBitSet( &bitSet );
return 0;
}
int BitTest( void )
{
RUN_SUBTEST( TestBitMath );
RUN_SUBTEST( TestBitSet );
return 0;
}

210
test/test_collision.c Normal file
View file

@ -0,0 +1,210 @@
// SPDX-FileCopyrightText: 2025 Erin Catto
// SPDX-License-Identifier: MIT
#include "aabb.h"
#include "test_macros.h"
#include "box3d/math_functions.h"
static int AABBTest( void )
{
b3AABB a;
a.lowerBound = ( b3Vec3 ){ -1.0f, -1.0f, -1.0f };
a.upperBound = ( b3Vec3 ){ -2.0f, -2.0f, -2.0f };
ENSURE( b3IsValidAABB( a ) == false );
a.upperBound = ( b3Vec3 ){ 1.0f, 1.0f };
ENSURE( b3IsValidAABB( a ) == true );
b3AABB b = { { 2.0f, 2.0f }, { 4.0f, 4.0f } };
ENSURE( b3AABB_Overlaps( a, b ) == false );
ENSURE( b3AABB_Contains( a, b ) == false );
return 0;
}
static int TestRayAABBIntersection( void )
{
// Test 1: Ray passing through center of AABB
{
b3Vec3 lowerBound = { -1.0f, -1.0f, -1.0f };
b3Vec3 upperBound = { 1.0f, 1.0f, 1.0f };
b3Vec3 p1 = { -2.0f, 0.0f, 0.0f };
b3Vec3 p2 = { 2.0f, 0.0f, 0.0f };
float minFraction, maxFraction;
bool hit = b3IntersectRayAndAABB( lowerBound, upperBound, p1, p2, &minFraction, &maxFraction );
ENSURE( hit == true );
ENSURE( b3AbsFloat( minFraction - 0.25f ) < 0.001f ); // Enters at 25% of ray
ENSURE( b3AbsFloat( maxFraction - 0.75f ) < 0.001f ); // Exits at 75% of ray
}
// Test 2: Ray starting inside AABB
{
b3Vec3 lowerBound = { -1.0f, -1.0f, -1.0f };
b3Vec3 upperBound = { 1.0f, 1.0f, 1.0f };
b3Vec3 p1 = { 0.0f, 0.0f, 0.0f };
b3Vec3 p2 = { 2.0f, 0.0f, 0.0f };
float minFraction, maxFraction;
bool hit = b3IntersectRayAndAABB( lowerBound, upperBound, p1, p2, &minFraction, &maxFraction );
ENSURE( hit == true );
ENSURE( minFraction == 0.0f ); // Starts inside
ENSURE( b3AbsFloat( maxFraction - 0.5f ) < 0.001f ); // Exits at 50% of ray
}
// Test 3: Ray ending inside AABB
{
b3Vec3 lowerBound = { -1.0f, -1.0f, -1.0f };
b3Vec3 upperBound = { 1.0f, 1.0f, 1.0f };
b3Vec3 p1 = { -2.0f, 0.0f, 0.0f };
b3Vec3 p2 = { 0.0f, 0.0f, 0.0f };
float minFraction, maxFraction;
bool hit = b3IntersectRayAndAABB( lowerBound, upperBound, p1, p2, &minFraction, &maxFraction );
ENSURE( hit == true );
ENSURE( b3AbsFloat( minFraction - 0.5f ) < 0.001f ); // Enters at 50% of ray
ENSURE( maxFraction == 1.0f ); // Ends inside
}
// Test 4: Ray completely inside AABB
{
b3Vec3 lowerBound = { -2.0f, -2.0f, -2.0f };
b3Vec3 upperBound = { 2.0f, 2.0f, 2.0f };
b3Vec3 p1 = { -1.0f, 0.0f, 0.0f };
b3Vec3 p2 = { 1.0f, 0.0f, 0.0f };
float minFraction, maxFraction;
bool hit = b3IntersectRayAndAABB( lowerBound, upperBound, p1, p2, &minFraction, &maxFraction );
ENSURE( hit == true );
ENSURE( minFraction == 0.0f );
ENSURE( maxFraction == 1.0f );
}
// Test 5: Ray missing AABB
{
b3Vec3 lowerBound = { 0.0f, 0.0f, 0.0f };
b3Vec3 upperBound = { 1.0f, 1.0f, 1.0f };
b3Vec3 p1 = { -1.0f, 2.0f, 0.5f };
b3Vec3 p2 = { 2.0f, 2.0f, 0.5f };
float minFraction, maxFraction;
bool hit = b3IntersectRayAndAABB( lowerBound, upperBound, p1, p2, &minFraction, &maxFraction );
ENSURE( hit == false );
}
// Test 6: Ray parallel to AABB face (no intersection)
{
b3Vec3 lowerBound = { 0.0f, 0.0f, 0.0f };
b3Vec3 upperBound = { 1.0f, 1.0f, 1.0f };
b3Vec3 p1 = { -1.0f, 2.0f, 0.5f };
b3Vec3 p2 = { 2.0f, 2.0f, 0.5f };
float minFraction, maxFraction;
bool hit = b3IntersectRayAndAABB( lowerBound, upperBound, p1, p2, &minFraction, &maxFraction );
ENSURE( hit == false );
}
// Test 7: Ray parallel to AABB face (within bounds)
{
b3Vec3 lowerBound = { 0.0f, 0.0f, 0.0f };
b3Vec3 upperBound = { 1.0f, 1.0f, 1.0f };
b3Vec3 p1 = { -1.0f, 0.5f, 0.5f };
b3Vec3 p2 = { 2.0f, 0.5f, 0.5f };
float minFraction, maxFraction;
bool hit = b3IntersectRayAndAABB( lowerBound, upperBound, p1, p2, &minFraction, &maxFraction );
ENSURE( hit == true );
ENSURE( b3AbsFloat( minFraction - 1.0f / 3.0f ) < 0.001f );
ENSURE( b3AbsFloat( maxFraction - 2.0f / 3.0f ) < 0.001f );
}
// Test 8: Degenerate ray (point) inside AABB
{
b3Vec3 lowerBound = { 0.0f, 0.0f, 0.0f };
b3Vec3 upperBound = { 1.0f, 1.0f, 1.0f };
b3Vec3 p1 = { 0.5f, 0.5f, 0.5f };
b3Vec3 p2 = { 0.5f, 0.5f, 0.5f };
float minFraction, maxFraction;
bool hit = b3IntersectRayAndAABB( lowerBound, upperBound, p1, p2, &minFraction, &maxFraction );
ENSURE( hit == true );
ENSURE( minFraction == 0.0f );
ENSURE( maxFraction == 0.0f );
}
// Test 9: Degenerate ray (point) outside AABB
{
b3Vec3 lowerBound = { 0.0f, 0.0f, 0.0f };
b3Vec3 upperBound = { 1.0f, 1.0f, 1.0f };
b3Vec3 p1 = { 2.0f, 2.0f, 2.0f };
b3Vec3 p2 = { 2.0f, 2.0f, 2.0f };
float minFraction, maxFraction;
bool hit = b3IntersectRayAndAABB( lowerBound, upperBound, p1, p2, &minFraction, &maxFraction );
ENSURE( hit == false );
}
// Test 10: Ray pointing away from AABB
{
b3Vec3 lowerBound = { 0.0f, 0.0f, 0.0f };
b3Vec3 upperBound = { 1.0f, 1.0f, 1.0f };
b3Vec3 p1 = { -1.0f, 0.5f, 0.5f };
b3Vec3 p2 = { -2.0f, 0.5f, 0.5f };
float minFraction, maxFraction;
bool hit = b3IntersectRayAndAABB( lowerBound, upperBound, p1, p2, &minFraction, &maxFraction );
ENSURE( hit == false );
}
// Test 11: Ray hitting corner of AABB
{
b3Vec3 lowerBound = { 0.0f, 0.0f, 0.0f };
b3Vec3 upperBound = { 1.0f, 1.0f, 1.0f };
b3Vec3 p1 = { -1.0f, -1.0f, -1.0f };
b3Vec3 p2 = { 2.0f, 2.0f, 2.0f };
float minFraction, maxFraction;
bool hit = b3IntersectRayAndAABB( lowerBound, upperBound, p1, p2, &minFraction, &maxFraction );
ENSURE( hit == true );
ENSURE( b3AbsFloat( minFraction - 1.0f / 3.0f ) < 0.001f );
ENSURE( b3AbsFloat( maxFraction - 2.0f / 3.0f ) < 0.001f );
}
// Test 12: Ray grazing edge of AABB
{
b3Vec3 lowerBound = { 0.0f, 0.0f, 0.0f };
b3Vec3 upperBound = { 1.0f, 1.0f, 1.0f };
b3Vec3 p1 = { -1.0f, 0.0f, 0.5f };
b3Vec3 p2 = { 2.0f, 0.0f, 0.5f };
float minFraction, maxFraction;
bool hit = b3IntersectRayAndAABB( lowerBound, upperBound, p1, p2, &minFraction, &maxFraction );
ENSURE( hit == true );
ENSURE( b3AbsFloat( minFraction - 1.0f / 3.0f ) < 0.001f );
ENSURE( b3AbsFloat( maxFraction - 2.0f / 3.0f ) < 0.001f );
}
return 0;
}
int CollisionTest( void )
{
RUN_SUBTEST( AABBTest );
RUN_SUBTEST( TestRayAABBIntersection );
return 0;
}

876
test/test_compound.c Normal file
View file

@ -0,0 +1,876 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
#include "test_macros.h"
// b3CollideMoverAndCompound, b3GetCompoundChild, b3QueryCompound are internal
#include "compound.h"
#include "box3d/collision.h"
#include "box3d/math_functions.h"
#include <float.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
static b3SurfaceMaterial MakeMaterial( float friction, uint64_t userId )
{
b3SurfaceMaterial m = b3DefaultSurfaceMaterial();
m.friction = friction;
m.userMaterialId = userId;
return m;
}
// ---------------------------------------------------------------------------
// Construction & layout
// ---------------------------------------------------------------------------
static int CompoundCreateMixed( void )
{
b3SurfaceMaterial mat = b3DefaultSurfaceMaterial();
b3CompoundCapsuleDef capsules[1] = {
{ .capsule = { { -1.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f }, 0.25f }, .material = mat },
};
b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f );
b3CompoundHullDef hulls[1] = {
{ .hull = &box.base, .transform = b3Transform_identity, .material = mat },
};
b3MeshData* meshData = b3CreateBoxMesh( b3Vec3_zero, (b3Vec3){ 0.5f, 0.5f, 0.5f }, false );
b3CompoundMeshDef meshes[1] = {
{
.meshData = meshData,
.transform = b3Transform_identity,
.scale = { 1.0f, 1.0f, 1.0f },
.materials = &mat,
.materialCount = 1,
},
};
b3CompoundSphereDef spheres[2] = {
{ .sphere = { { 5.0f, 0.0f, 0.0f }, 0.5f }, .material = mat },
{ .sphere = { { -5.0f, 0.0f, 0.0f }, 0.5f }, .material = mat },
};
b3CompoundDef def = {
.capsules = capsules, .capsuleCount = 1,
.hulls = hulls, .hullCount = 1,
.meshes = meshes, .meshCount = 1,
.spheres = spheres, .sphereCount = 2,
};
b3Compound* compound = b3CreateCompound( &def );
ENSURE( compound != NULL );
ENSURE( compound->version == B3_COMPOUND_VERSION );
ENSURE( compound->byteCount > (int)sizeof( b3Compound ) );
ENSURE( compound->capsuleCount == 1 );
ENSURE( compound->hullCount == 1 );
ENSURE( compound->meshCount == 1 );
ENSURE( compound->sphereCount == 2 );
ENSURE( compound->materialCount == 1 );
ENSURE( compound->sharedHullCount == 1 );
ENSURE( compound->sharedMeshCount == 1 );
ENSURE( compound->tree.nodeCount > 0 );
ENSURE( compound->tree.nodes != NULL );
b3DestroyCompound( compound );
b3DestroyMesh( meshData );
return 0;
}
static int CompoundCreateSingleType( void )
{
b3SurfaceMaterial mat = b3DefaultSurfaceMaterial();
// Capsule only
{
b3CompoundCapsuleDef cap = { .capsule = { { 0, 0, 0 }, { 1, 0, 0 }, 0.5f }, .material = mat };
b3CompoundDef def = { .capsules = &cap, .capsuleCount = 1 };
b3Compound* c = b3CreateCompound( &def );
ENSURE( c != NULL && c->capsuleCount == 1 && c->hullCount == 0 && c->meshCount == 0 && c->sphereCount == 0 );
b3DestroyCompound( c );
}
// Hull only
{
b3BoxHull box = b3MakeBoxHull( 1, 1, 1 );
b3CompoundHullDef h = { .hull = &box.base, .transform = b3Transform_identity, .material = mat };
b3CompoundDef def = { .hulls = &h, .hullCount = 1 };
b3Compound* c = b3CreateCompound( &def );
ENSURE( c != NULL && c->hullCount == 1 && c->sharedHullCount == 1 && c->capsuleCount == 0 );
b3DestroyCompound( c );
}
// Mesh only
{
b3MeshData* md = b3CreateBoxMesh( b3Vec3_zero, (b3Vec3){ 1, 1, 1 }, false );
b3CompoundMeshDef m = {
.meshData = md,
.transform = b3Transform_identity,
.scale = { 1, 1, 1 },
.materials = &mat,
.materialCount = 1,
};
b3CompoundDef def = { .meshes = &m, .meshCount = 1 };
b3Compound* c = b3CreateCompound( &def );
ENSURE( c != NULL && c->meshCount == 1 && c->sharedMeshCount == 1 );
b3DestroyCompound( c );
b3DestroyMesh( md );
}
// Sphere only
{
b3CompoundSphereDef s = { .sphere = { { 0, 0, 0 }, 1.0f }, .material = mat };
b3CompoundDef def = { .spheres = &s, .sphereCount = 1 };
b3Compound* c = b3CreateCompound( &def );
ENSURE( c != NULL && c->sphereCount == 1 );
b3DestroyCompound( c );
}
return 0;
}
// ---------------------------------------------------------------------------
// Material deduplication
// ---------------------------------------------------------------------------
static int CompoundMaterialDedup( void )
{
b3SurfaceMaterial mat = MakeMaterial( 0.4f, 7 );
b3CompoundCapsuleDef caps[3];
for ( int i = 0; i < 3; ++i )
{
caps[i].capsule = (b3Capsule){ { (float)i, 0, 0 }, { (float)i + 1, 0, 0 }, 0.25f };
caps[i].material = mat;
}
b3CompoundDef def = { .capsules = caps, .capsuleCount = 3 };
b3Compound* c = b3CreateCompound( &def );
ENSURE( c->materialCount == 1 );
for ( int i = 0; i < 3; ++i )
{
b3CompoundCapsule cc = b3GetCompoundCapsule( c, i );
ENSURE( cc.materialIndex == 0 );
}
b3DestroyCompound( c );
return 0;
}
static int CompoundMaterialDistinct( void )
{
b3CompoundCapsuleDef caps[3];
for ( int i = 0; i < 3; ++i )
{
caps[i].capsule = (b3Capsule){ { (float)i, 0, 0 }, { (float)i + 1, 0, 0 }, 0.25f };
caps[i].material = MakeMaterial( 0.1f * (float)( i + 1 ), (uint64_t)( i + 1 ) );
}
b3CompoundDef def = { .capsules = caps, .capsuleCount = 3 };
b3Compound* c = b3CreateCompound( &def );
ENSURE( c->materialCount == 3 );
const b3SurfaceMaterial* mats = b3GetCompoundMaterials( c );
ENSURE( mats != NULL );
for ( int i = 0; i < 3; ++i )
{
b3CompoundCapsule cc = b3GetCompoundCapsule( c, i );
ENSURE( cc.materialIndex >= 0 && cc.materialIndex < 3 );
ENSURE( mats[cc.materialIndex].userMaterialId == (uint64_t)( i + 1 ) );
}
b3DestroyCompound( c );
return 0;
}
static int CompoundMaterialCrossShape( void )
{
// One material shared across capsule, hull, and sphere → 1 material slot.
b3SurfaceMaterial mat = MakeMaterial( 0.5f, 99 );
b3CompoundCapsuleDef cap = { .capsule = { { 0, 0, 0 }, { 1, 0, 0 }, 0.25f }, .material = mat };
b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f );
b3CompoundHullDef hull = { .hull = &box.base, .transform = b3Transform_identity, .material = mat };
b3CompoundSphereDef sph = { .sphere = { { 5, 0, 0 }, 0.5f }, .material = mat };
b3CompoundDef def = {
.capsules = &cap, .capsuleCount = 1,
.hulls = &hull, .hullCount = 1,
.spheres = &sph, .sphereCount = 1,
};
b3Compound* c = b3CreateCompound( &def );
ENSURE( c->materialCount == 1 );
ENSURE( b3GetCompoundCapsule( c, 0 ).materialIndex == 0 );
ENSURE( b3GetCompoundHull( c, 0 ).materialIndex == 0 );
ENSURE( b3GetCompoundSphere( c, 0 ).materialIndex == 0 );
b3DestroyCompound( c );
return 0;
}
static int CompoundMaterialMeshShared( void )
{
// Mesh material entries are routed through the same material map as convex
// materials, so an identical material is deduped across mesh and convex.
// (The comment in compound.c about meshes "not being shared" refers to the
// per-instance materialIndices arrays, not the b3SurfaceMaterial table.)
b3SurfaceMaterial mat = MakeMaterial( 0.3f, 11 );
b3MeshData* md = b3CreateBoxMesh( b3Vec3_zero, (b3Vec3){ 1, 1, 1 }, false );
ENSURE( md->materialCount == 1 );
b3CompoundSphereDef sph = { .sphere = { { 5, 0, 0 }, 0.5f }, .material = mat };
b3CompoundMeshDef mesh = {
.meshData = md,
.transform = b3Transform_identity,
.scale = { 1, 1, 1 },
.materials = &mat,
.materialCount = 1,
};
b3CompoundDef def = {
.meshes = &mesh, .meshCount = 1,
.spheres = &sph, .sphereCount = 1,
};
b3Compound* c = b3CreateCompound( &def );
ENSURE( c->materialCount == 1 );
b3DestroyCompound( c );
b3DestroyMesh( md );
return 0;
}
// ---------------------------------------------------------------------------
// Hull / mesh blob sharing
// ---------------------------------------------------------------------------
static int CompoundHullSharingPointer( void )
{
b3SurfaceMaterial mat = b3DefaultSurfaceMaterial();
b3BoxHull box = b3MakeBoxHull( 1, 1, 1 );
b3CompoundHullDef hulls[3];
for ( int i = 0; i < 3; ++i )
{
hulls[i].hull = &box.base;
hulls[i].transform = b3Transform_identity;
hulls[i].transform.p.x = (float)( 4 * i );
hulls[i].material = mat;
}
b3CompoundDef def = { .hulls = hulls, .hullCount = 3 };
b3Compound* c = b3CreateCompound( &def );
ENSURE( c->hullCount == 3 );
ENSURE( c->sharedHullCount == 1 );
b3DestroyCompound( c );
return 0;
}
static int CompoundHullSharingContent( void )
{
b3SurfaceMaterial mat = b3DefaultSurfaceMaterial();
// Two box hulls built independently with identical args are byte-identical
// (b3MakeBoxHull is deterministic and the hash is computed over the bytes).
b3BoxHull boxA = b3MakeBoxHull( 1, 1, 1 );
b3BoxHull boxB = b3MakeBoxHull( 1, 1, 1 );
ENSURE( &boxA != &boxB );
b3CompoundHullDef hulls[2] = {
{ .hull = &boxA.base, .transform = b3Transform_identity, .material = mat },
{ .hull = &boxB.base, .transform = b3Transform_identity, .material = mat },
};
hulls[1].transform.p.x = 5.0f;
b3CompoundDef def = { .hulls = hulls, .hullCount = 2 };
b3Compound* c = b3CreateCompound( &def );
ENSURE( c->sharedHullCount == 1 );
b3DestroyCompound( c );
return 0;
}
static int CompoundHullDistinct( void )
{
b3SurfaceMaterial mat = b3DefaultSurfaceMaterial();
b3BoxHull boxA = b3MakeBoxHull( 1, 1, 1 );
b3BoxHull boxB = b3MakeBoxHull( 2, 1, 1 );
b3CompoundHullDef hulls[2] = {
{ .hull = &boxA.base, .transform = b3Transform_identity, .material = mat },
{ .hull = &boxB.base, .transform = b3Transform_identity, .material = mat },
};
hulls[1].transform.p.x = 5.0f;
b3CompoundDef def = { .hulls = hulls, .hullCount = 2 };
b3Compound* c = b3CreateCompound( &def );
ENSURE( c->sharedHullCount == 2 );
b3DestroyCompound( c );
return 0;
}
static int CompoundMeshSharingPointer( void )
{
b3SurfaceMaterial mat = b3DefaultSurfaceMaterial();
b3MeshData* md = b3CreateBoxMesh( b3Vec3_zero, (b3Vec3){ 1, 1, 1 }, false );
b3CompoundMeshDef meshes[3];
for ( int i = 0; i < 3; ++i )
{
meshes[i].meshData = md;
meshes[i].transform = b3Transform_identity;
meshes[i].transform.p.x = (float)( 4 * i );
meshes[i].scale = (b3Vec3){ 1, 1, 1 };
meshes[i].materials = &mat;
meshes[i].materialCount = 1;
}
b3CompoundDef def = { .meshes = meshes, .meshCount = 3 };
b3Compound* c = b3CreateCompound( &def );
ENSURE( c->meshCount == 3 );
ENSURE( c->sharedMeshCount == 1 );
b3DestroyCompound( c );
b3DestroyMesh( md );
return 0;
}
static int CompoundMeshSharingContent( void )
{
b3SurfaceMaterial mat = b3DefaultSurfaceMaterial();
b3MeshData* mdA = b3CreateBoxMesh( b3Vec3_zero, (b3Vec3){ 1, 1, 1 }, false );
b3MeshData* mdB = b3CreateBoxMesh( b3Vec3_zero, (b3Vec3){ 1, 1, 1 }, false );
ENSURE( mdA != mdB );
b3CompoundMeshDef meshes[2] = {
{ .meshData = mdA, .transform = b3Transform_identity, .scale = { 1, 1, 1 }, .materials = &mat, .materialCount = 1 },
{ .meshData = mdB, .transform = b3Transform_identity, .scale = { 1, 1, 1 }, .materials = &mat, .materialCount = 1 },
};
meshes[1].transform.p.x = 5.0f;
b3CompoundDef def = { .meshes = meshes, .meshCount = 2 };
b3Compound* c = b3CreateCompound( &def );
ENSURE( c->sharedMeshCount == 1 );
b3DestroyCompound( c );
b3DestroyMesh( mdA );
b3DestroyMesh( mdB );
return 0;
}
static int CompoundMeshDistinct( void )
{
b3SurfaceMaterial mat = b3DefaultSurfaceMaterial();
b3MeshData* mdA = b3CreateBoxMesh( b3Vec3_zero, (b3Vec3){ 1, 1, 1 }, false );
b3MeshData* mdB = b3CreateBoxMesh( b3Vec3_zero, (b3Vec3){ 2, 1, 1 }, false );
b3CompoundMeshDef meshes[2] = {
{ .meshData = mdA, .transform = b3Transform_identity, .scale = { 1, 1, 1 }, .materials = &mat, .materialCount = 1 },
{ .meshData = mdB, .transform = b3Transform_identity, .scale = { 1, 1, 1 }, .materials = &mat, .materialCount = 1 },
};
meshes[1].transform.p.x = 5.0f;
b3CompoundDef def = { .meshes = meshes, .meshCount = 2 };
b3Compound* c = b3CreateCompound( &def );
ENSURE( c->sharedMeshCount == 2 );
b3DestroyCompound( c );
b3DestroyMesh( mdA );
b3DestroyMesh( mdB );
return 0;
}
// ---------------------------------------------------------------------------
// Child accessors and dispatch
// ---------------------------------------------------------------------------
static int CompoundChildDispatch( void )
{
b3SurfaceMaterial mat = b3DefaultSurfaceMaterial();
b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f );
b3MeshData* md = b3CreateBoxMesh( b3Vec3_zero, (b3Vec3){ 0.5f, 0.5f, 0.5f }, false );
b3CompoundCapsuleDef caps[2] = {
{ .capsule = { { 0, 0, 0 }, { 1, 0, 0 }, 0.2f }, .material = mat },
{ .capsule = { { 0, 2, 0 }, { 1, 2, 0 }, 0.2f }, .material = mat },
};
b3CompoundHullDef hulls[1] = { { .hull = &box.base, .transform = b3Transform_identity, .material = mat } };
hulls[0].transform.p = (b3Vec3){ 5, 0, 0 };
b3CompoundMeshDef meshes[1] = { {
.meshData = md,
.transform = b3Transform_identity,
.scale = { 1, 1, 1 },
.materials = &mat,
.materialCount = 1,
} };
meshes[0].transform.p = (b3Vec3){ 0, 0, 5 };
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,
};
b3Compound* c = b3CreateCompound( &def );
// Index ordering is capsules → hulls → meshes → spheres.
ENSURE( b3GetCompoundChild( c, 0 ).type == b3_capsuleShape );
ENSURE( b3GetCompoundChild( c, 1 ).type == b3_capsuleShape );
ENSURE( b3GetCompoundChild( c, 2 ).type == b3_hullShape );
ENSURE( b3GetCompoundChild( c, 3 ).type == b3_meshShape );
ENSURE( b3GetCompoundChild( c, 4 ).type == b3_sphereShape );
// Capsule and sphere children always report identity transform — the position
// is encoded in the shape itself (capsule->center{1,2}, sphere->center).
b3ChildShape cap0 = b3GetCompoundChild( c, 0 );
ENSURE_SMALL( cap0.transform.p.x, FLT_EPSILON );
ENSURE_SMALL( cap0.transform.p.y, FLT_EPSILON );
ENSURE_SMALL( cap0.transform.p.z, FLT_EPSILON );
ENSURE_SMALL( cap0.capsule.center2.x - 1.0f, FLT_EPSILON );
b3ChildShape sph = b3GetCompoundChild( c, 4 );
ENSURE_SMALL( sph.transform.p.x, FLT_EPSILON );
ENSURE_SMALL( sph.sphere.center.x + 5.0f, FLT_EPSILON );
// Hull and mesh children carry their stored transform.
b3ChildShape hull = b3GetCompoundChild( c, 2 );
ENSURE_SMALL( hull.transform.p.x - 5.0f, FLT_EPSILON );
b3ChildShape mesh = b3GetCompoundChild( c, 3 );
ENSURE_SMALL( mesh.transform.p.z - 5.0f, FLT_EPSILON );
ENSURE( mesh.mesh.data != NULL );
b3DestroyCompound( c );
b3DestroyMesh( md );
return 0;
}
// ---------------------------------------------------------------------------
// AABB
// ---------------------------------------------------------------------------
static int CompoundAABBContainsChildren( void )
{
b3SurfaceMaterial mat = b3DefaultSurfaceMaterial();
b3CompoundSphereDef spheres[2] = {
{ .sphere = { { -3, 0, 0 }, 1.0f }, .material = mat },
{ .sphere = { { 4, 0, 0 }, 0.5f }, .material = mat },
};
b3CompoundDef def = { .spheres = spheres, .sphereCount = 2 };
b3Compound* c = b3CreateCompound( &def );
b3AABB local = b3ComputeCompoundAABB( c, b3Transform_identity );
ENSURE( local.lowerBound.x <= -4.0f + 1e-5f );
ENSURE( local.upperBound.x >= 4.5f - 1e-5f );
ENSURE( local.lowerBound.y <= -1.0f + 1e-5f );
ENSURE( local.upperBound.y >= 1.0f - 1e-5f );
// Translation commutes through the bounding-box transform.
b3Transform xf = { .p = { 10, 20, 30 }, .q = b3Quat_identity };
b3AABB world = b3ComputeCompoundAABB( c, xf );
ENSURE_SMALL( world.lowerBound.x - ( local.lowerBound.x + 10.0f ), 1e-4f );
ENSURE_SMALL( world.upperBound.y - ( local.upperBound.y + 20.0f ), 1e-4f );
ENSURE_SMALL( world.lowerBound.z - ( local.lowerBound.z + 30.0f ), 1e-4f );
b3DestroyCompound( c );
return 0;
}
// ---------------------------------------------------------------------------
// Ray cast / shape cast
// ---------------------------------------------------------------------------
static int CompoundRayCastMiss( void )
{
b3SurfaceMaterial mat = b3DefaultSurfaceMaterial();
b3CompoundSphereDef sph = { .sphere = { { 0, 0, 0 }, 0.5f }, .material = mat };
b3CompoundDef def = { .spheres = &sph, .sphereCount = 1 };
b3Compound* c = b3CreateCompound( &def );
// Ray well above the sphere on a parallel path.
b3RayCastInput input = { .origin = { -5, 5, 0 }, .translation = { 10, 0, 0 }, .maxFraction = 1.0f };
b3CastOutput out = b3RayCastCompound( c, &input );
ENSURE( out.hit == false );
b3DestroyCompound( c );
return 0;
}
static int CompoundRayCastClosest( void )
{
b3SurfaceMaterial matA = MakeMaterial( 0.4f, 100 );
b3SurfaceMaterial matB = MakeMaterial( 0.4f, 200 );
// Two unit spheres along +X. Ray from origin must hit the nearer one first.
b3CompoundSphereDef spheres[2] = {
{ .sphere = { { 5, 0, 0 }, 1.0f }, .material = matA },
{ .sphere = { { 10, 0, 0 }, 1.0f }, .material = matB },
};
b3CompoundDef def = { .spheres = spheres, .sphereCount = 2 };
b3Compound* c = b3CreateCompound( &def );
b3RayCastInput input = { .origin = { 0, 0, 0 }, .translation = { 20, 0, 0 }, .maxFraction = 1.0f };
b3CastOutput out = b3RayCastCompound( c, &input );
ENSURE( out.hit == true );
// Front face of the nearer sphere is at x=4 → fraction 4/20 = 0.2.
ENSURE_SMALL( out.fraction - 0.2f, 1e-4f );
ENSURE_SMALL( out.normal.x + 1.0f, 1e-4f );
ENSURE( out.childIndex == 0 );
const b3SurfaceMaterial* mats = b3GetCompoundMaterials( c );
ENSURE( mats[out.materialIndex].userMaterialId == 100 );
b3DestroyCompound( c );
return 0;
}
static int CompoundRayCastHullNormalRotation( void )
{
// A unit box rotated 90° about Z, placed at compound +X. The ray hits the
// face that, in compound space, points back toward -X. Verifies that the
// normal returned by the cast has been rotated from hull-local space back
// into compound space.
b3SurfaceMaterial mat = b3DefaultSurfaceMaterial();
b3BoxHull box = b3MakeBoxHull( 1, 1, 1 );
b3CompoundHullDef hull = {
.hull = &box.base,
.transform = { .p = { 5, 0, 0 }, .q = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, 0.5f * B3_PI ) },
.material = mat,
};
b3CompoundDef def = { .hulls = &hull, .hullCount = 1 };
b3Compound* c = b3CreateCompound( &def );
b3RayCastInput input = { .origin = { 0, 0, 0 }, .translation = { 20, 0, 0 }, .maxFraction = 1.0f };
b3CastOutput out = b3RayCastCompound( c, &input );
ENSURE( out.hit == true );
// Box has |hx|=1; with the rotation a face still intersects the +X ray at x=4.
ENSURE_SMALL( out.fraction - 0.2f, 1e-4f );
ENSURE_SMALL( out.normal.x + 1.0f, 1e-3f );
ENSURE_SMALL( out.normal.y, 1e-3f );
ENSURE_SMALL( out.normal.z, 1e-3f );
b3DestroyCompound( c );
return 0;
}
static int CompoundShapeCastClosest( void )
{
b3SurfaceMaterial mat = b3DefaultSurfaceMaterial();
b3CompoundSphereDef spheres[2] = {
{ .sphere = { { 5, 0, 0 }, 1.0f }, .material = mat },
{ .sphere = { { 10, 0, 0 }, 1.0f }, .material = mat },
};
b3CompoundDef def = { .spheres = spheres, .sphereCount = 2 };
b3Compound* c = b3CreateCompound( &def );
b3Vec3 point = { 0, 0, 0 };
b3ShapeCastInput input = {
.proxy = { .points = &point, .count = 1, .radius = 0.25f },
.translation = { 20, 0, 0 },
.maxFraction = 1.0f,
.canEncroach = false,
};
b3CastOutput out = b3ShapeCastCompound( c, &input );
ENSURE( out.hit == true );
// Closest contact: caster radius 0.25 + sphere radius 1.0 → first contact at x ≈ 3.75.
ENSURE_SMALL( out.fraction - 3.75f / 20.0f, 1e-3f );
ENSURE( out.childIndex == 0 );
b3DestroyCompound( c );
return 0;
}
// ---------------------------------------------------------------------------
// Overlap
// ---------------------------------------------------------------------------
static int CompoundOverlap( void )
{
b3SurfaceMaterial mat = b3DefaultSurfaceMaterial();
b3CompoundSphereDef spheres[2] = {
{ .sphere = { { -3, 0, 0 }, 0.5f }, .material = mat },
{ .sphere = { { 3, 0, 0 }, 0.5f }, .material = mat },
};
b3CompoundDef def = { .spheres = spheres, .sphereCount = 2 };
b3Compound* c = b3CreateCompound( &def );
// Proxy at the origin lies in the gap between the two spheres.
b3Vec3 origin = { 0, 0, 0 };
b3ShapeProxy gap = { .points = &origin, .count = 1, .radius = 0.25f };
ENSURE( b3OverlapCompound( c, b3Transform_identity, &gap ) == false );
// Proxy at the center of the second sphere overlaps it.
b3Vec3 onSecond = { 3, 0, 0 };
b3ShapeProxy hit = { .points = &onSecond, .count = 1, .radius = 0.1f };
ENSURE( b3OverlapCompound( c, b3Transform_identity, &hit ) == true );
b3DestroyCompound( c );
return 0;
}
// ---------------------------------------------------------------------------
// Query
// ---------------------------------------------------------------------------
struct QueryAccum
{
int childIndices[8];
int count;
int stopAfter; // -1 = never stop early
};
static bool QueryCallback( const b3Compound* compound, int childIndex, void* context )
{
(void)compound;
struct QueryAccum* acc = context;
if ( acc->count < (int)( sizeof( acc->childIndices ) / sizeof( acc->childIndices[0] ) ) )
{
acc->childIndices[acc->count++] = childIndex;
}
if ( acc->stopAfter >= 0 && acc->count >= acc->stopAfter )
{
return false;
}
return true;
}
static int CompoundQuery( void )
{
b3SurfaceMaterial mat = b3DefaultSurfaceMaterial();
b3CompoundSphereDef spheres[3] = {
{ .sphere = { { -10, 0, 0 }, 0.5f }, .material = mat },
{ .sphere = { { 0, 0, 0 }, 0.5f }, .material = mat },
{ .sphere = { { 10, 0, 0 }, 0.5f }, .material = mat },
};
b3CompoundDef def = { .spheres = spheres, .sphereCount = 3 };
b3Compound* c = b3CreateCompound( &def );
// Tight box around the middle sphere — only it should be reported.
b3AABB middle = { { -1, -1, -1 }, { 1, 1, 1 } };
struct QueryAccum 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 };
b3QueryCompound( c, wide, QueryCallback, &stop );
ENSURE( stop.count == 1 );
// Without early-exit, all three are visited.
struct QueryAccum all = { .stopAfter = -1 };
b3QueryCompound( c, wide, QueryCallback, &all );
ENSURE( all.count == 3 );
b3DestroyCompound( c );
return 0;
}
// ---------------------------------------------------------------------------
// Mover
// ---------------------------------------------------------------------------
static int CompoundMover( void )
{
b3SurfaceMaterial mat = b3DefaultSurfaceMaterial();
b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f );
// Two boxes side-by-side along X, gap of 1 between them.
b3CompoundHullDef hulls[2] = {
{ .hull = &box.base, .transform = { .p = { -1.0f, 0, 0 }, .q = b3Quat_identity }, .material = mat },
{ .hull = &box.base, .transform = { .p = { 1.0f, 0, 0 }, .q = b3Quat_identity }, .material = mat },
};
b3CompoundDef def = { .hulls = hulls, .hullCount = 2 };
b3Compound* c = b3CreateCompound( &def );
// Small capsule mover sitting on top of the boxes, low enough to penetrate both.
b3Capsule mover = { { -1.0f, 0.6f, 0 }, { 1.0f, 0.6f, 0 }, 0.2f };
b3PlaneResult planes[8] = { 0 };
int planeCount = b3CollideMoverAndCompound( planes, 8, c, &mover );
// Both boxes contribute at least one plane each; the +Y face of each box
// should produce a plane whose normal points roughly +Y in compound space.
ENSURE( planeCount >= 2 );
int upPlanes = 0;
for ( int i = 0; i < planeCount; ++i )
{
if ( planes[i].plane.normal.y > 0.9f )
{
upPlanes += 1;
}
}
ENSURE( upPlanes >= 2 );
// Capacity cap is honored: ask for 1 and the call must not exceed it.
b3PlaneResult one[1] = { 0 };
int capped = b3CollideMoverAndCompound( one, 1, c, &mover );
ENSURE( capped <= 1 );
b3DestroyCompound( c );
return 0;
}
// ---------------------------------------------------------------------------
// Serialization round-trip
// ---------------------------------------------------------------------------
static b3Compound* BuildSerializableCompound( b3MeshData* md )
{
b3SurfaceMaterial mat = b3DefaultSurfaceMaterial();
b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f );
b3CompoundCapsuleDef cap = { .capsule = { { -2, 0, 0 }, { -1, 0, 0 }, 0.2f }, .material = mat };
b3CompoundHullDef hull = { .hull = &box.base, .transform = { .p = { 5, 0, 0 }, .q = b3Quat_identity }, .material = mat };
b3CompoundMeshDef mesh = {
.meshData = md,
.transform = { .p = { 0, 0, 5 }, .q = b3Quat_identity },
.scale = { 1, 1, 1 },
.materials = &mat,
.materialCount = 1,
};
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,
};
return b3CreateCompound( &def );
}
static int CompoundSerializeRoundtrip( void )
{
b3MeshData* md = b3CreateBoxMesh( b3Vec3_zero, (b3Vec3){ 0.5f, 0.5f, 0.5f }, false );
b3Compound* a = BuildSerializableCompound( md );
// Snapshot a few queries on the original.
b3AABB aabbA = b3ComputeCompoundAABB( a, b3Transform_identity );
b3RayCastInput rayInput = { .origin = { 0, 0, 0 }, .translation = { 20, 0, 0 }, .maxFraction = 1.0f };
b3CastOutput rayA = b3RayCastCompound( a, &rayInput );
ENSURE( rayA.hit );
int byteCount = a->byteCount;
uint8_t* buffer = (uint8_t*)malloc( (size_t)byteCount );
ENSURE( buffer != NULL );
uint8_t* serialized = b3ConvertCompoundToBytes( a );
memcpy( buffer, serialized, (size_t)byteCount );
b3DestroyCompound( a );
b3Compound* b = b3ConvertBytesToCompound( buffer, byteCount );
ENSURE( b != NULL );
ENSURE( b->byteCount == byteCount );
ENSURE( b->capsuleCount == 1 );
ENSURE( b->hullCount == 1 );
ENSURE( b->meshCount == 1 );
ENSURE( b->sphereCount == 1 );
ENSURE( b->tree.nodes != NULL );
// Bounds and ray cast on the deserialized compound match the original.
b3AABB aabbB = b3ComputeCompoundAABB( b, b3Transform_identity );
ENSURE_SMALL( aabbA.lowerBound.x - aabbB.lowerBound.x, 1e-5f );
ENSURE_SMALL( aabbA.upperBound.z - aabbB.upperBound.z, 1e-5f );
b3CastOutput rayB = b3RayCastCompound( b, &rayInput );
ENSURE( rayB.hit == rayA.hit );
ENSURE_SMALL( rayB.fraction - rayA.fraction, 1e-5f );
ENSURE( rayB.childIndex == rayA.childIndex );
free( buffer );
b3DestroyMesh( md );
return 0;
}
static int CompoundSerializeBadVersion( void )
{
b3MeshData* md = b3CreateBoxMesh( b3Vec3_zero, (b3Vec3){ 0.5f, 0.5f, 0.5f }, false );
b3Compound* a = BuildSerializableCompound( md );
int byteCount = a->byteCount;
uint8_t* buffer = (uint8_t*)malloc( (size_t)byteCount );
memcpy( buffer, b3ConvertCompoundToBytes( a ), (size_t)byteCount );
b3DestroyCompound( a );
// Corrupt the version word (first 8 bytes of b3Compound).
((b3Compound*)buffer)->version ^= 0x1ull;
b3Compound* b = b3ConvertBytesToCompound( buffer, byteCount );
ENSURE( b == NULL );
free( buffer );
b3DestroyMesh( md );
return 0;
}
static int CompoundSerializeWrongByteCount( void )
{
b3MeshData* md = b3CreateBoxMesh( b3Vec3_zero, (b3Vec3){ 0.5f, 0.5f, 0.5f }, false );
b3Compound* a = BuildSerializableCompound( md );
int byteCount = a->byteCount;
uint8_t* buffer = (uint8_t*)malloc( (size_t)byteCount );
memcpy( buffer, b3ConvertCompoundToBytes( a ), (size_t)byteCount );
b3DestroyCompound( a );
// Off-by-one in the declared length is rejected.
b3Compound* b = b3ConvertBytesToCompound( buffer, byteCount + 1 );
ENSURE( b == NULL );
free( buffer );
b3DestroyMesh( md );
return 0;
}
// ---------------------------------------------------------------------------
int CompoundTest( void )
{
RUN_SUBTEST( CompoundCreateMixed );
RUN_SUBTEST( CompoundCreateSingleType );
RUN_SUBTEST( CompoundMaterialDedup );
RUN_SUBTEST( CompoundMaterialDistinct );
RUN_SUBTEST( CompoundMaterialCrossShape );
RUN_SUBTEST( CompoundMaterialMeshShared );
RUN_SUBTEST( CompoundHullSharingPointer );
RUN_SUBTEST( CompoundHullSharingContent );
RUN_SUBTEST( CompoundHullDistinct );
RUN_SUBTEST( CompoundMeshSharingPointer );
RUN_SUBTEST( CompoundMeshSharingContent );
RUN_SUBTEST( CompoundMeshDistinct );
RUN_SUBTEST( CompoundChildDispatch );
RUN_SUBTEST( CompoundAABBContainsChildren );
RUN_SUBTEST( CompoundRayCastMiss );
RUN_SUBTEST( CompoundRayCastClosest );
RUN_SUBTEST( CompoundRayCastHullNormalRotation );
RUN_SUBTEST( CompoundShapeCastClosest );
RUN_SUBTEST( CompoundOverlap );
RUN_SUBTEST( CompoundQuery );
RUN_SUBTEST( CompoundMover );
RUN_SUBTEST( CompoundSerializeRoundtrip );
RUN_SUBTEST( CompoundSerializeBadVersion );
RUN_SUBTEST( CompoundSerializeWrongByteCount );
return 0;
}

195
test/test_container.c Normal file
View file

@ -0,0 +1,195 @@
// SPDX-FileCopyrightText: 2025 Erin Catto
// SPDX-License-Identifier: MIT
#include "container.h"
#include "core.h"
#include "test_macros.h"
#include <assert.h>
#include <stdint.h>
b3DeclareArrayNative( uint64_t );
b3DeclareArrayNative( int16_t );
b3DeclareArrayNative( uint8_t );
typedef struct Foo
{
int a;
float b;
} Foo;
b3DeclareArray( Foo );
typedef struct Bar
{
b3ArrayC( int ) a;
} Bar;
static int TestCreateDestroy( void )
{
b3ArrayC( int ) a;
b3Array_Create( a );
b3Array_Destroy( a );
return 0;
}
static int TestAccess( void )
{
b3ArrayC( int ) a;
b3Array_Create( a );
b3Array_Push( a, 42 );
int* element = b3Array_Get( a, 0 );
ENSURE( *element == 42 );
b3Array_Destroy( a );
return 0;
}
static int TestIteration( void )
{
b3ArrayC( int ) a = { 0 };
b3Array_Push( a, 1 );
b3Array_Push( a, 2 );
b3Array_Push( a, 3 );
int sum = 0;
for ( int i = 0; i < a.count; ++i )
{
sum += a.data[i];
}
ENSURE( sum == 6 );
b3Array_Destroy( a );
return 0;
}
static int TestArrayOfStruct( void )
{
b3ArrayC( Foo ) a;
b3Array_Create( a );
b3Array_Push( a, ( (Foo){ .a = 1, .b = 5.0f } ) );
b3Array_Push( a, ( (Foo){ .a = 2, .b = 6.0f } ) );
b3Array_Push( a, ( (Foo){ .a = 3, .b = 7.0f } ) );
int sum1 = 0;
float sum2 = 0.0f;
for ( int i = 0; i < a.count; ++i )
{
sum1 += a.data[i].a;
sum2 += a.data[i].b;
}
ENSURE( sum1 == 6 );
ENSURE( sum2 == 18.0f );
b3Array_Destroy( a );
return 0;
}
static int TestStructWithArray( void )
{
Bar a;
b3Array_Create( a.a );
b3Array_Push( a.a, 1 );
b3Array_Push( a.a, 2 );
b3Array_Push( a.a, 3 );
int sum1 = 0;
for ( int i = 0; i < a.a.count; ++i )
{
sum1 += a.a.data[i];
}
ENSURE( sum1 == 6 );
b3Array_Destroy( a.a );
return 0;
}
static int TestArrayEmplace( void )
{
b3ArrayC( int ) a = { 0 };
int n = 100;
for ( int i = 0; i < n; ++i )
{
int* j = b3Array_Emplace( a );
*j = i;
}
int sum = 0;
for ( int i = 0; i < a.count; ++i )
{
sum += a.data[i];
}
ENSURE( sum == n * (n - 1) / 2);
b3Array_Destroy( a );
return 0;
}
static int TestArrayRemove( void )
{
b3ArrayC( int16_t ) a = { 0 };
int n = 100;
b3Array_Reserve( a, n );
ENSURE( a.capacity == n && a.count == 0 );
for ( int i = 0; i < n; ++i )
{
b3Array_Push( a, i );
}
int sum = 0;
for ( int i = 0; i < n; ++i )
{
int16_t* value = b3Array_Get( a, 0 );
sum += *value;
b3Array_RemoveSwap(a, 0);
}
ENSURE( sum == n * ( n - 1 ) / 2 );
b3Array_Destroy( a );
return 0;
}
static int TestArrayPop( void )
{
b3ArrayC( int ) a = { 0 };
int n = 10;
b3Array_Resize( a, n );
ENSURE( a.capacity == n && a.count == n );
for ( int i = 0; i < n; ++i )
{
a.data[i] = i;
}
int sum = 0;
while (a.count > 0)
{
sum += b3Array_Pop( a );
}
ENSURE( sum == n * ( n - 1 ) / 2 );
b3Array_Destroy( a );
return 0;
}
int ContainerTest( void )
{
RUN_SUBTEST( TestCreateDestroy );
RUN_SUBTEST( TestAccess );
RUN_SUBTEST( TestIteration );
RUN_SUBTEST( TestArrayOfStruct );
RUN_SUBTEST( TestStructWithArray );
RUN_SUBTEST( TestArrayEmplace );
RUN_SUBTEST( TestArrayRemove );
RUN_SUBTEST( TestArrayPop );
return 0;
}

113
test/test_determinism.c Normal file
View file

@ -0,0 +1,113 @@
// SPDX-FileCopyrightText: 2025 Erin Catto
// SPDX-License-Identifier: MIT
#include "box3d/box3d.h"
#include "determinism.h"
#include "test_macros.h"
#include <stdio.h>
#include <stdlib.h>
#ifdef BOX3D_PROFILE
#include <tracy/TracyC.h>
#else
#define TracyCFrameMark
#endif
#define EXPECTED_SLEEP_STEP 306
#define EXPECTED_HASH 0xCBF958A1
static int SingleMultithreadingTest( int workerCount )
{
b3WorldDef worldDef = b3DefaultWorldDef();
worldDef.workerCount = workerCount;
b3WorldId worldId = b3CreateWorld( &worldDef );
FallingRagdollData data = CreateFallingRagdolls( worldId );
float timeStep = 1.0f / 60.0f;
int stepLimit = 500;
for ( int i = 0; i < stepLimit; ++i )
{
int subStepCount = 4;
b3World_Step( worldId, timeStep, subStepCount );
TracyCFrameMark;
bool done = UpdateFallingRagdolls( worldId, &data );
if ( done )
{
break;
}
}
b3DestroyWorld( worldId );
if ( data.sleepStep != EXPECTED_SLEEP_STEP || data.hash != EXPECTED_HASH )
{
printf( " workers=%d sleepStep=%d hash=0x%08X\n", workerCount, data.sleepStep, data.hash );
}
ENSURE( data.sleepStep == EXPECTED_SLEEP_STEP );
ENSURE( data.hash == EXPECTED_HASH );
DestroyFallingRagdolls( &data );
return 0;
}
// Test multithreaded determinism.
static int MultithreadingTest( void )
{
for ( int workerCount = 1; workerCount < 6; ++workerCount )
{
int result = SingleMultithreadingTest( workerCount );
ENSURE( result == 0 );
}
return 0;
}
// Test cross platform determinism.
static int CrossPlatformTest( void )
{
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
FallingRagdollData data = CreateFallingRagdolls( worldId );
float timeStep = 1.0f / 60.0f;
bool done = false;
while ( done == false )
{
int subStepCount = 4;
b3World_Step( worldId, timeStep, subStepCount );
TracyCFrameMark;
done = UpdateFallingRagdolls( worldId, &data );
}
if ( data.sleepStep != EXPECTED_SLEEP_STEP || data.hash != EXPECTED_HASH )
{
printf( " cross-platform sleepStep=%d hash=0x%08X\n", data.sleepStep, data.hash );
}
ENSURE( data.sleepStep == EXPECTED_SLEEP_STEP );
ENSURE( data.hash == EXPECTED_HASH );
DestroyFallingRagdolls( &data );
b3DestroyWorld( worldId );
return 0;
}
int DeterminismTest( void )
{
RUN_SUBTEST( MultithreadingTest );
RUN_SUBTEST( CrossPlatformTest );
return 0;
}

112
test/test_distance.c Normal file
View file

@ -0,0 +1,112 @@
// SPDX-FileCopyrightText: 2023 Erin Catto
// SPDX-License-Identifier: MIT
#include "test_macros.h"
#include "box2d/collision.h"
#include "box2d/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 };
b2SegmentDistanceResult result = b2SegmentDistance( 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 );
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 } };
b2Vec2 vbs[] = {
( b2Vec2 ){ 2.0f, -1.0f },
( b2Vec2 ){ 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;
input.useRadii = false;
b2DistanceCache cache = { 0 };
b2DistanceOutput output = b2ShapeDistance( &cache, &input, NULL, 0 );
ENSURE_SMALL( output.distance - 1.0f, FLT_EPSILON );
return 0;
}
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 } };
b2Vec2 vbs[] = {
( b2Vec2 ){ 2.0f, -1.0f },
( b2Vec2 ){ 2.0f, 1.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 };
input.maxFraction = 1.0f;
b2CastOutput output = b2ShapeCast( &input );
ENSURE( output.hit );
ENSURE_SMALL( output.fraction - 0.5f, 0.005f );
return 0;
}
static int TimeOfImpactTest( void )
{
b2Vec2 vas[] = { { -1.0f, -1.0f }, { 1.0f, -1.0f }, { 1.0f, 1.0f }, { -1.0f, 1.0f } };
b2Vec2 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;
b2TOIOutput output = b2TimeOfImpact( &input );
ENSURE( output.state == b2_toiStateHit );
ENSURE_SMALL( output.t - 0.5f, 0.005f );
return 0;
}
int DistanceTest( void )
{
RUN_SUBTEST( SegmentDistanceTest );
RUN_SUBTEST( ShapeDistanceTest );
RUN_SUBTEST( ShapeCastTest );
RUN_SUBTEST( TimeOfImpactTest );
return 0;
}

246
test/test_height_field.c Normal file
View file

@ -0,0 +1,246 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
#include "test_macros.h"
// b3GetHeightFieldTriangle is internal
#include "shape.h"
#include "box3d/collision.h"
#include "box3d/math_functions.h"
#include <float.h>
#include <stdio.h>
static int HeightFieldCreate( void )
{
b3Vec3 scale = { 1.0f, 1.0f, 1.0f };
b3HeightField* hf = b3CreateGrid( 4, 4, scale, false );
ENSURE( hf->rowCount == 4 );
ENSURE( hf->columnCount == 4 );
ENSURE( hf->clockwise == false );
ENSURE( hf->version == B3_HEIGHT_FIELD_VERSION );
ENSURE_SMALL( hf->aabb.lowerBound.x, FLT_EPSILON );
ENSURE_SMALL( hf->aabb.lowerBound.y, FLT_EPSILON );
ENSURE_SMALL( hf->aabb.lowerBound.z, FLT_EPSILON );
ENSURE_SMALL( hf->aabb.upperBound.x - 3.0f, FLT_EPSILON );
ENSURE_SMALL( hf->aabb.upperBound.y, FLT_EPSILON );
ENSURE_SMALL( hf->aabb.upperBound.z - 3.0f, FLT_EPSILON );
b3DestroyHeightField( hf );
return 0;
}
static int HeightFieldTriangleIndex( void )
{
// Asymmetric grid (rows != cols) catches off-by-one errors between
// vertex stride (columnCount) and cell stride (columnCount - 1).
int rowCount = 4;
int columnCount = 5;
b3Vec3 scale = { 1.0f, 1.0f, 1.0f };
b3HeightField* hf = b3CreateGrid( rowCount, columnCount, scale, false );
int triangleCount = 2 * ( rowCount - 1 ) * ( columnCount - 1 );
for ( int triangleIndex = 0; triangleIndex < triangleCount; ++triangleIndex )
{
int quadIndex = triangleIndex >> 1;
int sub = triangleIndex & 1;
int row = quadIndex / ( columnCount - 1 );
int column = quadIndex - row * ( columnCount - 1 );
int index11 = row * columnCount + column;
int index12 = index11 + 1;
int index21 = ( row + 1 ) * columnCount + column;
int index22 = index21 + 1;
b3Triangle t = b3GetHeightFieldTriangle( hf, triangleIndex );
if ( sub == 0 )
{
// Triangle 0 (CCW): {11, 21, 12}
ENSURE( t.i1 == index11 );
ENSURE( t.i2 == index21 );
ENSURE( t.i3 == index12 );
}
else
{
// Triangle 1 (CCW): {22, 12, 21}
ENSURE( t.i1 == index22 );
ENSURE( t.i2 == index12 );
ENSURE( t.i3 == index21 );
}
}
b3DestroyHeightField( hf );
return 0;
}
static int HeightFieldWinding( void )
{
// Build the same flat 3x3 field with CCW and CW winding. The cross-product
// normal of triangle 0 must flip sign accordingly.
float heights[9] = { 0 };
uint8_t materials[4] = { 0, 0, 0, 0 };
b3HeightFieldDef def = { 0 };
def.heights = heights;
def.materialIndices = materials;
def.scale = (b3Vec3){ 1.0f, 1.0f, 1.0f };
def.countX = 3;
def.countZ = 3;
def.globalMinimumHeight = -1.0f;
def.globalMaximumHeight = 1.0f;
def.clockwiseWinding = false;
b3HeightField* ccw = b3CreateHeightField( &def );
def.clockwiseWinding = true;
b3HeightField* cw = b3CreateHeightField( &def );
b3Triangle ta = b3GetHeightFieldTriangle( ccw, 0 );
b3Triangle tb = b3GetHeightFieldTriangle( cw, 0 );
b3Vec3 na =
b3Normalize( b3Cross( b3Sub( ta.vertices[1], ta.vertices[0] ), b3Sub( ta.vertices[2], ta.vertices[0] ) ) );
b3Vec3 nb =
b3Normalize( b3Cross( b3Sub( tb.vertices[1], tb.vertices[0] ), b3Sub( tb.vertices[2], tb.vertices[0] ) ) );
ENSURE_SMALL( na.x, FLT_EPSILON );
ENSURE_SMALL( na.y - 1.0f, FLT_EPSILON );
ENSURE_SMALL( na.z, FLT_EPSILON );
ENSURE_SMALL( nb.x, FLT_EPSILON );
ENSURE_SMALL( nb.y + 1.0f, FLT_EPSILON );
ENSURE_SMALL( nb.z, FLT_EPSILON );
b3DestroyHeightField( ccw );
b3DestroyHeightField( cw );
return 0;
}
static int RayCastFlatField( void )
{
// Build a flat 4x4 field with a tight quantization range so the recovered
// surface stays within ~1e-5 of y=0 (b3CreateGrid uses -256..256 which
// blows the 1/UINT16_MAX quantum up to ~4e-3 in y).
float heights[16] = { 0 };
uint8_t materials[9] = { 0 };
b3HeightFieldDef def = { 0 };
def.heights = heights;
def.materialIndices = materials;
def.scale = (b3Vec3){ 1.0f, 1.0f, 1.0f };
def.countX = 4;
def.countZ = 4;
def.globalMinimumHeight = -1.0f;
def.globalMaximumHeight = 1.0f;
def.clockwiseWinding = false;
b3HeightField* hf = b3CreateHeightField( &def );
// Origin sits clearly inside triangle 0 of cell (1, 1) — off the cell
// diagonal x+z = 3. The translation overshoots the surface so the hit
// fraction is strictly less than maxFraction.
b3RayCastInput input = { 0 };
input.origin = (b3Vec3){ 1.25f, 10.0f, 1.25f };
input.translation = (b3Vec3){ 0.0f, -20.0f, 0.0f };
input.maxFraction = 1.0f;
b3CastOutput out = b3RayCastHeightField( hf, &input );
ENSURE( out.hit == true );
ENSURE_SMALL( out.fraction - 0.5f, 1e-5f );
ENSURE_SMALL( out.normal.x, 1e-5f );
ENSURE_SMALL( out.normal.y - 1.0f, 1e-5f );
ENSURE_SMALL( out.normal.z, 1e-5f );
b3DestroyHeightField( hf );
return 0;
}
static int OverlapAtSurface( void )
{
b3Vec3 scale = { 1.0f, 1.0f, 1.0f };
b3HeightField* hf = b3CreateGrid( 4, 4, scale, false );
// Sphere center 1.0 above the surface, radius 0.5 — clear gap.
b3Vec3 above = { 1.5f, 1.0f, 1.5f };
b3ShapeProxy proxyAbove = { &above, 1, 0.5f };
bool hitAbove = b3OverlapHeightField( hf, b3Transform_identity, &proxyAbove );
ENSURE( hitAbove == false );
// Sphere centered on the surface — radius pokes through.
b3Vec3 through = { 1.5f, 0.0f, 1.5f };
b3ShapeProxy proxyThrough = { &through, 1, 0.5f };
bool hitThrough = b3OverlapHeightField( hf, b3Transform_identity, &proxyThrough );
ENSURE( hitThrough == true );
b3DestroyHeightField( hf );
return 0;
}
static int FileRoundtrip( void )
{
float heights[9] = { 0.0f, 0.5f, -0.3f, 0.1f, 0.0f, 0.0f, 0.0f, 0.2f, 0.0f };
uint8_t materials[4] = { 0, B3_HEIGHT_FIELD_HOLE, 1, 2 };
b3HeightFieldDef def = { 0 };
def.heights = heights;
def.materialIndices = materials;
def.scale = (b3Vec3){ 1.5f, 2.0f, 0.75f };
def.countX = 3;
def.countZ = 3;
def.globalMinimumHeight = -1.0f;
def.globalMaximumHeight = 1.0f;
def.clockwiseWinding = true;
const char* path = "test_height_field_roundtrip.dat";
b3DumpHeightData( &def, path );
b3HeightField* loaded = b3LoadHeightField( path );
remove( path );
ENSURE( loaded != NULL );
ENSURE( loaded->rowCount == def.countZ );
ENSURE( loaded->columnCount == def.countX );
ENSURE( loaded->clockwise == def.clockwiseWinding );
ENSURE_SMALL( loaded->scale.x - def.scale.x, FLT_EPSILON );
ENSURE_SMALL( loaded->scale.y - def.scale.y, FLT_EPSILON );
ENSURE_SMALL( loaded->scale.z - def.scale.z, FLT_EPSILON );
ENSURE_SMALL( loaded->minHeight - def.globalMinimumHeight, FLT_EPSILON );
ENSURE_SMALL( loaded->maxHeight - def.globalMaximumHeight, FLT_EPSILON );
int cellCount = ( def.countX - 1 ) * ( def.countZ - 1 );
for ( int i = 0; i < cellCount; ++i )
{
ENSURE( loaded->materialIndices[i] == materials[i] );
}
// Recovered heights round-trip within the quantization tolerance.
float quantum = ( def.globalMaximumHeight - def.globalMinimumHeight ) / (float)UINT16_MAX;
for ( int i = 0; i < def.countX * def.countZ; ++i )
{
float recovered = loaded->minHeight + loaded->heightScale * loaded->compressedHeights[i];
ENSURE_SMALL( recovered - heights[i], 2.0f * quantum );
}
b3DestroyHeightField( loaded );
return 0;
}
int HeightFieldTest( void )
{
RUN_SUBTEST( HeightFieldCreate );
RUN_SUBTEST( HeightFieldTriangleIndex );
RUN_SUBTEST( HeightFieldWinding );
RUN_SUBTEST( RayCastFlatField );
RUN_SUBTEST( OverlapAtSurface );
RUN_SUBTEST( FileRoundtrip );
return 0;
}

462
test/test_hull.c Normal file
View file

@ -0,0 +1,462 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
#include "test_macros.h"
#include "box3d/collision.h"
#include "box3d/math_functions.h"
#include <float.h>
#include <math.h>
#include <string.h>
static const b3Vec3 s_cubeCorners[8] = {
{ 1.0f, 1.0f, 1.0f }, { -1.0f, 1.0f, 1.0f }, { -1.0f, -1.0f, 1.0f }, { 1.0f, -1.0f, 1.0f },
{ 1.0f, 1.0f, -1.0f }, { -1.0f, 1.0f, -1.0f }, { -1.0f, -1.0f, -1.0f }, { 1.0f, -1.0f, -1.0f },
};
static int CreateHullCubeTest( void )
{
b3Hull* hull = b3CreateHull( s_cubeCorners, 8, 8 );
ENSURE( hull != NULL );
ENSURE( hull->vertexCount == 8 );
ENSURE( hull->edgeCount == 24 );
ENSURE( hull->faceCount == 6 );
// Euler's identity for convex polyhedron
ENSURE( hull->vertexCount - hull->edgeCount / 2 + hull->faceCount == 2 );
b3BoxHull ref = b3MakeBoxHull( 1.0f, 1.0f, 1.0f );
ENSURE_SMALL( hull->volume - ref.base.volume, 1e-4f );
ENSURE_SMALL( hull->surfaceArea - ref.base.surfaceArea, 1e-4f );
ENSURE_SMALL( hull->innerRadius - ref.base.innerRadius, FLT_EPSILON );
ENSURE_SMALL( hull->center.x - ref.base.center.x, 1e-5f );
ENSURE_SMALL( hull->center.y - ref.base.center.y, 1e-5f );
ENSURE_SMALL( hull->center.z - ref.base.center.z, 1e-5f );
ENSURE_SMALL( hull->aabb.lowerBound.x + 1.0f, FLT_EPSILON );
ENSURE_SMALL( hull->aabb.lowerBound.y + 1.0f, FLT_EPSILON );
ENSURE_SMALL( hull->aabb.lowerBound.z + 1.0f, FLT_EPSILON );
ENSURE_SMALL( hull->aabb.upperBound.x - 1.0f, FLT_EPSILON );
ENSURE_SMALL( hull->aabb.upperBound.y - 1.0f, FLT_EPSILON );
ENSURE_SMALL( hull->aabb.upperBound.z - 1.0f, FLT_EPSILON );
b3Matrix3 d = b3SubMM( hull->centralInertia, ref.base.centralInertia );
ENSURE_SMALL( d.cx.x, 1e-4f );
ENSURE_SMALL( d.cy.y, 1e-4f );
ENSURE_SMALL( d.cz.z, 1e-4f );
ENSURE_SMALL( d.cx.y, 1e-4f );
ENSURE_SMALL( d.cx.z, 1e-4f );
ENSURE_SMALL( d.cy.z, 1e-4f );
ENSURE_SMALL( d.cy.x, 1e-4f );
ENSURE_SMALL( d.cz.x, 1e-4f );
ENSURE_SMALL( d.cz.y, 1e-4f );
b3DestroyHull( hull );
return 0;
}
static int CreateHullTetrahedronTest( void )
{
b3Vec3 points[4] = {
{ 0.0f, 0.0f, 0.0f },
{ 1.0f, 0.0f, 0.0f },
{ 0.0f, 1.0f, 0.0f },
{ 0.0f, 0.0f, 1.0f },
};
b3Hull* hull = b3CreateHull( points, 4, 4 );
ENSURE( hull != NULL );
ENSURE( hull->vertexCount == 4 );
ENSURE( hull->edgeCount == 12 );
ENSURE( hull->faceCount == 4 );
ENSURE( hull->vertexCount - hull->edgeCount / 2 + hull->faceCount == 2 );
// Analytic values for the unit-corner tetrahedron at the origin.
float expectedVolume = 1.0f / 6.0f;
float expectedSurfaceArea = 1.5f + 0.5f * sqrtf( 3.0f );
float expectedInnerRadius = 0.25f / sqrtf( 3.0f );
ENSURE_SMALL( hull->volume - expectedVolume, 1e-5f );
ENSURE_SMALL( hull->surfaceArea - expectedSurfaceArea, 1e-5f );
ENSURE_SMALL( hull->innerRadius - expectedInnerRadius, 1e-5f );
ENSURE_SMALL( hull->center.x - 0.25f, 1e-5f );
ENSURE_SMALL( hull->center.y - 0.25f, 1e-5f );
ENSURE_SMALL( hull->center.z - 0.25f, 1e-5f );
ENSURE_SMALL( hull->aabb.lowerBound.x, FLT_EPSILON );
ENSURE_SMALL( hull->aabb.lowerBound.y, FLT_EPSILON );
ENSURE_SMALL( hull->aabb.lowerBound.z, FLT_EPSILON );
ENSURE_SMALL( hull->aabb.upperBound.x - 1.0f, FLT_EPSILON );
ENSURE_SMALL( hull->aabb.upperBound.y - 1.0f, FLT_EPSILON );
ENSURE_SMALL( hull->aabb.upperBound.z - 1.0f, FLT_EPSILON );
b3DestroyHull( hull );
return 0;
}
static int CreateHullDeterminismTest( void )
{
b3Hull* h1 = b3CreateHull( s_cubeCorners, 8, 8 );
b3Hull* h2 = b3CreateHull( s_cubeCorners, 8, 8 );
ENSURE( h1 != NULL && h2 != NULL );
ENSURE( h1->byteCount == h2->byteCount );
ENSURE( h1->hash != 0 );
ENSURE( h1->hash == h2->hash );
ENSURE( memcmp( h1, h2, h1->byteCount ) == 0 );
b3DestroyHull( h1 );
b3DestroyHull( h2 );
return 0;
}
#define SPHERE_N 6
static int CreateHullMaxVertexTest( void )
{
// Sphere-sampled point cloud, dense enough that the builder has room to grow.
b3Vec3 points[SPHERE_N * SPHERE_N];
int index = 0;
for ( int i = 0; i < SPHERE_N; ++i )
{
float theta = B3_PI * (float)i / (float)( SPHERE_N - 1 );
for ( int j = 0; j < SPHERE_N; ++j )
{
float phi = 2.0f * B3_PI * (float)j / (float)SPHERE_N;
points[index].x = sinf( theta ) * cosf( phi );
points[index].y = sinf( theta ) * sinf( phi );
points[index].z = cosf( theta );
index += 1;
}
}
int count = SPHERE_N * SPHERE_N;
// maxVertexCount honored as a strict cap.
b3Hull* 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 );
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 );
ENSURE( h3 != NULL );
ENSURE( h3->vertexCount >= 4 && h3->vertexCount <= 255 );
b3DestroyHull( h3 );
return 0;
}
static int CreateHullRedundantInputTest( void )
{
// 8 cube corners + duplicates + interior points. Builder should produce the cube.
b3Vec3 points[20] = {
{ 1.0f, 1.0f, 1.0f }, // corners
{ -1.0f, 1.0f, 1.0f },
{ -1.0f, -1.0f, 1.0f },
{ 1.0f, -1.0f, 1.0f },
{ 1.0f, 1.0f, -1.0f },
{ -1.0f, 1.0f, -1.0f },
{ -1.0f, -1.0f, -1.0f },
{ 1.0f, -1.0f, -1.0f },
{ 1.0f, 1.0f, 1.0f }, // duplicates
{ 1.0f, 1.0f, 1.0f },
{ 0.0f, 0.0f, 0.0f }, // interior points
{ 0.5f, 0.0f, 0.0f },
{ 0.0f, 0.5f, 0.0f },
{ 0.0f, 0.0f, 0.5f },
{ -0.5f, 0.0f, 0.0f },
{ 0.0f, -0.5f, 0.0f },
{ 0.0f, 0.0f, -0.5f },
{ 0.25f, 0.25f, 0.25f },
{ -0.25f, -0.25f, -0.25f },
{ 0.5f, 0.5f, 0.5f },
};
b3Hull* hull = b3CreateHull( points, 20, 8 );
ENSURE( hull != NULL );
ENSURE( hull->vertexCount == 8 );
ENSURE( hull->edgeCount == 24 );
ENSURE( hull->faceCount == 6 );
b3BoxHull ref = b3MakeBoxHull( 1.0f, 1.0f, 1.0f );
ENSURE_SMALL( hull->volume - ref.base.volume, 1e-4f );
ENSURE_SMALL( hull->surfaceArea - ref.base.surfaceArea, 1e-4f );
ENSURE_SMALL( hull->innerRadius - ref.base.innerRadius, FLT_EPSILON );
ENSURE_SMALL( hull->center.x - ref.base.center.x, 1e-5f );
ENSURE_SMALL( hull->center.y - ref.base.center.y, 1e-5f );
ENSURE_SMALL( hull->center.z - ref.base.center.z, 1e-5f );
ENSURE_SMALL( hull->aabb.lowerBound.x + 1.0f, FLT_EPSILON );
ENSURE_SMALL( hull->aabb.lowerBound.y + 1.0f, FLT_EPSILON );
ENSURE_SMALL( hull->aabb.lowerBound.z + 1.0f, FLT_EPSILON );
ENSURE_SMALL( hull->aabb.upperBound.x - 1.0f, FLT_EPSILON );
ENSURE_SMALL( hull->aabb.upperBound.y - 1.0f, FLT_EPSILON );
ENSURE_SMALL( hull->aabb.upperBound.z - 1.0f, FLT_EPSILON );
b3DestroyHull( hull );
return 0;
}
static int CreateHullCloneTest( void )
{
b3Hull* original = b3CreateHull( s_cubeCorners, 8, 8 );
ENSURE( original != NULL );
b3Hull* clone = b3CloneHull( original );
ENSURE( clone != NULL );
ENSURE( clone->byteCount == original->byteCount );
ENSURE( memcmp( clone, original, original->byteCount ) == 0 );
b3DestroyHull( clone );
b3DestroyHull( original );
return 0;
}
static int CreateHullCylinderTest( void )
{
const float height = 2.0f;
const float radius = 1.0f;
const int sides = 8;
const float yOffset = 0.0f;
b3Hull* hull = b3CreateCylinder( height, radius, yOffset, sides );
ENSURE( hull != NULL );
ENSURE( hull->vertexCount == 2 * sides );
ENSURE( hull->edgeCount == 6 * sides );
ENSURE( hull->faceCount == sides + 2 );
// Analytic n-gon prism values (exact targets, not the circular cylinder approximations).
float halfAngle = B3_PI / (float)sides;
float capArea = (float)sides * 0.5f * radius * radius * sinf( 2.0f * halfAngle );
float chordLen = 2.0f * radius * sinf( halfAngle );
float lateralArea = (float)sides * chordLen * height;
float expectedVolume = capArea * height;
float expectedSurfaceArea = 2.0f * capArea + lateralArea;
float expectedInnerRadius = radius * cosf( halfAngle );
ENSURE_SMALL( ( hull->volume - expectedVolume ) / expectedVolume, 1e-4f );
ENSURE_SMALL( ( hull->surfaceArea - expectedSurfaceArea ) / expectedSurfaceArea, 1e-4f );
ENSURE_SMALL( hull->innerRadius - expectedInnerRadius, 1e-5f );
ENSURE_SMALL( hull->center.x, 1e-5f );
ENSURE_SMALL( hull->center.y - ( yOffset + 0.5f * height ), 1e-5f );
ENSURE_SMALL( hull->center.z, 1e-5f );
ENSURE_SMALL( hull->aabb.lowerBound.x + radius, FLT_EPSILON );
ENSURE_SMALL( hull->aabb.lowerBound.y - yOffset, FLT_EPSILON );
ENSURE_SMALL( hull->aabb.lowerBound.z + radius, FLT_EPSILON );
ENSURE_SMALL( hull->aabb.upperBound.x - radius, FLT_EPSILON );
ENSURE_SMALL( hull->aabb.upperBound.y - ( yOffset + height ), FLT_EPSILON );
ENSURE_SMALL( hull->aabb.upperBound.z - radius, FLT_EPSILON );
b3DestroyHull( hull );
return 0;
}
// Inlined XorShift32 + Shoemake unit-vector recipe matches shared/utils.h exactly so
// generated points are bit-identical to samples that share the seed.
static void FillSphereSample( b3Vec3* points, int count, uint32_t seed )
{
const uint32_t RAND_LIMIT_LOCAL = 32767u;
for ( int i = 0; i < count; ++i )
{
float u[3];
for ( int k = 0; k < 3; ++k )
{
seed ^= seed << 13;
seed ^= seed >> 17;
seed ^= seed << 5;
float r = (float)( seed & RAND_LIMIT_LOCAL );
r /= (float)RAND_LIMIT_LOCAL;
u[k] = r;
}
float u1 = u[0];
float u2 = 2.0f * B3_PI * u[1];
float u3 = 2.0f * B3_PI * u[2];
float sqrt1MinusU1 = sqrtf( 1.0f - u1 );
float sqrtU1 = sqrtf( u1 );
points[i].x = sqrt1MinusU1 * sinf( u2 );
points[i].y = sqrt1MinusU1 * cosf( u2 );
points[i].z = sqrtU1 * sinf( u3 );
}
}
// Reproduces the HullReduction sample (Sphere, 64 points, count=20) that used to assert on
// b->faceCount < b->faceCapacity. The free-list reclaim in NewFace/NewEdge keeps the bump
// counts proportional to the live hull instead of cumulative creations.
static int CreateHullSphereReductionTest( void )
{
b3Vec3 points[64];
FillSphereSample( points, 64, 12345 ); // RAND_SEED
b3Hull* hull = b3CreateHull( points, 64, 20 );
ENSURE( hull != NULL );
ENSURE( hull->vertexCount >= 4 && hull->vertexCount <= 20 );
ENSURE( hull->vertexCount - hull->edgeCount / 2 + hull->faceCount == 2 );
b3DestroyHull( hull );
return 0;
}
// XorShift32 + uniform-cube point generator. Same engine as FillSphereSample.
static void FillCubeSample( b3Vec3* points, int count, uint32_t seed )
{
const uint32_t RAND_LIMIT_LOCAL = 32767u;
for ( int i = 0; i < count; ++i )
{
float v[3];
for ( int k = 0; k < 3; ++k )
{
seed ^= seed << 13;
seed ^= seed >> 17;
seed ^= seed << 5;
float r = (float)( seed & RAND_LIMIT_LOCAL );
r /= (float)RAND_LIMIT_LOCAL;
v[k] = 2.0f * r - 1.0f;
}
points[i].x = v[0];
points[i].y = v[1];
points[i].z = v[2];
}
}
// Pushes the working-stage bump capacities (faceCapacity = 5*M - 10, edgeCapacity =
// 24*M - 48 in src/hull.c::b3ComputeHullWorkSizes) close to their peak by sweeping M
// on a dense random sphere. If the peak face/edge count exceeds the cap and the free
// list fails to reclaim slots in time, the assertion at src/hull.c::NewFace/NewEdge
// fires (exit code 3). M is held <= 80 because the finalization stage caps the final
// hull's face/edge count at B3_HULL_LIMIT (255), and a fully-triangulated hull with
// V > 87 vertices has 3V - 6 > 255 edges (src/hull.c:2010 returns NULL).
static int CreateHullSphereStressTest( void )
{
enum { N = 512 };
b3Vec3 points[N];
// Multiple seeds exercise different horizon-size / merge-cascade sequences.
const uint32_t seeds[] = { 12345u, 1u, 0xdeadbeefu, 0xcafef00du };
// M kept <= 40: random sphere inputs at higher M exceed the half edge limit of UINT8_MAX
const int M_values[] = { 16, 24, 32, 40 };
for ( int s = 0; s < ARRAY_COUNT( seeds ); ++s )
{
FillSphereSample( points, N, seeds[s] );
for ( int m = 0; m < ARRAY_COUNT( M_values ); ++m )
{
int M = M_values[m];
b3Hull* hull = b3CreateHull( points, N, M );
ENSURE( hull != NULL );
ENSURE( hull->vertexCount >= 4 && hull->vertexCount <= M );
ENSURE( hull->vertexCount - hull->edgeCount / 2 + hull->faceCount == 2 );
ENSURE( hull->faceCount >= 4 );
b3DestroyHull( hull );
}
}
return 0;
}
// Random points inside a cube produce a small final hull (8 corners, 6 faces) but
// generate heavy internal churn: every interior point gets fed to the conflict-list
// machinery, and most cone faces created during apex insertion are then merged out
// when their newly-created neighbors are coplanar. Exercises the merge cascade in
// b3HullBuilder_ConnectEdges/ConnectFaces and the corresponding RetireFace/RetireEdge
// reclaim path much harder than the sphere case (which has few merges).
static int CreateHullMergeChurnStressTest( void )
{
enum { N = 4096 };
static b3Vec3 points[N];
const uint32_t seeds[] = { 12345u, 0xdeadbeefu };
for ( int s = 0; s < ARRAY_COUNT( seeds ); ++s )
{
FillCubeSample( points, N, seeds[s] );
// Stamp the 8 corners last so they're guaranteed extremes.
for ( int c = 0; c < 8; ++c )
{
points[N - 8 + c].x = ( c & 1 ) ? 1.0f : -1.0f;
points[N - 8 + c].y = ( c & 2 ) ? 1.0f : -1.0f;
points[N - 8 + c].z = ( c & 4 ) ? 1.0f : -1.0f;
}
b3Hull* hull = b3CreateHull( points, N, 64 );
ENSURE( hull != NULL );
ENSURE( hull->vertexCount == 8 );
ENSURE( hull->edgeCount == 24 );
ENSURE( hull->faceCount == 6 );
b3DestroyHull( hull );
}
return 0;
}
static int CreateHullDegenerateTest( void )
{
// Real (non-null) buffer; pointCount < 4 cases are guarded inside Construct().
b3Vec3 collinear[8] = {
{ 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f }, { 2.0f, 0.0f, 0.0f }, { 3.0f, 0.0f, 0.0f },
{ 4.0f, 0.0f, 0.0f }, { 5.0f, 0.0f, 0.0f }, { 6.0f, 0.0f, 0.0f }, { 7.0f, 0.0f, 0.0f },
};
// Empty input.
ENSURE( b3CreateHull( collinear, 0, 8 ) == NULL );
// Fewer than 4 points.
ENSURE( b3CreateHull( collinear, 3, 8 ) == NULL );
// 8 coincident points.
b3Vec3 coincident[8] = {
{ 1.0f, 2.0f, 3.0f }, { 1.0f, 2.0f, 3.0f }, { 1.0f, 2.0f, 3.0f }, { 1.0f, 2.0f, 3.0f },
{ 1.0f, 2.0f, 3.0f }, { 1.0f, 2.0f, 3.0f }, { 1.0f, 2.0f, 3.0f }, { 1.0f, 2.0f, 3.0f },
};
ENSURE( b3CreateHull( coincident, 8, 8 ) == NULL );
// Collinear (along x-axis).
ENSURE( b3CreateHull( collinear, 8, 8 ) == NULL );
// Coplanar (in the xy-plane).
b3Vec3 coplanar[6] = {
{ 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f },
{ 1.0f, 1.0f, 0.0f }, { 2.0f, 0.5f, 0.0f }, { 0.5f, 2.0f, 0.0f },
};
ENSURE( b3CreateHull( coplanar, 6, 8 ) == NULL );
return 0;
}
int HullTest( void )
{
RUN_SUBTEST( CreateHullCubeTest );
RUN_SUBTEST( CreateHullTetrahedronTest );
RUN_SUBTEST( CreateHullDeterminismTest );
RUN_SUBTEST( CreateHullMaxVertexTest );
RUN_SUBTEST( CreateHullRedundantInputTest );
RUN_SUBTEST( CreateHullCloneTest );
RUN_SUBTEST( CreateHullCylinderTest );
RUN_SUBTEST( CreateHullSphereReductionTest );
RUN_SUBTEST( CreateHullSphereStressTest );
RUN_SUBTEST( CreateHullMergeChurnStressTest );
RUN_SUBTEST( CreateHullDegenerateTest );
return 0;
}

31
test/test_id.c Normal file
View file

@ -0,0 +1,31 @@
// SPDX-FileCopyrightText: 2023 Erin Catto
// SPDX-License-Identifier: MIT
#include "test_macros.h"
#include "box3d/types.h"
int IdTest( void )
{
uint64_t x = 0x0123456789ABCDEFull;
{
b3BodyId id = b3LoadBodyId( x );
uint64_t y = b3StoreBodyId( id );
ENSURE( x == y );
}
{
b3ShapeId id = b3LoadShapeId( x );
uint64_t y = b3StoreShapeId( id );
ENSURE( x == y );
}
{
b3JointId id = b3LoadJointId( x );
uint64_t y = b3StoreJointId( id );
ENSURE( x == y );
}
return 0;
}

66
test/test_macros.h Normal file
View file

@ -0,0 +1,66 @@
// SPDX-FileCopyrightText: 2024 Erin Catto
// SPDX-License-Identifier: MIT
#pragma once
#include <stdbool.h>
#include <stdio.h>
#define RUN_TEST( T ) \
do \
{ \
int result = T(); \
if ( result == 1 ) \
{ \
printf( "test failed: " #T "\n" ); \
return 1; \
} \
else \
{ \
printf( "test passed: " #T "\n" ); \
} \
} \
while ( false )
#define RUN_SUBTEST( T ) \
do \
{ \
int result = T(); \
if ( result == 1 ) \
{ \
printf( " subtest failed: " #T "\n" ); \
return 1; \
} \
else \
{ \
printf( " subtest passed: " #T "\n" ); \
} \
} \
while ( false )
#define ENSURE( C ) \
do \
{ \
if ( ( C ) == false ) \
{ \
printf( "condition false: " #C "\n" ); \
return 1; \
} \
} \
while ( false )
#define ENSURE_SMALL( C, tol ) \
do \
{ \
if ( ( C ) < -( tol ) || ( tol ) < ( C ) ) \
{ \
printf( "condition false: abs(" #C ") < %g\n", tol ); \
return 1; \
} \
} \
while ( false )
#define ARRAY_COUNT( A ) (int)( sizeof( A ) / sizeof( A[0] ) )
/// Used to prevent the compiler from warning about unused variables
#define MAYBE_UNUSED( x ) ( (void)( x ) )

277
test/test_math.c Normal file
View file

@ -0,0 +1,277 @@
// SPDX-FileCopyrightText: 2023 Erin Catto
// SPDX-License-Identifier: MIT
#include "math_internal.h"
#include "utils.h"
#include "test_macros.h"
#include <float.h>
#include <stdio.h>
// 0.0023 degrees
#define ATAN_TOL 0.00004f
int MathTest( void )
{
for ( float t = -10.0f; t < 10.0f; t += 0.01f )
{
float angle = B3_PI * t;
b3CosSin cs = b3ComputeCosSin( angle );
float c = cosf( angle );
float s = sinf( angle );
// The cosine and sine approximations are accurate to about 0.1 degrees (0.002 radians)
// printf( "%g %g\n", r.c - c, r.s - s );
ENSURE_SMALL( cs.cosine - c, 0.002f );
ENSURE_SMALL( cs.sine - s, 0.002f );
float xn = b3UnwindAngle( angle );
float a = b3Atan2( s, c );
ENSURE( b3IsValidFloat( a ) );
float diff = b3AbsFloat( a - xn );
// The two results can be off by 360 degrees (-pi and pi)
if ( diff > B3_PI )
{
diff -= 2.0f * B3_PI;
}
// The approximate atan2 is quite accurate
ENSURE_SMALL( diff, ATAN_TOL );
}
for ( float y = -1.0f; y <= 1.0f; y += 0.01f )
{
for ( float x = -1.0f; x <= 1.0f; x += 0.01f )
{
float a1 = b3Atan2( y, x );
float a2 = atan2f( y, x );
float diff = b3AbsFloat( a1 - a2 );
ENSURE( b3IsValidFloat( a1 ) );
ENSURE_SMALL( diff, ATAN_TOL );
}
}
{
float a1 = b3Atan2( 1.0f, 0.0f );
float a2 = atan2f( 1.0f, 0.0f );
float diff = b3AbsFloat( a1 - a2 );
ENSURE( b3IsValidFloat( a1 ) );
ENSURE_SMALL( diff, ATAN_TOL );
}
{
float a1 = b3Atan2( -1.0f, 0.0f );
float a2 = atan2f( -1.0f, 0.0f );
float diff = b3AbsFloat( a1 - a2 );
ENSURE( b3IsValidFloat( a1 ) );
ENSURE_SMALL( diff, ATAN_TOL );
}
{
float a1 = b3Atan2( 0.0f, 1.0f );
float a2 = atan2f( 0.0f, 1.0f );
float diff = b3AbsFloat( a1 - a2 );
ENSURE( b3IsValidFloat( a1 ) );
ENSURE_SMALL( diff, ATAN_TOL );
}
{
float a1 = b3Atan2( 0.0f, -1.0f );
float a2 = atan2f( 0.0f, -1.0f );
float diff = b3AbsFloat( a1 - a2 );
ENSURE( b3IsValidFloat( a1 ) );
ENSURE_SMALL( diff, ATAN_TOL );
}
{
float a1 = b3Atan2( 0.0f, 0.0f );
float a2 = atan2f( 0.0f, 0.0f );
float diff = b3AbsFloat( a1 - a2 );
ENSURE( b3IsValidFloat( a1 ) );
ENSURE_SMALL( diff, ATAN_TOL );
}
b3Vec3 zero = { 0 };
b3Vec3 one = { 1.0f, 1.0f, 1.0f };
b3Vec3 two = { 2.0f, 2.0f, 2.0f };
b3Vec3 v = b3Add( one, two );
ENSURE( v.x == 3.0f && v.y == 3.0f );
v = b3Sub( zero, two );
ENSURE( v.x == -2.0f && v.y == -2.0f );
v = b3Add( two, two );
ENSURE( v.x != 5.0f && v.y != 5.0f );
b3Vec3 axis = b3Normalize( (b3Vec3){ -0.75f, 0.5f, 1.0f } );
b3Transform transform1 = { { -2.0f, 3.0f, 0.0f }, b3Quat_identity };
b3Transform transform2 = { { 1.0f, 0.0f, 0.0f }, b3MakeQuatFromAxisAngle( axis, B3_PI ) };
b3Transform transform = b3MulTransforms( transform2, transform1 );
v = b3TransformPoint( transform2, b3TransformPoint( transform1, two ) );
b3Vec3 u = b3TransformPoint( transform, two );
ENSURE_SMALL( u.x - v.x, 10.0f * FLT_EPSILON );
ENSURE_SMALL( u.y - v.y, 10.0f * FLT_EPSILON );
v = b3TransformPoint( transform1, two );
v = b3InvTransformPoint( transform1, v );
ENSURE_SMALL( v.x - two.x, 8.0f * FLT_EPSILON );
ENSURE_SMALL( v.y - two.y, 8.0f * FLT_EPSILON );
b3Transform relTransform = b3InvMulTransforms( transform1, transform2 );
v = b3InvTransformPoint( transform1, b3TransformPoint( transform2, two ) );
u = b3TransformPoint( relTransform, two );
ENSURE_SMALL( u.x - v.x, 10.0f * FLT_EPSILON );
ENSURE_SMALL( u.y - v.y, 10.0f * FLT_EPSILON );
{
axis = (b3Vec3){ 0.0f, 0.0f, 1.0f };
b3Quat q1 = b3MakeQuatFromAxisAngle( axis, -0.5f * B3_PI );
b3Quat q2 = b3ComputeQuatBetweenUnitVectors( (b3Vec3){ 1.0f, 0.0f, 0.0f }, (b3Vec3){ 0.0f, -1.0f, 0.0f } );
ENSURE_SMALL( q1.v.x - q2.v.x, FLT_EPSILON );
ENSURE_SMALL( q1.v.y - q2.v.y, FLT_EPSILON );
ENSURE_SMALL( q1.v.z - q2.v.z, FLT_EPSILON );
ENSURE_SMALL( q1.s - q2.s, FLT_EPSILON );
b3Quat q3 = b3NormalizeQuat( (b3Quat){ { 1.0f, -2.0f, 3.0f }, 4.0f } );
b3Quat q4 = b3InvMulQuat( q3, q1 );
b3Quat q5 = b3MulQuat( q3, q4 );
ENSURE_SMALL( q1.v.x - q5.v.x, FLT_EPSILON );
ENSURE_SMALL( q1.v.y - q5.v.y, FLT_EPSILON );
ENSURE_SMALL( q1.v.z - q5.v.z, FLT_EPSILON );
ENSURE_SMALL( q1.s - q5.s, FLT_EPSILON );
b3Quat q6 = b3ComputeQuatBetweenUnitVectors( (b3Vec3){ 0.0f, 1.0f, 0.0f }, (b3Vec3){ 0.0f, -1.0f, 0.0f } );
ENSURE_SMALL( q6.s, FLT_EPSILON );
(void)q6;
}
v = b3Normalize( (b3Vec3){ 0.2f, -0.5f, 3.0f } );
for ( float z = -1.0f; z <= 1.0f; z += 0.02f )
{
for ( float y = -1.0f; y <= 1.0f; y += 0.02f )
{
for ( float x = -1.0f; x <= 1.0f; x += 0.02f )
{
if ( x == 0.0f && y == 0.0f && z == 0.0f )
{
continue;
}
u = b3Normalize( (b3Vec3){ x, y, z } );
b3Quat r = b3ComputeQuatBetweenUnitVectors( v, u );
ENSURE( b3IsValidQuat( r ) );
b3Vec3 w = b3RotateVector( r, v );
ENSURE_SMALL( b3Dot( r.v, b3Cross( u, w ) ) - b3ScalarTripleProduct( r.v, u, w ), FLT_EPSILON );
// The quaternion between vectors can have lots of round off error at large angles.
ENSURE_SMALL( w.x - u.x, 0.001f );
ENSURE_SMALL( w.y - u.y, 0.001f );
ENSURE_SMALL( w.z - u.z, 0.001f );
// Twist angle testing
float twist = r.s < 0.0f ? b3Atan2( -r.v.z, -r.s ) : b3Atan2( r.v.z, r.s );
twist *= 2.0f;
ENSURE( -B3_PI <= twist && twist <= B3_PI );
}
}
}
{
// More twist angle testing
b3Quat q = { .v = { -0.0558656752f, -0.188799798f, 0.00689807534f }, .s = -0.980401039f };
float twist = q.s < 0.0f ? b3Atan2( -q.v.z, -q.s ) : b3Atan2( q.v.z, q.s );
twist *= 2.0f;
ENSURE( -B3_PI <= twist && twist <= B3_PI );
}
{
b3Matrix3 m = { { 3.0f, 1.0f, -1.0f }, { -1.0f, 3.0f, 1.0f }, { 1.0f, -1.0f, 3.0f } };
b3Matrix3 invM = b3InvertMatrix( m );
b3Matrix3 a = b3MulMM( m, invM );
ENSURE_SMALL( a.cx.x - 1.0f, FLT_EPSILON );
ENSURE_SMALL( a.cx.y, FLT_EPSILON );
ENSURE_SMALL( a.cx.z, FLT_EPSILON );
ENSURE_SMALL( a.cy.x, FLT_EPSILON );
ENSURE_SMALL( a.cy.y - 1.0f, FLT_EPSILON );
ENSURE_SMALL( a.cy.z, FLT_EPSILON );
ENSURE_SMALL( a.cz.x, FLT_EPSILON );
ENSURE_SMALL( a.cz.y, FLT_EPSILON );
ENSURE_SMALL( a.cz.z - 1.0f, FLT_EPSILON );
v = (b3Vec3){ 1.0f, -2.0f, 3.0f };
u = b3MulMV( invM, b3MulMV( m, v ) );
ENSURE_SMALL( v.x - u.x, FLT_EPSILON );
ENSURE_SMALL( v.y - u.y, FLT_EPSILON );
ENSURE_SMALL( v.z - u.z, FLT_EPSILON );
b3Vec3 w = b3MulMV( invM, v );
u = b3Solve3( m, v );
ENSURE_SMALL( w.x - u.x, FLT_EPSILON );
ENSURE_SMALL( w.y - u.y, FLT_EPSILON );
ENSURE_SMALL( w.z - u.z, FLT_EPSILON );
}
{
b3Matrix2 m = { { 3.0f, 1.0f }, { -1.0f, 3.0f } };
b3Matrix2 invM = b3Invert2( m );
b3Matrix2 a = b3MulMM2( m, invM );
ENSURE_SMALL( a.cx.x - 1.0f, FLT_EPSILON );
ENSURE_SMALL( a.cx.y, FLT_EPSILON );
ENSURE_SMALL( a.cy.x, FLT_EPSILON );
ENSURE_SMALL( a.cy.y - 1.0f, FLT_EPSILON );
b3Vec2 v2 = { 1.0f, -2.0f };
b3Vec2 u2 = b3MulMV2( invM, b3MulMV2( m, v2 ) );
ENSURE_SMALL( v2.x - u2.x, FLT_EPSILON );
ENSURE_SMALL( v2.y - u2.y, FLT_EPSILON );
b3Vec2 w = b3MulMV2( invM, v2 );
u2 = b3Solve2( m, v2 );
ENSURE_SMALL( w.x - u2.x, FLT_EPSILON );
ENSURE_SMALL( w.y - u2.y, FLT_EPSILON );
w = b3MulMV2( m, u2 );
ENSURE_SMALL( w.x - v2.x, 10.0f * FLT_EPSILON );
ENSURE_SMALL( w.y - v2.y, 10.0f * FLT_EPSILON );
}
for (int i = 0; i < 100; ++i)
{
float a = RandomFloat();
double b = a;
float c = (float)b;
ENSURE( c == a );
}
b3Quat q1 = b3Quat_identity;
b3Quat q2 = b3MakeQuatFromAxisAngle(b3Vec3_axisZ, 0.5f * B3_PI );
int n = 100;
for ( int i = 0; i <= n; ++i )
{
float alpha = (float)i / (float)n;
b3Quat q = b3NLerp( q1, q2, alpha );
float angle = b3GetTwistAngle( q );
ENSURE_SMALL( alpha * 0.5f * B3_PI - angle, 1.0f * B3_DEG_TO_RAD );
//printf( "angle = [%g %g %g]\n", alpha, alpha * 0.5f * B3_PI, angle );
}
{
b3Vec3 normal = { 0.504055440f, 0.621548057f, 0.599671543f };
b3Vec3 perp = b3ArbitraryPerp( normal );
ENSURE_SMALL( b3Dot( normal, perp ), 2.0f * FLT_EPSILON );
}
return 0;
}

60
test/test_mover.c Normal file
View file

@ -0,0 +1,60 @@
// SPDX-FileCopyrightText: 2025 Erin Catto
// SPDX-License-Identifier: MIT
#include "test_macros.h"
#include "box3d/collision.h"
static int ParallelPlanes( void )
{
b3CollisionPlane planes[3] = { 0 };
planes[0].plane.normal = (b3Vec3){ 0.0f, 0.0f, 1.0f };
planes[0].plane.offset = 0.5f;
planes[0].pushLimit = FLT_MAX;
planes[1].plane.normal = (b3Vec3){ 0.0f, 0.0f, 1.0f };
planes[1].plane.offset = 1.0f;
planes[1].pushLimit = FLT_MAX;
// planes[2].plane.normal = b3Normalize((b3Vec3){ 0.2f, 0.0f, 0.9f });
// planes[2].plane.offset = 0.25f;
// planes[2].pushLimit = FLT_MAX;
b3Vec3 target = { 0.0f, 0.0f, 0.0f };
b3PlaneSolverResult result = b3SolvePlanes( target, planes, 2 );
ENSURE( result.iterationCount == 2 );
ENSURE_SMALL( result.delta.z - 1.0f, 0.0055f );
return 0;
}
static int GamePlanes( void )
{
// This scenario takes many iterations because the target is deep into the plane.
b3CollisionPlane planes[3] = { 0 };
planes[0].plane.normal = (b3Vec3){ 0.0f, -0.23941046f, 0.970918416f };
planes[0].plane.offset = 0.390724182f;
planes[0].pushLimit = FLT_MAX;
planes[1].plane.normal = (b3Vec3){ 0.0f, 0.0f, 1.0f };
planes[1].plane.offset = 1.49998093f;
planes[1].pushLimit = FLT_MAX;
b3Vec3 target = { -2.5390625f, 0.0f, -73.6880798f };
planes[0].plane.offset -= b3Dot( planes[0].plane.normal, target );
planes[1].plane.offset -= b3Dot( planes[1].plane.normal, target );
target = b3Vec3_zero;
b3PlaneSolverResult result = b3SolvePlanes( target, planes, 2 );
ENSURE( result.iterationCount == 20 );
return 0;
}
int MoverTest( void )
{
RUN_SUBTEST( GamePlanes );
RUN_SUBTEST( ParallelPlanes );
return 0;
}

322
test/test_shape.c Normal file
View file

@ -0,0 +1,322 @@
// SPDX-FileCopyrightText: 2023 Erin Catto
// SPDX-License-Identifier: MIT
#include "test_macros.h"
#include "box3d/collision.h"
#include "box3d/math_functions.h"
#include <float.h>
static b3Capsule capsule = { { -1.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f }, 1.0f };
static b3Sphere sphere = { { 1.0f, 0.0f, 0.0f }, 1.0f };
static b3BoxHull box = { 0 };
#define N 4
static int ShapeMassTest( void )
{
// Sphere
{
b3MassData md = b3ComputeSphereMass( &sphere, 1.0f );
float mass = 4.0f / 3.0f * B3_PI;
ENSURE_SMALL( md.mass - mass, FLT_EPSILON );
ENSURE( md.center.x == 1.0f && md.center.y == 0.0f );
float inertia = 2.0f / 5.0f * mass;
float offsetInertia = inertia + mass;
ENSURE_SMALL( md.inertia.cx.x - inertia, FLT_EPSILON );
ENSURE_SMALL( md.inertia.cy.y - offsetInertia, FLT_EPSILON );
ENSURE_SMALL( md.inertia.cz.z - offsetInertia, FLT_EPSILON );
}
// Analytic box hull
{
b3MassData md = b3ComputeHullMass( &box.base, 1.0f );
float mass = 2.0f * 2.0f * 2.0f;
ENSURE_SMALL( md.mass - mass, FLT_EPSILON );
ENSURE_SMALL( md.center.x, FLT_EPSILON );
ENSURE_SMALL( md.center.y, FLT_EPSILON );
ENSURE_SMALL( md.center.z, FLT_EPSILON );
float inertia = ( 1.0f / 12.0f ) * mass * ( 2.0f * 2.0f + 2.0f * 2.0f );
ENSURE_SMALL( md.inertia.cx.x - inertia, 2.0f * FLT_EPSILON );
ENSURE_SMALL( md.inertia.cy.y - inertia, 2.0f * FLT_EPSILON );
ENSURE_SMALL( md.inertia.cz.z - inertia, 2.0f * FLT_EPSILON );
}
// Translated box
{
b3Vec3 offset = { 0.4f, -0.7f, 0.1f };
b3Transform transform = {
.p = offset,
.q = b3Quat_identity,
};
b3Vec3 h = { 0.25f, 0.5f, 0.3f };
b3BoxHull b1 = b3MakeBoxHull( h.x, h.y, h.z );
b3BoxHull b2 = b3MakeTransformedBoxHull( h.x, h.y, h.z, transform );
b3MassData m1 = b3ComputeHullMass( &b1.base, 1.0f );
b3MassData m2 = b3ComputeHullMass( &b2.base, 1.0f );
ENSURE_SMALL( m1.mass - m2.mass, FLT_EPSILON );
b3Matrix3 d = b3SubMM( b1.base.centralInertia, b2.base.centralInertia );
ENSURE_SMALL( d.cx.x, FLT_EPSILON );
ENSURE_SMALL( d.cx.y, FLT_EPSILON );
ENSURE_SMALL( d.cx.z, FLT_EPSILON );
ENSURE_SMALL( d.cy.x, FLT_EPSILON );
ENSURE_SMALL( d.cy.y, FLT_EPSILON );
ENSURE_SMALL( d.cy.z, FLT_EPSILON );
ENSURE_SMALL( d.cz.x, FLT_EPSILON );
ENSURE_SMALL( d.cz.y, FLT_EPSILON );
ENSURE_SMALL( d.cz.z, FLT_EPSILON );
ENSURE_SMALL( m2.center.x - offset.x, FLT_EPSILON );
ENSURE_SMALL( m2.center.y - offset.y, FLT_EPSILON );
ENSURE_SMALL( m2.center.z - offset.z, FLT_EPSILON );
}
// Rotated box
{
b3Vec3 h1 = { 0.25f, 0.5f, 0.3f };
b3Vec3 h2 = { 0.25f, 0.3f, 0.5f };
b3Quat q = b3ComputeQuatBetweenUnitVectors( b3Vec3_axisY, b3Vec3_axisZ );
b3Transform transform = {
.p = b3Vec3_zero,
.q = q,
};
b3BoxHull b1 = b3MakeTransformedBoxHull( h1.x, h1.y, h1.z, transform );
b3BoxHull b2 = b3MakeBoxHull( h2.x, h2.y, h2.z );
b3MassData m1 = b3ComputeHullMass( &b1.base, 1.0f );
b3MassData m2 = b3ComputeHullMass( &b2.base, 1.0f );
ENSURE_SMALL( m1.mass - m2.mass, FLT_EPSILON );
b3Matrix3 d = b3SubMM( b1.base.centralInertia, b2.base.centralInertia );
ENSURE_SMALL( d.cx.x, FLT_EPSILON );
ENSURE_SMALL( d.cx.y, FLT_EPSILON );
ENSURE_SMALL( d.cx.z, FLT_EPSILON );
ENSURE_SMALL( d.cy.x, FLT_EPSILON );
ENSURE_SMALL( d.cy.y, FLT_EPSILON );
ENSURE_SMALL( d.cy.z, FLT_EPSILON );
ENSURE_SMALL( d.cz.x, FLT_EPSILON );
ENSURE_SMALL( d.cz.y, FLT_EPSILON );
ENSURE_SMALL( d.cz.z, FLT_EPSILON );
ENSURE_SMALL( m1.center.x - m2.center.x, FLT_EPSILON );
ENSURE_SMALL( m1.center.y - m2.center.y, FLT_EPSILON );
ENSURE_SMALL( m1.center.z - m2.center.z, FLT_EPSILON );
}
// Transformed box
{
b3Vec3 offset = { 0.4f, -0.7f, 0.1f };
b3Vec3 h1 = { 0.25f, 0.5f, 0.3f };
b3Vec3 h2 = { 0.25f, 0.3f, 0.5f };
b3Quat q = b3ComputeQuatBetweenUnitVectors( b3Vec3_axisY, b3Vec3_axisZ );
b3Transform transform = {
.p = offset,
.q = q,
};
b3BoxHull b1 = b3MakeTransformedBoxHull( h1.x, h1.y, h1.z, transform );
b3BoxHull b2 = b3MakeBoxHull( h2.x, h2.y, h2.z );
b3MassData m1 = b3ComputeHullMass( &b1.base, 1.0f );
b3MassData m2 = b3ComputeHullMass( &b2.base, 1.0f );
ENSURE_SMALL( m1.mass - m2.mass, FLT_EPSILON );
b3Matrix3 d = b3SubMM( b1.base.centralInertia, b2.base.centralInertia );
ENSURE_SMALL( d.cx.x, FLT_EPSILON );
ENSURE_SMALL( d.cx.y, FLT_EPSILON );
ENSURE_SMALL( d.cx.z, FLT_EPSILON );
ENSURE_SMALL( d.cy.x, FLT_EPSILON );
ENSURE_SMALL( d.cy.y, FLT_EPSILON );
ENSURE_SMALL( d.cy.z, FLT_EPSILON );
ENSURE_SMALL( d.cz.x, FLT_EPSILON );
ENSURE_SMALL( d.cz.y, FLT_EPSILON );
ENSURE_SMALL( d.cz.z, FLT_EPSILON );
ENSURE_SMALL( m1.center.x - offset.x, FLT_EPSILON );
ENSURE_SMALL( m1.center.y - offset.y, FLT_EPSILON );
ENSURE_SMALL( m1.center.z - offset.z, FLT_EPSILON );
}
// Capsule
{
float radius = capsule.radius;
float length = b3Distance( capsule.center1, capsule.center2 );
// Capsule along x-axis
b3MassData md = b3ComputeCapsuleMass( &capsule, 1.0f );
// Box that fully contains capsule. Upper bound on capsule mass.
b3BoxHull r = b3MakeBoxHull( radius + 0.5f * length, radius, radius );
b3MassData mdUpper = b3ComputeHullMass( &r.base, 1.0f );
// Approximate capsule using convex hull. This should be a lower bound on the
// capsule mass.
b3Vec3 points[2 * N * N];
float d = B3_PI / ( N - 1.0f );
float angle1 = -0.5f * B3_PI;
int index = 0;
for ( int i = 0; i < N; ++i )
{
float s1 = sinf( angle1 );
float c1 = cosf( angle1 );
float angle2 = -0.5f * B3_PI;
for ( int j = 0; j < N; ++j )
{
points[index].x = 1.0f + radius * c1;
points[index].y = radius * s1 * cosf( angle2 );
points[index].z = radius * s1 * sinf( angle2 );
angle2 += d;
index += 1;
}
angle1 += d;
}
angle1 = 0.5f * B3_PI;
for ( int i = 0; i < N; ++i )
{
float s1 = sinf( angle1 );
float c1 = cosf( angle1 );
float angle2 = -0.5f * B3_PI;
for ( int j = 0; j < N; ++j )
{
points[index].x = -1.0f + radius * c1;
points[index].y = radius * s1 * cosf( angle2 );
points[index].z = radius * s1 * sinf( angle2 );
angle2 += d;
index += 1;
}
angle1 += d;
}
ENSURE( index == 2 * N * N );
b3Hull* hull = b3CreateHull( points, 2 * N * N, 2 * N * N );
b3MassData mdLower = b3ComputeHullMass( hull, 1.0f );
ENSURE( mdLower.mass < md.mass && md.mass < mdUpper.mass );
ENSURE( mdLower.inertia.cx.x < md.inertia.cx.x && md.inertia.cx.x < mdUpper.inertia.cx.x );
ENSURE( mdLower.inertia.cy.y < md.inertia.cy.y && md.inertia.cy.y < mdUpper.inertia.cy.y );
ENSURE( mdLower.inertia.cz.z < md.inertia.cz.z && md.inertia.cz.z < mdUpper.inertia.cz.z );
b3DestroyHull( hull );
}
return 0;
}
static int ShapeAABBTest( void )
{
{
b3AABB b = b3ComputeSphereAABB( &sphere, b3Transform_identity );
ENSURE_SMALL( b.lowerBound.x, FLT_EPSILON );
ENSURE_SMALL( b.lowerBound.y + 1.0f, FLT_EPSILON );
ENSURE_SMALL( b.lowerBound.z + 1.0f, FLT_EPSILON );
ENSURE_SMALL( b.upperBound.x - 2.0f, FLT_EPSILON );
ENSURE_SMALL( b.upperBound.y - 1.0f, FLT_EPSILON );
ENSURE_SMALL( b.upperBound.z - 1.0f, FLT_EPSILON );
}
{
b3AABB b = b3ComputeCapsuleAABB( &capsule, b3Transform_identity );
ENSURE_SMALL( b.lowerBound.x + 2.0f, FLT_EPSILON );
ENSURE_SMALL( b.lowerBound.y + 1.0f, FLT_EPSILON );
ENSURE_SMALL( b.lowerBound.z + 1.0f, FLT_EPSILON );
ENSURE_SMALL( b.upperBound.x - 2.0f, FLT_EPSILON );
ENSURE_SMALL( b.upperBound.y - 1.0f, FLT_EPSILON );
ENSURE_SMALL( b.upperBound.z - 1.0f, FLT_EPSILON );
}
{
b3AABB b = b3ComputeHullAABB( &box.base, b3Transform_identity );
ENSURE_SMALL( b.lowerBound.x + 1.0f, FLT_EPSILON );
ENSURE_SMALL( b.lowerBound.y + 1.0f, FLT_EPSILON );
ENSURE_SMALL( b.lowerBound.z + 1.0f, FLT_EPSILON );
ENSURE_SMALL( b.upperBound.x - 1.0f, FLT_EPSILON );
ENSURE_SMALL( b.upperBound.y - 1.0f, FLT_EPSILON );
ENSURE_SMALL( b.upperBound.z - 1.0f, FLT_EPSILON );
}
return 0;
}
#if 0
static int PointInShapeTest( void )
{
b3Vec2 p1 = { 0.5f, 0.5f };
b3Vec2 p2 = { 4.0f, -4.0f };
{
bool hit;
hit = b3PointInSphere( p1, &sphere );
ENSURE( hit == true );
hit = b3PointInSphere( p2, &sphere );
ENSURE( hit == false );
}
{
bool hit;
hit = b3PointInPolygon( p1, &box );
ENSURE( hit == true );
hit = b3PointInPolygon( p2, &box );
ENSURE( hit == false );
}
return 0;
}
#endif
static int RayCastShapeTest( void )
{
b3RayCastInput input = {
.origin = { -4.0f, 0.0f, 0.0f },
.translation = { 8.0f, 0.0f, 0.0f },
.maxFraction = 1.0f,
};
{
b3CastOutput output = b3RayCastSphere( &sphere, &input );
ENSURE( output.hit );
ENSURE_SMALL( output.normal.x + 1.0f, FLT_EPSILON );
ENSURE_SMALL( output.normal.y, FLT_EPSILON );
ENSURE_SMALL( output.normal.z, FLT_EPSILON );
ENSURE_SMALL( output.fraction - 0.5f, FLT_EPSILON );
}
{
b3CastOutput output = b3RayCastCapsule( &capsule, &input );
ENSURE( output.hit );
ENSURE_SMALL( output.normal.x + 1.0f, FLT_EPSILON );
ENSURE_SMALL( output.normal.y, FLT_EPSILON );
ENSURE_SMALL( output.normal.z, FLT_EPSILON );
ENSURE_SMALL( output.fraction - 1.0f / 4.0f, FLT_EPSILON );
}
{
b3CastOutput output = b3RayCastHull( &box.base, &input );
ENSURE( output.hit );
ENSURE_SMALL( output.normal.x + 1.0f, FLT_EPSILON );
ENSURE_SMALL( output.normal.y, FLT_EPSILON );
ENSURE_SMALL( output.normal.z, FLT_EPSILON );
ENSURE_SMALL( output.fraction - 3.0f / 8.0f, FLT_EPSILON );
}
return 0;
}
int ShapeTest( void )
{
box = b3MakeBoxHull( 1.0f, 1.0f, 1.0f );
RUN_SUBTEST( ShapeMassTest );
RUN_SUBTEST( ShapeAABBTest );
// RUN_SUBTEST( PointInShapeTest );
RUN_SUBTEST( RayCastShapeTest );
return 0;
}

113
test/test_table.c Normal file
View file

@ -0,0 +1,113 @@
// SPDX-FileCopyrightText: 2023 Erin Catto
// SPDX-License-Identifier: MIT
#include "ctz.h"
#include "table.h"
#include "test_macros.h"
#include "box2d/base.h"
#include <stdatomic.h>
#define SET_SPAN 317
#define ITEM_COUNT ( ( SET_SPAN * SET_SPAN - SET_SPAN ) / 2 )
int TableTest( void )
{
int power = b2BoundingPowerOf2( 3008 );
ENSURE( power == 12 );
int nextPowerOf2 = b2RoundUpPowerOf2( 3008 );
ENSURE( nextPowerOf2 == ( 1 << power ) );
const int32_t N = SET_SPAN;
const uint32_t itemCount = ITEM_COUNT;
bool removed[ITEM_COUNT] = { 0 };
for ( int32_t iter = 0; iter < 1; ++iter )
{
b2HashSet set = b2CreateSet( 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 );
}
}
ENSURE( set.count == itemCount );
// Remove a portion of the set
int32_t k = 0;
uint32_t removeCount = 0;
for ( int32_t i = 0; i < N; ++i )
{
for ( int32_t j = i + 1; j < N; ++j )
{
if ( j == i + 1 )
{
uint64_t key = B2_SHAPE_PAIR_KEY( i, j );
b2RemoveKey( &set, key );
removed[k++] = true;
removeCount += 1;
}
else
{
removed[k++] = false;
}
}
}
ENSURE( set.count == ( itemCount - removeCount ) );
#ifndef NDEBUG
extern _Atomic int g_probeCount;
g_probeCount = 0;
#endif
// Test key search
// ~5ns per search on an AMD 7950x
b2Timer timer = b2CreateTimer();
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] );
k += 1;
}
}
// uint64_t ticks = b2GetTicks(&timer);
// printf("set ticks = %llu\n", ticks);
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 );
#endif
// Remove all keys from 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 );
b2RemoveKey( &set, key );
}
}
ENSURE( set.count == 0 );
b2DestroySet( &set );
}
return 0;
}

720
test/test_world.c Normal file
View file

@ -0,0 +1,720 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
#include "benchmarks.h"
#include "stability.h"
#include "test_macros.h"
#include "box3d/box3d.h"
#include "box3d/collision.h"
#include "box3d/constants.h"
#include "box3d/math_functions.h"
#include <stdio.h>
// This is a simple example of building and running a simulation
// using Box3D. Here we create a large ground box and a small dynamic
// box.
// There are no graphics for this example. Box3D is meant to be used
// with your rendering engine in your game engine.
int HelloWorld( void )
{
// Construct a world object, which will hold and simulate the rigid bodies.
b3WorldDef worldDef = b3DefaultWorldDef();
worldDef.gravity = (b3Vec3){ 0.0f, -10.0f, 0.0f };
b3WorldId worldId = b3CreateWorld( &worldDef );
ENSURE( b3World_IsValid( worldId ) );
// Define the ground body.
b3BodyDef groundBodyDef = b3DefaultBodyDef();
groundBodyDef.position = (b3Vec3){ 0.0f, -10.0f, 0.0f };
// Call the body factory which allocates memory for the ground body
// from a pool and creates the ground box shape (also from a pool).
// The body is also added to the world.
b3BodyId groundId = b3CreateBody( worldId, &groundBodyDef );
ENSURE( b3Body_IsValid( groundId ) );
// Define the ground box shape. The extents are the half-widths of the box.
b3BoxHull groundBox = b3MakeBoxHull( 50.0f, 10.0f, 50.0f );
// Add the box shape to the ground body.
b3ShapeDef groundShapeDef = b3DefaultShapeDef();
b3CreateHullShape( groundId, &groundShapeDef, &groundBox.base );
// Define the dynamic body. We set its position and call the body factory.
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.position = (b3Vec3){ 0.0f, 4.0f, 0.0f };
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
// Define another box shape for our dynamic body.
b3BoxHull dynamicBox = b3MakeCubeHull( 1.0f );
// Define the dynamic body shape
b3ShapeDef shapeDef = b3DefaultShapeDef();
// Set the box density to be non-zero, so it will be dynamic.
shapeDef.density = 1.0f;
// Override the default friction.
shapeDef.baseMaterial.friction = 0.3f;
// Add the shape to the body.
b3CreateHullShape( bodyId, &shapeDef, &dynamicBox.base );
// Prepare for simulation. Typically we use a time step of 1/60 of a
// second (60Hz) and 4 sub-steps. This provides a high quality simulation
// in most game scenarios.
float timeStep = 1.0f / 60.0f;
int subStepCount = 4;
b3Vec3 position = b3Body_GetPosition( bodyId );
b3Quat rotation = b3Body_GetRotation( bodyId );
// This is our little game loop.
for ( int i = 0; i < 90; ++i )
{
// Instruct the world to perform a single step of simulation.
// It is generally best to keep the time step and iterations fixed.
b3World_Step( worldId, timeStep, subStepCount );
// Now print the position and angle of the body.
position = b3Body_GetPosition( bodyId );
rotation = b3Body_GetRotation( bodyId );
// printf("%4.2f %4.2f %4.2f\n", position.x, position.y, b3Rot_GetAngle(rotation));
}
// When the world destructor is called, all bodies and joints are freed. This can
// create orphaned ids, so be careful about your world management.
b3DestroyWorld( worldId );
ENSURE_SMALL( position.y - 1.00f, 0.01f );
ENSURE_SMALL( rotation.v.x, 0.01f );
ENSURE_SMALL( rotation.v.z, 0.01f );
return 0;
}
int EmptyWorld( void )
{
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
ENSURE( b3World_IsValid( worldId ) == true );
float timeStep = 1.0f / 60.0f;
int subStepCount = 1;
for ( int i = 0; i < 60; ++i )
{
b3World_Step( worldId, timeStep, subStepCount );
}
b3DestroyWorld( worldId );
ENSURE( b3World_IsValid( worldId ) == false );
return 0;
}
#define BODY_COUNT 10
int DestroyAllBodiesWorld( void )
{
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
ENSURE( b3World_IsValid( worldId ) == true );
int count = 0;
bool creating = true;
b3BodyId bodyIds[BODY_COUNT];
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
b3BoxHull cube = b3MakeCubeHull( 0.5f );
for ( int i = 0; i < 2 * BODY_COUNT + 10; ++i )
{
if ( creating )
{
if ( count < BODY_COUNT )
{
bodyIds[count] = b3CreateBody( worldId, &bodyDef );
b3ShapeDef shapeDef = b3DefaultShapeDef();
b3CreateHullShape( bodyIds[count], &shapeDef, &cube.base );
count += 1;
}
else
{
creating = false;
}
}
else if ( count > 0 )
{
b3DestroyBody( bodyIds[count - 1] );
bodyIds[count - 1] = b3_nullBodyId;
count -= 1;
}
b3World_Step( worldId, 1.0f / 60.0f, 3 );
}
b3Counters counters = b3World_GetCounters( worldId );
ENSURE( counters.bodyCount == 0 );
b3DestroyWorld( worldId );
ENSURE( b3World_IsValid( worldId ) == false );
return 0;
}
static int TestIsValid( void )
{
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
ENSURE( b3World_IsValid( worldId ) );
b3BodyDef bodyDef = b3DefaultBodyDef();
b3BodyId bodyId1 = b3CreateBody( worldId, &bodyDef );
ENSURE( b3Body_IsValid( bodyId1 ) == true );
b3BodyId bodyId2 = b3CreateBody( worldId, &bodyDef );
ENSURE( b3Body_IsValid( bodyId2 ) == true );
b3DestroyBody( bodyId1 );
ENSURE( b3Body_IsValid( bodyId1 ) == false );
b3DestroyBody( bodyId2 );
ENSURE( b3Body_IsValid( bodyId2 ) == false );
b3DestroyWorld( worldId );
ENSURE( b3World_IsValid( worldId ) == false );
ENSURE( b3Body_IsValid( bodyId2 ) == false );
ENSURE( b3Body_IsValid( bodyId1 ) == false );
return 0;
}
#define WORLD_COUNT ( B3_MAX_WORLDS / 2 )
int TestWorldRecycle( void )
{
_Static_assert( WORLD_COUNT > 0, "world count" );
int count = 100;
b3WorldId worldIds[WORLD_COUNT];
for ( int i = 0; i < count; ++i )
{
b3WorldDef worldDef = b3DefaultWorldDef();
for ( int j = 0; j < WORLD_COUNT; ++j )
{
worldIds[j] = b3CreateWorld( &worldDef );
ENSURE( b3World_IsValid( worldIds[j] ) == true );
b3BodyDef bodyDef = b3DefaultBodyDef();
b3CreateBody( worldIds[j], &bodyDef );
}
for ( int j = 0; j < WORLD_COUNT; ++j )
{
float timeStep = 1.0f / 60.0f;
int subStepCount = 1;
for ( int k = 0; k < 10; ++k )
{
b3World_Step( worldIds[j], timeStep, subStepCount );
}
}
for ( int j = WORLD_COUNT - 1; j >= 0; --j )
{
b3DestroyWorld( worldIds[j] );
ENSURE( b3World_IsValid( worldIds[j] ) == false );
worldIds[j] = b3_nullWorldId;
}
}
return 0;
}
static bool CustomFilter( b3ShapeId shapeIdA, b3ShapeId shapeIdB, void* context )
{
(void)shapeIdA;
(void)shapeIdB;
ENSURE( context == NULL );
return true;
}
static bool PreSolveStatic( b3ShapeId shapeIdA, b3ShapeId shapeIdB, b3Vec3 point, b3Vec3 normal, void* context )
{
(void)shapeIdA;
(void)shapeIdB;
(void)point;
(void)normal;
ENSURE( context == NULL );
return false;
}
// This test is here to ensure all API functions link correctly.
int TestWorldCoverage( void )
{
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
ENSURE( b3World_IsValid( worldId ) );
b3World_EnableSleeping( worldId, true );
b3World_EnableSleeping( worldId, false );
bool flag = b3World_IsSleepingEnabled( worldId );
ENSURE( flag == false );
b3World_EnableContinuous( worldId, false );
b3World_EnableContinuous( worldId, true );
flag = b3World_IsContinuousEnabled( worldId );
ENSURE( flag == true );
b3World_SetRestitutionThreshold( worldId, 0.0f );
b3World_SetRestitutionThreshold( worldId, 2.0f );
float value = b3World_GetRestitutionThreshold( worldId );
ENSURE( value == 2.0f );
b3World_SetHitEventThreshold( worldId, 0.0f );
b3World_SetHitEventThreshold( worldId, 100.0f );
value = b3World_GetHitEventThreshold( worldId );
ENSURE( value == 100.0f );
b3World_SetCustomFilterCallback( worldId, CustomFilter, NULL );
b3World_SetPreSolveCallback( worldId, PreSolveStatic, NULL );
b3Vec3 g = { 1.0f, 2.0f };
b3World_SetGravity( worldId, g );
b3Vec3 v = b3World_GetGravity( worldId );
ENSURE( v.x == g.x );
ENSURE( v.y == g.y );
b3ExplosionDef explosionDef = b3DefaultExplosionDef();
b3World_Explode( worldId, &explosionDef );
b3World_SetContactTuning( worldId, 10.0f, 2.0f, 4.0f );
b3World_SetMaximumLinearSpeed( worldId, 10.0f );
value = b3World_GetMaximumLinearSpeed( worldId );
ENSURE( value == 10.0f );
b3World_EnableWarmStarting( worldId, true );
flag = b3World_IsWarmStartingEnabled( worldId );
ENSURE( flag == true );
int count = b3World_GetAwakeBodyCount( worldId );
ENSURE( count == 0 );
b3World_SetUserData( worldId, &value );
void* userData = b3World_GetUserData( worldId );
ENSURE( userData == &value );
b3World_Step( worldId, 1.0f, 1 );
b3DestroyWorld( worldId );
return 0;
}
static int TestSensor( void )
{
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
// Wall from x = 1 to x = 2
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_staticBody;
bodyDef.position = (b3Vec3){ 1.5f, 11.0f, 0.0f };
b3BodyId wallId = b3CreateBody( worldId, &bodyDef );
b3BoxHull box = b3MakeBoxHull( 0.5f, 10.0f, 1.0f );
b3ShapeDef shapeDef = b3DefaultShapeDef();
shapeDef.enableSensorEvents = true;
b3CreateHullShape( wallId, &shapeDef, &box.base );
// Bullet fired towards the wall
bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.isBullet = true;
bodyDef.gravityScale = 0.0f;
bodyDef.position = (b3Vec3){ 7.39814f, 4.0f, 0.0f };
bodyDef.linearVelocity = (b3Vec3){ -20.0f, 0.0f, 0.0f };
b3BodyId bulletId = b3CreateBody( worldId, &bodyDef );
shapeDef = b3DefaultShapeDef();
shapeDef.isSensor = true;
shapeDef.enableSensorEvents = true;
b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, 0.1f };
b3CreateSphereShape( bulletId, &shapeDef, &sphere );
int beginCount = 0;
int endCount = 0;
while ( true )
{
float timeStep = 1.0f / 60.0f;
int subStepCount = 4;
b3World_Step( worldId, timeStep, subStepCount );
b3Vec3 bulletPos = b3Body_GetPosition( bulletId );
// printf( "Bullet pos: %g %g\n", bulletPos.x, bulletPos.y );
b3SensorEvents events = b3World_GetSensorEvents( worldId );
if ( events.beginCount > 0 )
{
beginCount += 1;
}
if ( events.endCount > 0 )
{
endCount += 1;
}
if ( bulletPos.x < -1.0f )
{
break;
}
}
b3DestroyWorld( worldId );
ENSURE( beginCount == 1 );
ENSURE( endCount == 1 );
return 0;
}
static int TestContactEvents( void )
{
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
// Static ground
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_staticBody;
bodyDef.position = (b3Vec3){ 0.0f, -0.5f, 0.0f };
b3BodyId groundId = b3CreateBody( worldId, &bodyDef );
b3BoxHull groundBox = b3MakeBoxHull( 10.0f, 0.5f, 10.0f );
b3ShapeDef groundShapeDef = b3DefaultShapeDef();
b3ShapeId groundShapeId = b3CreateHullShape( groundId, &groundShapeDef, &groundBox.base );
// Dynamic sphere dropped onto the ground; restitution causes it to bounce so we get end events
bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.position = (b3Vec3){ 0.0f, 5.0f, 0.0f };
b3BodyId sphereBodyId = b3CreateBody( worldId, &bodyDef );
b3ShapeDef shapeDef = b3DefaultShapeDef();
shapeDef.density = 1.0f;
shapeDef.enableContactEvents = true;
shapeDef.baseMaterial.restitution = 0.6f;
b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, 0.5f };
b3ShapeId sphereShapeId = b3CreateSphereShape( sphereBodyId, &shapeDef, &sphere );
int beginCount = 0;
int endCount = 0;
bool idsChecked = false;
for ( int i = 0; i < 120; ++i )
{
b3World_Step( worldId, 1.0f / 60.0f, 4 );
b3ContactEvents events = b3World_GetContactEvents( worldId );
if ( events.beginCount > 0 && idsChecked == false )
{
b3ContactBeginTouchEvent be = events.beginEvents[0];
bool aIsSphere = B3_ID_EQUALS( be.shapeIdA, sphereShapeId );
bool bIsSphere = B3_ID_EQUALS( be.shapeIdB, sphereShapeId );
bool aIsGround = B3_ID_EQUALS( be.shapeIdA, groundShapeId );
bool bIsGround = B3_ID_EQUALS( be.shapeIdB, groundShapeId );
ENSURE( ( aIsSphere && bIsGround ) || ( aIsGround && bIsSphere ) );
ENSURE( b3Contact_IsValid( be.contactId ) );
idsChecked = true;
}
beginCount += events.beginCount;
endCount += events.endCount;
}
b3DestroyWorld( worldId );
ENSURE( idsChecked );
ENSURE( beginCount >= 1 );
ENSURE( endCount >= 1 );
return 0;
}
static int TestHitEvents( void )
{
b3WorldDef worldDef = b3DefaultWorldDef();
worldDef.hitEventThreshold = 1.0f;
b3WorldId worldId = b3CreateWorld( &worldDef );
// Static ground
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_staticBody;
bodyDef.position = (b3Vec3){ 0.0f, -0.5f, 0.0f };
b3BodyId groundId = b3CreateBody( worldId, &bodyDef );
b3BoxHull groundBox = b3MakeBoxHull( 10.0f, 0.5f, 10.0f );
b3ShapeDef groundShapeDef = b3DefaultShapeDef();
b3CreateHullShape( groundId, &groundShapeDef, &groundBox.base );
// Sphere driven into the ground fast enough to clear the hit threshold
bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.gravityScale = 0.0f;
bodyDef.position = (b3Vec3){ 0.0f, 2.0f, 0.0f };
bodyDef.linearVelocity = (b3Vec3){ 0.0f, -30.0f, 0.0f };
b3BodyId sphereBodyId = b3CreateBody( worldId, &bodyDef );
b3ShapeDef shapeDef = b3DefaultShapeDef();
shapeDef.density = 1.0f;
shapeDef.enableHitEvents = true;
shapeDef.baseMaterial.userMaterialId = 7;
b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, 0.5f };
b3CreateSphereShape( sphereBodyId, &shapeDef, &sphere );
int hitCount = 0;
float capturedSpeed = 0.0f;
uint64_t capturedMaterialA = 0;
uint64_t capturedMaterialB = 0;
b3Vec3 capturedNormal = { 0.0f, 0.0f, 0.0f };
for ( int i = 0; i < 30; ++i )
{
b3World_Step( worldId, 1.0f / 60.0f, 4 );
b3ContactEvents events = b3World_GetContactEvents( worldId );
if ( events.hitCount > 0 && hitCount == 0 )
{
b3ContactHitEvent hit = events.hitEvents[0];
capturedSpeed = hit.approachSpeed;
capturedNormal = hit.normal;
capturedMaterialA = hit.userMaterialIdA;
capturedMaterialB = hit.userMaterialIdB;
}
hitCount += events.hitCount;
}
b3DestroyWorld( worldId );
ENSURE( hitCount >= 1 );
ENSURE( capturedSpeed > 1.0f );
// Head-on vertical impact: normal lies along Y
ENSURE_SMALL( capturedNormal.x, 0.01f );
ENSURE_SMALL( capturedNormal.z, 0.01f );
// One side of the contact carries the sphere's user material
ENSURE( capturedMaterialA == 7 || capturedMaterialB == 7 );
return 0;
}
// Hit-event material lookup must respect the compound child that participated in the
// contact. Two children with distinct userMaterialIds at separated positions, dropped
// sphere strikes one specifically. Without the fix, both children would report
// materials[0] and the strike on hull 1 would be misattributed.
static int TestCompoundHitEvents( void )
{
const uint64_t kHullMaterialA = 11;
const uint64_t kHullMaterialB = 22;
const uint64_t kSphereMaterial = 99;
const float kHullCenterX = 3.0f;
for ( int side = 0; side < 2; ++side )
{
uint64_t expectedHullMaterial = ( side == 0 ) ? kHullMaterialA : kHullMaterialB;
float spawnX = ( side == 0 ) ? -kHullCenterX : kHullCenterX;
b3WorldDef worldDef = b3DefaultWorldDef();
worldDef.hitEventThreshold = 1.0f;
b3WorldId worldId = b3CreateWorld( &worldDef );
// Build a compound with two hulls at opposite x positions, distinct userMaterialIds
b3BoxHull boxA = b3MakeBoxHull( 1.0f, 1.0f, 1.0f );
b3BoxHull boxB = b3MakeBoxHull( 1.0f, 1.0f, 1.0f );
b3SurfaceMaterial matA = b3DefaultSurfaceMaterial();
matA.userMaterialId = kHullMaterialA;
b3SurfaceMaterial matB = b3DefaultSurfaceMaterial();
matB.userMaterialId = kHullMaterialB;
b3CompoundHullDef hulls[2];
hulls[0].hull = &boxA.base;
hulls[0].transform = (b3Transform){ { -kHullCenterX, 0.0f, 0.0f }, b3Quat_identity };
hulls[0].material = matA;
hulls[1].hull = &boxB.base;
hulls[1].transform = (b3Transform){ { kHullCenterX, 0.0f, 0.0f }, b3Quat_identity };
hulls[1].material = matB;
b3CompoundDef compoundDef = { 0 };
compoundDef.hulls = hulls;
compoundDef.hullCount = 2;
b3Compound* compound = b3CreateCompound( &compoundDef );
ENSURE( compound != NULL );
// Static body holds the compound
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_staticBody;
b3BodyId compoundBodyId = b3CreateBody( worldId, &bodyDef );
b3ShapeDef compoundShapeDef = b3DefaultShapeDef();
b3CreateCompoundShape( compoundBodyId, &compoundShapeDef, compound );
// Sphere driven straight down onto the chosen child
bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.gravityScale = 0.0f;
bodyDef.position = (b3Vec3){ spawnX, 3.0f, 0.0f };
bodyDef.linearVelocity = (b3Vec3){ 0.0f, -30.0f, 0.0f };
b3BodyId sphereBodyId = b3CreateBody( worldId, &bodyDef );
b3ShapeDef sphereShapeDef = b3DefaultShapeDef();
sphereShapeDef.density = 1.0f;
sphereShapeDef.enableHitEvents = true;
sphereShapeDef.baseMaterial.userMaterialId = kSphereMaterial;
b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, 0.5f };
b3CreateSphereShape( sphereBodyId, &sphereShapeDef, &sphere );
int hitCount = 0;
uint64_t capturedMaterialA = 0;
uint64_t capturedMaterialB = 0;
for ( int i = 0; i < 30; ++i )
{
b3World_Step( worldId, 1.0f / 60.0f, 4 );
b3ContactEvents events = b3World_GetContactEvents( worldId );
if ( events.hitCount > 0 && hitCount == 0 )
{
b3ContactHitEvent hit = events.hitEvents[0];
capturedMaterialA = hit.userMaterialIdA;
capturedMaterialB = hit.userMaterialIdB;
}
hitCount += events.hitCount;
}
b3DestroyWorld( worldId );
b3DestroyCompound( compound );
ENSURE( hitCount >= 1 );
// Sphere material on one side
ENSURE( capturedMaterialA == kSphereMaterial || capturedMaterialB == kSphereMaterial );
// Struck compound child's material on the other side. The pre-fix code returned
// materials[0] (kHullMaterialA) for both sides, so a strike on the +x child would fail.
ENSURE( capturedMaterialA == expectedHullMaterial || capturedMaterialB == expectedHullMaterial );
}
return 0;
}
#if 0
static int TestSetWorkerCount( void )
{
b3WorldDef worldDef = b3DefaultWorldDef();
worldDef.workerCount = 1;
b3WorldId worldId = b3CreateWorld( &worldDef );
ENSURE( b3World_IsValid( worldId ) );
ENSURE( b3World_GetWorkerCount( worldId ) == 1 );
CreateJunkyard( worldId );
StepJunkyard( worldId, 1 );
b3World_SetWorkerCount( worldId, 4 );
ENSURE( b3World_GetWorkerCount( worldId ) == 4 );
StepJunkyard( worldId, 2 );
b3World_SetWorkerCount( worldId, 4 );
ENSURE( b3World_GetWorkerCount( worldId ) == 4 );
StepJunkyard( worldId, 3 );
b3World_SetWorkerCount( worldId, 0 );
ENSURE( b3World_GetWorkerCount( worldId ) == 1 );
StepJunkyard( worldId, 4 );
b3World_SetWorkerCount( worldId, -5 );
ENSURE( b3World_GetWorkerCount( worldId ) == 1 );
StepJunkyard( worldId, 5 );
b3World_SetWorkerCount( worldId, B2_MAX_WORKERS + 10 );
ENSURE( b3World_GetWorkerCount( worldId ) == B2_MAX_WORKERS );
StepJunkyard( worldId, 2 );
b3DestroyWorld( worldId );
return 0;
}
#endif
// This tests continuous collision and mesh contact stability
static int TestMeshDrop( void )
{
b3WorldDef worldDef = b3DefaultWorldDef();
// todo GetCoreCount
worldDef.workerCount = 4;
b3WorldId worldId = b3CreateWorld( &worldDef );
MeshDropData data = CreateMeshDrop( worldId );
float timeStep = 1.0f / 60.0f;
int stepIndex = 0;
int stepLimit = 400;
while ( stepIndex < stepLimit )
{
int subStepCount = 4;
b3World_Step( worldId, timeStep, subStepCount );
b3BodyEvents events = b3World_GetBodyEvents( worldId );
if (events.moveCount == 0)
{
// All bodies sleeping
break;
}
stepIndex += 1;
}
printf( " TestMeshDrop stepIndex = %d\n", stepIndex );
DestroyMeshDrop( &data );
b3DestroyWorld( worldId );
ENSURE( stepIndex < stepLimit );
return 0;
}
int WorldTest( void )
{
RUN_SUBTEST( HelloWorld );
RUN_SUBTEST( EmptyWorld );
RUN_SUBTEST( DestroyAllBodiesWorld );
RUN_SUBTEST( TestIsValid );
RUN_SUBTEST( TestWorldRecycle );
RUN_SUBTEST( TestWorldCoverage );
RUN_SUBTEST( TestSensor );
RUN_SUBTEST( TestContactEvents );
RUN_SUBTEST( TestHitEvents );
RUN_SUBTEST( TestCompoundHitEvents );
RUN_SUBTEST( TestMeshDrop );
// RUN_SUBTEST( TestSetWorkerCount );
return 0;
}