Box2D 3.1.0
A 2D physics engine for games
|
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 | b2DebugDraw |
This struct holds callbacks you can implement to draw a Box2D world. More... | |
Typedefs | |
typedef void | b2TaskCallback(int32_t startIndex, int32_t endIndex, uint32_t workerIndex, void *taskContext) |
Task interface This is prototype for a Box2D task. | |
typedef void * | b2EnqueueTaskCallback(b2TaskCallback *task, int32_t itemCount, int32_t 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 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 | |
b2WorldId | b2CreateWorld (const b2WorldDef *def) |
Create a world for rigid body simulation. | |
void | b2DestroyWorld (b2WorldId worldId) |
Destroy a world. | |
bool | b2World_IsValid (b2WorldId id) |
World id validation. Provides validation for up to 64K allocations. | |
void | b2World_Step (b2WorldId worldId, float timeStep, int subStepCount) |
Simulate a world for one time step. | |
void | b2World_Draw (b2WorldId worldId, b2DebugDraw *draw) |
Call this to draw shapes and other debug draw data. | |
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. | |
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. | |
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. | |
void | b2World_OverlapAABB (b2WorldId worldId, b2AABB aabb, b2QueryFilter filter, b2OverlapResultFcn *fcn, void *context) |
Overlap test for all shapes that potentially overlap the provided AABB. | |
void | b2World_OverlapCircle (b2WorldId worldId, const b2Circle *circle, b2Transform transform, b2QueryFilter filter, b2OverlapResultFcn *fcn, void *context) |
Overlap test for for all shapes that overlap the provided circle. | |
void | b2World_OverlapCapsule (b2WorldId worldId, const b2Capsule *capsule, b2Transform transform, b2QueryFilter filter, b2OverlapResultFcn *fcn, void *context) |
Overlap test for all shapes that overlap the provided capsule. | |
void | b2World_OverlapPolygon (b2WorldId worldId, const b2Polygon *polygon, b2Transform transform, b2QueryFilter filter, b2OverlapResultFcn *fcn, void *context) |
Overlap test for all shapes that overlap the provided polygon. | |
void | 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. | |
b2RayResult | b2World_CastRayClosest (b2WorldId worldId, b2Vec2 origin, b2Vec2 translation, b2QueryFilter filter) |
Cast a ray into the world to collect the closest hit. | |
void | b2World_CastCircle (b2WorldId worldId, const b2Circle *circle, b2Transform originTransform, b2Vec2 translation, b2QueryFilter filter, b2CastResultFcn *fcn, void *context) |
Cast a circle through the world. Similar to a cast ray except that a circle is cast instead of a point. | |
void | b2World_CastCapsule (b2WorldId worldId, const b2Capsule *capsule, b2Transform originTransform, b2Vec2 translation, b2QueryFilter filter, b2CastResultFcn *fcn, void *context) |
Cast a capsule through the world. Similar to a cast ray except that a capsule is cast instead of a point. | |
void | b2World_CastPolygon (b2WorldId worldId, const b2Polygon *polygon, b2Transform originTransform, b2Vec2 translation, b2QueryFilter filter, b2CastResultFcn *fcn, void *context) |
Cast a polygon through the world. Similar to a cast ray except that a polygon is cast instead of a point. | |
void | b2World_EnableSleeping (b2WorldId worldId, bool flag) |
Enable/disable sleep. | |
void | b2World_EnableContinuous (b2WorldId worldId, bool flag) |
Enable/disable continuous collision between dynamic and static bodies. | |
void | b2World_SetRestitutionThreshold (b2WorldId worldId, float value) |
Adjust the restitution threshold. | |
void | b2World_SetHitEventThreshold (b2WorldId worldId, float value) |
Adjust the hit event threshold. | |
void | b2World_SetCustomFilterCallback (b2WorldId worldId, b2CustomFilterFcn *fcn, void *context) |
Register the custom filter callback. This is optional. | |
void | b2World_SetPreSolveCallback (b2WorldId worldId, b2PreSolveFcn *fcn, void *context) |
Register the pre-solve callback. This is optional. | |
void | b2World_SetGravity (b2WorldId worldId, b2Vec2 gravity) |
Set the gravity vector for the entire world. | |
b2Vec2 | b2World_GetGravity (b2WorldId worldId) |
Get the gravity vector. | |
void | b2World_Explode (b2WorldId worldId, b2Vec2 position, float radius, float impulse) |
Apply a radial explosion. | |
void | b2World_SetContactTuning (b2WorldId worldId, float hertz, float dampingRatio, float pushVelocity) |
Adjust contact tuning parameters. | |
void | b2World_EnableWarmStarting (b2WorldId worldId, bool flag) |
Enable/disable constraint warm starting. | |
b2Profile | b2World_GetProfile (b2WorldId worldId) |
Get the current world performance profile. | |
b2Counters | b2World_GetCounters (b2WorldId worldId) |
Get world counters and sizes. | |
void | b2World_DumpMemoryStats (b2WorldId worldId) |
Dump memory stats to box2d_memory.txt. | |
b2WorldDef | b2DefaultWorldDef (void) |
Use this to initialize your world 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. |
float | contactHertz | Contact stiffness. Cycles per second. |
float | contactPushoutVelocity | This parameter controls how fast overlap is resolved and has units of meters per second. |
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. |
b2Vec2 | gravity | Gravity vector. Box2D has no up-vector defined. |
float | hitEventThreshold | Threshold velocity for hit events. Usually meters per second. |
int32_t | 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 | maximumLinearVelocity | Maximum linear velocity. Usually meters per second. |
float | restitutionThreshold |
Restitution velocity threshold, usually in m/s. Collisions above this speed have restitution applied (will bounce). |
void * | userTaskContext | User context that is provided to enqueueTask and finishTask. |
int32_t | 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 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 | drawAABBs | Option to draw the bounding boxes for shapes. |
void(*)(b2Vec2 p1, b2Vec2 p2, float radius, b2HexColor color, void *context) | DrawCapsule | Draw a capsule. |
void(*)(b2Vec2 center, float radius, b2HexColor color, void *context) | DrawCircle | Draw a circle. |
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 | 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) | DrawPoint | Draw a point. |
void(*)(const b2Vec2 *vertices, int vertexCount, b2HexColor color, void *context) | DrawPolygon | Draw a closed polygon provided in CCW order. |
void(*)(b2Vec2 p1, b2Vec2 p2, b2HexColor color, void *context) | DrawSegment | Draw a line segment. |
bool | drawShapes | Option to draw shapes. |
void(*)(b2Vec2 p1, b2Vec2 p2, float radius, b2HexColor color, void *context) | DrawSolidCapsule | Draw a solid capsule. |
void(*)(b2Transform transform, float radius, b2HexColor color, void *context) | DrawSolidCircle | Draw a solid circle. |
void(*)(b2Transform transform, const b2Vec2 *vertices, int vertexCount, float radius, b2HexColor color, void *context) | DrawSolidPolygon | Draw a solid closed polygon provided in CCW order. |
void(*)(b2Vec2 p, const char *s, void *context) | DrawString | Draw a string. |
void(*)(b2Transform transform, void *context) | DrawTransform | 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.
typedef void * b2EnqueueTaskCallback(b2TaskCallback *task, int32_t itemCount, int32_t 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 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 void b2TaskCallback(int32_t startIndex, int32_t 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:
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.
void 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 |
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.
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.
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.
void b2World_EnableWarmStarting | ( | b2WorldId | worldId, |
bool | flag ) |
Enable/disable constraint warm starting.
Advanced feature for testing. Disabling sleeping greatly reduces stability and provides no performance gain.
Apply a radial explosion.
worldId | The world id |
position | The center of the explosion |
radius | The radius of the explosion |
impulse | The impulse of the explosion, typically in kg * m / s or N * s. |
void b2World_SetContactTuning | ( | b2WorldId | worldId, |
float | hertz, | ||
float | dampingRatio, | ||
float | pushVelocity ) |
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) |
pushVelocity | The maximum contact constraint push out velocity (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. Typically in m/s^2.
void b2World_SetHitEventThreshold | ( | b2WorldId | worldId, |
float | value ) |
Adjust the hit event threshold.
This controls the collision velocity needed to generate a b2ContactHitEvent. Typically in meters per second.
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. Typically in meters per second.
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. Typically 1/60. |
subStepCount | The number of sub-steps, increasing the sub-step count can increase accuracy. Typically 4. |