Box3D 0.1.0
A 3D physics engine for games
Loading...
Searching...
No Matches

These functions allow you to create a simulation world. More...

Collaboration diagram for World:

Topics

 Recording
 Record and replay world state for debugging.

Data Structures

struct  b3Capacity
 Optional world capacities that can be use to avoid run-time allocations. More...
struct  b3WorldDef
 World definition used to create a simulation world. More...
struct  b3ExplosionDef
 The explosion definition is used to configure options for explosions. More...

Typedefs

typedef void b3TaskCallback(void *taskContext)
 Task interface This is the prototype for a Box3D task.
typedef void * b3EnqueueTaskCallback(b3TaskCallback *task, void *taskContext, void *userContext, const char *taskName)
 These functions can be provided to Box3D to invoke a task system.
typedef void b3FinishTaskCallback(void *userTask, void *userContext)
 Finishes a user task object that wraps a Box3D task.
typedef float b3FrictionCallback(float frictionA, uint64_t userMaterialIdA, float frictionB, uint64_t userMaterialIdB)
 Optional friction mixing callback.
typedef float b3RestitutionCallback(float restitutionA, uint64_t userMaterialIdA, float restitutionB, uint64_t userMaterialIdB)
 Optional restitution mixing callback.
typedef bool b3CustomFilterFcn(b3ShapeId shapeIdA, b3ShapeId shapeIdB, void *context)
 Prototype for a contact filter callback.
typedef bool b3PreSolveFcn(b3ShapeId shapeIdA, b3ShapeId shapeIdB, b3Pos point, b3Vec3 normal, void *context)
 Prototype for a pre-solve callback.
typedef bool b3OverlapResultFcn(b3ShapeId shapeId, void *context)
 Prototype callback for overlap queries.
typedef float b3CastResultFcn(b3ShapeId shapeId, b3Pos point, b3Vec3 normal, float fraction, uint64_t userMaterialId, int triangleIndex, int childIndex, void *context)
 Prototype callback for ray casts.

Functions

b3WorldId b3CreateWorld (const b3WorldDef *def)
 Create a world for rigid body simulation.
void b3DestroyWorld (b3WorldId worldId)
 Destroy a world.
int b3GetWorldCount (void)
 Get the current number of worlds.
int b3GetMaxWorldCount (void)
 Get the maximum number of simultaneous worlds that have been created.
bool b3World_IsValid (b3WorldId id)
 World id validation. Provides validation for up to 64K allocations.
void b3World_Step (b3WorldId worldId, float timeStep, int subStepCount)
 Simulate a world for one time step.
void b3World_Draw (b3WorldId worldId, b3DebugDraw *draw, uint64_t maskBits)
 Call this to draw shapes and other debug draw data.
b3AABB b3World_GetBounds (b3WorldId worldId)
 Get the world's bounds.
b3BodyEvents b3World_GetBodyEvents (b3WorldId worldId)
 Get the body events for the current time step. The event data is transient. Do not store a reference to this data.
b3SensorEvents b3World_GetSensorEvents (b3WorldId worldId)
 Get sensor events for the current time step. The event data is transient. Do not store a reference to this data.
b3ContactEvents b3World_GetContactEvents (b3WorldId worldId)
 Get contact events for this current time step. The event data is transient. Do not store a reference to this data.
b3JointEvents b3World_GetJointEvents (b3WorldId worldId)
 Get the joint events for the current time step. The event data is transient. Do not store a reference to this data.
b3TreeStats b3World_OverlapAABB (b3WorldId worldId, b3AABB aabb, b3QueryFilter filter, b3OverlapResultFcn *fcn, void *context)
 Overlap test for all shapes that potentially overlap the provided AABB.
b3TreeStats b3World_OverlapShape (b3WorldId worldId, b3Pos origin, const b3ShapeProxy *proxy, b3QueryFilter filter, b3OverlapResultFcn *fcn, void *context)
 Overlap test for all shapes that overlap the provided shape proxy.
b3TreeStats b3World_CastRay (b3WorldId worldId, b3Pos origin, b3Vec3 translation, b3QueryFilter filter, b3CastResultFcn *fcn, void *context)
 Cast a ray into the world to collect shapes in the path of the ray.
