These functions allow you to create a simulation world. More...
Data Structures | |
struct | b2RayResult |
Result from b2World_RayCastClosest. More... | |
struct | b2WorldDef |
World definition used to create a simulation world. More... | |
struct | b2ExplosionDef |
The explosion definition is used to configure options for explosions. More... | |
struct | b2DebugDraw |
This struct holds callbacks you can implement to draw a Box2D world. More... | |
Typedefs | |
typedef void | b2TaskCallback(int startIndex, int endIndex, uint32_t workerIndex, void *taskContext) |
Task interface This is prototype for a Box2D task. | |
typedef void * | b2EnqueueTaskCallback(b2TaskCallback *task, int itemCount, int minRange, void *taskContext, void *userContext) |
These functions can be provided to Box2D to invoke a task system. | |
typedef void | b2FinishTaskCallback(void *userTask, void *userContext) |
Finishes a user task object that wraps a Box2D task. | |
typedef float | b2FrictionCallback(float frictionA, int userMaterialIdA, float frictionB, int userMaterialIdB) |
Optional friction mixing callback. | |
typedef float | b2RestitutionCallback(float restitutionA, int userMaterialIdA, float restitutionB, int userMaterialIdB) |
Optional restitution mixing callback. | |
typedef bool | b2CustomFilterFcn(b2ShapeId shapeIdA, b2ShapeId shapeIdB, void *context) |
Prototype for a contact filter callback. | |
typedef bool | b2PreSolveFcn(b2ShapeId shapeIdA, b2ShapeId shapeIdB, b2Manifold *manifold, void *context) |
Prototype for a pre-solve callback. | |
typedef bool | b2OverlapResultFcn(b2ShapeId shapeId, void *context) |
Prototype callback for overlap queries. | |
typedef float | b2CastResultFcn(b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void *context) |
Prototype callback for ray casts. | |
Functions | |
B2_API b2WorldId | b2CreateWorld (const b2WorldDef *def) |
Create a world for rigid body simulation. | |
B2_API void | b2DestroyWorld (b2WorldId worldId) |
Destroy a world. | |
B2_API bool | b2World_IsValid (b2WorldId id) |
World id validation. Provides validation for up to 64K allocations. | |
B2_API void | b2World_Step (b2WorldId worldId, float timeStep, int subStepCount) |
Simulate a world for one time step. | |
B2_API void | b2World_Draw (b2WorldId worldId, b2DebugDraw *draw) |
Call this to draw shapes and other debug draw data. | |
B2_API b2BodyEvents | b2World_GetBodyEvents (b2WorldId worldId) |
Get the body events for the current time step. The event data is transient. Do not store a reference to this data. | |
B2_API b2SensorEvents | b2World_GetSensorEvents (b2WorldId worldId) |
Get sensor events for the current time step. The event data is transient. Do not store a reference to this data. | |
B2_API b2ContactEvents | b2World_GetContactEvents (b2WorldId worldId) |
Get contact events for this current time step. The event data is transient. Do not store a reference to this data. | |
B2_API b2TreeStats | b2World_OverlapAABB (b2WorldId worldId, b2AABB aabb, b2QueryFilter filter, b2OverlapResultFcn *fcn, void *context) |
Overlap test for all shapes that potentially overlap the provided AABB. | |
B2_API b2TreeStats | b2World_OverlapShape (b2WorldId worldId, const b2ShapeProxy *proxy, b2QueryFilter filter, b2OverlapResultFcn *fcn, void *context) |
Overlap test for all shapes that overlap the provided shape proxy. | |
B2_API b2TreeStats | b2World_CastRay (b2WorldId worldId, b2Vec2 origin, b2Vec2 translation, b2QueryFilter filter, b2CastResultFcn *fcn, void *context) |
Cast a ray into the world to collect shapes in the path of the ray. | |
B2_API b2RayResult | b2World_CastRayClosest (b2WorldId worldId, b2Vec2 origin, b2Vec2 translation, b2QueryFilter filter) |
Cast a ray into the world to collect the closest hit. | |
B2_API b2TreeStats | b2World_CastShape (b2WorldId worldId, const b2ShapeProxy *proxy, b2Vec2 translation, b2QueryFilter filter, b2CastResultFcn *fcn, void *context) |
Cast a shape through the world. | |
B2_API float | b2World_CastMover (b2WorldId worldId, const b2Capsule *mover, b2Vec2 translation, b2QueryFilter filter) |
Cast a capsule mover through the world. | |
B2_API void | b2World_CollideMover (b2WorldId worldId, const b2Capsule *mover, b2QueryFilter filter, b2PlaneResultFcn *fcn, void *context) |
Collide a capsule mover with the world, gathering collision planes that can be fed to b2SolvePlanes. | |
B2_API void | b2World_EnableSleeping (b2WorldId worldId, bool flag) |
Enable/disable sleep. | |
B2_API bool | b2World_IsSleepingEnabled (b2WorldId worldId) |
Is body sleeping enabled? | |
B2_API void | b2World_EnableContinuous (b2WorldId worldId, bool flag) |
Enable/disable continuous collision between dynamic and static bodies. | |
B2_API bool | b2World_IsContinuousEnabled (b2WorldId worldId) |
Is continuous collision enabled? | |
B2_API void | b2World_SetRestitutionThreshold (b2WorldId worldId, float value) |
Adjust the restitution threshold. | |
B2_API float | b2World_GetRestitutionThreshold (b2WorldId worldId) |
Get the the restitution speed threshold. Usually in meters per second. | |
B2_API void | b2World_SetHitEventThreshold (b2WorldId worldId, float value) |
Adjust the hit event threshold. | |
B2_API float | b2World_GetHitEventThreshold (b2WorldId worldId) |
Get the the hit event speed threshold. Usually in meters per second. | |
B2_API void | b2World_SetCustomFilterCallback (b2WorldId worldId, b2CustomFilterFcn *fcn, void *context) |
Register the custom filter callback. This is optional. | |
B2_API void | b2World_SetPreSolveCallback (b2WorldId worldId, b2PreSolveFcn *fcn, void *context) |
Register the pre-solve callback. This is optional. | |
B2_API void | b2World_SetGravity (b2WorldId worldId, b2Vec2 gravity) |
Set the gravity vector for the entire world. | |
B2_API b2Vec2 | b2World_GetGravity (b2WorldId worldId) |
Get the gravity vector. | |
B2_API void | b2World_Explode (b2WorldId worldId, const b2ExplosionDef *explosionDef) |
Apply a radial explosion. | |
B2_API void | b2World_SetContactTuning (b2WorldId worldId, float hertz, float dampingRatio, float pushSpeed) |
Adjust contact tuning parameters. | |
B2_API void | b2World_SetJointTuning (b2WorldId worldId, float hertz, float dampingRatio) |
Adjust joint tuning parameters. | |
B2_API void | b2World_SetMaximumLinearSpeed (b2WorldId worldId, float maximumLinearSpeed) |
Set the maximum linear speed. Usually in m/s. | |
B2_API float | b2World_GetMaximumLinearSpeed (b2WorldId worldId) |
Get the maximum linear speed. Usually in m/s. | |
B2_API void | b2World_EnableWarmStarting (b2WorldId worldId, bool flag) |
Enable/disable constraint warm starting. | |
B2_API bool | b2World_IsWarmStartingEnabled (b2WorldId worldId) |
Is constraint warm starting enabled? | |
B2_API int | b2World_GetAwakeBodyCount (b2WorldId worldId) |
Get the number of awake bodies. | |
B2_API b2Profile | b2World_GetProfile (b2WorldId worldId) |
Get the current world performance profile. | |
B2_API b2Counters | b2World_GetCounters (b2WorldId worldId) |
Get world counters and sizes. | |
B2_API void | b2World_SetUserData (b2WorldId worldId, void *userData) |
Set the user data pointer. | |
B2_API void * | b2World_GetUserData (b2WorldId worldId) |
Get the user data pointer. | |
B2_API void | b2World_SetFrictionCallback (b2WorldId worldId, b2FrictionCallback *callback) |
Set the friction callback. Passing NULL resets to default. | |
B2_API void | b2World_SetRestitutionCallback (b2WorldId worldId, b2RestitutionCallback *callback) |
Set the restitution callback. Passing NULL resets to default. | |
B2_API void | b2World_DumpMemoryStats (b2WorldId worldId) |
Dump memory stats to box2d_memory.txt. | |
B2_API void | b2World_RebuildStaticTree (b2WorldId worldId) |
This is for internal testing. | |
B2_API void | b2World_EnableSpeculative (b2WorldId worldId, bool flag) |
This is for internal testing. | |
b2WorldDef | b2DefaultWorldDef (void) |
Use this to initialize your world definition. | |
b2ExplosionDef | b2DefaultExplosionDef (void) |
Use this to initialize your explosion definition. | |
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 to 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/
struct b2RayResult |
struct b2WorldDef |
World definition used to create a simulation world.
Must be initialized using b2DefaultWorldDef().
Data Fields | ||
---|---|---|
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. |
bool | enableContinuous | Enable continuous collision. |
bool | enableSleep | Can bodies go to sleep to improve performance. |
b2EnqueueTaskCallback * | enqueueTask | Function to spawn tasks. |
b2FinishTaskCallback * | finishTask | Function to finish a task. |
b2FrictionCallback * | frictionCallback | Optional mixing callback for friction. The default uses sqrt(frictionA * frictionB). |
b2Vec2 | gravity | Gravity vector. Box2D has no up-vector defined. |
float | hitEventThreshold | Threshold speed for hit events. Usually meters per second. |
int | internalValue | Used internally to detect a valid definition. DO NOT SET. |
float | jointDampingRatio | Joint bounciness. Non-dimensional. |
float | jointHertz | Joint stiffness. Cycles per second. |
float | maxContactPushSpeed |
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. |
float | maximumLinearSpeed | Maximum linear speed. Usually meters per second. |
b2RestitutionCallback * | 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. |
void * | userTaskContext | User context that is provided to enqueueTask and finishTask. |
int | workerCount |
Number of workers to use with the provided task system. Box2D 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.
|
struct b2ExplosionDef |
The explosion definition is used to configure options for explosions.
Explosions consider shape geometry when computing the impulse.
Data Fields | ||
---|---|---|
float | falloff | The falloff distance beyond the radius. Impulse is reduced to zero at this distance. |
float | impulsePerLength |
Impulse per unit length. This applies an impulse according to the shape perimeter that is facing the explosion. Explosions only apply to circles, capsules, and polygons. This may be negative for implosions. |
uint64_t | maskBits | Mask bits to filter shapes. |
b2Vec2 | position | The center of the explosion in world space. |
float | radius | The radius of the explosion. |
struct b2DebugDraw |
This struct holds callbacks you can implement to draw a Box2D world.
This structure should be zero initialized.
Data Fields | ||
---|---|---|
void * | context | User context that is passed as an argument to drawing callback functions. |
bool | drawBodyNames | Option to draw body names. |
bool | drawBounds | Option to draw the bounding boxes for shapes. |
void(*)(b2Vec2 center, float radius, b2HexColor color, void *context) | DrawCircleFcn | Draw a circle. |
bool | drawContactFeatures | Option to draw contact feature ids. |
bool | drawContactImpulses | Option to draw contact normal impulses. |
bool | drawContactNormals | Option to draw contact normals. |
bool | drawContacts | Option to draw contact points. |
bool | drawFrictionImpulses | Option to draw contact friction impulses. |
bool | drawGraphColors | Option to visualize the graph coloring used for contacts and joints. |
b2AABB | drawingBounds | Bounds to use if restricting drawing to a rectangular region. |
bool | drawIslands | Option to draw islands as bounding boxes. |
bool | drawJointExtras | Option to draw additional information for joints. |
bool | drawJoints | Option to draw joints. |
bool | drawMass | Option to draw the mass and center of mass of dynamic bodies. |
void(*)(b2Vec2 p, float size, b2HexColor color, void *context) | DrawPointFcn | Draw a point. |
void(*)(const b2Vec2 *vertices, int vertexCount, b2HexColor color, void *context) | DrawPolygonFcn | Draw a closed polygon provided in CCW order. |
void(*)(b2Vec2 p1, b2Vec2 p2, b2HexColor color, void *context) | DrawSegmentFcn | Draw a line segment. |
bool | drawShapes | Option to draw shapes. |
void(*)(b2Vec2 p1, b2Vec2 p2, float radius, b2HexColor color, void *context) | DrawSolidCapsuleFcn | Draw a solid capsule. |
void(*)(b2Transform transform, float radius, b2HexColor color, void *context) | DrawSolidCircleFcn | Draw a solid circle. |
void(*)(b2Transform transform, const b2Vec2 *vertices, int vertexCount, float radius, b2HexColor color, void *context) | DrawSolidPolygonFcn | Draw a solid closed polygon provided in CCW order. |
void(*)(b2Vec2 p, const char *s, b2HexColor color, void *context) | DrawStringFcn | Draw a string in world space. |
void(*)(b2Transform transform, void *context) | DrawTransformFcn | Draw a transform. Choose your own length scale. |
bool | useDrawingBounds | Option to restrict drawing to a rectangular region. May suffer from unstable depth sorting. |
typedef float b2CastResultFcn(b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, 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
shapeId | the shape hit by the ray |
point | the point of initial intersection |
normal | the normal vector at the point of intersection |
fraction | the fraction along the ray at the point of intersection |
context | the user 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. Notes:
typedef void * b2EnqueueTaskCallback(b2TaskCallback *task, int itemCount, int minRange, void *taskContext, void *userContext) |
These functions can be provided to Box2D to invoke a task system.
These are designed to work well with enkiTS. Returns a pointer to the user's task object. May be nullptr. A nullptr indicates to Box2D that the work was executed serially within the callback and there is no need to call b2FinishTaskCallback. The itemCount is the number of Box2D work items that are to be partitioned among workers by the user's task system. This is essentially a parallel-for. The minRange parameter is a suggestion of the minimum number of items to assign per worker to reduce overhead. For example, suppose the task is small and that itemCount is 16. A minRange of 8 suggests that your task system should split the work items among just two workers, even if you have more available. In general the range [startIndex, endIndex) send to b2TaskCallback should obey: endIndex - startIndex >= minRange The exception of course is when itemCount < minRange.
typedef float b2FrictionCallback(float frictionA, int userMaterialIdA, float frictionB, int userMaterialIdB) |
Optional friction mixing callback.
This intentionally provides no context objects because this is called from a worker thread.
typedef bool b2OverlapResultFcn(b2ShapeId shapeId, void *context) |
Prototype callback for overlap queries.
Called for each shape found in the query.
typedef bool b2PreSolveFcn(b2ShapeId shapeIdA, b2ShapeId shapeIdB, b2Manifold *manifold, void *context) |
Prototype for a pre-solve callback.
This is called after a contact is updated. This allows you to inspect a contact before it goes to the solver. If you are careful, you can modify the contact manifold (e.g. modify the normal). Notes:
typedef float b2RestitutionCallback(float restitutionA, int userMaterialIdA, float restitutionB, int userMaterialIdB) |
Optional restitution mixing callback.
This intentionally provides no context objects because this is called from a worker thread.
typedef void b2TaskCallback(int startIndex, int endIndex, uint32_t workerIndex, void *taskContext) |
Task interface This is prototype for a Box2D task.
Your task system is expected to invoke the Box2D task with these arguments. The task spans a range of the parallel-for: [startIndex, endIndex) The worker index must correctly identify each worker in the user thread pool, expected in [0, workerCount). A worker must only exist on only one thread at a time and is analogous to the thread index. The task context is the context pointer sent from Box2D when it is enqueued. The startIndex and endIndex are expected in the range [0, itemCount) where itemCount is the argument to b2EnqueueTaskCallback below. Box2D expects startIndex < endIndex and will execute a loop like this:
B2_API b2WorldId b2CreateWorld | ( | const b2WorldDef * | def | ) |
Create a world for rigid body simulation.
A world contains bodies, shapes, and constraints. You make create up to 128 worlds. Each world is completely independent and may be simulated in parallel.
B2_API float b2World_CastMover | ( | b2WorldId | worldId, |
const b2Capsule * | mover, | ||
b2Vec2 | translation, | ||
b2QueryFilter | filter ) |
Cast a capsule mover through the world.
This is a special shape cast that handles sliding along other shapes while reducing clipping.
B2_API b2TreeStats b2World_CastRay | ( | b2WorldId | worldId, |
b2Vec2 | origin, | ||
b2Vec2 | translation, | ||
b2QueryFilter | filter, | ||
b2CastResultFcn * | 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. The ray-cast ignores shapes that contain the starting point.
worldId | The world to cast the ray against |
origin | The start point of the ray |
translation | The translation of the ray from the start point to the end point |
filter | Contains bit flags to filter unwanted shapes from the results |
fcn | A user implemented callback function |
context | A user context that is passed along to the callback function |
B2_API b2RayResult b2World_CastRayClosest | ( | b2WorldId | worldId, |
b2Vec2 | origin, | ||
b2Vec2 | translation, | ||
b2QueryFilter | filter ) |
Cast a ray into the world to collect the closest hit.
This is a convenience function. This is less general than b2World_CastRay() and does not allow for custom filtering.
B2_API b2TreeStats b2World_CastShape | ( | b2WorldId | worldId, |
const b2ShapeProxy * | proxy, | ||
b2Vec2 | translation, | ||
b2QueryFilter | filter, | ||
b2CastResultFcn * | fcn, | ||
void * | context ) |
Cast a shape through the world.
Similar to a cast ray except that a shape is cast instead of a point.
B2_API void b2World_CollideMover | ( | b2WorldId | worldId, |
const b2Capsule * | mover, | ||
b2QueryFilter | filter, | ||
b2PlaneResultFcn * | fcn, | ||
void * | context ) |
Collide a capsule mover with the world, gathering collision planes that can be fed to b2SolvePlanes.
Useful for kinematic character movement.
B2_API void b2World_EnableContinuous | ( | b2WorldId | 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.
B2_API void b2World_EnableSleeping | ( | b2WorldId | 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.
B2_API void b2World_EnableWarmStarting | ( | b2WorldId | worldId, |
bool | flag ) |
Enable/disable constraint warm starting.
Advanced feature for testing. Disabling warm starting greatly reduces stability and provides no performance gain.
B2_API void b2World_Explode | ( | b2WorldId | worldId, |
const b2ExplosionDef * | explosionDef ) |
Apply a radial explosion.
worldId | The world id |
explosionDef | The explosion definition |
B2_API void b2World_SetContactTuning | ( | b2WorldId | worldId, |
float | hertz, | ||
float | dampingRatio, | ||
float | pushSpeed ) |
Adjust contact tuning parameters.
worldId | The world id |
hertz | The contact stiffness (cycles per second) |
dampingRatio | The contact bounciness with 1 being critical damping (non-dimensional) |
pushSpeed | The maximum contact constraint push out speed (meters per second) |
Set the gravity vector for the entire world.
Box2D has no concept of an up direction and this is left as a decision for the application. Usually in m/s^2.
B2_API void b2World_SetHitEventThreshold | ( | b2WorldId | worldId, |
float | value ) |
Adjust the hit event threshold.
This controls the collision speed needed to generate a b2ContactHitEvent. Usually in meters per second.
B2_API void b2World_SetJointTuning | ( | b2WorldId | worldId, |
float | hertz, | ||
float | dampingRatio ) |
Adjust joint tuning parameters.
worldId | The world id |
hertz | The contact stiffness (cycles per second) |
dampingRatio | The contact bounciness with 1 being critical damping (non-dimensional) |
B2_API void b2World_SetRestitutionThreshold | ( | b2WorldId | 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.
B2_API void b2World_Step | ( | b2WorldId | worldId, |
float | timeStep, | ||
int | subStepCount ) |
Simulate a world for one time step.
This performs collision detection, integration, and constraint solution.
worldId | The world to simulate |
timeStep | The amount of time to simulate, this should be a fixed number. Usually 1/60. |
subStepCount | The number of sub-steps, increasing the sub-step count can increase accuracy. Usually 4. |