Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .clang-format
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ BraceWrapping:
AfterUnion: true
BeforeWhile: true

ColumnLimit: 100
ColumnLimit: 120
PointerAlignment: Left
UseTab: Always
BreakConstructorInitializers: BeforeComma
Expand Down
2 changes: 1 addition & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
root = true

[*.{c,h,cpp,inl}]
guidelines = 100
guidelines = 120
guidelines_style = 1px dotted gray
1 change: 1 addition & 0 deletions build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,7 @@ fn buildCTests(b: *Build, target: ResolvedTarget, optimize: OptimizeMode, box2d_
"test/test_shape.c",
"test/test_snapshot.c",
"test/test_sort.c",
"test/test_step.c",
"test/test_table.c",
"test/test_thread.c",
"test/test_world.c",
Expand Down
48 changes: 47 additions & 1 deletion docs/foundation.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,53 @@ def.userTaskContext = myTaskContext;
The worker count is a target. If your threads are busy, Box2D can still finish its work with a
single thread.

The finish callback is optional. Without it `b2World_Step()` waits on an internal semaphore that
the last task of each phase signals. This suits task systems that can launch work but cannot wait
on a single task.

### Stepping without blocking

`b2World_Step()` holds the calling thread until the step is done. Some task systems cannot allow
this, for example a phased or wavefront scheduler where a thread that joins a parallel job cannot
leave it. For these you can drive the step yourself with `b2World_BeginStep()` and
`b2World_ContinueStep()`. Each call runs the serial work between two phases and returns the next
batch of tasks. An empty batch means the step is complete.

```c
b2TaskBatch batch = b2World_BeginStep( worldId, timeStep, subStepCount );
while ( batch.count > 0 )
{
// Run every task in the batch on any threads, in any order, then wait for them.
// MyRunTasks is a function you implement.
MyRunTasks( batch.tasks, batch.count );

batch = b2World_ContinueStep( worldId );
}
```

No callbacks are needed and the built-in scheduler is never created. The worker count still sets
the most tasks in a batch, `workerCount + 2`, and the size of the per-worker data. Each parallel
task claims blocks of work from a shared counter until none are left, so the tasks that run first
do most of the work and a task that starts late returns right away. Fewer threads than tasks costs
only the extra task launches, and you can adjust the worker count with `b2World_SetWorkerCount()` at
runtime.

The rules:

- Call each task function exactly once. Tasks in a batch may run concurrently on any threads.
- Begin and continue may be called from any thread, but never while a task of the current batch is
running.
- The world is locked until the step completes. Do not read or write it in between.
- The tasks of the constraint solver wait on each other. They work with any number of threads,
even when run one after another on a single thread, but a solver task that has started must not
be suspended indefinitely.

One task may be marked `b2Task::deferred`. This is the rebuild of the dynamic tree, which overlaps
the narrow phase and the solver. You may leave it running across continue calls. A later batch
lists it in `b2TaskBatch::joinTasks` and it must be complete before the continue that follows that
batch. If you ignore the flag and run it with the rest of its batch, the step is still correct, it
just loses the overlap.

### Threading considerations

The multithreading design for Box2D is focused on [data
Expand Down Expand Up @@ -188,4 +235,3 @@ improve performance. On x64 CPUs it will use AVX2 if possible and otherwise fall
decision is made at runtime using the [CPUID](https://en.wikipedia.org/wiki/CPUID) instruction. On
ARM64 and Apple Silicon Box2D will use Neon instructions. You can completely disable SIMD using the
preprocessor argument `BOX2D_DISABLE_SIMD`.

7 changes: 7 additions & 0 deletions include/box2d/box2d.h
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,13 @@ B2_API bool b2World_IsValid( b2WorldId id );
/// accuracy. Usually 4.
B2_API void b2World_Step( b2WorldId worldId, float timeStep, int subStepCount );

/// The pull model for tasking. Instead of getting task callbacks from b2World_Step you can call
/// this to kick off a step and get an array of tasks to execute.
B2_API b2TaskBatch b2World_BeginStep( b2WorldId worldId, float timeStep, int subStepCount );

/// Call this after executing each task batch. The step is done when the batch is empty.
B2_API b2TaskBatch b2World_ContinueStep( b2WorldId worldId );

/// Call this to draw shapes and other debug draw data
B2_API void b2World_Draw( b2WorldId worldId, b2DebugDraw* draw );

Expand Down
84 changes: 63 additions & 21 deletions include/box2d/types.h
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,59 @@ typedef void b2TaskCallbackFcn( void* taskContext );
/// 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 b2FinishTaskCallbackFcn.
/// @ingroup world
typedef void* b2EnqueueTaskCallbackFcn( b2TaskCallbackFcn* task, void* taskContext,
void* userContext );
typedef void* b2EnqueueTaskCallbackFcn( b2TaskCallbackFcn* task, void* taskContext, void* userContext );

/// Finishes a user task object that wraps a Box2D task.
/// @ingroup world
typedef void b2FinishTaskCallbackFcn( void* userTask, void* userContext );

/// The task type for the pull model.
typedef enum b2TaskType
{
b2_taskPairs, ///< Finding pairs of potentially colliding shapes. The broad-phase.
b2_taskCollide, ///< Computing contact manifolds. The narrow-phase.
b2_taskTreeRebuild, ///< Rebuilding the bounding volume hierarchy. A long running side task.
b2_taskIslandSplit, ///< Splitting an island in order to let an island sleep.
b2_taskSolver, ///< Solving contraints.
b2_taskFinalize, ///< Updating body transforms and shape bounding boxes.
b2_taskContinuous, ///< Continuous collision detection.
b2_taskSensors, ///< Sensor overlaps and events.
b2_taskTypeCount ///< The type count.
} b2TaskType;

/// A task in the pull model.
typedef struct b2Task
{
/// The task function.
b2TaskCallbackFcn* fcn;

/// The context that must be passed to the task function.
void* context;

/// The task type. Informational.
b2TaskType type;

/// Is this task deferred? This indicates that this task must be joined
/// at a later stage instead of immediately before the next stage.
/// @see b2TaskBatch::joinTasks
bool deferred;
} b2Task;

typedef struct b2TaskBatch
{
/// The regular tasks that must be executed in this stage.
const b2Task* tasks;

/// The task count.
int count;

/// Earlier tasks that must now be joined before the next stage.
const b2Task* joinTasks;

/// The join task count.
int joinCount;
} b2TaskBatch;

/// 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 Box2D state or user application state.
Expand All @@ -47,8 +93,8 @@ typedef float b2FrictionCallbackFcn( float frictionA, uint64_t userMaterialIdA,
/// this is called from a worker thread.
/// @warning This function should not attempt to modify Box2D state or user application state.
/// @ingroup world
typedef float b2RestitutionCallbackFcn( float restitutionA, uint64_t userMaterialIdA,
float restitutionB, uint64_t userMaterialIdB );
typedef float b2RestitutionCallbackFcn( float restitutionA, uint64_t userMaterialIdA, float restitutionB,
uint64_t userMaterialIdB );

/// Result from b2World_CastRayClosest If there is initial overlap the fraction and normal will be
/// zero while the point is an arbitrary point in the overlap region.
Expand Down Expand Up @@ -163,7 +209,7 @@ typedef struct b2WorldDef
/// Function to spawn tasks
b2EnqueueTaskCallbackFcn* enqueueTask;

/// Function to finish a task
/// Function to finish a task. Blocks and helps make progress.
b2FinishTaskCallbackFcn* finishTask;

/// User context that is provided to enqueueTask and finishTask
Expand Down Expand Up @@ -1288,8 +1334,7 @@ typedef bool b2CustomFilterCallbackFcn( b2ShapeId shapeIdA, b2ShapeId shapeIdB,
/// - the supplied manifold impulses are not reliable
/// @warning Do not attempt to modify the world inside this callback
/// @ingroup world
typedef void b2PreSolveCallbackFcn( b2ShapeId shapeIdA, b2ShapeId shapeIdB, b2Manifold* manifold,
void* context );
typedef void b2PreSolveCallbackFcn( b2ShapeId shapeIdA, b2ShapeId shapeIdB, b2Manifold* manifold, void* context );

/// Prototype for a pre-continuous callback. This is called when a time of impact event is computed
/// in continuous collision. This function can be used to skip the event. Unlike the pre-solve
Expand All @@ -1301,8 +1346,8 @@ typedef void b2PreSolveCallbackFcn( b2ShapeId shapeIdA, b2ShapeId shapeIdB, b2Ma
/// - this is not called for sensors Return false if you want to disable the time of impact event.
/// @warning Do not attempt to modify the world inside this callback
/// @ingroup world
typedef bool b2PreContinuousCallbackFcn( b2ShapeId shapeIdA, b2ShapeId shapeIdB, b2Pos point,
b2Vec2 normal, void* context );
typedef bool b2PreContinuousCallbackFcn( b2ShapeId shapeIdA, b2ShapeId shapeIdB, b2Pos point, b2Vec2 normal,
void* context );

/// Prototype callback for overlap queries. Called for each shape found in the query.
/// @see b2World_OverlapAABB
Expand All @@ -1327,13 +1372,11 @@ typedef bool b2OverlapResultCallbackFcn( b2ShapeId shapeId, void* context );
/// @return -1 to filter, 0 to terminate, fraction to clip the ray for closest hit, 1 to continue
/// @see b2World_CastRay
/// @ingroup world
typedef float b2CastResultCallbackFcn( b2ShapeId shapeId, b2Pos point, b2Vec2 normal,
float fraction, void* context );
typedef float b2CastResultCallbackFcn( b2ShapeId shapeId, b2Pos point, b2Vec2 normal, float fraction, void* context );

/// Used to collect collision planes for character movers. Return true to continue gathering planes.
/// @ingroup character
typedef bool b2PlaneResultCallbackFcn( b2ShapeId shapeId, const b2PlaneResult* plane,
void* context );
typedef bool b2PlaneResultCallbackFcn( b2ShapeId shapeId, const b2PlaneResult* plane, void* context );

/**
* @defgroup debug Debug Draw
Expand Down Expand Up @@ -1507,23 +1550,22 @@ B2_API b2HexColor b2GetGraphColor( int index );
typedef struct b2DebugDraw
{
/// Draw a closed polygon provided in CCW order.
void ( *DrawPolygonFcn )( b2WorldTransform transform, const b2Vec2* vertices, int vertexCount,
b2HexColor color, void* context );
void ( *DrawPolygonFcn )( b2WorldTransform transform, const b2Vec2* vertices, int vertexCount, b2HexColor color,
void* context );

/// Draw a solid closed polygon provided in CCW order.
void ( *DrawSolidPolygonFcn )( b2WorldTransform transform, const b2Vec2* vertices,
int vertexCount, float radius, b2HexColor color, void* context );
void ( *DrawSolidPolygonFcn )( b2WorldTransform transform, const b2Vec2* vertices, int vertexCount, float radius,
b2HexColor color, void* context );

/// Draw a circle.
void ( *DrawCircleFcn )( b2Pos center, float radius, b2HexColor color, void* context );

/// Draw a solid circle.
void ( *DrawSolidCircleFcn )( b2WorldTransform transform, b2Vec2 center, float radius,
b2HexColor color, void* context );
void ( *DrawSolidCircleFcn )( b2WorldTransform transform, b2Vec2 center, float radius, b2HexColor color,
void* context );

/// Draw a solid capsule.
void ( *DrawSolidCapsuleFcn )( b2Pos p1, b2Pos p2, float radius, b2HexColor color,
void* context );
void ( *DrawSolidCapsuleFcn )( b2Pos p1, b2Pos p2, float radius, b2HexColor color, void* context );

/// Draw a line segment.
void ( *DrawLineFcn )( b2Pos p1, b2Pos p2, b2HexColor color, void* context );
Expand Down
1 change: 1 addition & 0 deletions samples/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -581,6 +581,7 @@ int main( int argc, char** argv )
s_context.showControls = s_context.newUser;

s_context.workerCount = b2MinInt( 8, GetNumberOfCores() / 2 );
s_context.workerCount = 1;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Intended or leftover from testing? Sample will always run with a single thread.


// A recording path on the command line opens straight into the replay viewer.
// Dragging a file onto the exe arrives here as argv[1] too.
Expand Down
99 changes: 50 additions & 49 deletions src/broad_phase.c
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ void b2CreateBroadPhase( b2BroadPhase* bp, const b2Capacity* capacity )
b2CreateDynamicTreeInternal( bp->trees + b2_dynamicBody, dynamicCapacity );

bp->movedSiblings = NULL;
bp->crossContext = NULL;
}

void b2DestroyBroadPhase( b2BroadPhase* bp )
Expand Down Expand Up @@ -480,8 +481,10 @@ static int b2GatherCrossSeeds( const b2DynamicTree* treeA, const b2DynamicTree*
typedef struct b2CrossContext
{
b2World* world;
const b2NodePair* seeds;
b2NodePair seeds[2 * B2_CROSS_SEED_COUNT];
int staticSeedCount;
int crossMoveCount;
int dynamicMoveCount;
} b2CrossContext;

static void b2CrossPairsTask( int startIndex, int endIndex, int workerIndex, void* context )
Expand Down Expand Up @@ -574,24 +577,7 @@ static void b2UpdateTreesTask( void* context )
b2TracyCZoneEnd( tree_task );
}

// Task that can be done in parallel with the narrow-phase
// - rebuild the collision tree for dynamic and kinematic bodies to keep their query performance good
static void b2EnqueueTreeUpdate( b2World* world )
{
if ( world->taskCount < B2_MAX_TASKS )
{
world->userTreeTask = world->enqueueTaskFcn( &b2UpdateTreesTask, world, world->userTaskContext );
world->taskCount += 1;
world->activeTaskCount += world->userTreeTask == NULL ? 0 : 1;
}
else
{
world->userTreeTask = NULL;
b2UpdateTreesTask( world );
}
}

void b2UpdateBroadPhasePairs( b2World* world )
bool b2BeginPairs( b2World* world )
{
b2BroadPhase* bp = &world->broadPhase;

Expand All @@ -601,10 +587,10 @@ void b2UpdateBroadPhasePairs( b2World* world )

if ( needUpdate == false )
{
return;
return false;
}

b2TracyCZoneNC( update_pairs, "Find Pairs", b2_colorMediumSlateBlue, true );
b2TracyCZoneNC( update_pairs, "Find Pairs Setup", b2_colorMediumSlateBlue, true );

b2Stack* alloc = &world->stack;

Expand All @@ -615,41 +601,56 @@ void b2UpdateBroadPhasePairs( b2World* world )

// Generate pairs by querying the dynamic body tree against itself and against
// the kinematic and static trees.
{
// Get the sibling pairs of the dynamic body tree that have moved.
const b2DynamicTree* dynamicTree = bp->trees + b2_dynamicBody;
int pairCapacity = dynamicTree->nodeEnd / 2;
bp->movedSiblings = b2StackAlloc( alloc, pairCapacity * sizeof( int ), "moved pairs" );
int dynamicMoveCount = b2GatherMovedSiblings( dynamicTree, bp->movedSiblings );

// Get seeds for colliding against the static and kinematic trees.
b2NodePair crossSeeds[2 * B2_CROSS_SEED_COUNT];
int staticSeedCount = b2GatherCrossSeeds( dynamicTree, bp->trees + b2_staticBody, crossSeeds );
B2_ASSERT( staticSeedCount <= B2_CROSS_SEED_COUNT );
int kinematicSeedCount = b2GatherCrossSeeds( dynamicTree, bp->trees + b2_kinematicBody, crossSeeds + staticSeedCount );
B2_ASSERT( kinematicSeedCount <= B2_CROSS_SEED_COUNT );
int crossMoveCount = staticSeedCount + kinematicSeedCount;

// Collide the dynamic body tree against the static and kinematic trees.
b2CrossContext crossContext = {
.world = world,
.seeds = crossSeeds,
.staticSeedCount = staticSeedCount,
};
b2ParallelFor( world, &b2CrossPairsTask, crossMoveCount, 1, &crossContext );

// Collide the dynamic body tree against itself.
b2ParallelFor( world, &b2SelfPairsTask, dynamicMoveCount, 64, world );
}

b2DynamicTree_ClearMoved( bp->trees + b2_staticBody );
// Get the sibling pairs of the dynamic body tree that have moved.
const b2DynamicTree* dynamicTree = bp->trees + b2_dynamicBody;
int pairCapacity = dynamicTree->nodeEnd / 2;
bp->movedSiblings = b2StackAlloc( alloc, pairCapacity * sizeof( int ), "moved pairs" );
int dynamicMoveCount = b2GatherMovedSiblings( dynamicTree, bp->movedSiblings );

b2CrossContext* crossContext = b2StackAlloc( alloc, sizeof( b2CrossContext ), "cross context" );
bp->crossContext = crossContext;

// Get seeds for colliding against the static and kinematic trees.
int staticSeedCount = b2GatherCrossSeeds( dynamicTree, bp->trees + b2_staticBody, crossContext->seeds );
B2_ASSERT( staticSeedCount <= B2_CROSS_SEED_COUNT );
int kinematicSeedCount =
b2GatherCrossSeeds( dynamicTree, bp->trees + b2_kinematicBody, crossContext->seeds + staticSeedCount );
B2_ASSERT( kinematicSeedCount <= B2_CROSS_SEED_COUNT );

crossContext->world = world;
crossContext->staticSeedCount = staticSeedCount;
crossContext->crossMoveCount = staticSeedCount + kinematicSeedCount;
crossContext->dynamicMoveCount = dynamicMoveCount;

// Collide the dynamic body tree against the static and kinematic trees.
b2StageParallelFor( world, b2_taskPairs, &b2CrossPairsTask, crossContext->crossMoveCount, 1, crossContext );

b2TracyCZoneEnd( update_pairs );

return true;
}

void b2StageSelfPairs( b2World* world )
{
// Collide the dynamic body tree against itself.
b2StageParallelFor( world, b2_taskPairs, &b2SelfPairsTask, world->broadPhase.crossContext->dynamicMoveCount, 64, world );
}

void b2EndPairs( b2World* world )
{
b2BroadPhase* bp = &world->broadPhase;
b2Stack* alloc = &world->stack;

b2StackFree( alloc, bp->crossContext );
bp->crossContext = NULL;

b2DynamicTree_ClearMoved( bp->trees + b2_staticBody );

b2TracyCZoneNC( create_contacts, "Create Contacts", b2_colorCoral, true );

// Update stale trees.
b2EnqueueTreeUpdate( world );
b2StageDeferredTask( world->stepContext, b2_taskTreeRebuild, &b2UpdateTreesTask, world );

// Pairs arrive in deterministic order but scrambled relative to body and shape order
// sorting them here improves solver performance.
Expand Down
Loading
Loading