b3RayResult b3World_CastRayClosest (b3WorldId worldId, b3Pos origin, b3Vec3 translation, b3QueryFilter filter)
 Cast a ray into the world to collect the closest hit.
b3TreeStats b3World_CastShape (b3WorldId worldId, b3Pos origin, const b3ShapeProxy *proxy, b3Vec3 translation, b3QueryFilter filter, b3CastResultFcn *fcn, void *context)
 Cast a shape through the world.
float b3World_CastMover (b3WorldId worldId, b3Pos origin, const b3Capsule *mover, b3Vec3 translation, b3QueryFilter filter, b3MoverFilterFcn *fcn, void *context)
 Cast a capsule mover through the world.
void b3World_CollideMover (b3WorldId worldId, b3Pos origin, const b3Capsule *mover, b3QueryFilter filter, b3PlaneResultFcn *fcn, void *context)
 Collide a capsule mover with the world, gathering collision planes that can be fed to b3SolvePlanes.
void b3World_EnableSleeping (b3WorldId worldId, bool flag)
 Enable/disable sleep.
bool b3World_IsSleepingEnabled (b3WorldId worldId)
 Is body sleeping enabled?
void b3World_EnableContinuous (b3WorldId worldId, bool flag)
 Enable/disable continuous collision between dynamic and static bodies.
bool b3World_IsContinuousEnabled (b3WorldId worldId)
 Is continuous collision enabled?
void b3World_SetRestitutionThreshold (b3WorldId worldId, float value)
 Adjust the restitution threshold.
float b3World_GetRestitutionThreshold (b3WorldId worldId)
 Get the restitution speed threshold. Usually in meters per second.
void b3World_SetHitEventThreshold (b3WorldId worldId, float value)
 Adjust the hit event threshold.
float b3World_GetHitEventThreshold (b3WorldId worldId)
 Get the hit event speed threshold. Usually in meters per second.
void b3World_SetCustomFilterCallback (b3WorldId worldId, b3CustomFilterFcn *fcn, void *context)
 Register the custom filter callback. This is optional.
void b3World_SetPreSolveCallback (b3WorldId worldId, b3PreSolveFcn *fcn, void *context)
 Register the pre-solve callback. This is optional.
void b3World_SetGravity (b3WorldId worldId, b3Vec3 gravity)
 Set the gravity vector for the entire world.
b3Vec3 b3World_GetGravity (b3WorldId worldId)
 Get the gravity vector.
void b3World_Explode (b3WorldId worldId, const b3ExplosionDef *explosionDef)
 Apply a radial explosion.
void b3World_SetContactTuning (b3WorldId worldId, float hertz, float dampingRatio, float contactSpeed)
 Adjust contact tuning parameters.
void b3World_SetContactRecycleDistance (b3WorldId worldId, float recycleDistance)
 Set the contact point recycling distance.
float b3World_GetContactRecycleDistance (b3WorldId worldId)
 Get the contact point recycling distance. Usually in meters.
void b3World_SetMaximumLinearSpeed (b3WorldId worldId, float maximumLinearSpeed)
 Set the maximum linear speed. Usually in m/s.
float b3World_GetMaximumLinearSpeed (b3WorldId worldId)
 Get the maximum linear speed. Usually in m/s.
void b3World_EnableWarmStarting (b3WorldId worldId, bool flag)
 Enable/disable constraint warm starting.
bool b3World_IsWarmStartingEnabled (b3WorldId worldId)
 Is constraint warm starting enabled?
int b3World_GetAwakeBodyCount (b3WorldId worldId)
 Get the number of awake bodies.
b3Profile b3World_GetProfile (b3WorldId worldId)
 Get the current world performance profile.
b3Counters b3World_GetCounters (b3WorldId worldId)
 Get world counters and sizes.
b3Capacity b3World_GetMaxCapacity (b3WorldId worldId)
 Get max capacity. This can be used with b3WorldDef to avoid run-time allocations and copies.
void b3World_SetUserData (b3WorldId worldId, void *userData)
 Set the user data pointer.
void * b3World_GetUserData (b3WorldId worldId)
 Get the user data pointer.
void b3World_SetFrictionCallback (b3WorldId worldId, b3FrictionCallback *callback)
 Set the friction callback. Passing NULL resets to default.
