Add box3d headers

This commit is contained in:
gingerBill
2026-07-02 13:41:11 +01:00
parent 723a431145
commit 8a0d37efaf
8 changed files with 7142 additions and 0 deletions

193
vendor/box3d/src/include/box3d/base.h vendored Normal file
View File

@@ -0,0 +1,193 @@
// SPDX-FileCopyrightText: 2025 Erin Catto
// SPDX-License-Identifier: MIT
#pragma once
#include <stdbool.h>
#include <stdint.h>
// Compile-time options. Edit box3d/config.h, or define BOX3D_USER_CONFIG to
// point at your own copy.
#ifdef BOX3D_USER_CONFIG
#include BOX3D_USER_CONFIG
#endif
#include "config.h"
// clang-format off
//
// Shared library macros
// Predefine BOX3D_EXPORT to reuse an existing export/import scheme, for example
// when compiling Box3D into another shared library.
#ifndef BOX3D_EXPORT
#if defined(_WIN32) && defined(box3d_EXPORTS)
// build the Windows DLL
#define BOX3D_EXPORT __declspec(dllexport)
#elif defined(_WIN32) && defined(BOX3D_DLL)
// using the Windows DLL
#define BOX3D_EXPORT __declspec(dllimport)
#elif defined(box3d_EXPORTS)
// building or using the shared library
#define BOX3D_EXPORT __attribute__((visibility("default")))
#else
// static library
#define BOX3D_EXPORT
#endif
#endif
// C++ macros
#ifdef __cplusplus
#define B3_API extern "C" BOX3D_EXPORT
#define B3_INLINE inline
#if defined( _MSC_VER )
#define B3_FORCE_INLINE __forceinline
#elif defined( __GNUC__ ) || defined( __clang__ )
#define B3_FORCE_INLINE inline __attribute__((always_inline))
#else
#define B3_FORCE_INLINE inline
#endif
#define B3_LITERAL(T) T
#define B3_ZERO_INIT {}
#else
#define B3_API BOX3D_EXPORT
#define B3_INLINE static inline
#if defined( _MSC_VER )
#define B3_FORCE_INLINE static __forceinline
#elif defined( __GNUC__ ) || defined( __clang__ )
#define B3_FORCE_INLINE static inline __attribute__((always_inline))
#else
#define B3_FORCE_INLINE static inline
#endif
/// Used for C literals like (b3Vec3){1.0f, 2.0f, 3.0f} where C++ requires b3Vec3{1.0f, 2.0f, 3.0f}
#define B3_LITERAL(T) (T)
#define B3_ZERO_INIT {0}
#endif
// clang-format on
#if defined( BOX3D_VALIDATE ) && !defined( NDEBUG )
#define B3_ENABLE_VALIDATION 1
#else
#define B3_ENABLE_VALIDATION 0
#endif
/**
* @defgroup base Base
* Base functionality
* @{
*/
/// This is used to indicate null for interfaces that work with indices instead of pointers
#define B3_NULL_INDEX -1
/// Prototype for user allocation function.
/// @param size the allocation size in bytes
/// @param alignment the required alignment, guaranteed to be a power of 2
typedef void* b3AllocFcn( int32_t size, int32_t alignment );
/// Prototype for user free function.
/// @param mem the memory previously allocated through `b3AllocFcn`
typedef void b3FreeFcn( void* mem );
/// Prototype for the user assert callback. Return 0 to skip the debugger break.
typedef int b3AssertFcn( const char* condition, const char* fileName, int lineNumber );
/// Prototype for user log callback. Used to log warnings.
typedef void b3LogFcn( const char* message );
/// This allows the user to override the allocation functions. These should be
/// set during application startup.
B3_API void b3SetAllocator( b3AllocFcn* allocFcn, b3FreeFcn* freeFcn );
/// Total bytes allocated by Box3D
B3_API int32_t b3GetByteCount( void );
/// Override the default assert callback.
/// @param assertFcn a non-null assert callback
B3_API void b3SetAssertFcn( b3AssertFcn* assertFcn );
/// see https://github.com/scottt/debugbreak
#if defined( _MSC_VER )
/// Break to the debugger
#define B3_BREAKPOINT __debugbreak()
#elif defined( __GNUC__ ) || defined( __clang__ )
#define B3_BREAKPOINT __builtin_trap()
#else
/// Unknown compiler
#include <assert.h>
#define B3_BREAKPOINT assert( 0 )
#endif
#if !defined( NDEBUG ) || defined( B3_ENABLE_ASSERT )
/// Internal assertion handler. Allows for host intervention.
B3_API int b3InternalAssert( const char* condition, const char* fileName, int lineNumber );
/// Assert that a condition is true.
#define B3_ASSERT( condition ) \
( (void)( ( !!( condition ) ) || ( b3InternalAssert( #condition, __FILE__, (int)( __LINE__ ) ), 0 ) ) )
#else
#define B3_ASSERT( ... ) ( (void)0 )
#endif
#if B3_ENABLE_VALIDATION
/// Validation is typically only enabled in debug builds.
/// Floating point tolerance checks should use this instead of the regular assertion
#define B3_VALIDATE( condition ) B3_ASSERT( condition )
#else
/// Validation is typically only enabled in debug builds.
/// Floating point tolerance checks should use this instead of the regular assertion
#define B3_VALIDATE( ... ) ( (void)0 )
#endif
/// Override the default logging callback.
B3_API void b3SetLogFcn( b3LogFcn* logFcn );
/// Version numbering scheme.
/// See https://semver.org/
typedef struct b3Version
{
/// Significant changes
int major;
/// Incremental changes
int minor;
/// Bug fixes
int revision;
} b3Version;
/// Get the current version of Box3D
B3_API b3Version b3GetVersion( void );
/// @return true if the library was built with BOX3D_DOUBLE_PRECISION (large world mode)
B3_API bool b3IsDoublePrecision( void );
/**@}*/
//! @cond
/// Get the absolute number of system ticks. The value is platform specific.
B3_API uint64_t b3GetTicks( void );
/// Get the milliseconds passed from an initial tick value.
B3_API float b3GetMilliseconds( uint64_t ticks );
/// Get the milliseconds passed from an initial tick value.
B3_API float b3GetMillisecondsAndReset( uint64_t* ticks );
/// Yield to be used in a busy loop.
B3_API void b3Yield( void );
/// Sleep the current thread for a number of milliseconds.
B3_API void b3Sleep( int milliseconds );
// Simple djb2 hash function for determinism testing
#define B3_HASH_INIT 5381
B3_API uint32_t b3Hash( uint32_t hash, const uint8_t* data, int count );
// Dump file support functions
B3_API void b3WriteBinaryFile( void* data, int size, const char* fileName );
B3_API void* b3ReadBinaryFile( const char* prefix, const char* fileName, int* memSize );
//! @endcond

1730
vendor/box3d/src/include/box3d/box3d.h vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,645 @@
// SPDX-FileCopyrightText: 2025 Erin Catto
// SPDX-License-Identifier: MIT
#pragma once
#include "base.h"
#include "math_functions.h"
#include "types.h"
#include <stdbool.h>
#include <stddef.h>
/**
* @addtogroup tree
* @{
*/
/// Constructing the tree initializes the node pool.
B3_API b3DynamicTree b3DynamicTree_Create( int proxyCapacity );
/// Destroy the tree, freeing the node pool.
B3_API void b3DynamicTree_Destroy( b3DynamicTree* tree );
/// Create a proxy. Provide an AABB and a userData value.
B3_API int b3DynamicTree_CreateProxy( b3DynamicTree* tree, b3AABB aabb, uint64_t categoryBits, uint64_t userData );
/// Destroy a proxy. This asserts if the id is invalid.
B3_API void b3DynamicTree_DestroyProxy( b3DynamicTree* tree, int proxyId );
/// Move a proxy to a new AABB by removing and reinserting into the tree.
B3_API void b3DynamicTree_MoveProxy( b3DynamicTree* tree, int proxyId, b3AABB aabb );
/// Enlarge a proxy and enlarge ancestors as necessary.
B3_API void b3DynamicTree_EnlargeProxy( b3DynamicTree* tree, int proxyId, b3AABB aabb );
/// Modify the category bits on a proxy. This is an expensive operation.
B3_API void b3DynamicTree_SetCategoryBits( b3DynamicTree* tree, int proxyId, uint64_t categoryBits );
/// Get the category bits on a proxy.
B3_API uint64_t b3DynamicTree_GetCategoryBits( b3DynamicTree* tree, int proxyId );
/// Query an AABB for overlapping proxies. The callback function is called for each proxy that overlaps the supplied AABB.
/// @return performance data
B3_API b3TreeStats b3DynamicTree_Query( const b3DynamicTree* tree, b3AABB aabb, uint64_t maskBits, bool requireAllBits,
b3TreeQueryCallbackFcn* callback, void* context );
/// Query an AABB for the closest object. The callback function is called for each proxy that might be closest to the supplied point.
/// @param tree the dynamic tree to query
/// @param point the query point
/// @param maskBits nodes are skipped if the bit-wise AND with the node category bits is zero
/// @param requireAllBits nodes are skipped if the bit-wise AND with the node category bits does not equal the maskBits
/// @param callback a user provided instance of b3TreeQueryClosestCallbackFcn
/// @param context a user context object that is provided to the callback
/// @param minDistanceSqr the initial and final minimum squared distance. Provide a small initial to restrict the search and
/// improve performance. If the value is large this query has performance that scales linearly with the number of proxies and
/// would be slower than a brute force search.
/// @return performance data
B3_API b3TreeStats b3DynamicTree_QueryClosest( const b3DynamicTree* tree, b3Vec3 point, uint64_t maskBits, bool requireAllBits,
b3TreeQueryClosestCallbackFcn* callback, void* context, float* minDistanceSqr );
/// Ray cast against the proxies in the tree. This relies on the callback
/// to perform an exact ray cast in the case where the proxy contains a shape.
/// The callback also performs any collision filtering. This has performance
/// roughly equal to k * log(n), where k is the number of collisions and n is the
/// number of proxies in the tree.
/// Bit-wise filtering using mask bits can greatly improve performance in some scenarios.
/// However, this filtering may be approximate, so the user should still apply filtering to results.
/// @param tree the dynamic tree to ray cast
/// @param input the ray cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1)
/// @param maskBits bit mask test: `bool accept = (maskBits & node->categoryBits) != 0;`
/// @param requireAllBits modifies bit mask test: `bool accept = (maskBits & node->categoryBits) == maskBits;`
/// @param callback a callback function that is called for each proxy that is hit by the ray
/// @param context user context that is passed to the callback
/// @return performance data
B3_API b3TreeStats b3DynamicTree_RayCast( const b3DynamicTree* tree, const b3RayCastInput* input, uint64_t maskBits,
bool requireAllBits, b3TreeRayCastCallbackFcn* callback, void* context );
/// Sweep an AABB through the tree. The box is in the tree's world float frame and the callback
/// re-differences each shape at full precision against the query origin. Used by the large world
/// spatial queries so the tree traversal stays float while the narrow phase stays precise.
B3_API b3TreeStats b3DynamicTree_BoxCast( const b3DynamicTree* tree, const b3BoxCastInput* input, uint64_t maskBits,
bool requireAllBits, b3TreeBoxCastCallbackFcn* callback, void* context );
/// Validate this tree. For testing.
B3_API void b3DynamicTree_Validate( const b3DynamicTree* tree );
/// Get the height of the binary tree.
B3_API int b3DynamicTree_GetHeight( const b3DynamicTree* tree );
/// Get the ratio of the sum of the node areas to the root area.
B3_API float b3DynamicTree_GetAreaRatio( const b3DynamicTree* tree );
/// Get the bounding box that contains the entire tree
B3_API b3AABB b3DynamicTree_GetRootBounds( const b3DynamicTree* tree );
/// Get the number of proxies created
B3_API int b3DynamicTree_GetProxyCount( const b3DynamicTree* tree );
/// Rebuild the tree while retaining subtrees that haven't changed. Returns the number of boxes sorted.
B3_API int b3DynamicTree_Rebuild( b3DynamicTree* tree, bool fullBuild );
/// Get the number of bytes used by this tree
B3_API int b3DynamicTree_GetByteCount( const b3DynamicTree* tree );
/// Validate this tree. For testing.
B3_API void b3DynamicTree_Validate( const b3DynamicTree* tree );
/// Validate this tree has no enlarged AABBs. For testing.
B3_API void b3DynamicTree_ValidateNoEnlarged( const b3DynamicTree* tree );
/// Save this tree to a file for debugging
B3_API void b3DynamicTree_Save( const b3DynamicTree* tree, const char* fileName );
/// Load a file for debugging
B3_API b3DynamicTree b3DynamicTree_Load( const char* fileName, float scale );
/// Get proxy user data
B3_INLINE uint64_t b3DynamicTree_GetUserData( const b3DynamicTree* tree, int proxyId )
{
return tree->nodes[proxyId].userData;
}
/// Get the AABB of a proxy
B3_INLINE b3AABB b3DynamicTree_GetAABB( const b3DynamicTree* tree, int proxyId )
{
return tree->nodes[proxyId].aabb;
}
/**@}*/ // tree
/**
* @addtogroup hull
* @{
*/
/// Get read only hull vertices.
B3_INLINE const b3HullVertex* b3GetHullVertices( const b3HullData* hull )
{
if ( hull->vertexOffset == 0 )
{
return NULL;
}
return (const b3HullVertex*)( (intptr_t)hull + hull->vertexOffset );
}
/// Get read only hull points.
B3_INLINE const b3Vec3* b3GetHullPoints( const b3HullData* hull )
{
if ( hull->pointOffset == 0 )
{
return NULL;
}
return (const b3Vec3*)( (intptr_t)hull + hull->pointOffset );
}
/// Get read only hull half edges.
B3_INLINE const b3HullHalfEdge* b3GetHullEdges( const b3HullData* hull )
{
if ( hull->edgeOffset == 0 )
{
return NULL;
}
return (const b3HullHalfEdge*)( (intptr_t)hull + hull->edgeOffset );
}
/// Get read only hull faces.
B3_INLINE const b3HullFace* b3GetHullFaces( const b3HullData* hull )
{
if ( hull->faceOffset == 0 )
{
return NULL;
}
return (const b3HullFace*)( (intptr_t)hull + hull->faceOffset );
}
/// Get read only hull planes.
B3_INLINE const b3Plane* b3GetHullPlanes( const b3HullData* hull )
{
if ( hull->planeOffset == 0 )
{
return NULL;
}
return (const b3Plane*)( (intptr_t)hull + hull->planeOffset );
}
/// Create a tessellated cylinder as a hull.
B3_API b3HullData* b3CreateCylinder( float height, float radius, float yOffset, int sides );
/// Create a tessellated cone as a hull.
B3_API b3HullData* b3CreateCone( float height, float radius1, float radius2, int slices );
/// Create a rock shaped hull.
B3_API b3HullData* b3CreateRock( float radius );
/// Create a generic convex hull.
B3_API b3HullData* b3CreateHull( const b3Vec3* points, int pointCount, int maxVertexCount );
/// Deep clone a hull.
B3_API b3HullData* b3CloneHull( const b3HullData* hull );
/// Clone and transform a hull. Supports non-uniform and mirroring scale.
B3_API b3HullData* b3CloneAndTransformHull( const b3HullData* original, b3Transform transform, b3Vec3 scale );
/// Destroy a hull.
B3_API void b3DestroyHull( b3HullData* hull );
/// Make a cube as a hull. Do not call b3DestroyHull on this.
B3_API b3BoxHull b3MakeCubeHull( float halfWidth );
/// Make a box as a hull. Do not call b3DestroyHull on this.
B3_API b3BoxHull b3MakeBoxHull( float hx, float hy, float hz );
/// Make an offset box as a hull. Do not call b3DestroyHull on this.
B3_API b3BoxHull b3MakeOffsetBoxHull( float hx, float hy, float hz, b3Vec3 offset );
/// Make a transformed box as a hull. Do not call b3DestroyHull on this.
/// @param hx, hy, hz positive half widths
/// @param transform local transform of box
B3_API b3BoxHull b3MakeTransformedBoxHull( float hx, float hy, float hz, b3Transform transform );
/// This makes a transformed box hull with post scaling. This is useful for boxes that are scaled in
/// a level editor. Such scaling can have reflection and shear. In the case of shear the result
/// may be approximate. If you need to support shear consider using b3CreateHull.
/// Do not call b3DestroyHull on this.
/// @param halfWidths positive half widths
/// @param transform local transform of box
/// @param postScale scale applied after the transform, may be negative
B3_API b3BoxHull b3MakeScaledBoxHull( b3Vec3 halfWidths, b3Transform transform, b3Vec3 postScale );
/// This takes a box with a transform and post scale and converts it into a box with the post scale
/// resolved with new half-widths and transform. This accepts non-uniform and negative scale.
/// This is approximate if there is shear.
/// @param halfWidths [in/out] the box half widths
/// @param transform [in/out] the box transform with rotation and translation
/// @param postScale the post scale being applied to the box after the transform
/// @param minHalfWidth the minimum half width after scale is applied
B3_API void b3ScaleBox( b3Vec3* halfWidths, b3Transform* transform, b3Vec3 postScale, float minHalfWidth );
/**@}*/ // hull
/**
* @addtogroup mesh
* @{
*/
/// Get read only mesh BVH nodes.
B3_INLINE const b3MeshNode* b3GetMeshNodes( const b3MeshData* mesh )
{
if ( mesh->nodeOffset == 0 )
{
return NULL;
}
return (const b3MeshNode*)( (intptr_t)mesh + mesh->nodeOffset );
}
/// Get read only mesh vertices.
B3_INLINE const b3Vec3* b3GetMeshVertices( const b3MeshData* mesh )
{
if ( mesh->vertexOffset == 0 )
{
return NULL;
}
return (const b3Vec3*)( (intptr_t)mesh + mesh->vertexOffset );
}
/// Get read only mesh triangles.
B3_INLINE const b3MeshTriangle* b3GetMeshTriangles( const b3MeshData* mesh )
{
if ( mesh->triangleOffset == 0 )
{
return NULL;
}
return (const b3MeshTriangle*)( (intptr_t)mesh + mesh->triangleOffset );
}
/// Get read only mesh materials. The count is equal to the triangle count.
B3_INLINE const uint8_t* b3GetMeshMaterialIndices( const b3MeshData* mesh )
{
if ( mesh->materialOffset == 0 )
{
return NULL;
}
return (const uint8_t*)( (intptr_t)mesh + mesh->materialOffset );
}
/// Get read only mesh flags. The count is equal to the triangle count.
B3_INLINE const uint8_t* b3GetMeshFlags( const b3MeshData* mesh )
{
if ( mesh->flagsOffset == 0 )
{
return NULL;
}
return (const uint8_t*)( (intptr_t)mesh + mesh->flagsOffset );
}
/// Create a grid mesh along the x and z axes.
/// @param xCount the number of rows in the x direction
/// @param zCount the number of rows in the z direction
/// @param cellWidth the width of each cell
/// @param materialCount the number of materials to generate
/// @param identifyEdges compute adjacency information
B3_API b3MeshData* b3CreateGridMesh( int xCount, int zCount, float cellWidth, int materialCount, bool identifyEdges );
/// Create a wave mesh along the x and z axes.
B3_API b3MeshData* b3CreateWaveMesh( int xCount, int zCount, float cellWidth, float amplitude, float rowFrequency,
float columnFrequency );
/// Create a torus mesh.
B3_API b3MeshData* b3CreateTorusMesh( int radialResolution, int tubularResolution, float radius, float thickness );
/// Create a box mesh.
B3_API b3MeshData* b3CreateBoxMesh( b3Vec3 center, b3Vec3 extent, bool identifyEdges );
/// Create a hollow box mesh.
B3_API b3MeshData* b3CreateHollowBoxMesh( b3Vec3 center, b3Vec3 extent );
/// Create a platform mesh. A truncated pyramid.
B3_API b3MeshData* b3CreatePlatformMesh( b3Vec3 center, float height, float topWidth, float bottomWidth );
/// Create a generic mesh.
B3_API b3MeshData* b3CreateMesh( const b3MeshDef* def, int* degenerateTriangleIndices, int degenerateCapacity );
/// Destroy a mesh.
B3_API void b3DestroyMesh( b3MeshData* mesh );
/// Get the height of the mesh BVH.
B3_API int b3GetHeight( const b3MeshData* mesh );
/**@}*/ // mesh
/**
* @addtogroup height_field
* @{
*/
/// Get read only compressed heights. One uint16_t per grid point.
B3_INLINE const uint16_t* b3GetHeightFieldCompressedHeights( const b3HeightFieldData* hf )
{
if ( hf->heightsOffset == 0 )
{
return NULL;
}
return (const uint16_t*)( (intptr_t)hf + hf->heightsOffset );
}
/// Get read only material indices. One uint8_t per cell.
B3_INLINE const uint8_t* b3GetHeightFieldMaterialIndices( const b3HeightFieldData* hf )
{
if ( hf->materialOffset == 0 )
{
return NULL;
}
return (const uint8_t*)( (intptr_t)hf + hf->materialOffset );
}
/// Get read only triangle flags. One uint8_t per triangle.
B3_INLINE const uint8_t* b3GetHeightFieldFlags( const b3HeightFieldData* hf )
{
if ( hf->flagsOffset == 0 )
{
return NULL;
}
return (const uint8_t*)( (intptr_t)hf + hf->flagsOffset );
}
/// Create a generic height field.
B3_API b3HeightFieldData* b3CreateHeightField( const b3HeightFieldDef* data );
/// Create a grid as a height field.
B3_API b3HeightFieldData* b3CreateGrid( int rowCount, int columnCount, b3Vec3 scale, bool makeHoles );
/// Create a wave grid as a height field.
B3_API b3HeightFieldData* b3CreateWave( int rowCount, int columnCount, b3Vec3 scale, float rowFrequency, float columnFrequency,
bool makeHoles );
/// Destroy a height field.
B3_API void b3DestroyHeightField( b3HeightFieldData* heightField );
/// Save input height data to a file
B3_API void b3DumpHeightData( const b3HeightFieldDef* data, const char* fileName );
/// Create a height field by loading a previously saved height data
B3_API b3HeightFieldData* b3LoadHeightField( const char* fileName );
/**@}*/ // height_field
/**
* @addtogroup compound
* @{
*/
/// Get a child shape of a compound.
B3_API b3ChildShape b3GetCompoundChild( const b3CompoundData* compound, int childIndex );
/// Query a compound shape for children that overlap an AABB.
B3_API void b3QueryCompound( const b3CompoundData* compound, b3AABB aabb, b3CompoundQueryFcn* fcn, void* context );
/// Access a child capsule by index.
B3_API b3CompoundCapsule b3GetCompoundCapsule( const b3CompoundData* compound, int index );
/// Access a child hull by index.
B3_API b3CompoundHull b3GetCompoundHull( const b3CompoundData* compound, int index );
/// Access a child mesh by index.
B3_API b3CompoundMesh b3GetCompoundMesh( const b3CompoundData* compound, int index );
/// Access a child sphere by index.
B3_API b3CompoundSphere b3GetCompoundSphere( const b3CompoundData* compound, int index );
/// Access the compound material array.
B3_API const b3SurfaceMaterial* b3GetCompoundMaterials( const b3CompoundData* compound );
/// Create a compound shape. All input data in the definition is cloned into the resulting compound.
B3_API b3CompoundData* b3CreateCompound( const b3CompoundDef* def );
/// Destroy a compound shape.
B3_API void b3DestroyCompound( b3CompoundData* compound );
/// If bytes is null then this returns the number of required bytes. This clones all the
/// data into the bytes buffer. This is expected to run offline or asynchronously.
/// This mutates the compound to nullify pointers, leaving the compound in an unusable state.
B3_API uint8_t* b3ConvertCompoundToBytes( b3CompoundData* compound );
/// Convert bytes to compound. This does not clone. The bytes must remain in scope while the
/// compound is used. This is done to improve run-time performance and allow for instancing.
/// The bytes are mutated to fixup pointers.
B3_API b3CompoundData* b3ConvertBytesToCompound( uint8_t* bytes, int byteCount );
/**@}*/ // compound
/**
* @addtogroup geometry
* @{
*/
/// Compute mass properties of a sphere
B3_API b3MassData b3ComputeSphereMass( const b3Sphere* shape, float density );
/// Compute mass properties of a capsule
B3_API b3MassData b3ComputeCapsuleMass( const b3Capsule* shape, float density );
/// Compute mass properties of a hull
B3_API b3MassData b3ComputeHullMass( const b3HullData* shape, float density );
/// Compute the bounding box of a transformed sphere
B3_API b3AABB b3ComputeSphereAABB( const b3Sphere* shape, b3Transform transform );
/// Compute the bounding box of a transformed capsule
B3_API b3AABB b3ComputeCapsuleAABB( const b3Capsule* shape, b3Transform transform );
/// Compute the bounding box of a transformed hull
B3_API b3AABB b3ComputeHullAABB( const b3HullData* shape, b3Transform transform );
/// Compute the bounding box of a transformed mesh. Scale may be non-uniform and have negative components.
B3_API b3AABB b3ComputeMeshAABB( const b3MeshData* shape, b3Transform transform, b3Vec3 scale );
/// Compute the bounding box of a transformed height-field
B3_API b3AABB b3ComputeHeightFieldAABB( const b3HeightFieldData* shape, b3Transform transform );
/// Compute the bounding box of a compound
B3_API b3AABB b3ComputeCompoundAABB( const b3CompoundData* shape, b3Transform transform );
/**@}*/ // geometry
/**
* @addtogroup query
* @{
*/
/// Use this to ensure your ray cast input is valid and avoid internal assertions.
B3_API bool b3IsValidRay( const b3RayCastInput* input );
/// Overlap shape versus capsule
B3_API bool b3OverlapCapsule( const b3Capsule* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy );
/// Overlap shape versus compound
B3_API bool b3OverlapCompound( const b3CompoundData* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy );
/// Overlap shape versus height field
B3_API bool b3OverlapHeightField( const b3HeightFieldData* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy );
/// Overlap shape versus hull
B3_API bool b3OverlapHull( const b3HullData* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy );
/// Overlap shape versus mesh
B3_API bool b3OverlapMesh( const b3Mesh* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy );
/// Overlap shape versus sphere
B3_API bool b3OverlapSphere( const b3Sphere* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy );
/// Ray cast versus sphere in local space. A zero length ray is a point query. Initial overlap
/// reports a hit at the ray origin with zero fraction and zero normal.
B3_API b3CastOutput b3RayCastSphere( const b3Sphere* shape, const b3RayCastInput* input );
/// Ray cast versus a hollow sphere shell in local space. Unlike the solid sphere a ray starting
/// inside is not an overlap: it passes through and hits the far wall.
B3_API b3CastOutput b3RayCastHollowSphere( const b3Sphere* shape, const b3RayCastInput* input );
/// Ray cast versus capsule in local space. A zero length ray is a point query. Initial overlap
/// reports a hit at the ray origin with zero fraction and zero normal.
B3_API b3CastOutput b3RayCastCapsule( const b3Capsule* shape, const b3RayCastInput* input );
/// Ray cast versus compound in local space. A zero length ray is a point query. Initial overlap
/// with a child reports a hit at the ray origin with zero fraction and zero normal.
B3_API b3CastOutput b3RayCastCompound( const b3CompoundData* shape, const b3RayCastInput* input );
/// Ray cast versus hull shape in local space. A zero length ray is a point query. Initial overlap
/// reports a hit at the ray origin with zero fraction and zero normal.
B3_API b3CastOutput b3RayCastHull( const b3HullData* shape, const b3RayCastInput* input );
/// Ray cast versus mesh in local space. A thin surface with no interior, so there is no overlap case.
B3_API b3CastOutput b3RayCastMesh( const b3Mesh* shape, const b3RayCastInput* input );
/// Ray cast versus height field in local space. A thin surface with no interior, so there is no overlap case.
B3_API b3CastOutput b3RayCastHeightField( const b3HeightFieldData* shape, const b3RayCastInput* input );
/// Shape cast versus a sphere. Initial overlap is treated as a miss.
B3_API b3CastOutput b3ShapeCastSphere( const b3Sphere* shape, const b3ShapeCastInput* input );
/// Shape cast versus a capsule. Initial overlap is treated as a miss.
B3_API b3CastOutput b3ShapeCastCapsule( const b3Capsule* shape, const b3ShapeCastInput* input );
/// Shape cast versus compound. Initial overlap is treated as a miss.
B3_API b3CastOutput b3ShapeCastCompound( const b3CompoundData* shape, const b3ShapeCastInput* input );
/// Shape cast versus a hull. Initial overlap is treated as a miss.
B3_API b3CastOutput b3ShapeCastHull( const b3HullData* shape, const b3ShapeCastInput* input );
/// Shape cast versus a mesh. Initial overlap is treated as a miss.
B3_API b3CastOutput b3ShapeCastMesh( const b3Mesh* shape, const b3ShapeCastInput* input );
/// Shape cast versus a height field. Initial overlap is treated as a miss.
B3_API b3CastOutput b3ShapeCastHeightField( const b3HeightFieldData* shape, const b3ShapeCastInput* input );
/// Query callback.
typedef bool b3MeshQueryFcn( b3Vec3 a, b3Vec3 b, b3Vec3 c, int triangleIndex, void* context );
/// Query a mesh for triangles overlapping a bounding box in local space. May have false positives. Useful for debug draw.
/// @param mesh the mesh to query, includes scale
/// @param bounds the bounding box in local space
/// @param fcn a user function to collect triangles
/// @param context the context sent to the user function.
B3_API void b3QueryMesh( const b3Mesh* mesh, const b3AABB bounds, b3MeshQueryFcn* fcn, void* context );
/// Query a height field for triangles overlapping a bounding box in local space. May have false positives. Useful for debug draw.
/// @param heightField the height field to query
/// @param bounds the bounding box in local space
/// @param fcn a user function to collect triangles
/// @param context the context sent to the user function.
B3_API void b3QueryHeightField( const b3HeightFieldData* heightField, b3AABB bounds, b3MeshQueryFcn* fcn, void* context );
/// Compute the closest points between two shapes represented as point clouds.
/// b3SimplexCache cache is input/output. On the first call set b3SimplexCache.count to zero.
/// The query runs in frame A, so the witness points and normal are returned in frame A.
/// The underlying GJK algorithm may be debugged by passing in debug simplexes and capacity. You may pass in NULL and 0 for these.
B3_API b3DistanceOutput b3ShapeDistance( const b3DistanceInput* input, b3SimplexCache* cache, b3Simplex* simplexes,
int simplexCapacity );
/// Perform a linear shape cast of shape B moving and shape A fixed. Determines the hit point, normal, and translation fraction.
/// The query runs in frame A, so the hit point and normal are returned in frame A. Initially touching shapes are a miss.
B3_API b3CastOutput b3ShapeCast( const b3ShapeCastPairInput* input );
/// Evaluate the transform sweep at a specific time.
B3_API b3Transform b3GetSweepTransform( const b3Sweep* sweep, float time );
/// Compute the upper bound on time before two shapes penetrate. Time is represented as
/// a fraction between [0,tMax]. This uses a swept separating axis and may miss some intermediate,
/// non-tunneling collisions. If you change the time interval, you should call this function
/// again.
B3_API b3TOIOutput b3TimeOfImpact( const b3TOIInput* input );
/**@}*/ // query
/**
* @addtogroup collision
* @{
*/
/// Collide two spheres.
B3_API void b3CollideSpheres( b3LocalManifold* manifold, int capacity, const b3Sphere* sphereA, const b3Sphere* sphereB,
b3Transform transformBtoA );
/// Collide a capsule and a sphere.
B3_API void b3CollideCapsuleAndSphere( b3LocalManifold* manifold, int capacity, const b3Capsule* capsuleA,
const b3Sphere* sphereB, b3Transform transformBtoA );
/// Collide a hull and a sphere.
B3_API void b3CollideHullAndSphere( b3LocalManifold* manifold, int capacity, const b3HullData* hullA, const b3Sphere* sphereB,
b3Transform transformBtoA, b3SimplexCache* cache );
/// Collide two capsules.
B3_API void b3CollideCapsules( b3LocalManifold* manifold, int capacity, const b3Capsule* capsuleA, const b3Capsule* capsuleB,
b3Transform transformBtoA );
/// Collide a hull and a capsule.
B3_API void b3CollideHullAndCapsule( b3LocalManifold* manifold, int capacity, const b3HullData* hullA, const b3Capsule* capsuleB,
b3Transform transformBtoA, b3SimplexCache* cache );
/// Collide two hulls.
B3_API void b3CollideHulls( b3LocalManifold* manifold, int capacity, const b3HullData* hullA, const b3HullData* hullB,
b3Transform transformBtoA, b3SATCache* cache );
/// Collide a capsule and a triangle.
B3_API void b3CollideCapsuleAndTriangle( b3LocalManifold* manifold, int capacity, const b3Capsule* capsuleA,
const b3Vec3* triangleB, b3SimplexCache* cache );
/// Collide a hull and a triangle.
B3_API void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3HullData* hullA, b3Vec3 v1, b3Vec3 v2,
b3Vec3 v3, int triangleFlags, b3SATCache* cache );
/// Collide a sphere and a triangle.
B3_API void b3CollideSphereAndTriangle( b3LocalManifold* manifold, int capacity, const b3Sphere* sphereA,
const b3Vec3* triangleB );
/**@}*/ // collision
/**
* @addtogroup character
* @{
*/
/// Solves the position of a mover that satisfies the given collision planes.
/// @param targetDelta the desired translation from the position used to generate the collision planes
/// @param planes the collision planes
/// @param count the number of collision planes
B3_API b3PlaneSolverResult b3SolvePlanes( b3Vec3 targetDelta, b3CollisionPlane* planes, int count );
/// Clips the velocity against the given collision planes. Planes with zero push or clipVelocity
/// set to false are skipped.
B3_API b3Vec3 b3ClipVector( b3Vec3 vector, const b3CollisionPlane* planes, int count );
/**@}*/ // character

31
vendor/box3d/src/include/box3d/config.h vendored Normal file
View File

@@ -0,0 +1,31 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
#pragma once
// Box3D compile-time options.
//
// Normally set by the CMake BOX3D_* options. If you build Box3D without its
// CMake (dropping the sources into another project), set them here so the
// library and your code agree. Edit this file, or keep your settings elsewhere
// and point Box3D at them from your build:
//
// #define BOX3D_USER_CONFIG "my_box3d_config.h"
//
// A define passed on the compiler command line still wins over this file.
// Large world mode. Stores world positions in double precision. Affects ABI.
//#define BOX3D_DOUBLE_PRECISION
// Build the scalar fallback instead of SSE2/NEON.
//#define BOX3D_DISABLE_SIMD
// Enable internal validation in debug builds.
//#define BOX3D_VALIDATE
// Decorate the public API with your own export macro instead of Box3D's
// box3d_EXPORTS/BOX3D_DLL scheme, for example when compiling Box3D into another
// shared library. A single value cannot switch between dllexport and dllimport,
// so this suits embedding more than shipping Box3D as its own DLL.
//#define BOX3D_EXPORT MYENGINE_API

View File

@@ -0,0 +1,123 @@
// SPDX-FileCopyrightText: 2025 Erin Catto
// SPDX-License-Identifier: MIT
#pragma once
#include "base.h"
/// Box3D bases all length units on meters, but you may need different units for your game.
/// You can set this value to use different units. This should be done at application startup
/// and only modified once. Default value is 1.
/// @warning This must be modified before any calls to Box3D
B3_API void b3SetLengthUnitsPerMeter( float lengthUnits );
/// Get the current length units per meter.
B3_API float b3GetLengthUnitsPerMeter( void );
/// Set the threshold for logging stalls.
B3_API void b3SetStallThreshold( float seconds );
/// Get the threshold for logging stalls.
B3_API float b3GetStallThreshold( void );
// Used to detect bad values. In float mode positions greater than about 16km have precision
// problems, so 100km is a safe limit. Large world mode keeps coordinates accurate much farther
// from the origin, so the sanity limit widens to keep valid far-field positions from tripping it.
#if defined( BOX3D_DOUBLE_PRECISION )
#define B3_HUGE ( 1.0e9f * b3GetLengthUnitsPerMeter() )
#else
#define B3_HUGE ( 1.0e5f * b3GetLengthUnitsPerMeter() )
#endif
/// Maximum parallel workers. Used for some fixed size arrays.
#define B3_MAX_WORKERS 32
/// Maximum number of tasks queued per world step. b3EnqueueTaskCallback will never be called
/// more than this per world step. This is related to B3_MAX_WORKERS. With 32 workers,
/// the maximum observed task count is 130. This allows an external task system to use a fixed
/// size array for Box3D task, which may help with creating stable user task pointers.
#define B3_MAX_TASKS 256
// Maximum number of colors in the constraint graph. Constraints that cannot
// find a color are added to the overflow set which are solved single-threaded.
// The compound barrel benchmark has minor overflow with 24 colors
#define B3_GRAPH_COLOR_COUNT 24
// Number of contact point buckets for counting the number of contact points per
// shape contact pair. This is just for reporting and doesn't affect simulation.
#define B3_CONTACT_MANIFOLD_COUNT_BUCKETS 8
// A small length used as a collision and constraint tolerance. Usually it is
// chosen to be numerically significant, but visually insignificant. In meters.
// @warning modifying this can have a significant impact on stability
#define B3_LINEAR_SLOP ( 0.005f * b3GetLengthUnitsPerMeter() )
#define B3_MIN_CAPSULE_LENGTH ( B3_LINEAR_SLOP )
/// The distance between shapes where they are considered overlapped. This is needed
/// because GJK may return small positive values for overlapped shapes in degenerate
/// configurations.
#define B3_OVERLAP_SLOP ( 0.1f * B3_LINEAR_SLOP )
/// Maximum number of simultaneous worlds that can be allocated
#ifndef B3_MAX_WORLDS
#define B3_MAX_WORLDS 128
#endif
/// The maximum rotation of a body per time step. This limit is very large and is used
/// to prevent numerical problems. You shouldn't need to adjust this.
/// @warning increasing this to 0.5f * B3_PI or greater will break continuous collision.
#define B3_MAX_ROTATION ( 0.25f * B3_PI )
/// @warning modifying this can have a significant impact on performance and stability
#define B3_SPECULATIVE_DISTANCE ( 4.0f * B3_LINEAR_SLOP )
/// The rest offset is used for mesh contact to reduce ghost collisions and assist with CCD.
/// The rest offset adjusts the contact point separation value, making the solver push the shapes
/// apart by this distance.
/// Must be at least B3_LINEAR_SLOP and less than B3_SPECULATIVE_DISTANCE.
#define B3_MESH_REST_OFFSET ( 1.0f * B3_LINEAR_SLOP )
/// The default contact recycling distance.
#define B3_CONTACT_RECYCLE_DISTANCE ( 10.0f * B3_LINEAR_SLOP )
/// The default contact recycling world angle threshold. For performance this value
/// is cos(angle/2)^2. This value corresponds to 10 degrees.
#define B3_CONTACT_RECYCLE_ANGULAR_DISTANCE ( 0.99240388f )
/// This is used to fatten AABBs in the dynamic tree. This allows proxies
/// to move by a small amount without triggering a tree adjustment. This is in meters.
/// @warning modifying this can have a significant impact on performance
#define B3_MAX_AABB_MARGIN ( 0.05f * b3GetLengthUnitsPerMeter() )
/// Per-shape AABB margin is a fraction of the shape extent (capped by B3_MAX_AABB_MARGIN).
/// Small shapes get small margins; large shapes are clamped to the cap.
#define B3_AABB_MARGIN_FRACTION 0.125f
/// The time that a body must be still before it will go to sleep. In seconds.
#define B3_TIME_TO_SLEEP 0.5f
/// Maximum length of the body name. Can be 0 if you don't need names.
/// Note: this gates recording capability.
#ifndef B3_BODY_NAME_LENGTH
#define B3_BODY_NAME_LENGTH 18
#endif
/// Maximum length of the shape name. Can be 0 if you don't need names.
/// Note: this gates recording capability.
/// todo waiting on this because it breaks existing recordings
#ifndef B3_SHAPE_NAME_LENGTH
#define B3_SHAPE_NAME_LENGTH 18
#endif
/// The maximum number of contact points between two touching shapes.
#define B3_MAX_MANIFOLD_POINTS 4
/// The maximum number points to use for shape cast proxies (swept point cloud).
#define B3_MAX_SHAPE_CAST_POINTS 64
/// These generous limits allow for easy hashing. See b3ShapePairKey.
#define B3_SHAPE_POWER 22
#define B3_CHILD_POWER ( 64 - 2 * B3_SHAPE_POWER )
#define B3_MAX_SHAPES ( 1 << B3_SHAPE_POWER )
#define B3_MAX_CHILD_SHAPES ( 1 << B3_CHILD_POWER )

178
vendor/box3d/src/include/box3d/id.h vendored Normal file
View File

@@ -0,0 +1,178 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
#pragma once
#include <stdint.h>
// Note: this file should be stand-alone
/**
* @defgroup id Ids
* These ids serve as handles to internal Box3D objects.
* These should be considered opaque data and passed by value.
* Include this header if you need the id types and not the whole Box3D API.
* All ids are considered null if initialized to zero.
*
* For example in C++:
*
* @code{.cxx}
* b3WorldId worldId = {};
* @endcode
*
* Or in C:
*
* @code{.c}
* b3WorldId worldId = {0};
* @endcode
*
* These are both considered null.
*
* @warning Do not use the internals of these ids. They are subject to change. Ids should be treated as opaque objects.
* @warning You should use ids to access objects in Box3D. Do not access files within the src folder. Such usage is unsupported.
* @{
*/
/// World id references a world instance. This should be treated as an opaque handle.
typedef struct b3WorldId
{
uint16_t index1;
uint16_t generation;
} b3WorldId;
/// Body id references a body instance. This should be treated as an opaque handle.
typedef struct b3BodyId
{
int32_t index1;
uint16_t world0;
uint16_t generation;
} b3BodyId;
/// Shape id references a shape instance. This should be treated as an opaque handle.
typedef struct b3ShapeId
{
int32_t index1;
uint16_t world0;
uint16_t generation;
} b3ShapeId;
/// Joint id references a joint instance. This should be treated as an opaque handle.
typedef struct b3JointId
{
int32_t index1;
uint16_t world0;
uint16_t generation;
} b3JointId;
/// Contact id references a contact instance. This should be treated as an opaque handle.
typedef struct b3ContactId
{
int32_t index1;
uint16_t world0;
int16_t padding;
uint32_t generation;
} b3ContactId;
// clang-format off
#ifdef __cplusplus
/// A null id. Works for any id type.
#define B3_NULL_ID {}
#define B3_ID_INLINE inline
#else
/// A null id. Works for any id type.
#define B3_NULL_ID { 0 }
/// This macro bridges C and C++ inline functions. C++ has the one definition rule that C lacks.
#define B3_ID_INLINE static inline
#endif
// clang-format on
/// Use these to make your identifiers null.
/// You may also use zero initialization to get null.
static const b3WorldId b3_nullWorldId = B3_NULL_ID;
static const b3BodyId b3_nullBodyId = B3_NULL_ID;
static const b3ShapeId b3_nullShapeId = B3_NULL_ID;
static const b3JointId b3_nullJointId = B3_NULL_ID;
static const b3ContactId b3_nullContactId = B3_NULL_ID;
/// Macro to determine if any id is null.
#define B3_IS_NULL( id ) ( id.index1 == 0 )
/// Macro to determine if any id is non-null.
#define B3_IS_NON_NULL( id ) ( id.index1 != 0 )
/// Compare two ids for equality. Doesn't work for b3WorldId. Don't mix types.
#define B3_ID_EQUALS( id1, id2 ) ( id1.index1 == id2.index1 && id1.world0 == id2.world0 && id1.generation == id2.generation )
/// Store a world id into a uint32_t.
B3_ID_INLINE uint32_t b3StoreWorldId( b3WorldId id )
{
return ( (uint32_t)id.index1 << 16 ) | (uint32_t)id.generation;
}
/// Load a uint32_t into a world id.
B3_ID_INLINE b3WorldId b3LoadWorldId( uint32_t x )
{
b3WorldId id = { (uint16_t)( x >> 16 ), (uint16_t)( x ) };
return id;
}
/// Store a body id into a uint64_t.
B3_ID_INLINE uint64_t b3StoreBodyId( b3BodyId id )
{
return ( (uint64_t)id.index1 << 32 ) | ( (uint64_t)id.world0 ) << 16 | (uint64_t)id.generation;
}
/// Load a uint64_t into a body id.
B3_ID_INLINE b3BodyId b3LoadBodyId( uint64_t x )
{
b3BodyId id = { (int32_t)( x >> 32 ), (uint16_t)( x >> 16 ), (uint16_t)( x ) };
return id;
}
/// Store a shape id into a uint64_t.
B3_ID_INLINE uint64_t b3StoreShapeId( b3ShapeId id )
{
return ( (uint64_t)id.index1 << 32 ) | ( (uint64_t)id.world0 ) << 16 | (uint64_t)id.generation;
}
/// Load a uint64_t into a shape id.
B3_ID_INLINE b3ShapeId b3LoadShapeId( uint64_t x )
{
b3ShapeId id = { (int32_t)( x >> 32 ), (uint16_t)( x >> 16 ), (uint16_t)( x ) };
return id;
}
/// Store a joint id into a uint64_t.
B3_ID_INLINE uint64_t b3StoreJointId( b3JointId id )
{
return ( (uint64_t)id.index1 << 32 ) | ( (uint64_t)id.world0 ) << 16 | (uint64_t)id.generation;
}
/// Load a uint64_t into a joint id.
B3_ID_INLINE b3JointId b3LoadJointId( uint64_t x )
{
b3JointId id = { (int32_t)( x >> 32 ), (uint16_t)( x >> 16 ), (uint16_t)( x ) };
return id;
}
/// Store a contact id into three uint32 values
B3_ID_INLINE void b3StoreContactId( b3ContactId id, uint32_t values[3] )
{
values[0] = (uint32_t)id.index1;
values[1] = (uint32_t)id.world0;
values[2] = (uint32_t)id.generation;
}
/// Load a contact id from three uint32 values.
B3_ID_INLINE b3ContactId b3LoadContactId( uint32_t values[3] )
{
b3ContactId id;
id.index1 = (int32_t)values[0];
id.world0 = (uint16_t)values[1];
id.padding = 0;
id.generation = (uint32_t)values[2];
return id;
}
/**@}*/

File diff suppressed because it is too large Load Diff

3034
vendor/box3d/src/include/box3d/types.h vendored Normal file

File diff suppressed because it is too large Load Diff