void b3World_SetRestitutionCallback (b3WorldId worldId, b3RestitutionCallback *callback)
 Set the restitution callback. Passing NULL resets to default.
void b3World_SetWorkerCount (b3WorldId worldId, int count)
 Set the worker count. Must be in the range [1, B3_MAX_WORKERS].
int b3World_GetWorkerCount (b3WorldId worldId)
 Get the worker count.
void b3World_DumpMemoryStats (b3WorldId worldId)
 Dump memory stats to log.
void b3World_DumpShapeBounds (b3WorldId worldId, b3BodyType type)
 Dump shape bounds to box3d_bounds.txt.
void b3World_RebuildStaticTree (b3WorldId worldId)
 This is for internal testing.
void b3World_EnableSpeculative (b3WorldId worldId, bool flag)
 This is for internal testing.
void b3World_DumpAwake (b3WorldId worldId)
 Dump world to a text file.
void b3World_Dump (b3WorldId worldId)
 Dump world to a text file. Meshes are saved to binary b3m files.
b3WorldDef b3DefaultWorldDef (void)
 Use this to initialize your world definition.
b3ExplosionDef b3DefaultExplosionDef (void)
 Use this to initialize your explosion definition.

Detailed Description

These functions allow you to create a simulation world.

You can add rigid bodies and joint constraints to the world and run the simulation. You can get contact information to get contact points and normals as well as events. You can query the world, checking for overlaps and casting rays or shapes. There is also debugging information such as debug draw, timing information, and counters. You can find documentation here: https://box2d.org/


Data Structure Documentation

◆ b3Capacity

struct b3Capacity

Optional world capacities that can be use to avoid run-time allocations.

Data Fields
int contactCount Number of expected contacts.
int dynamicBodyCount Number of expected dynamic and kinematic bodies.
int dynamicShapeCount Number of expected dynamic and kinematic shapes.
int staticBodyCount Number of expected static bodies.
int staticShapeCount Number of expected static shapes.

◆ b3WorldDef

struct b3WorldDef

World definition used to create a simulation world.

Must be initialized using b3DefaultWorldDef.

Collaboration diagram for b3WorldDef:
Data Fields
b3Capacity capacity Optional initial capacities.
float contactDampingRatio Contact bounciness.

Non-dimensional. You can speed up overlap recovery by decreasing this with the trade-off that overlap resolution becomes more energetic.

float contactHertz Contact stiffness. Cycles per second. Increasing this increases the speed of overlap recovery, but can introduce jitter.
float contactSpeed This parameter controls how fast overlap is resolved and usually has units of meters per second.

This only puts a cap on the resolution speed. The resolution speed is increased by increasing the hertz and/or decreasing the damping ratio.

b3CreateDebugShapeCallback * createDebugShape Used to create debug draw shapes.

This is called when a shape is first drawn using b3DebugDraw.

b3DestroyDebugShapeCallback * destroyDebugShape Used to destroy debug draw shapes. This is called when a shape is modified or destroyed.
bool enableContinuous Enable continuous collision.
bool enableSleep Can bodies go to sleep to improve performance.
b3EnqueueTaskCallback * enqueueTask function to spawn task
b3FinishTaskCallback * finishTask function to finish a task
b3FrictionCallback * frictionCallback Optional mixing callback for friction. The default uses sqrt(frictionA * frictionB).
b3Vec3 gravity Gravity vector. Box3D has no up-vector defined.
float hitEventThreshold Hit event speed threshold, usually in m/s.

Collisions above this speed can generate hit events if the shape also enables hit events.

int internalValue Used internally to detect a valid definition. DO NOT SET.
float maximumLinearSpeed Maximum linear speed. Usually meters per second.
b3RestitutionCallback * restitutionCallback Optional mixing callback for restitution. The default uses max(restitutionA, restitutionB).
float restitutionThreshold Restitution speed threshold, usually in m/s.

Collisions above this speed have restitution applied (will bounce).

void * userData User data associated with a world.
void * userDebugShapeContext This is passed to the debug shape callbacks to provide a user context.
void * userTaskContext User context that is provided to enqueueTask and finishTask.
uint32_t workerCount Number of workers to use with the provided task system.

Box3D performs best when using only performance cores and accessing a single L2 cache. Efficiency cores and hyper-threading provide little benefit and may even harm performance. This is clamped to the range [1, B3_MAX_WORKERS]. Using a value above 1 will turn on multithreading. If task callbacks are provided then Box3D will use the user provided task system. Otherwise Box3D will create threads and use an internal scheduler.

◆ b3ExplosionDef

struct b3ExplosionDef

The explosion definition is used to configure options for explosions.

Explosions consider shape geometry when computing the impulse.

Collaboration diagram for b3ExplosionDef:
Data Fields
float falloff The falloff distance beyond the radius. Impulse is reduced to zero at this distance.
float impulsePerArea Impulse per unit area.

This applies an impulse according to the shape area that is facing the explosion. Explosions only apply to spheres, capsules, and hulls. This may be negative for implosions.

uint64_t maskBits Mask bits to filter shapes.
b3Pos position The center of the explosion in world space.
float radius The radius of the explosion.

Typedef Documentation

◆ b3CastResultFcn

typedef float b3CastResultFcn(b3ShapeId shapeId, b3Pos point, b3Vec3 normal, float fraction, uint64_t userMaterialId, int triangleIndex, int childIndex, void *context)

Prototype callback for ray casts.

Called for each shape found in the query. You control how the ray cast proceeds by returning a float: return -1: ignore this shape and continue return 0: terminate the ray cast return fraction: clip the ray to this point return 1: don't clip the ray and continue

Parameters
shapeIdthe shape hit by the ray
pointthe point of initial intersection
normalthe normal vector at the point of intersection
fractionthe fraction along the ray at the point of intersection
userMaterialIdthe shape or triangle surface type
triangleIndexthe triangle index for mesh or height field shapes or -1 for other shape types
childIndexthe child shape index for compound shapes
contextthe user context
Returns
-1 to filter, 0 to terminate, fraction to clip the ray for closest hit, 1 to continue
See also
b3World_CastRay

◆ b3CustomFilterFcn

typedef bool b3CustomFilterFcn(b3ShapeId shapeIdA, b3ShapeId shapeIdB, void *context)

Prototype for a contact filter callback.

This is called when a contact pair is considered for collision. This allows you to perform custom logic to prevent collision between shapes. This is only called if one of the two shapes has custom filtering enabled.

See also
b3ShapeDef. Notes:
  • this function must be thread-safe
  • this is only called if one of the two shapes has enabled custom filtering
  • this is called only for awake dynamic bodies Return false if you want to disable the Shape Collision
Warning
Do not attempt to modify the world inside this callback

◆ b3EnqueueTaskCallback

typedef void * b3EnqueueTaskCallback(b3TaskCallback *task, void *taskContext, void *userContext, const char *taskName)

These functions can be provided to Box3D to invoke a task system.

Returns a pointer to the user's task object. May be nullptr. A nullptr indicates to Box3D that the work was executed serially within the callback and there is no need to call b3FinishTaskCallback. Otherwise the returned value must be non-null will be passed to b3FinishTaskCallback as the userTask.

Parameters
taskthe Box3D task to be called by the scheduler
taskContextthe Box3D context object that the scheduler must pass to the task
userContextthe scheduler context object that is opaque to Box3D
taskNamethe Box3D task name that the scheduler can use for diagnostics

◆ b3FinishTaskCallback

typedef void b3FinishTaskCallback(void *userTask, void *userContext)

Finishes a user task object that wraps a Box3D task.

This must block until the task has completed. The step blocks here on the tasks it spawned, so b3World_Step holds its stack across every fork/join. Drive it from a thread you can dedicate to the step, or from a fiber this callback can park to free the underlying thread. In a job system that cannot park a job's stack, do not call b3World_Step from inside a job: a job that blocks on its own sub-jobs without yielding its thread can deadlock. The in-tree scheduler instead runs other pending tasks on the waiting thread.

◆ b3FrictionCallback

typedef float b3FrictionCallback(float frictionA, uint64_t userMaterialIdA, float frictionB, uint64_t userMaterialIdB)

Optional friction mixing callback.

This intentionally provides no context objects because this is called from a worker thread.

Warning
This function should not attempt to modify Box3D state or user application state.

◆ b3OverlapResultFcn

typedef bool b3OverlapResultFcn(b3ShapeId shapeId, void *context)

Prototype callback for overlap queries.

Called for each shape found in the query.

See also
b3World_OverlapAABB
Returns
false to terminate the query.

◆ b3PreSolveFcn

typedef bool b3PreSolveFcn(b3ShapeId shapeIdA, b3ShapeId shapeIdB, b3Pos point, b3Vec3 normal, void *context)

Prototype for a pre-solve callback.

This is called after a contact is updated. This allows you to inspect a collision before it goes to the solver. Notes:

  • this function must be thread-safe
  • this is only called if the shape has enabled pre-solve events
  • this may be called for awake dynamic bodies and sensors
  • this is not called for sensors Return false if you want to disable the contact this step This has limited information because it is used during CCD which does not have the full contact manifold.
    Warning
    Do not attempt to modify the world inside this callback

◆ b3RestitutionCallback

typedef float b3RestitutionCallback(float restitutionA, uint64_t userMaterialIdA, float restitutionB, uint64_t userMaterialIdB)

Optional restitution mixing callback.

This intentionally provides no context objects because this is called from a worker thread.

Warning
This function should not attempt to modify Box3D state or user application state.

◆ b3TaskCallback

typedef void b3TaskCallback(void *taskContext)

Task interface This is the prototype for a Box3D task.

Your task system is expected to run this callback on a worker thread, exactly once per enqueue, passing back the same taskContext pointer supplied to b3EnqueueTaskCallback.

Function Documentation

◆ b3CreateWorld()

b3WorldId b3CreateWorld ( const b3WorldDef * def)

Create a world for rigid body simulation.

A world contains bodies, shapes, and constraints. You may create up to 128 worlds. Each world is completely independent and may be simulated in parallel.

Returns
the world id.

◆ b3World_CastMover()

float b3World_CastMover ( b3WorldId worldId,
b3Pos origin,
const b3Capsule * mover,
b3Vec3 translation,
b3QueryFilter filter,
b3MoverFilterFcn * fcn,
void * context )

Cast a capsule mover through the world.

This is a special shape cast that handles sliding along other shapes while reducing clipping. This is not a good source of information about what the mover is touching. Instead use the planes returned by b3World_CollideMover.

Parameters
worldIdWorld to cast the mover against
originWorld position the mover capsule is relative to
moverCapsule mover, relative to the origin
translationDesired mover translation
filterContains bit flags to filter unwanted shapes from the results
fcnOptional callback for custom shape filtering
contextA user context that is passed along to the callback function
Returns
the translation fraction

◆ b3World_CastRay()

b3TreeStats b3World_CastRay ( b3WorldId worldId,
b3Pos origin,
b3Vec3 translation,
b3QueryFilter filter,
b3CastResultFcn * fcn,
void * context )

Cast a ray into the world to collect shapes in the path of the ray.

Your callback function controls whether you get the closest point, any point, or n-points.

Note
The callback function may receive shapes in any order
Parameters
worldIdThe world to cast the ray against
originThe start point of the ray
translationThe translation of the ray from the start point to the end point
filterContains bit flags to filter unwanted shapes from the results
fcnA user implemented callback function
contextA user context that is passed along to the callback function
Returns
traversal performance counters

◆ b3World_CastRayClosest()

b3RayResult b3World_CastRayClosest ( b3WorldId worldId,
b3Pos origin,
b3Vec3 translation,
b3QueryFilter filter )

Cast a ray into the world to collect the closest hit.

This is a convenience function. Ignores initial overlap. This is less general than b3World_CastRay() and does not allow for custom filtering.

◆ b3World_CastShape()

b3TreeStats b3World_CastShape ( b3WorldId worldId,
b3Pos origin,
const b3ShapeProxy * proxy,
b3Vec3 translation,
b3QueryFilter filter,
b3CastResultFcn * fcn,
void * context )

Cast a shape through the world.

Similar to a cast ray except that a shape is cast instead of a point. The proxy points are relative to the origin and the hit points come back as world positions, so the cast stays precise far from the world origin.

See also
b3World_CastRay

◆ b3World_CollideMover()

void b3World_CollideMover ( b3WorldId worldId,
b3Pos origin,
const b3Capsule * mover,
b3QueryFilter filter,
b3PlaneResultFcn * fcn,
void * context )

Collide a capsule mover with the world, gathering collision planes that can be fed to b3SolvePlanes.

Useful for kinematic character movement. The mover and the returned planes are relative to the origin.

◆ b3World_DumpAwake()

void b3World_DumpAwake ( b3WorldId worldId)

Dump world to a text file.

Saves only awake bodies and associated static bodies. Meshes are saved to binary b3m files.

◆ b3World_EnableContinuous()

void b3World_EnableContinuous ( b3WorldId worldId,
bool flag )

Enable/disable continuous collision between dynamic and static bodies.

Generally you should keep continuous collision enabled to prevent fast moving objects from going through static objects. The performance gain from disabling continuous collision is minor.

See also
b3WorldDef

◆ b3World_EnableSleeping()

void b3World_EnableSleeping ( b3WorldId worldId,
bool flag )

Enable/disable sleep.

If your application does not need sleeping, you can gain some performance by disabling sleep completely at the world level.

See also
b3WorldDef

◆ b3World_EnableWarmStarting()

void b3World_EnableWarmStarting ( b3WorldId worldId,
bool flag )

Enable/disable constraint warm starting.

Advanced feature for testing. Disabling warm starting greatly reduces stability and provides no performance gain.

◆ b3World_Explode()

void b3World_Explode ( b3WorldId worldId,
const b3ExplosionDef * explosionDef )

Apply a radial explosion.

Parameters
worldIdThe world id
explosionDefThe explosion definition

◆ b3World_GetBounds()

b3AABB b3World_GetBounds ( b3WorldId worldId)

Get the world's bounds.

This is the bounding box that covers the current simulation. May have a small amount of padding.

◆ b3World_OverlapShape()

b3TreeStats b3World_OverlapShape ( b3WorldId worldId,
b3Pos origin,
const b3ShapeProxy * proxy,
b3QueryFilter filter,
b3OverlapResultFcn * fcn,
void * context )

Overlap test for all shapes that overlap the provided shape proxy.

The proxy points are relative to the world origin, which lets the query stay precise far from the world origin.

◆ b3World_SetContactRecycleDistance()

void b3World_SetContactRecycleDistance ( b3WorldId worldId,
float recycleDistance )

Set the contact point recycling distance.

Setting this to zero disables contact point recycling. Usually in meters.

◆ b3World_SetContactTuning()

void b3World_SetContactTuning ( b3WorldId worldId,
float hertz,
float dampingRatio,
float contactSpeed )

Adjust contact tuning parameters.

Parameters
worldIdThe world id
hertzThe contact stiffness (cycles per second)
dampingRatioThe contact bounciness with 1 being critical damping (non-dimensional)
contactSpeedThe maximum contact constraint push out speed (meters per second)
Note
Advanced feature

◆ b3World_SetGravity()

void b3World_SetGravity ( b3WorldId worldId,
b3Vec3 gravity )

Set the gravity vector for the entire world.

Box3D has no concept of an up direction and this is left as a decision for the application. Usually in m/s^2.

See also
b3WorldDef

◆ b3World_SetHitEventThreshold()

void b3World_SetHitEventThreshold ( b3WorldId worldId,
float value )

Adjust the hit event threshold.

This controls the collision speed needed to generate a b3ContactHitEvent. Usually in meters per second.

See also
b3WorldDef::hitEventThreshold

◆ b3World_SetRestitutionThreshold()

void b3World_SetRestitutionThreshold ( b3WorldId worldId,
float value )

Adjust the restitution threshold.

It is recommended not to make this value very small because it will prevent bodies from sleeping. Usually in meters per second.

See also
b3WorldDef

◆ b3World_Step()

void b3World_Step ( b3WorldId worldId,
float timeStep,
int subStepCount )

Simulate a world for one time step.

This performs collision detection, integration, and constraint solution.

Parameters
worldIdThe world to simulate
timeStepThe amount of time to simulate, this should be a fixed number. Usually 1/60.
subStepCountThe number of sub-steps, increasing the sub-step count can increase accuracy. Usually 4.