From 73f572b718e3b799ad9a7cc3ed2476440b8a2c9d Mon Sep 17 00:00:00 2001 From: Erin Catto Date: Fri, 9 Aug 2024 20:09:13 -0700 Subject: [PATCH] Getting ready (#181) New clang format. Clean up. --- .clang-format | 7 +- benchmark/amd7950x_sse2/joint_grid.csv | 9 + benchmark/amd7950x_sse2/large_pyramid.csv | 9 + benchmark/amd7950x_sse2/many_pyramids.csv | 9 + benchmark/amd7950x_sse2/smash.csv | 9 + benchmark/amd7950x_sse2/tumbler.csv | 9 + benchmark/joint_grid.c | 40 +- benchmark/large_pyramid.c | 28 +- benchmark/main.c | 166 +- benchmark/many_pyramids.c | 44 +- benchmark/smash.c | 26 +- benchmark/tumbler.c | 46 +- docs/CMakeLists.txt | 2 +- docs/hello.md | 2 +- docs/migration.md | 19 +- docs/simulation.md | 2 +- include/box2d/base.h | 48 +- include/box2d/box2d.h | 546 ++--- include/box2d/collision.h | 203 +- include/box2d/id.h | 7 +- include/box2d/math_functions.h | 288 +-- include/box2d/types.h | 74 +- samples/car.cpp | 254 ++- samples/car.h | 33 +- samples/data/background.fs | 33 + samples/data/background.vs | 10 + samples/donut.cpp | 44 +- samples/donut.h | 2 +- samples/doohickey.cpp | 68 +- samples/doohickey.h | 4 +- samples/draw.cpp | 1108 +++++----- samples/draw.h | 32 +- samples/human.cpp | 444 ++-- samples/human.h | 12 +- samples/main.cpp | 476 +++-- samples/sample.cpp | 329 +-- samples/sample.h | 54 +- samples/sample_benchmark.cpp | 872 ++++---- samples/sample_bodies.cpp | 541 +++-- samples/sample_collision.cpp | 2359 ++++++++++----------- samples/sample_continuous.cpp | 560 ++--- samples/sample_events.cpp | 549 ++--- samples/sample_geometry.cpp | 140 +- samples/sample_joints.cpp | 1527 ++++++------- samples/sample_robustness.cpp | 171 +- samples/sample_shapes.cpp | 838 ++++---- samples/sample_stacking.cpp | 595 +++--- samples/sample_world.cpp | 125 +- samples/settings.cpp | 96 +- samples/settings.h | 10 +- samples/shader.cpp | 179 +- samples/shader.h | 6 +- src/aabb.c | 50 +- src/aabb.h | 32 +- src/allocate.c | 70 +- src/allocate.h | 4 +- src/array.c | 56 +- src/array.h | 50 +- src/bitset.c | 48 +- src/bitset.h | 40 +- src/block_array.c | 180 +- src/block_array.h | 40 +- src/body.c | 1123 +++++----- src/body.h | 28 +- src/broad_phase.c | 274 +-- src/broad_phase.h | 39 +- src/constraint_graph.c | 176 +- src/constraint_graph.h | 14 +- src/contact.c | 325 +-- src/contact.h | 14 +- src/contact_solver.c | 886 ++++---- src/contact_solver.h | 21 +- src/core.c | 19 +- src/core.h | 82 +- src/ctz.h | 64 +- src/distance.c | 575 ++--- src/distance_joint.c | 367 ++-- src/dynamic_tree.c | 879 ++++---- src/geometry.c | 500 ++--- src/hull.c | 140 +- src/id_pool.c | 44 +- src/id_pool.h | 18 +- src/island.c | 557 ++--- src/island.h | 22 +- src/joint.c | 854 ++++---- src/joint.h | 28 +- src/manifold.c | 728 +++---- src/math_functions.c | 50 +- src/motor_joint.c | 146 +- src/mouse_joint.c | 102 +- src/prismatic_joint.c | 310 +-- src/revolute_joint.c | 287 +-- src/shape.c | 861 ++++---- src/shape.h | 23 +- src/solver.c | 917 ++++---- src/solver.h | 12 +- src/solver_set.c | 360 ++-- src/solver_set.h | 12 +- src/stack_allocator.c | 65 +- src/stack_allocator.h | 16 +- src/table.c | 112 +- src/table.h | 16 +- src/timer.c | 108 +- src/types.c | 28 +- src/weld_joint.c | 130 +- src/wheel_joint.c | 298 +-- src/world.c | 1934 ++++++++--------- src/world.h | 14 +- test/main.c | 60 +- test/test_bitset.c | 28 +- test/test_collision.c | 32 +- test/test_determinism.c | 102 +- test/test_distance.c | 111 +- test/test_macros.h | 112 +- test/test_math.c | 43 +- test/test_shape.c | 169 +- test/test_table.c | 66 +- test/test_world.c | 139 +- 118 files changed, 14372 insertions(+), 13702 deletions(-) create mode 100644 benchmark/amd7950x_sse2/joint_grid.csv create mode 100644 benchmark/amd7950x_sse2/large_pyramid.csv create mode 100644 benchmark/amd7950x_sse2/many_pyramids.csv create mode 100644 benchmark/amd7950x_sse2/smash.csv create mode 100644 benchmark/amd7950x_sse2/tumbler.csv create mode 100644 samples/data/background.fs create mode 100644 samples/data/background.vs diff --git a/.clang-format b/.clang-format index 7f08d921..806b4f01 100644 --- a/.clang-format +++ b/.clang-format @@ -38,4 +38,9 @@ IndentAccessModifiers: false AccessModifierOffset: -4 # AlignArrayOfStructures: Left -# AlignAfterOpenBracket: BlockIndent \ No newline at end of file +# AlignAfterOpenBracket: BlockIndent + +SpacesInParens: Custom +SpacesInParensOptions: + Other: true + \ No newline at end of file diff --git a/benchmark/amd7950x_sse2/joint_grid.csv b/benchmark/amd7950x_sse2/joint_grid.csv new file mode 100644 index 00000000..6c58c02a --- /dev/null +++ b/benchmark/amd7950x_sse2/joint_grid.csv @@ -0,0 +1,9 @@ +threads,fps +1,357.551 +2,691.193 +3,1010.45 +4,1317.42 +5,1590.65 +6,1858.78 +7,2074.2 +8,2261.67 diff --git a/benchmark/amd7950x_sse2/large_pyramid.csv b/benchmark/amd7950x_sse2/large_pyramid.csv new file mode 100644 index 00000000..a62e7c90 --- /dev/null +++ b/benchmark/amd7950x_sse2/large_pyramid.csv @@ -0,0 +1,9 @@ +threads,fps +1,186.185 +2,351.045 +3,511.316 +4,636.035 +5,765.404 +6,875.296 +7,991.353 +8,961.402 diff --git a/benchmark/amd7950x_sse2/many_pyramids.csv b/benchmark/amd7950x_sse2/many_pyramids.csv new file mode 100644 index 00000000..57ed916d --- /dev/null +++ b/benchmark/amd7950x_sse2/many_pyramids.csv @@ -0,0 +1,9 @@ +threads,fps +1,48.5561 +2,92.6231 +3,137.175 +4,176.644 +5,214.941 +6,253.39 +7,288.631 +8,312.527 diff --git a/benchmark/amd7950x_sse2/smash.csv b/benchmark/amd7950x_sse2/smash.csv new file mode 100644 index 00000000..9763183a --- /dev/null +++ b/benchmark/amd7950x_sse2/smash.csv @@ -0,0 +1,9 @@ +threads,fps +1,142.532 +2,228.987 +3,299.951 +4,364.679 +5,413.564 +6,453.351 +7,489.239 +8,519.379 diff --git a/benchmark/amd7950x_sse2/tumbler.csv b/benchmark/amd7950x_sse2/tumbler.csv new file mode 100644 index 00000000..82d5aaae --- /dev/null +++ b/benchmark/amd7950x_sse2/tumbler.csv @@ -0,0 +1,9 @@ +threads,fps +1,276.905 +2,453.522 +3,592.946 +4,702.383 +5,826.52 +6,919.179 +7,1009.05 +8,1062.61 diff --git a/benchmark/joint_grid.c b/benchmark/joint_grid.c index a36edd07..1198b7b0 100644 --- a/benchmark/joint_grid.c +++ b/benchmark/joint_grid.c @@ -6,13 +6,13 @@ #include -b2WorldId JointGrid(b2WorldDef* worldDef) +b2WorldId JointGrid( b2WorldDef* worldDef ) { // Turning gravity off to isolate joint performance. worldDef->gravity = b2Vec2_zero; - b2WorldId worldId = b2CreateWorld(worldDef); - + b2WorldId worldId = b2CreateWorld( worldDef ); + #ifdef NDEBUG int N = 100; #else @@ -20,7 +20,7 @@ b2WorldId JointGrid(b2WorldDef* worldDef) #endif // Allocate to avoid huge stack usage - b2BodyId* bodies = malloc(N * N * sizeof(b2BodyId)); + b2BodyId* bodies = malloc( N * N * sizeof( b2BodyId ) ); int index = 0; b2ShapeDef shapeDef = b2DefaultShapeDef(); @@ -28,20 +28,20 @@ b2WorldId JointGrid(b2WorldDef* worldDef) shapeDef.filter.categoryBits = 2; shapeDef.filter.maskBits = ~2u; - b2Circle circle = {{0.0f, 0.0f}, 0.4f}; + b2Circle circle = { { 0.0f, 0.0f }, 0.4f }; b2RevoluteJointDef jd = b2DefaultRevoluteJointDef(); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.enableSleep = false; - for (int k = 0; k < N; ++k) + for ( int k = 0; k < N; ++k ) { - for (int i = 0; i < N; ++i) + for ( int i = 0; i < N; ++i ) { float fk = (float)k; float fi = (float)i; - if (k >= N / 2 - 3 && k <= N / 2 + 3 && i == 0) + if ( k >= N / 2 - 3 && k <= N / 2 + 3 && i == 0 ) { bodyDef.type = b2_staticBody; } @@ -50,35 +50,35 @@ b2WorldId JointGrid(b2WorldDef* worldDef) bodyDef.type = b2_dynamicBody; } - bodyDef.position = (b2Vec2){fk, -fi}; + bodyDef.position = ( b2Vec2 ){ fk, -fi }; - b2BodyId body = b2CreateBody(worldId, &bodyDef); + b2BodyId body = b2CreateBody( worldId, &bodyDef ); - b2CreateCircleShape(body, &shapeDef, &circle); + b2CreateCircleShape( body, &shapeDef, &circle ); - if (i > 0) + if ( i > 0 ) { jd.bodyIdA = bodies[index - 1]; jd.bodyIdB = body; - jd.localAnchorA = (b2Vec2){0.0f, -0.5f}; - jd.localAnchorB = (b2Vec2){0.0f, 0.5f}; - b2CreateRevoluteJoint(worldId, &jd); + jd.localAnchorA = ( b2Vec2 ){ 0.0f, -0.5f }; + jd.localAnchorB = ( b2Vec2 ){ 0.0f, 0.5f }; + b2CreateRevoluteJoint( worldId, &jd ); } - if (k > 0) + if ( k > 0 ) { jd.bodyIdA = bodies[index - N]; jd.bodyIdB = body; - jd.localAnchorA = (b2Vec2){0.5f, 0.0f}; - jd.localAnchorB = (b2Vec2){-0.5f, 0.0f}; - b2CreateRevoluteJoint(worldId, &jd); + jd.localAnchorA = ( b2Vec2 ){ 0.5f, 0.0f }; + jd.localAnchorB = ( b2Vec2 ){ -0.5f, 0.0f }; + b2CreateRevoluteJoint( worldId, &jd ); } bodies[index++] = body; } } - free(bodies); + free( bodies ); return worldId; } diff --git a/benchmark/large_pyramid.c b/benchmark/large_pyramid.c index 9b922735..76774291 100644 --- a/benchmark/large_pyramid.c +++ b/benchmark/large_pyramid.c @@ -4,7 +4,7 @@ #include "box2d/box2d.h" #include "box2d/math_functions.h" -b2WorldId LargePyramid(b2WorldDef* worldDef) +b2WorldId LargePyramid( b2WorldDef* worldDef ) { #ifdef NDEBUG int baseCount = 100; @@ -12,16 +12,16 @@ b2WorldId LargePyramid(b2WorldDef* worldDef) int baseCount = 20; #endif - b2WorldId worldId = b2CreateWorld(worldDef); + b2WorldId worldId = b2CreateWorld( worldDef ); { b2BodyDef bodyDef = b2DefaultBodyDef(); - bodyDef.position = (b2Vec2){0.0f, -1.0f}; - b2BodyId groundId = b2CreateBody(worldId, &bodyDef); + bodyDef.position = ( b2Vec2 ){ 0.0f, -1.0f }; + b2BodyId groundId = b2CreateBody( worldId, &bodyDef ); - b2Polygon box = b2MakeBox(100.0f, 1.0f); + b2Polygon box = b2MakeBox( 100.0f, 1.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreatePolygonShape(groundId, &shapeDef, &box); + b2CreatePolygonShape( groundId, &shapeDef, &box ); } b2BodyDef bodyDef = b2DefaultBodyDef(); @@ -32,22 +32,22 @@ b2WorldId LargePyramid(b2WorldDef* worldDef) shapeDef.density = 1.0f; float h = 0.5f; - b2Polygon box = b2MakeSquare(h); + b2Polygon box = b2MakeSquare( h ); float shift = 1.0f * h; - for (int i = 0; i < baseCount; ++i) + for ( int i = 0; i < baseCount; ++i ) { - float y = (2.0f * i + 1.0f) * shift; + float y = ( 2.0f * i + 1.0f ) * shift; - for (int j = i; j < baseCount; ++j) + for ( int j = i; j < baseCount; ++j ) { - float x = (i + 1.0f) * shift + 2.0f * (j - i) * shift - h * baseCount; + float x = ( i + 1.0f ) * shift + 2.0f * ( j - i ) * shift - h * baseCount; - bodyDef.position = (b2Vec2){x, y}; + bodyDef.position = ( b2Vec2 ){ x, y }; - b2BodyId bodyId = b2CreateBody(worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2BodyId bodyId = b2CreateBody( worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); } } diff --git a/benchmark/main.c b/benchmark/main.c index 7797cefe..c026fbe9 100644 --- a/benchmark/main.c +++ b/benchmark/main.c @@ -14,23 +14,23 @@ #include #include -#if defined(_WIN64) +#if defined( _WIN64 ) #include -#elif defined(__APPLE__) +#elif defined( __APPLE__ ) #include -#elif defined(__linux__) +#elif defined( __linux__ ) #include #endif -#define ARRAY_COUNT(A) (int)(sizeof(A) / sizeof(A[0])) -#define MAYBE_UNUSED(x) ((void)(x)) +#define ARRAY_COUNT( A ) (int)( sizeof( A ) / sizeof( A[0] ) ) +#define MAYBE_UNUSED( x ) ( (void)( x ) ) -typedef b2WorldId CreateBenchmarkFcn(b2WorldDef* worldDef); -extern b2WorldId JointGrid(b2WorldDef* worldDef); -extern b2WorldId LargePyramid(b2WorldDef* worldDef); -extern b2WorldId ManyPyramids(b2WorldDef* worldDef); -extern b2WorldId Smash(b2WorldDef* worldDef); -extern b2WorldId Tumbler(b2WorldDef* worldDef); +typedef b2WorldId CreateBenchmarkFcn( b2WorldDef* worldDef ); +extern b2WorldId JointGrid( b2WorldDef* worldDef ); +extern b2WorldId LargePyramid( b2WorldDef* worldDef ); +extern b2WorldId ManyPyramids( b2WorldDef* worldDef ); +extern b2WorldId Smash( b2WorldDef* worldDef ); +extern b2WorldId Tumbler( b2WorldDef* worldDef ); typedef struct Benchmark { @@ -55,30 +55,30 @@ int taskCount; int GetNumberOfCores() { -#if defined(_WIN64) +#if defined( _WIN64 ) SYSTEM_INFO sysinfo; - GetSystemInfo(&sysinfo); + GetSystemInfo( &sysinfo ); return sysinfo.dwNumberOfProcessors; -#elif defined(__APPLE__) - return (int)sysconf(_SC_NPROCESSORS_ONLN); -#elif defined(__linux__) - (int)return sysconf(_SC_NPROCESSORS_ONLN); +#elif defined( __APPLE__ ) + return (int)sysconf( _SC_NPROCESSORS_ONLN ); +#elif defined( __linux__ ) + (int)return sysconf( _SC_NPROCESSORS_ONLN ); #else return 1; #endif } -void ExecuteRangeTask(uint32_t start, uint32_t end, uint32_t threadIndex, void* context) +void ExecuteRangeTask( uint32_t start, uint32_t end, uint32_t threadIndex, void* context ) { TaskData* data = context; - data->box2dTask(start, end, threadIndex, data->box2dContext); + data->box2dTask( start, end, threadIndex, data->box2dContext ); } -static void* EnqueueTask(b2TaskCallback* box2dTask, int itemCount, int minRange, void* box2dContext, void* userContext) +static void* EnqueueTask( b2TaskCallback* box2dTask, int itemCount, int minRange, void* box2dContext, void* userContext ) { - MAYBE_UNUSED(userContext); + MAYBE_UNUSED( userContext ); - if (taskCount < MAX_TASKS) + if ( taskCount < MAX_TASKS ) { enkiTaskSet* task = tasks[taskCount]; TaskData* data = taskData + taskCount; @@ -91,8 +91,8 @@ static void* EnqueueTask(b2TaskCallback* box2dTask, int itemCount, int minRange, params.pArgs = data; params.priority = 0; - enkiSetParamsTaskSet(task, params); - enkiAddTaskSet(scheduler, task); + enkiSetParamsTaskSet( task, params ); + enkiAddTaskSet( scheduler, task ); ++taskCount; @@ -100,58 +100,58 @@ static void* EnqueueTask(b2TaskCallback* box2dTask, int itemCount, int minRange, } else { - printf("MAX_TASKS exceeded!!!\n"); - box2dTask(0, itemCount, 0, box2dContext); + printf( "MAX_TASKS exceeded!!!\n" ); + box2dTask( 0, itemCount, 0, box2dContext ); return NULL; } } -static void FinishTask(void* userTask, void* userContext) +static void FinishTask( void* userTask, void* userContext ) { - MAYBE_UNUSED(userContext); + MAYBE_UNUSED( userContext ); enkiTaskSet* task = userTask; - enkiWaitForTaskSet(scheduler, task); + enkiWaitForTaskSet( scheduler, task ); } -int main(int argc, char** argv) +int main( int argc, char** argv ) { int maxThreadCount = GetNumberOfCores(); int runCount = 4; - b2Counters counters = {0}; + b2Counters counters = { 0 }; bool enableContinuous = true; - assert(maxThreadCount <= THREAD_LIMIT); + assert( maxThreadCount <= THREAD_LIMIT ); - for (int i = 1; i < argc; ++i) + for ( int i = 1; i < argc; ++i ) { const char* arg = argv[i]; - if (strncmp(arg, "-t=", 3) == 0) + if ( strncmp( arg, "-t=", 3 ) == 0 ) { - int threadCount = atoi(arg + 3); - maxThreadCount = b2MinInt(maxThreadCount, threadCount); + int threadCount = atoi( arg + 3 ); + maxThreadCount = b2MinInt( maxThreadCount, threadCount ); } - else if (strcmp(arg, "-h") == 0) + else if ( strcmp( arg, "-h" ) == 0 ) { - printf("Usage\n" - "-t=: the maximum number of threads to use\n"); + printf( "Usage\n" + "-t=: the maximum number of threads to use\n" ); } } Benchmark benchmarks[] = { - {"joint_grid", JointGrid, 500}, - {"large_pyramid", LargePyramid, 500}, - {"many_pyramids", ManyPyramids, 200}, - {"smash", Smash, 300}, - {"tumbler", Tumbler, 750}, + { "joint_grid", JointGrid, 500 }, + { "large_pyramid", LargePyramid, 500 }, + { "many_pyramids", ManyPyramids, 200 }, + { "smash", Smash, 300 }, + { "tumbler", Tumbler, 750 }, }; - int benchmarkCount = ARRAY_COUNT(benchmarks); + int benchmarkCount = ARRAY_COUNT( benchmarks ); - printf("Starting Box2D benchmarks\n"); - printf("======================================\n"); + printf( "Starting Box2D benchmarks\n" ); + printf( "======================================\n" ); - for (int benchmarkIndex = 0; benchmarkIndex < benchmarkCount; ++benchmarkIndex) + for ( int benchmarkIndex = 0; benchmarkIndex < benchmarkCount; ++benchmarkIndex ) { #ifdef NDEBUG int stepCount = benchmarks[benchmarkIndex].stepCount; @@ -161,24 +161,24 @@ int main(int argc, char** argv) bool countersAcquired = false; - printf("benchmark: %s, steps = %d\n", benchmarks[benchmarkIndex].name, stepCount); + printf( "benchmark: %s, steps = %d\n", benchmarks[benchmarkIndex].name, stepCount ); - float maxFps[THREAD_LIMIT] = {0}; + float maxFps[THREAD_LIMIT] = { 0 }; - for (int threadCount = 1; threadCount <= maxThreadCount; ++threadCount) + for ( int threadCount = 1; threadCount <= maxThreadCount; ++threadCount ) { - printf("thread count: %d\n", threadCount); + printf( "thread count: %d\n", threadCount ); - for (int runIndex = 0; runIndex < runCount; ++runIndex) + for ( int runIndex = 0; runIndex < runCount; ++runIndex ) { scheduler = enkiNewTaskScheduler(); - struct enkiTaskSchedulerConfig config = enkiGetTaskSchedulerConfig(scheduler); + struct enkiTaskSchedulerConfig config = enkiGetTaskSchedulerConfig( scheduler ); config.numTaskThreadsToCreate = threadCount - 1; - enkiInitTaskSchedulerWithConfig(scheduler, config); + enkiInitTaskSchedulerWithConfig( scheduler, config ); - for (int taskIndex = 0; taskIndex < MAX_TASKS; ++taskIndex) + for ( int taskIndex = 0; taskIndex < MAX_TASKS; ++taskIndex ) { - tasks[taskIndex] = enkiCreateTaskSet(scheduler, ExecuteRangeTask); + tasks[taskIndex] = enkiCreateTaskSet( scheduler, ExecuteRangeTask ); } b2WorldDef worldDef = b2DefaultWorldDef(); @@ -188,70 +188,70 @@ int main(int argc, char** argv) worldDef.finishTask = FinishTask; worldDef.workerCount = threadCount; - b2WorldId worldId = benchmarks[benchmarkIndex].createFcn(&worldDef); + b2WorldId worldId = benchmarks[benchmarkIndex].createFcn( &worldDef ); float timeStep = 1.0f / 60.0f; int subStepCount = 4; // Initial step can be expensive and skew benchmark - b2World_Step(worldId, timeStep, subStepCount); + b2World_Step( worldId, timeStep, subStepCount ); b2Timer timer = b2CreateTimer(); - for (int step = 0; step < stepCount; ++step) + for ( int step = 0; step < stepCount; ++step ) { - b2World_Step(worldId, timeStep, subStepCount); + b2World_Step( worldId, timeStep, subStepCount ); taskCount = 0; } - float ms = b2GetMilliseconds(&timer); + float ms = b2GetMilliseconds( &timer ); float fps = 1000.0f * stepCount / ms; - printf("run %d : %g (ms), %g (fps)\n", runIndex, ms, fps); + printf( "run %d : %g (ms), %g (fps)\n", runIndex, ms, fps ); - maxFps[threadCount - 1] = b2MaxFloat(maxFps[threadCount - 1], fps); + maxFps[threadCount - 1] = b2MaxFloat( maxFps[threadCount - 1], fps ); - if (countersAcquired == false) + if ( countersAcquired == false ) { - counters = b2World_GetCounters(worldId); + counters = b2World_GetCounters( worldId ); countersAcquired = true; } - b2DestroyWorld(worldId); + b2DestroyWorld( worldId ); - for (int taskIndex = 0; taskIndex < MAX_TASKS; ++taskIndex) + for ( int taskIndex = 0; taskIndex < MAX_TASKS; ++taskIndex ) { - enkiDeleteTaskSet(scheduler, tasks[taskIndex]); + enkiDeleteTaskSet( scheduler, tasks[taskIndex] ); tasks[taskIndex] = NULL; - taskData[taskIndex] = (TaskData){0}; + taskData[taskIndex] = ( TaskData ){ 0 }; } - enkiDeleteTaskScheduler(scheduler); + enkiDeleteTaskScheduler( scheduler ); scheduler = NULL; } } - printf("body %d / shape %d / contact %d / joint %d / stack %d\n\n", counters.bodyCount, counters.shapeCount, - counters.contactCount, counters.jointCount, counters.stackUsed); + printf( "body %d / shape %d / contact %d / joint %d / stack %d\n\n", counters.bodyCount, counters.shapeCount, + counters.contactCount, counters.jointCount, counters.stackUsed ); - char fileName[64] = {0}; - snprintf(fileName, 64, "%s.csv", benchmarks[benchmarkIndex].name); - FILE* file = fopen(fileName, "w"); - if (file == NULL) + char fileName[64] = { 0 }; + snprintf( fileName, 64, "%s.csv", benchmarks[benchmarkIndex].name ); + FILE* file = fopen( fileName, "w" ); + if ( file == NULL ) { continue; } - fprintf(file, "threads,fps\n"); - for (int threadCount = 1; threadCount <= maxThreadCount; ++threadCount) + fprintf( file, "threads,fps\n" ); + for ( int threadCount = 1; threadCount <= maxThreadCount; ++threadCount ) { - fprintf(file, "%d,%g\n", threadCount, maxFps[threadCount - 1]); + fprintf( file, "%d,%g\n", threadCount, maxFps[threadCount - 1] ); } - fclose(file); + fclose( file ); } - printf("======================================\n"); - printf("All Box2D benchmarks complete!\n"); + printf( "======================================\n" ); + printf( "All Box2D benchmarks complete!\n" ); return 0; } diff --git a/benchmark/many_pyramids.c b/benchmark/many_pyramids.c index 0ccfd28d..46e3f79c 100644 --- a/benchmark/many_pyramids.c +++ b/benchmark/many_pyramids.c @@ -4,32 +4,32 @@ #include "box2d/box2d.h" #include "box2d/math_functions.h" -static void CreatePyramid(b2WorldId worldId, int baseCount, float extent, float centerX, float baseY) +static void CreatePyramid( b2WorldId worldId, int baseCount, float extent, float centerX, float baseY ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - //bodyDef.enableSleep = false; + // bodyDef.enableSleep = false; b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Polygon box = b2MakeSquare(extent); + b2Polygon box = b2MakeSquare( extent ); - for (int i = 0; i < baseCount; ++i) + for ( int i = 0; i < baseCount; ++i ) { - float y = (2.0f * i + 1.0f) * extent + baseY; + float y = ( 2.0f * i + 1.0f ) * extent + baseY; - for (int j = i; j < baseCount; ++j) + for ( int j = i; j < baseCount; ++j ) { - float x = (i + 1.0f) * extent + 2.0f * (j - i) * extent + centerX - 0.5f; - bodyDef.position = (b2Vec2){x, y}; + float x = ( i + 1.0f ) * extent + 2.0f * ( j - i ) * extent + centerX - 0.5f; + bodyDef.position = ( b2Vec2 ){ x, y }; - b2BodyId bodyId = b2CreateBody(worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2BodyId bodyId = b2CreateBody( worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); } } } -b2WorldId ManyPyramids(b2WorldDef* worldDef) +b2WorldId ManyPyramids( b2WorldDef* worldDef ) { int baseCount = 10; float extent = 0.5f; @@ -43,33 +43,33 @@ b2WorldId ManyPyramids(b2WorldDef* worldDef) worldDef->enableSleep = false; - b2WorldId worldId = b2CreateWorld(worldDef); + b2WorldId worldId = b2CreateWorld( worldDef ); b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( worldId, &bodyDef ); - float groundDeltaY = 2.0f * extent * (baseCount + 1.0f); - float groundWidth = 2.0f * extent * columnCount * (baseCount + 1.0f); + float groundDeltaY = 2.0f * extent * ( baseCount + 1.0f ); + float groundWidth = 2.0f * extent * columnCount * ( baseCount + 1.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); float groundY = 0.0f; - for (int i = 0; i < rowCount; ++i) + for ( int i = 0; i < rowCount; ++i ) { - b2Segment segment = {{-0.5f * 2.0f * groundWidth, groundY}, {0.5f * 2.0f * groundWidth, groundY}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2Segment segment = { { -0.5f * 2.0f * groundWidth, groundY }, { 0.5f * 2.0f * groundWidth, groundY } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment ); groundY += groundDeltaY; } float baseWidth = 2.0f * extent * baseCount; float baseY = 0.0f; - for (int i = 0; i < rowCount; ++i) + for ( int i = 0; i < rowCount; ++i ) { - for (int j = 0; j < columnCount; ++j) + for ( int j = 0; j < columnCount; ++j ) { - float centerX = -0.5f * groundWidth + j * (baseWidth + 2.0f * extent) + extent; - CreatePyramid(worldId, baseCount, extent, centerX, baseY); + float centerX = -0.5f * groundWidth + j * ( baseWidth + 2.0f * extent ) + extent; + CreatePyramid( worldId, baseCount, extent, centerX, baseY ); } baseY += groundDeltaY; diff --git a/benchmark/smash.c b/benchmark/smash.c index 02e9276f..9e25c08c 100644 --- a/benchmark/smash.c +++ b/benchmark/smash.c @@ -4,26 +4,26 @@ #include "box2d/box2d.h" #include "box2d/math_functions.h" -b2WorldId Smash(b2WorldDef* worldDef) +b2WorldId Smash( b2WorldDef* worldDef ) { - b2WorldId worldId = b2CreateWorld(worldDef); + b2WorldId worldId = b2CreateWorld( worldDef ); { - b2Polygon box = b2MakeBox(4.0f, 4.0f); + b2Polygon box = b2MakeBox( 4.0f, 4.0f ); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = (b2Vec2){-20.0f, 0.0f}; - bodyDef.linearVelocity = (b2Vec2){40.0f, 0.0f}; - b2BodyId bodyId = b2CreateBody(worldId, &bodyDef); + bodyDef.position = ( b2Vec2 ){ -20.0f, 0.0f }; + bodyDef.linearVelocity = ( b2Vec2 ){ 40.0f, 0.0f }; + b2BodyId bodyId = b2CreateBody( worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 8.0f; - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); } float d = 0.4f; - b2Polygon box = b2MakeSquare(0.5f * d); + b2Polygon box = b2MakeSquare( 0.5f * d ); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; @@ -39,14 +39,14 @@ b2WorldId Smash(b2WorldDef* worldDef) int rows = 10; #endif - for (int i = 0; i < columns; ++i) + for ( int i = 0; i < columns; ++i ) { - for (int j = 0; j < rows; ++j) + for ( int j = 0; j < rows; ++j ) { bodyDef.position.x = i * d + 30.0f; - bodyDef.position.y = (j - rows / 2.0f) * d; - b2BodyId bodyId = b2CreateBody(worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &box); + bodyDef.position.y = ( j - rows / 2.0f ) * d; + b2BodyId bodyId = b2CreateBody( worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); } } diff --git a/benchmark/tumbler.c b/benchmark/tumbler.c index ea3baa14..fcfb77d3 100644 --- a/benchmark/tumbler.c +++ b/benchmark/tumbler.c @@ -4,48 +4,48 @@ #include "box2d/box2d.h" #include "box2d/math_functions.h" -b2WorldId Tumbler(b2WorldDef* worldDef) +b2WorldId Tumbler( b2WorldDef* worldDef ) { - b2WorldId worldId = b2CreateWorld(worldDef); + b2WorldId worldId = b2CreateWorld( worldDef ); b2BodyId groundId; { b2BodyDef bodyDef = b2DefaultBodyDef(); - groundId = b2CreateBody(worldId, &bodyDef); + groundId = b2CreateBody( worldId, &bodyDef ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = (b2Vec2){0.0f, 10.0f}; - b2BodyId bodyId = b2CreateBody(worldId, &bodyDef); + bodyDef.position = ( b2Vec2 ){ 0.0f, 10.0f }; + b2BodyId bodyId = b2CreateBody( worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 50.0f; b2Polygon polygon; - polygon = b2MakeOffsetBox(0.5f, 10.0f, (b2Vec2){10.0f, 0.0f}, 0.0); - b2CreatePolygonShape(bodyId, &shapeDef, &polygon); - polygon = b2MakeOffsetBox(0.5f, 10.0f, (b2Vec2){-10.0f, 0.0f}, 0.0); - b2CreatePolygonShape(bodyId, &shapeDef, &polygon); - polygon = b2MakeOffsetBox(10.0f, 0.5f, (b2Vec2){0.0f, 10.0f}, 0.0); - b2CreatePolygonShape(bodyId, &shapeDef, &polygon); - polygon = b2MakeOffsetBox(10.0f, 0.5f, (b2Vec2){0.0f, -10.0f}, 0.0); - b2CreatePolygonShape(bodyId, &shapeDef, &polygon); + polygon = b2MakeOffsetBox( 0.5f, 10.0f, ( b2Vec2 ){ 10.0f, 0.0f }, 0.0 ); + b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); + polygon = b2MakeOffsetBox( 0.5f, 10.0f, ( b2Vec2 ){ -10.0f, 0.0f }, 0.0 ); + b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); + polygon = b2MakeOffsetBox( 10.0f, 0.5f, ( b2Vec2 ){ 0.0f, 10.0f }, 0.0 ); + b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); + polygon = b2MakeOffsetBox( 10.0f, 0.5f, ( b2Vec2 ){ 0.0f, -10.0f }, 0.0 ); + b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); float motorSpeed = 25.0f; b2RevoluteJointDef jd = b2DefaultRevoluteJointDef(); jd.bodyIdA = groundId; jd.bodyIdB = bodyId; - jd.localAnchorA = (b2Vec2){0.0f, 10.0f}; - jd.localAnchorB = (b2Vec2){0.0f, 0.0f}; + jd.localAnchorA = ( b2Vec2 ){ 0.0f, 10.0f }; + jd.localAnchorB = ( b2Vec2 ){ 0.0f, 0.0f }; jd.referenceAngle = 0.0f; - jd.motorSpeed = (b2_pi / 180.0f) * motorSpeed; + jd.motorSpeed = ( b2_pi / 180.0f ) * motorSpeed; jd.maxMotorTorque = 1e8f; jd.enableMotor = true; - b2CreateRevoluteJoint(worldId, &jd); + b2CreateRevoluteJoint( worldId, &jd ); } #ifdef NDEBUG @@ -54,22 +54,22 @@ b2WorldId Tumbler(b2WorldDef* worldDef) int gridCount = 20; #endif - b2Polygon polygon = b2MakeBox(0.125f, 0.125f); + b2Polygon polygon = b2MakeBox( 0.125f, 0.125f ); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; b2ShapeDef shapeDef = b2DefaultShapeDef(); float y = -0.2f * gridCount + 10.0f; - for (int i = 0; i < gridCount; ++i) + for ( int i = 0; i < gridCount; ++i ) { float x = -0.2f * gridCount; - for (int j = 0; j < gridCount; ++j) + for ( int j = 0; j < gridCount; ++j ) { - bodyDef.position = (b2Vec2){x, y}; - b2BodyId bodyId = b2CreateBody(worldId, &bodyDef); + bodyDef.position = ( b2Vec2 ){ x, y }; + b2BodyId bodyId = b2CreateBody( worldId, &bodyDef ); - b2CreatePolygonShape(bodyId, &shapeDef, &polygon); + b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); x += 0.4f; } diff --git a/docs/CMakeLists.txt b/docs/CMakeLists.txt index 72412269..fc5cc629 100644 --- a/docs/CMakeLists.txt +++ b/docs/CMakeLists.txt @@ -32,7 +32,7 @@ set(DOXYGEN_FULL_SIDEBAR NO) # force dark mode to work with extra.css set(DOXYGEN_HTML_COLORSTYLE DARK) -# this tells doxygen to label structs as structs intead of classes +# this tells doxygen to label structs as structs instead of classes set(DOXYGEN_OPTIMIZE_OUTPUT_FOR_C YES) set(DOXYGEN_WARN_IF_INCOMPLETE_DOC NO) diff --git a/docs/hello.md b/docs/hello.md index 4a0a3659..6263724f 100644 --- a/docs/hello.md +++ b/docs/hello.md @@ -226,7 +226,7 @@ for (int i = 0; i < 90; ++i) { b2World_Step(worldId, timeStep, subStepCount); b2Vec2 position = b2Body_GetPosition(bodyId); - b2Rot rotation = b2Body_GetRot(bodyId); + b2Rot rotation = b2Body_GetRotation(bodyId); printf("%4.2f %4.2f %4.2f\n", position.x, position.y, b2Rot_GetAngle(rotation)); } ``` diff --git a/docs/migration.md b/docs/migration.md index 8d2989a1..22b83e1e 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -9,11 +9,12 @@ Here are the highlights that affect the API: - multithreading support - fewer callbacks - more features (such as capsules and shape casts) -- new sub-stepping solver +- new sub-stepping solver (*Soft Step*) +- gear and pulley joint removed (temporarily) However, the scope of what Box2D does has not changed much. It is still a 2D rigid body engine. It is just faster and more robust (hopefully). And hopefully it is easier to work with and port/wrap for other languages/platforms. -I'm going to describe migration by comparing code snippets between 2.4 and 3.0. These should give you and idea of the sort of transformations you need to make to your code to migrate to v3.0. +I'm going to describe migration by comparing code snippets between 2.4 and 3.0. These should give you and idea of the sort of transformations you need to make to your code to migrate to v3.0. These snippets are written in C and may need some small adjustments to work with C++. I'm not going to cover all the details of v3.0 in this guide. That is the job of the manual, the doxygen reference, and the samples. @@ -57,7 +58,7 @@ Version 3.0: ```c b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; -bodyDef.position = {0.0f, 4.0f}; +bodyDef.position = (b2Vec2){0.0f, 4.0f}; b2BodyId bodyId = b2CreateBody(worldId, &bodyDef); ``` Body creation is very similar in v3.0. In this case there is a definition initialization function `b2DefaultBodyDef()`. This can help save a bit of typing in some cases. In v3.0 I recommend getting comfortable with curly brace initialization for initializing vectors. There are no member functions in C. Notice that the body is created using a loose function and providing the `b2WorldId` as an argument. Basically what you would expect going from C++ to C. @@ -73,7 +74,7 @@ Version 3.0: b2DestroyBody(bodyId); bodyId = b2_nullBodyId; ``` -Notice there is a little magic here in Version 3.0. `b2BodyId` knows what world it comes from. So you do not need to provide `worldId` when destroying the body. Version 3.0 supports up to 128 worlds. This may increased or be overridden in the future. +Notice there is a little magic here in Version 3.0. `b2BodyId` knows what world it comes from. So you do not need to provide `worldId` when destroying the body. Version 3.0 supports up to 128 worlds. This may be increased or be overridden in the future. Shapes and joints are still destroyed automatically. However, `b2DestructionListener` is gone. This holds to the theme of fewer callbacks. However, you can now use `b2Shape_IsValid()` and `b2Joint_IsValid()`. @@ -105,7 +106,7 @@ shapeDef.friction = 0.3f; b2ShapeId shapeId = b2CreatePolygonShape(bodyId, &shapeDef, &box); ``` -So basically v2.4 shapes are no longer shapes, they are *primitives* with no inheritance (of course). This freed the term _shape_ to be used where _fixture_ was used before. In v3.0 the shape definition is generic and there are different functions for creating each shape type, such as `b2CreateCircleShape` or `b2CreateSegmentShape`. +So basically v2.4 shapes are no longer shapes, they are *primitives* or *geometry* with no inheritance (of course). This freed the term _shape_ to be used where _fixture_ was used before. In v3.0 the shape definition is generic and there are different functions for creating each shape type, such as `b2CreateCircleShape` or `b2CreateSegmentShape`. Again notice the structure initialization with `b2DefaultShapeDef()`. Unfortunately we cannot have meaningful definitions with zero initialization. You must initialize your structures. @@ -126,7 +127,7 @@ shapeId = b2_nullShapeId; ``` ### Chains -In Version 2.4 chains are a type of shape. In Version 3.0 they are a separate concept. This lead to significant simplifications internally. In Version 2.4 all shapes had to support the notion of child shapes. This is gone. +In Version 2.4 chains are a type of shape. In Version 3.0 they are a separate concept. This leads to significant simplifications internally. In Version 2.4 all shapes had to support the notion of child shapes. This is gone. Version 2.4: ```cpp @@ -161,7 +162,7 @@ chainDef.loop = true; b2ChainId chainId = b2CreateChain(bodyId, &chainDef); ``` -Since chains are their own concept now, they get their own identifier, `b2ChainId`. You can view chains as macro objects, they create many `b2SmoothSegment` shapes internally. Normally you don't interact with these. However they are returned from queries. I may need to write an API to allow you to get the `b2ChainId` for a smooth segment that you get from a query. +Since chains are their own concept now, they get their own identifier, `b2ChainId`. You can view chains as macro objects, they create many `b2SmoothSegment` shapes internally. Normally you don't interact with these. However they are returned from queries. You can use `b2Shape_GetParentChain()` to get the `b2ChainId` for a smooth segment that you get from a query. > DO NOT destroy or modify a `b2SmoothSegment` that belongs to a chain shape directly @@ -201,10 +202,10 @@ Some of the joints have more options now. Check the code comments and samples fo The friction joint has been removed since it is a subset of the motor joint. -The pulley and gear joints have been removed. I'm not quite happy with how they work and plan to implement improved versions in the future. +The pulley and gear joints have been removed. I'm not satisfied with how they work in 2.4 and plan to implement improved versions in the future. ### New solver -There is a new solver that uses sub-stepping. Instead of specifying velocity iterations or position iterations, you now specify the number of sub-steps. +There is a new solver that uses sub-stepping called *Soft Step*. Instead of specifying velocity iterations or position iterations, you now specify the number of sub-steps. ```c void b2World_Step(b2WorldId worldId, float timeStep, int32_t subStepCount); ``` diff --git a/docs/simulation.md b/docs/simulation.md index 3e6e9f61..9f9502b7 100644 --- a/docs/simulation.md +++ b/docs/simulation.md @@ -1089,7 +1089,7 @@ for (int i = 0; i < contactEvents.hitCount; ++i) Shapes only generate hit events if `b2ShapeDef::enableHitEvents` is true. I recommend you only enable this for shapes that need hit events because it creates some overhead. Box2D also only reports hit events that have an -approach speed is larger than `b2WorldDef::hitEventThreshold`. +approach speed larger than `b2WorldDef::hitEventThreshold`. ### Contact Filtering Often in a game you don't want all objects to collide. For example, you diff --git a/include/box2d/base.h b/include/box2d/base.h index c8110a40..b98f2167 100644 --- a/include/box2d/base.h +++ b/include/box2d/base.h @@ -6,17 +6,17 @@ #include // Shared library macros -#if defined(_MSC_VER) && defined(box2d_EXPORTS) +#if defined( _MSC_VER ) && defined( box2d_EXPORTS ) // build the Windows DLL - #define BOX2D_EXPORT __declspec(dllexport) -#elif defined(_MSC_VER) && defined(BOX2D_DLL) - // using the Windows DLL - #define BOX2D_EXPORT __declspec(dllimport) -#elif defined(box2d_EXPORTS) - // building or using the Box2D shared library - #define BOX2D_EXPORT __attribute__((visibility("default"))) + #define BOX2D_EXPORT __declspec( dllexport ) +#elif defined( _MSC_VER ) && defined( BOX2D_DLL ) +// using the Windows DLL + #define BOX2D_EXPORT __declspec( dllimport ) +#elif defined( box2d_EXPORTS ) +// building or using the Box2D shared library + #define BOX2D_EXPORT __attribute__( ( visibility( "default" ) ) ) #else - // static library +// static library #define BOX2D_EXPORT #endif @@ -45,25 +45,25 @@ /// 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* b2AllocFcn(unsigned int size, int alignment); +typedef void* b2AllocFcn( unsigned int size, int alignment ); /// Prototype for user free function /// @param mem the memory previously allocated through `b2AllocFcn` -typedef void b2FreeFcn(void* mem); +typedef void b2FreeFcn( void* mem ); /// Prototype for the user assert callback. Return 0 to skip the debugger break. -typedef int b2AssertFcn(const char* condition, const char* fileName, int lineNumber); +typedef int b2AssertFcn( const char* condition, const char* fileName, int lineNumber ); /// This allows the user to override the allocation functions. These should be /// set during application startup. -B2_API void b2SetAllocator(b2AllocFcn* allocFcn, b2FreeFcn* freeFcn); +B2_API void b2SetAllocator( b2AllocFcn* allocFcn, b2FreeFcn* freeFcn ); /// @return the total bytes allocated by Box2D -B2_API int b2GetByteCount(void); +B2_API int b2GetByteCount( void ); /// Override the default assert callback /// @param assertFcn a non-null assert callback -B2_API void b2SetAssertFcn(b2AssertFcn* assertFcn); +B2_API void b2SetAssertFcn( b2AssertFcn* assertFcn ); /// Version numbering scheme. /// See https://semver.org/ @@ -80,7 +80,7 @@ typedef struct b2Version } b2Version; /// Get the current version of Box2D -B2_API b2Version b2GetVersion(void); +B2_API b2Version b2GetVersion( void ); /**@}*/ @@ -88,9 +88,9 @@ B2_API b2Version b2GetVersion(void); // Timer for profiling. This has platform specific code and may not work on every platform. typedef struct b2Timer { -#if defined(_WIN32) +#if defined( _WIN32 ) int64_t start; -#elif defined(__linux__) || defined(__APPLE__) +#elif defined( __linux__ ) || defined( __APPLE__ ) unsigned long long start_sec; unsigned long long start_usec; #else @@ -98,10 +98,10 @@ typedef struct b2Timer #endif } b2Timer; -B2_API b2Timer b2CreateTimer(void); -B2_API int64_t b2GetTicks(b2Timer* timer); -B2_API float b2GetMilliseconds(const b2Timer* timer); -B2_API float b2GetMillisecondsAndReset(b2Timer* timer); -B2_API void b2SleepMilliseconds(int milliseconds); -B2_API void b2Yield(void); +B2_API b2Timer b2CreateTimer( void ); +B2_API int64_t b2GetTicks( b2Timer* timer ); +B2_API float b2GetMilliseconds( const b2Timer* timer ); +B2_API float b2GetMillisecondsAndReset( b2Timer* timer ); +B2_API void b2SleepMilliseconds( int milliseconds ); +B2_API void b2Yield( void ); //! @endcond diff --git a/include/box2d/box2d.h b/include/box2d/box2d.h index 560e8444..cfe8bc94 100644 --- a/include/box2d/box2d.h +++ b/include/box2d/box2d.h @@ -24,46 +24,46 @@ /// 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. /// @return the world id. -B2_API b2WorldId b2CreateWorld(const b2WorldDef* def); +B2_API b2WorldId b2CreateWorld( const b2WorldDef* def ); /// Destroy a world -B2_API void b2DestroyWorld(b2WorldId worldId); +B2_API void b2DestroyWorld( b2WorldId worldId ); /// World id validation. Provides validation for up to 64K allocations. -B2_API bool b2World_IsValid(b2WorldId id); +B2_API bool b2World_IsValid( b2WorldId id ); /// Simulate a world for one time step. This performs collision detection, integration, and constraint solution. /// @param worldId The world to simulate /// @param timeStep The amount of time to simulate, this should be a fixed number. Typically 1/60. /// @param subStepCount The number of sub-steps, increasing the sub-step count can increase accuracy. Typically 4. -B2_API void b2World_Step(b2WorldId worldId, float timeStep, int subStepCount); +B2_API void b2World_Step( b2WorldId worldId, float timeStep, int subStepCount ); /// Call this to draw shapes and other debug draw data -B2_API void b2World_Draw(b2WorldId worldId, b2DebugDraw* draw); +B2_API void b2World_Draw( b2WorldId worldId, b2DebugDraw* draw ); /// Get the body events for the current time step. The event data is transient. Do not store a reference to this data. -B2_API b2BodyEvents b2World_GetBodyEvents(b2WorldId worldId); +B2_API b2BodyEvents b2World_GetBodyEvents( 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 b2SensorEvents b2World_GetSensorEvents(b2WorldId worldId); +B2_API b2SensorEvents b2World_GetSensorEvents( 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 b2ContactEvents b2World_GetContactEvents(b2WorldId worldId); +B2_API b2ContactEvents b2World_GetContactEvents( b2WorldId worldId ); /// Overlap test for all shapes that *potentially* overlap the provided AABB -B2_API void b2World_OverlapAABB(b2WorldId worldId, b2AABB aabb, b2QueryFilter filter, b2OverlapResultFcn* fcn, void* context); +B2_API void b2World_OverlapAABB( b2WorldId worldId, b2AABB aabb, b2QueryFilter filter, b2OverlapResultFcn* fcn, void* context ); /// Overlap test for for all shapes that overlap the provided circle -B2_API void b2World_OverlapCircle(b2WorldId worldId, const b2Circle* circle, b2Transform transform, b2QueryFilter filter, - b2OverlapResultFcn* fcn, void* context); +B2_API void b2World_OverlapCircle( b2WorldId worldId, const b2Circle* circle, b2Transform transform, b2QueryFilter filter, + b2OverlapResultFcn* fcn, void* context ); /// Overlap test for all shapes that overlap the provided capsule -B2_API void b2World_OverlapCapsule(b2WorldId worldId, const b2Capsule* capsule, b2Transform transform, b2QueryFilter filter, - b2OverlapResultFcn* fcn, void* context); +B2_API 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 polygon -B2_API void b2World_OverlapPolygon(b2WorldId worldId, const b2Polygon* polygon, b2Transform transform, b2QueryFilter filter, - b2OverlapResultFcn* fcn, void* context); +B2_API void b2World_OverlapPolygon( b2WorldId worldId, const b2Polygon* polygon, b2Transform transform, b2QueryFilter filter, + b2OverlapResultFcn* 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. @@ -75,66 +75,66 @@ B2_API void b2World_OverlapPolygon(b2WorldId worldId, const b2Polygon* polygon, /// @param fcn A user implemented callback function /// @param context A user context that is passed along to the callback function /// @note The callback function may receive shapes in any order -B2_API void b2World_CastRay(b2WorldId worldId, b2Vec2 origin, b2Vec2 translation, b2QueryFilter filter, b2CastResultFcn* fcn, - void* context); +B2_API void b2World_CastRay( b2WorldId worldId, b2Vec2 origin, b2Vec2 translation, b2QueryFilter filter, b2CastResultFcn* fcn, + void* context ); /// 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 b2RayResult b2World_CastRayClosest(b2WorldId worldId, b2Vec2 origin, b2Vec2 translation, b2QueryFilter filter); +B2_API b2RayResult b2World_CastRayClosest( b2WorldId worldId, b2Vec2 origin, b2Vec2 translation, b2QueryFilter filter ); /// Cast a circle through the world. Similar to a cast ray except that a circle is cast instead of a point. -B2_API void b2World_CastCircle(b2WorldId worldId, const b2Circle* circle, b2Transform originTransform, b2Vec2 translation, - b2QueryFilter filter, b2CastResultFcn* fcn, void* context); +B2_API void b2World_CastCircle( b2WorldId worldId, const b2Circle* circle, 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. -B2_API void b2World_CastCapsule(b2WorldId worldId, const b2Capsule* capsule, b2Transform originTransform, b2Vec2 translation, - b2QueryFilter filter, b2CastResultFcn* fcn, void* context); +B2_API void b2World_CastCapsule( b2WorldId worldId, const b2Capsule* capsule, 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. -B2_API void b2World_CastPolygon(b2WorldId worldId, const b2Polygon* polygon, b2Transform originTransform, b2Vec2 translation, - b2QueryFilter filter, b2CastResultFcn* fcn, void* context); +B2_API void b2World_CastPolygon( b2WorldId worldId, const b2Polygon* polygon, b2Transform originTransform, b2Vec2 translation, + b2QueryFilter filter, b2CastResultFcn* fcn, void* context ); /// Enable/disable sleep. If your application does not need sleeping, you can gain some performance /// by disabling sleep completely at the world level. /// @see b2WorldDef -B2_API void b2World_EnableSleeping(b2WorldId worldId, bool flag); +B2_API void b2World_EnableSleeping( 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. /// @see b2WorldDef -B2_API void b2World_EnableContinuous(b2WorldId worldId, bool flag); +B2_API void b2World_EnableContinuous( b2WorldId worldId, bool flag ); /// 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. /// @see b2WorldDef -B2_API void b2World_SetRestitutionThreshold(b2WorldId worldId, float value); +B2_API void b2World_SetRestitutionThreshold( b2WorldId worldId, float value ); /// Adjust the hit event threshold. This controls the collision velocity needed to generate a b2ContactHitEvent. /// Typically in meters per second. /// @see b2WorldDef::hitEventThreshold -B2_API void b2World_SetHitEventThreshold(b2WorldId worldId, float value); +B2_API void b2World_SetHitEventThreshold( b2WorldId worldId, float value ); /// Register the custom filter callback. This is optional. -B2_API void b2World_SetCustomFilterCallback(b2WorldId worldId, b2CustomFilterFcn* fcn, void* context); +B2_API void b2World_SetCustomFilterCallback( b2WorldId worldId, b2CustomFilterFcn* fcn, void* context ); /// Register the pre-solve callback. This is optional. -B2_API void b2World_SetPreSolveCallback(b2WorldId worldId, b2PreSolveFcn* fcn, void* context); +B2_API void b2World_SetPreSolveCallback( b2WorldId worldId, b2PreSolveFcn* fcn, void* context ); /// 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. /// @see b2WorldDef -B2_API void b2World_SetGravity(b2WorldId worldId, b2Vec2 gravity); +B2_API void b2World_SetGravity( b2WorldId worldId, b2Vec2 gravity ); /// Get the gravity vector -B2_API b2Vec2 b2World_GetGravity(b2WorldId worldId); +B2_API b2Vec2 b2World_GetGravity( b2WorldId worldId ); /// Apply a radial explosion /// @param worldId The world id /// @param position The center of the explosion /// @param radius The radius of the explosion /// @param impulse The impulse of the explosion, typically in kg * m / s or N * s. -B2_API void b2World_Explode(b2WorldId worldId, b2Vec2 position, float radius, float impulse); +B2_API void b2World_Explode( b2WorldId worldId, b2Vec2 position, float radius, float impulse ); /// Adjust contact tuning parameters /// @param worldId The world id @@ -142,20 +142,20 @@ B2_API void b2World_Explode(b2WorldId worldId, b2Vec2 position, float radius, fl /// @param dampingRatio The contact bounciness with 1 being critical damping (non-dimensional) /// @param pushVelocity The maximum contact constraint push out velocity (meters per second) /// @note Advanced feature -B2_API void b2World_SetContactTuning(b2WorldId worldId, float hertz, float dampingRatio, float pushVelocity); +B2_API void b2World_SetContactTuning( b2WorldId worldId, float hertz, float dampingRatio, float pushVelocity ); /// Enable/disable constraint warm starting. Advanced feature for testing. Disabling /// sleeping greatly reduces stability and provides no performance gain. -B2_API void b2World_EnableWarmStarting(b2WorldId worldId, bool flag); +B2_API void b2World_EnableWarmStarting( b2WorldId worldId, bool flag ); /// Get the current world performance profile -B2_API b2Profile b2World_GetProfile(b2WorldId worldId); +B2_API b2Profile b2World_GetProfile( b2WorldId worldId ); /// Get world counters and sizes -B2_API b2Counters b2World_GetCounters(b2WorldId worldId); +B2_API b2Counters b2World_GetCounters( b2WorldId worldId ); /// Dump memory stats to box2d_memory.txt -B2_API void b2World_DumpMemoryStats(b2WorldId worldId); +B2_API void b2World_DumpMemoryStats( b2WorldId worldId ); /** @} */ @@ -172,65 +172,65 @@ B2_API void b2World_DumpMemoryStats(b2WorldId worldId); /// b2BodyId myBodyId = b2CreateBody(myWorldId, &bodyDef); /// @endcode /// @warning This function is locked during callbacks. -B2_API b2BodyId b2CreateBody(b2WorldId worldId, const b2BodyDef* def); +B2_API b2BodyId b2CreateBody( b2WorldId worldId, const b2BodyDef* def ); /// Destroy a rigid body given an id. This destroys all shapes and joints attached to the body. /// Do not keep references to the associated shapes and joints. -B2_API void b2DestroyBody(b2BodyId bodyId); +B2_API void b2DestroyBody( b2BodyId bodyId ); /// Body identifier validation. Can be used to detect orphaned ids. Provides validation for up to 64K allocations. -B2_API bool b2Body_IsValid(b2BodyId id); +B2_API bool b2Body_IsValid( b2BodyId id ); /// Get the body type: static, kinematic, or dynamic -B2_API b2BodyType b2Body_GetType(b2BodyId bodyId); +B2_API b2BodyType b2Body_GetType( b2BodyId bodyId ); /// Change the body type. This is an expensive operation. This automatically updates the mass /// properties regardless of the automatic mass setting. -B2_API void b2Body_SetType(b2BodyId bodyId, b2BodyType type); +B2_API void b2Body_SetType( b2BodyId bodyId, b2BodyType type ); /// Set the user data for a body -B2_API void b2Body_SetUserData(b2BodyId bodyId, void* userData); +B2_API void b2Body_SetUserData( b2BodyId bodyId, void* userData ); /// Get the user data stored in a body -B2_API void* b2Body_GetUserData(b2BodyId bodyId); +B2_API void* b2Body_GetUserData( b2BodyId bodyId ); /// Get the world position of a body. This is the location of the body origin. -B2_API b2Vec2 b2Body_GetPosition(b2BodyId bodyId); +B2_API b2Vec2 b2Body_GetPosition( b2BodyId bodyId ); /// Get the world rotation of a body as a cosine/sine pair (complex number) -B2_API b2Rot b2Body_GetRotation(b2BodyId bodyId); +B2_API b2Rot b2Body_GetRotation( b2BodyId bodyId ); /// Get the world transform of a body. -B2_API b2Transform b2Body_GetTransform(b2BodyId bodyId); +B2_API b2Transform b2Body_GetTransform( b2BodyId bodyId ); /// Set the world transform of a body. This acts as a teleport and is fairly expensive. /// @note Generally you should create a body with then intended transform. /// @see b2BodyDef::position and b2BodyDef::angle -B2_API void b2Body_SetTransform(b2BodyId bodyId, b2Vec2 position, b2Rot rotation); +B2_API void b2Body_SetTransform( b2BodyId bodyId, b2Vec2 position, b2Rot rotation ); /// Get a local point on a body given a world point -B2_API b2Vec2 b2Body_GetLocalPoint(b2BodyId bodyId, b2Vec2 worldPoint); +B2_API b2Vec2 b2Body_GetLocalPoint( b2BodyId bodyId, b2Vec2 worldPoint ); /// Get a world point on a body given a local point -B2_API b2Vec2 b2Body_GetWorldPoint(b2BodyId bodyId, b2Vec2 localPoint); +B2_API b2Vec2 b2Body_GetWorldPoint( b2BodyId bodyId, b2Vec2 localPoint ); /// Get a local vector on a body given a world vector -B2_API b2Vec2 b2Body_GetLocalVector(b2BodyId bodyId, b2Vec2 worldVector); +B2_API b2Vec2 b2Body_GetLocalVector( b2BodyId bodyId, b2Vec2 worldVector ); /// Get a world vector on a body given a local vector -B2_API b2Vec2 b2Body_GetWorldVector(b2BodyId bodyId, b2Vec2 localVector); +B2_API b2Vec2 b2Body_GetWorldVector( b2BodyId bodyId, b2Vec2 localVector ); /// Get the linear velocity of a body's center of mass. Typically in meters per second. -B2_API b2Vec2 b2Body_GetLinearVelocity(b2BodyId bodyId); +B2_API b2Vec2 b2Body_GetLinearVelocity( b2BodyId bodyId ); /// Get the angular velocity of a body in radians per second -B2_API float b2Body_GetAngularVelocity(b2BodyId bodyId); +B2_API float b2Body_GetAngularVelocity( b2BodyId bodyId ); /// Set the linear velocity of a body. Typically in meters per second. -B2_API void b2Body_SetLinearVelocity(b2BodyId bodyId, b2Vec2 linearVelocity); +B2_API void b2Body_SetLinearVelocity( b2BodyId bodyId, b2Vec2 linearVelocity ); /// Set the angular velocity of a body in radians per second -B2_API void b2Body_SetAngularVelocity(b2BodyId bodyId, float angularVelocity); +B2_API void b2Body_SetAngularVelocity( b2BodyId bodyId, float angularVelocity ); /// Apply a force at a world point. If the force is not applied at the center of mass, /// it will generate a torque and affect the angular velocity. This optionally wakes up the body. @@ -239,21 +239,21 @@ B2_API void b2Body_SetAngularVelocity(b2BodyId bodyId, float angularVelocity); /// @param force The world force vector, typically in newtons (N) /// @param point The world position of the point of application /// @param wake Option to wake up the body -B2_API void b2Body_ApplyForce(b2BodyId bodyId, b2Vec2 force, b2Vec2 point, bool wake); +B2_API void b2Body_ApplyForce( b2BodyId bodyId, b2Vec2 force, b2Vec2 point, bool wake ); /// Apply a force to the center of mass. This optionally wakes up the body. /// The force is ignored if the body is not awake. /// @param bodyId The body id /// @param force the world force vector, usually in newtons (N). /// @param wake also wake up the body -B2_API void b2Body_ApplyForceToCenter(b2BodyId bodyId, b2Vec2 force, bool wake); +B2_API void b2Body_ApplyForceToCenter( b2BodyId bodyId, b2Vec2 force, bool wake ); /// Apply a torque. This affects the angular velocity without affecting the linear velocity. /// This optionally wakes the body. The torque is ignored if the body is not awake. /// @param bodyId The body id /// @param torque about the z-axis (out of the screen), typically in N*m. /// @param wake also wake up the body -B2_API void b2Body_ApplyTorque(b2BodyId bodyId, float torque, bool wake); +B2_API void b2Body_ApplyTorque( b2BodyId bodyId, float torque, bool wake ); /// Apply an impulse at a point. This immediately modifies the velocity. /// It also modifies the angular velocity if the point of application @@ -265,7 +265,7 @@ B2_API void b2Body_ApplyTorque(b2BodyId bodyId, float torque, bool wake); /// @param wake also wake up the body /// @warning This should be used for one-shot impulses. If you need a steady force, /// use a force instead, which will work better with the sub-stepping solver. -B2_API void b2Body_ApplyLinearImpulse(b2BodyId bodyId, b2Vec2 impulse, b2Vec2 point, bool wake); +B2_API void b2Body_ApplyLinearImpulse( b2BodyId bodyId, b2Vec2 impulse, b2Vec2 point, bool wake ); /// Apply an impulse to the center of mass. This immediately modifies the velocity. /// The impulse is ignored if the body is not awake. This optionally wakes the body. @@ -274,7 +274,7 @@ B2_API void b2Body_ApplyLinearImpulse(b2BodyId bodyId, b2Vec2 impulse, b2Vec2 po /// @param wake also wake up the body /// @warning This should be used for one-shot impulses. If you need a steady force, /// use a force instead, which will work better with the sub-stepping solver. -B2_API void b2Body_ApplyLinearImpulseToCenter(b2BodyId bodyId, b2Vec2 impulse, bool wake); +B2_API void b2Body_ApplyLinearImpulseToCenter( b2BodyId bodyId, b2Vec2 impulse, bool wake ); /// Apply an angular impulse. The impulse is ignored if the body is not awake. /// This optionally wakes the body. @@ -283,130 +283,130 @@ B2_API void b2Body_ApplyLinearImpulseToCenter(b2BodyId bodyId, b2Vec2 impulse, b /// @param wake also wake up the body /// @warning This should be used for one-shot impulses. If you need a steady force, /// use a force instead, which will work better with the sub-stepping solver. -B2_API void b2Body_ApplyAngularImpulse(b2BodyId bodyId, float impulse, bool wake); +B2_API void b2Body_ApplyAngularImpulse( b2BodyId bodyId, float impulse, bool wake ); /// Get the mass of the body, typically in kilograms -B2_API float b2Body_GetMass(b2BodyId bodyId); +B2_API float b2Body_GetMass( b2BodyId bodyId ); /// Get the inertia tensor of the body, typically in kg*m^2 -B2_API float b2Body_GetInertiaTensor(b2BodyId bodyId); +B2_API float b2Body_GetInertiaTensor( b2BodyId bodyId ); /// Get the center of mass position of the body in local space -B2_API b2Vec2 b2Body_GetLocalCenterOfMass(b2BodyId bodyId); +B2_API b2Vec2 b2Body_GetLocalCenterOfMass( b2BodyId bodyId ); /// Get the center of mass position of the body in world space -B2_API b2Vec2 b2Body_GetWorldCenterOfMass(b2BodyId bodyId); +B2_API b2Vec2 b2Body_GetWorldCenterOfMass( b2BodyId bodyId ); /// Override the body's mass properties. Normally this is computed automatically using the /// shape geometry and density. This information is lost if a shape is added or removed or if the /// body type changes. -B2_API void b2Body_SetMassData(b2BodyId bodyId, b2MassData massData); +B2_API void b2Body_SetMassData( b2BodyId bodyId, b2MassData massData ); /// Get the mass data for a body -B2_API b2MassData b2Body_GetMassData(b2BodyId bodyId); +B2_API b2MassData b2Body_GetMassData( b2BodyId bodyId ); /// This update the mass properties to the sum of the mass properties of the shapes. /// This normally does not need to be called unless you called SetMassData to override /// the mass and you later want to reset the mass. /// You may also use this when automatic mass computation has been disabled. /// You should call this regardless of body type. -B2_API void b2Body_ApplyMassFromShapes(b2BodyId bodyId); +B2_API void b2Body_ApplyMassFromShapes( b2BodyId bodyId ); /// Set the automatic mass setting. Normally this is set in b2BodyDef before creation. /// @see b2BodyDef::automaticMass -B2_API void b2Body_SetAutomaticMass(b2BodyId bodyId, bool automaticMass); +B2_API void b2Body_SetAutomaticMass( b2BodyId bodyId, bool automaticMass ); /// Get the automatic mass setting -B2_API bool b2Body_GetAutomaticMass(b2BodyId bodyId); +B2_API bool b2Body_GetAutomaticMass( b2BodyId bodyId ); /// Adjust the linear damping. Normally this is set in b2BodyDef before creation. -B2_API void b2Body_SetLinearDamping(b2BodyId bodyId, float linearDamping); +B2_API void b2Body_SetLinearDamping( b2BodyId bodyId, float linearDamping ); /// Get the current linear damping. -B2_API float b2Body_GetLinearDamping(b2BodyId bodyId); +B2_API float b2Body_GetLinearDamping( b2BodyId bodyId ); /// Adjust the angular damping. Normally this is set in b2BodyDef before creation. -B2_API void b2Body_SetAngularDamping(b2BodyId bodyId, float angularDamping); +B2_API void b2Body_SetAngularDamping( b2BodyId bodyId, float angularDamping ); /// Get the current angular damping. -B2_API float b2Body_GetAngularDamping(b2BodyId bodyId); +B2_API float b2Body_GetAngularDamping( b2BodyId bodyId ); /// Adjust the gravity scale. Normally this is set in b2BodyDef before creation. /// @see b2BodyDef::gravityScale -B2_API void b2Body_SetGravityScale(b2BodyId bodyId, float gravityScale); +B2_API void b2Body_SetGravityScale( b2BodyId bodyId, float gravityScale ); /// Get the current gravity scale -B2_API float b2Body_GetGravityScale(b2BodyId bodyId); +B2_API float b2Body_GetGravityScale( b2BodyId bodyId ); /// @return true if this body is awake -B2_API bool b2Body_IsAwake(b2BodyId bodyId); +B2_API bool b2Body_IsAwake( b2BodyId bodyId ); /// Wake a body from sleep. This wakes the entire island the body is touching. /// @warning Putting a body to sleep will put the entire island of bodies touching this body to sleep, /// which can be expensive and possibly unintuitive. -B2_API void b2Body_SetAwake(b2BodyId bodyId, bool awake); +B2_API void b2Body_SetAwake( b2BodyId bodyId, bool awake ); /// Enable or disable sleeping for this body. If sleeping is disabled the body will wake. -B2_API void b2Body_EnableSleep(b2BodyId bodyId, bool enableSleep); +B2_API void b2Body_EnableSleep( b2BodyId bodyId, bool enableSleep ); /// Returns true if sleeping is enabled for this body -B2_API bool b2Body_IsSleepEnabled(b2BodyId bodyId); +B2_API bool b2Body_IsSleepEnabled( b2BodyId bodyId ); /// Set the sleep threshold, typically in meters per second -B2_API void b2Body_SetSleepThreshold(b2BodyId bodyId, float sleepVelocity); +B2_API void b2Body_SetSleepThreshold( b2BodyId bodyId, float sleepVelocity ); /// Get the sleep threshold, typically in meters per second. -B2_API float b2Body_GetSleepThreshold(b2BodyId bodyId); +B2_API float b2Body_GetSleepThreshold( b2BodyId bodyId ); /// Returns true if this body is enabled -B2_API bool b2Body_IsEnabled(b2BodyId bodyId); +B2_API bool b2Body_IsEnabled( b2BodyId bodyId ); /// Disable a body by removing it completely from the simulation. This is expensive. -B2_API void b2Body_Disable(b2BodyId bodyId); +B2_API void b2Body_Disable( b2BodyId bodyId ); /// Enable a body by adding it to the simulation. This is expensive. -B2_API void b2Body_Enable(b2BodyId bodyId); +B2_API void b2Body_Enable( b2BodyId bodyId ); /// Set this body to have fixed rotation. This causes the mass to be reset in all cases. -B2_API void b2Body_SetFixedRotation(b2BodyId bodyId, bool flag); +B2_API void b2Body_SetFixedRotation( b2BodyId bodyId, bool flag ); /// Does this body have fixed rotation? -B2_API bool b2Body_IsFixedRotation(b2BodyId bodyId); +B2_API bool b2Body_IsFixedRotation( b2BodyId bodyId ); /// Set this body to be a bullet. A bullet does continuous collision detection /// against dynamic bodies (but not other bullets). -B2_API void b2Body_SetBullet(b2BodyId bodyId, bool flag); +B2_API void b2Body_SetBullet( b2BodyId bodyId, bool flag ); /// Is this body a bullet? -B2_API bool b2Body_IsBullet(b2BodyId bodyId); +B2_API bool b2Body_IsBullet( b2BodyId bodyId ); /// Enable/disable hit events on all shapes /// @see b2ShapeDef::enableHitEvents -B2_API void b2Body_EnableHitEvents(b2BodyId bodyId, bool enableHitEvents); +B2_API void b2Body_EnableHitEvents( b2BodyId bodyId, bool enableHitEvents ); /// Get the number of shapes on this body -B2_API int b2Body_GetShapeCount(b2BodyId bodyId); +B2_API int b2Body_GetShapeCount( b2BodyId bodyId ); /// Get the shape ids for all shapes on this body, up to the provided capacity. /// @returns the number of shape ids stored in the user array -B2_API int b2Body_GetShapes(b2BodyId bodyId, b2ShapeId* shapeArray, int capacity); +B2_API int b2Body_GetShapes( b2BodyId bodyId, b2ShapeId* shapeArray, int capacity ); /// Get the number of joints on this body -B2_API int b2Body_GetJointCount(b2BodyId bodyId); +B2_API int b2Body_GetJointCount( b2BodyId bodyId ); /// Get the joint ids for all joints on this body, up to the provided capacity /// @returns the number of joint ids stored in the user array -B2_API int b2Body_GetJoints(b2BodyId bodyId, b2JointId* jointArray, int capacity); +B2_API int b2Body_GetJoints( b2BodyId bodyId, b2JointId* jointArray, int capacity ); /// Get the maximum capacity required for retrieving all the touching contacts on a body -B2_API int b2Body_GetContactCapacity(b2BodyId bodyId); +B2_API int b2Body_GetContactCapacity( b2BodyId bodyId ); /// Get the touching contact data for a body -B2_API int b2Body_GetContactData(b2BodyId bodyId, b2ContactData* contactData, int capacity); +B2_API int b2Body_GetContactData( b2BodyId bodyId, b2ContactData* contactData, int capacity ); /// Get the current world AABB that contains all the attached shapes. Note that this may not encompass the body origin. /// If there are no shapes attached then the returned AABB is empty and centered on the body origin. -B2_API b2AABB b2Body_ComputeAABB(b2BodyId bodyId); +B2_API b2AABB b2Body_ComputeAABB( b2BodyId bodyId ); /** @} */ @@ -420,178 +420,178 @@ B2_API b2AABB b2Body_ComputeAABB(b2BodyId bodyId); /// Create a circle shape and attach it to a body. The shape definition and geometry are fully cloned. /// Contacts are not created until the next time step. /// @return the shape id for accessing the shape -B2_API b2ShapeId b2CreateCircleShape(b2BodyId bodyId, const b2ShapeDef* def, const b2Circle* circle); +B2_API b2ShapeId b2CreateCircleShape( b2BodyId bodyId, const b2ShapeDef* def, const b2Circle* circle ); /// Create a line segment shape and attach it to a body. The shape definition and geometry are fully cloned. /// Contacts are not created until the next time step. /// @return the shape id for accessing the shape -B2_API b2ShapeId b2CreateSegmentShape(b2BodyId bodyId, const b2ShapeDef* def, const b2Segment* segment); +B2_API b2ShapeId b2CreateSegmentShape( b2BodyId bodyId, const b2ShapeDef* def, const b2Segment* segment ); /// Create a capsule shape and attach it to a body. The shape definition and geometry are fully cloned. /// Contacts are not created until the next time step. /// @return the shape id for accessing the shape -B2_API b2ShapeId b2CreateCapsuleShape(b2BodyId bodyId, const b2ShapeDef* def, const b2Capsule* capsule); +B2_API b2ShapeId b2CreateCapsuleShape( b2BodyId bodyId, const b2ShapeDef* def, const b2Capsule* capsule ); /// Create a polygon shape and attach it to a body. The shape definition and geometry are fully cloned. /// Contacts are not created until the next time step. /// @return the shape id for accessing the shape -B2_API b2ShapeId b2CreatePolygonShape(b2BodyId bodyId, const b2ShapeDef* def, const b2Polygon* polygon); +B2_API b2ShapeId b2CreatePolygonShape( b2BodyId bodyId, const b2ShapeDef* def, const b2Polygon* polygon ); /// Destroy a shape -B2_API void b2DestroyShape(b2ShapeId shapeId); +B2_API void b2DestroyShape( b2ShapeId shapeId ); /// Shape identifier validation. Provides validation for up to 64K allocations. -B2_API bool b2Shape_IsValid(b2ShapeId id); +B2_API bool b2Shape_IsValid( b2ShapeId id ); /// Get the type of a shape -B2_API b2ShapeType b2Shape_GetType(b2ShapeId shapeId); +B2_API b2ShapeType b2Shape_GetType( b2ShapeId shapeId ); /// Get the id of the body that a shape is attached to -B2_API b2BodyId b2Shape_GetBody(b2ShapeId shapeId); +B2_API b2BodyId b2Shape_GetBody( b2ShapeId shapeId ); /// Returns true If the shape is a sensor -B2_API bool b2Shape_IsSensor(b2ShapeId shapeId); +B2_API bool b2Shape_IsSensor( b2ShapeId shapeId ); /// Set the user data for a shape -B2_API void b2Shape_SetUserData(b2ShapeId shapeId, void* userData); +B2_API void b2Shape_SetUserData( b2ShapeId shapeId, void* userData ); /// Get the user data for a shape. This is useful when you get a shape id /// from an event or query. -B2_API void* b2Shape_GetUserData(b2ShapeId shapeId); +B2_API void* b2Shape_GetUserData( b2ShapeId shapeId ); /// Set the mass density of a shape, typically in kg/m^2. /// This will not update the mass properties on the parent body. /// @see b2ShapeDef::density, b2Body_ApplyMassFromShapes -B2_API void b2Shape_SetDensity(b2ShapeId shapeId, float density); +B2_API void b2Shape_SetDensity( b2ShapeId shapeId, float density ); /// Get the density of a shape, typically in kg/m^2 -B2_API float b2Shape_GetDensity(b2ShapeId shapeId); +B2_API float b2Shape_GetDensity( b2ShapeId shapeId ); /// Set the friction on a shape /// @see b2ShapeDef::friction -B2_API void b2Shape_SetFriction(b2ShapeId shapeId, float friction); +B2_API void b2Shape_SetFriction( b2ShapeId shapeId, float friction ); /// Get the friction of a shape -B2_API float b2Shape_GetFriction(b2ShapeId shapeId); +B2_API float b2Shape_GetFriction( b2ShapeId shapeId ); /// Set the shape restitution (bounciness) /// @see b2ShapeDef::restitution -B2_API void b2Shape_SetRestitution(b2ShapeId shapeId, float restitution); +B2_API void b2Shape_SetRestitution( b2ShapeId shapeId, float restitution ); /// Get the shape restitution -B2_API float b2Shape_GetRestitution(b2ShapeId shapeId); +B2_API float b2Shape_GetRestitution( b2ShapeId shapeId ); /// Get the shape filter -B2_API b2Filter b2Shape_GetFilter(b2ShapeId shapeId); +B2_API b2Filter b2Shape_GetFilter( b2ShapeId shapeId ); /// Set the current filter. This is almost as expensive as recreating the shape. /// @see b2ShapeDef::filter -B2_API void b2Shape_SetFilter(b2ShapeId shapeId, b2Filter filter); +B2_API void b2Shape_SetFilter( b2ShapeId shapeId, b2Filter filter ); /// Enable sensor events for this shape. Only applies to kinematic and dynamic bodies. Ignored for sensors. /// @see b2ShapeDef::isSensor -B2_API void b2Shape_EnableSensorEvents(b2ShapeId shapeId, bool flag); +B2_API void b2Shape_EnableSensorEvents( b2ShapeId shapeId, bool flag ); /// Returns true if sensor events are enabled -B2_API bool b2Shape_AreSensorEventsEnabled(b2ShapeId shapeId); +B2_API bool b2Shape_AreSensorEventsEnabled( b2ShapeId shapeId ); /// Enable contact events for this shape. Only applies to kinematic and dynamic bodies. Ignored for sensors. /// @see b2ShapeDef::enableContactEvents -B2_API void b2Shape_EnableContactEvents(b2ShapeId shapeId, bool flag); +B2_API void b2Shape_EnableContactEvents( b2ShapeId shapeId, bool flag ); /// Returns true if contact events are enabled -B2_API bool b2Shape_AreContactEventsEnabled(b2ShapeId shapeId); +B2_API bool b2Shape_AreContactEventsEnabled( b2ShapeId shapeId ); /// Enable pre-solve contact events for this shape. Only applies to dynamic bodies. These are expensive /// and must be carefully handled due to multithreading. Ignored for sensors. /// @see b2PreSolveFcn -B2_API void b2Shape_EnablePreSolveEvents(b2ShapeId shapeId, bool flag); +B2_API void b2Shape_EnablePreSolveEvents( b2ShapeId shapeId, bool flag ); /// Returns true if pre-solve events are enabled -B2_API bool b2Shape_ArePreSolveEventsEnabled(b2ShapeId shapeId); +B2_API bool b2Shape_ArePreSolveEventsEnabled( b2ShapeId shapeId ); /// Enable contact hit events for this shape. Ignored for sensors. /// @see b2WorldDef.hitEventThreshold -B2_API void b2Shape_EnableHitEvents(b2ShapeId shapeId, bool flag); +B2_API void b2Shape_EnableHitEvents( b2ShapeId shapeId, bool flag ); /// Returns true if hit events are enabled -B2_API bool b2Shape_AreHitEventsEnabled(b2ShapeId shapeId); +B2_API bool b2Shape_AreHitEventsEnabled( b2ShapeId shapeId ); /// Test a point for overlap with a shape -B2_API bool b2Shape_TestPoint(b2ShapeId shapeId, b2Vec2 point); +B2_API bool b2Shape_TestPoint( b2ShapeId shapeId, b2Vec2 point ); /// Ray cast a shape directly -B2_API b2CastOutput b2Shape_RayCast(b2ShapeId shapeId, b2Vec2 origin, b2Vec2 translation); +B2_API b2CastOutput b2Shape_RayCast( b2ShapeId shapeId, b2Vec2 origin, b2Vec2 translation ); /// Get a copy of the shape's circle. Asserts the type is correct. -B2_API b2Circle b2Shape_GetCircle(b2ShapeId shapeId); +B2_API b2Circle b2Shape_GetCircle( b2ShapeId shapeId ); /// Get a copy of the shape's line segment. Asserts the type is correct. -B2_API b2Segment b2Shape_GetSegment(b2ShapeId shapeId); +B2_API b2Segment b2Shape_GetSegment( b2ShapeId shapeId ); /// Get a copy of the shape's smooth line segment. These come from chain shapes. /// Asserts the type is correct. -B2_API b2SmoothSegment b2Shape_GetSmoothSegment(b2ShapeId shapeId); +B2_API b2SmoothSegment b2Shape_GetSmoothSegment( b2ShapeId shapeId ); /// Get a copy of the shape's capsule. Asserts the type is correct. -B2_API b2Capsule b2Shape_GetCapsule(b2ShapeId shapeId); +B2_API b2Capsule b2Shape_GetCapsule( b2ShapeId shapeId ); /// Get a copy of the shape's convex polygon. Asserts the type is correct. -B2_API b2Polygon b2Shape_GetPolygon(b2ShapeId shapeId); +B2_API b2Polygon b2Shape_GetPolygon( b2ShapeId shapeId ); /// Allows you to change a shape to be a circle or update the current circle. /// This does not modify the mass properties. /// @see b2Body_ApplyMassFromShapes -B2_API void b2Shape_SetCircle(b2ShapeId shapeId, const b2Circle* circle); +B2_API void b2Shape_SetCircle( b2ShapeId shapeId, const b2Circle* circle ); /// Allows you to change a shape to be a capsule or update the current capsule. /// This does not modify the mass properties. /// @see b2Body_ApplyMassFromShapes -B2_API void b2Shape_SetCapsule(b2ShapeId shapeId, const b2Capsule* capsule); +B2_API void b2Shape_SetCapsule( b2ShapeId shapeId, const b2Capsule* capsule ); /// Allows you to change a shape to be a segment or update the current segment. -B2_API void b2Shape_SetSegment(b2ShapeId shapeId, const b2Segment* segment); +B2_API void b2Shape_SetSegment( b2ShapeId shapeId, const b2Segment* segment ); /// Allows you to change a shape to be a polygon or update the current polygon. /// This does not modify the mass properties. /// @see b2Body_ApplyMassFromShapes -B2_API void b2Shape_SetPolygon(b2ShapeId shapeId, const b2Polygon* polygon); +B2_API void b2Shape_SetPolygon( b2ShapeId shapeId, const b2Polygon* polygon ); /// Get the parent chain id if the shape type is b2_smoothSegmentShape, otherwise /// returns b2_nullChainId. -B2_API b2ChainId b2Shape_GetParentChain(b2ShapeId shapeId); +B2_API b2ChainId b2Shape_GetParentChain( b2ShapeId shapeId ); /// Get the maximum capacity required for retrieving all the touching contacts on a shape -B2_API int b2Shape_GetContactCapacity(b2ShapeId shapeId); +B2_API int b2Shape_GetContactCapacity( b2ShapeId shapeId ); /// Get the touching contact data for a shape. The provided shapeId will be either shapeIdA or shapeIdB on the contact data. -B2_API int b2Shape_GetContactData(b2ShapeId shapeId, b2ContactData* contactData, int capacity); +B2_API int b2Shape_GetContactData( b2ShapeId shapeId, b2ContactData* contactData, int capacity ); /// Get the current world AABB -B2_API b2AABB b2Shape_GetAABB(b2ShapeId shapeId); +B2_API b2AABB b2Shape_GetAABB( b2ShapeId shapeId ); /// Get the closest point on a shape to a target point. Target and result are in world space. -B2_API b2Vec2 b2Shape_GetClosestPoint(b2ShapeId shapeId, b2Vec2 target); +B2_API b2Vec2 b2Shape_GetClosestPoint( b2ShapeId shapeId, b2Vec2 target ); /// Chain Shape /// Create a chain shape /// @see b2ChainDef for details -B2_API b2ChainId b2CreateChain(b2BodyId bodyId, const b2ChainDef* def); +B2_API b2ChainId b2CreateChain( b2BodyId bodyId, const b2ChainDef* def ); /// Destroy a chain shape -B2_API void b2DestroyChain(b2ChainId chainId); +B2_API void b2DestroyChain( b2ChainId chainId ); /// Set the chain friction /// @see b2ChainDef::friction -B2_API void b2Chain_SetFriction(b2ChainId chainId, float friction); +B2_API void b2Chain_SetFriction( b2ChainId chainId, float friction ); /// Set the chain restitution (bounciness) /// @see b2ChainDef::restitution -B2_API void b2Chain_SetRestitution(b2ChainId chainId, float restitution); +B2_API void b2Chain_SetRestitution( b2ChainId chainId, float restitution ); /// Chain identifier validation. Provides validation for up to 64K allocations. -B2_API bool b2Chain_IsValid(b2ChainId id); +B2_API bool b2Chain_IsValid( b2ChainId id ); /** @} */ @@ -602,46 +602,46 @@ B2_API bool b2Chain_IsValid(b2ChainId id); */ /// Destroy a joint -B2_API void b2DestroyJoint(b2JointId jointId); +B2_API void b2DestroyJoint( b2JointId jointId ); /// Joint identifier validation. Provides validation for up to 64K allocations. -B2_API bool b2Joint_IsValid(b2JointId id); +B2_API bool b2Joint_IsValid( b2JointId id ); /// Get the joint type -B2_API b2JointType b2Joint_GetType(b2JointId jointId); +B2_API b2JointType b2Joint_GetType( b2JointId jointId ); /// Get body A id on a joint -B2_API b2BodyId b2Joint_GetBodyA(b2JointId jointId); +B2_API b2BodyId b2Joint_GetBodyA( b2JointId jointId ); /// Get body B id on a joint -B2_API b2BodyId b2Joint_GetBodyB(b2JointId jointId); +B2_API b2BodyId b2Joint_GetBodyB( b2JointId jointId ); /// Get the local anchor on bodyA -B2_API b2Vec2 b2Joint_GetLocalAnchorA(b2JointId jointId); +B2_API b2Vec2 b2Joint_GetLocalAnchorA( b2JointId jointId ); /// Get the local anchor on bodyB -B2_API b2Vec2 b2Joint_GetLocalAnchorB(b2JointId jointId); +B2_API b2Vec2 b2Joint_GetLocalAnchorB( b2JointId jointId ); /// Toggle collision between connected bodies -B2_API void b2Joint_SetCollideConnected(b2JointId jointId, bool shouldCollide); +B2_API void b2Joint_SetCollideConnected( b2JointId jointId, bool shouldCollide ); /// Is collision allowed between connected bodies? -B2_API bool b2Joint_GetCollideConnected(b2JointId jointId); +B2_API bool b2Joint_GetCollideConnected( b2JointId jointId ); /// Set the user data on a joint -B2_API void b2Joint_SetUserData(b2JointId jointId, void* userData); +B2_API void b2Joint_SetUserData( b2JointId jointId, void* userData ); /// Get the user data on a joint -B2_API void* b2Joint_GetUserData(b2JointId jointId); +B2_API void* b2Joint_GetUserData( b2JointId jointId ); /// Wake the bodies connect to this joint -B2_API void b2Joint_WakeBodies(b2JointId jointId); +B2_API void b2Joint_WakeBodies( b2JointId jointId ); /// Get the current constraint force for this joint -B2_API b2Vec2 b2Joint_GetConstraintForce(b2JointId jointId); +B2_API b2Vec2 b2Joint_GetConstraintForce( b2JointId jointId ); /// Get the current constraint torque for this joint -B2_API float b2Joint_GetConstraintTorque(b2JointId jointId); +B2_API float b2Joint_GetConstraintTorque( b2JointId jointId ); /** * @defgroup distance_joint Distance Joint @@ -651,73 +651,73 @@ B2_API float b2Joint_GetConstraintTorque(b2JointId jointId); /// Create a distance joint /// @see b2DistanceJointDef for details -B2_API b2JointId b2CreateDistanceJoint(b2WorldId worldId, const b2DistanceJointDef* def); +B2_API b2JointId b2CreateDistanceJoint( b2WorldId worldId, const b2DistanceJointDef* def ); /// Set the rest length of a distance joint /// @param jointId The id for a distance joint /// @param length The new distance joint length -B2_API void b2DistanceJoint_SetLength(b2JointId jointId, float length); +B2_API void b2DistanceJoint_SetLength( b2JointId jointId, float length ); /// Get the rest length of a distance joint -B2_API float b2DistanceJoint_GetLength(b2JointId jointId); +B2_API float b2DistanceJoint_GetLength( b2JointId jointId ); /// Enable/disable the distance joint spring. When disabled the distance joint is rigid. -B2_API void b2DistanceJoint_EnableSpring(b2JointId jointId, bool enableSpring); +B2_API void b2DistanceJoint_EnableSpring( b2JointId jointId, bool enableSpring ); /// Is the distance joint spring enabled? -B2_API bool b2DistanceJoint_IsSpringEnabled(b2JointId jointId); +B2_API bool b2DistanceJoint_IsSpringEnabled( b2JointId jointId ); /// Set the spring stiffness in Hertz -B2_API void b2DistanceJoint_SetSpringHertz(b2JointId jointId, float hertz); +B2_API void b2DistanceJoint_SetSpringHertz( b2JointId jointId, float hertz ); /// Set the spring damping ratio, non-dimensional -B2_API void b2DistanceJoint_SetSpringDampingRatio(b2JointId jointId, float dampingRatio); +B2_API void b2DistanceJoint_SetSpringDampingRatio( b2JointId jointId, float dampingRatio ); /// Get the spring Hertz -B2_API float b2DistanceJoint_GetHertz(b2JointId jointId); +B2_API float b2DistanceJoint_GetHertz( b2JointId jointId ); /// Get the spring damping ratio -B2_API float b2DistanceJoint_GetDampingRatio(b2JointId jointId); +B2_API float b2DistanceJoint_GetDampingRatio( b2JointId jointId ); /// Enable joint limit. The limit only works if the joint spring is enabled. Otherwise the joint is rigid /// and the limit has no effect. -B2_API void b2DistanceJoint_EnableLimit(b2JointId jointId, bool enableLimit); +B2_API void b2DistanceJoint_EnableLimit( b2JointId jointId, bool enableLimit ); /// Is the distance joint limit enabled? -B2_API bool b2DistanceJoint_IsLimitEnabled(b2JointId jointId); +B2_API bool b2DistanceJoint_IsLimitEnabled( b2JointId jointId ); /// Set the minimum and maximum length parameters of a distance joint -B2_API void b2DistanceJoint_SetLengthRange(b2JointId jointId, float minLength, float maxLength); +B2_API void b2DistanceJoint_SetLengthRange( b2JointId jointId, float minLength, float maxLength ); /// Get the distance joint minimum length -B2_API float b2DistanceJoint_GetMinLength(b2JointId jointId); +B2_API float b2DistanceJoint_GetMinLength( b2JointId jointId ); /// Get the distance joint maximum length -B2_API float b2DistanceJoint_GetMaxLength(b2JointId jointId); +B2_API float b2DistanceJoint_GetMaxLength( b2JointId jointId ); /// Get the current length of a distance joint -B2_API float b2DistanceJoint_GetCurrentLength(b2JointId jointId); +B2_API float b2DistanceJoint_GetCurrentLength( b2JointId jointId ); /// Enable/disable the distance joint motor -B2_API void b2DistanceJoint_EnableMotor(b2JointId jointId, bool enableMotor); +B2_API void b2DistanceJoint_EnableMotor( b2JointId jointId, bool enableMotor ); /// Is the distance joint motor enabled? -B2_API bool b2DistanceJoint_IsMotorEnabled(b2JointId jointId); +B2_API bool b2DistanceJoint_IsMotorEnabled( b2JointId jointId ); /// Set the distance joint motor speed, typically in meters per second -B2_API void b2DistanceJoint_SetMotorSpeed(b2JointId jointId, float motorSpeed); +B2_API void b2DistanceJoint_SetMotorSpeed( b2JointId jointId, float motorSpeed ); /// Get the distance joint motor speed, typically in meters per second -B2_API float b2DistanceJoint_GetMotorSpeed(b2JointId jointId); +B2_API float b2DistanceJoint_GetMotorSpeed( b2JointId jointId ); /// Set the distance joint maximum motor force, typically in newtons -B2_API void b2DistanceJoint_SetMaxMotorForce(b2JointId jointId, float force); +B2_API void b2DistanceJoint_SetMaxMotorForce( b2JointId jointId, float force ); /// Get the distance joint maximum motor force, typically in newtons -B2_API float b2DistanceJoint_GetMaxMotorForce(b2JointId jointId); +B2_API float b2DistanceJoint_GetMaxMotorForce( b2JointId jointId ); /// Get the distance joint current motor force, typically in newtons -B2_API float b2DistanceJoint_GetMotorForce(b2JointId jointId); +B2_API float b2DistanceJoint_GetMotorForce( b2JointId jointId ); /** @} */ @@ -733,44 +733,44 @@ B2_API float b2DistanceJoint_GetMotorForce(b2JointId jointId); /// Create a motor joint /// @see b2MotorJointDef for details -B2_API b2JointId b2CreateMotorJoint(b2WorldId worldId, const b2MotorJointDef* def); +B2_API b2JointId b2CreateMotorJoint( b2WorldId worldId, const b2MotorJointDef* def ); /// Set the motor joint linear offset target -B2_API void b2MotorJoint_SetLinearOffset(b2JointId jointId, b2Vec2 linearOffset); +B2_API void b2MotorJoint_SetLinearOffset( b2JointId jointId, b2Vec2 linearOffset ); /// Get the motor joint linear offset target -B2_API b2Vec2 b2MotorJoint_GetLinearOffset(b2JointId jointId); +B2_API b2Vec2 b2MotorJoint_GetLinearOffset( b2JointId jointId ); /// Set the motor joint angular offset target in radians -B2_API void b2MotorJoint_SetAngularOffset(b2JointId jointId, float angularOffset); +B2_API void b2MotorJoint_SetAngularOffset( b2JointId jointId, float angularOffset ); /// Get the motor joint angular offset target in radians -B2_API float b2MotorJoint_GetAngularOffset(b2JointId jointId); +B2_API float b2MotorJoint_GetAngularOffset( b2JointId jointId ); /// Set the motor joint maximum force, typically in newtons -B2_API void b2MotorJoint_SetMaxForce(b2JointId jointId, float maxForce); +B2_API void b2MotorJoint_SetMaxForce( b2JointId jointId, float maxForce ); /// Get the motor joint maximum force, typically in newtons -B2_API float b2MotorJoint_GetMaxForce(b2JointId jointId); +B2_API float b2MotorJoint_GetMaxForce( b2JointId jointId ); /// Set the motor joint maximum torque, typically in newton-meters -B2_API void b2MotorJoint_SetMaxTorque(b2JointId jointId, float maxTorque); +B2_API void b2MotorJoint_SetMaxTorque( b2JointId jointId, float maxTorque ); /// Get the motor joint maximum torque, typically in newton-meters -B2_API float b2MotorJoint_GetMaxTorque(b2JointId jointId); +B2_API float b2MotorJoint_GetMaxTorque( b2JointId jointId ); /// Set the motor joint correction factor, typically in [0, 1] -B2_API void b2MotorJoint_SetCorrectionFactor(b2JointId jointId, float correctionFactor); +B2_API void b2MotorJoint_SetCorrectionFactor( b2JointId jointId, float correctionFactor ); /// Get the motor joint correction factor, typically in [0, 1] -B2_API float b2MotorJoint_GetCorrectionFactor(b2JointId jointId); +B2_API float b2MotorJoint_GetCorrectionFactor( b2JointId jointId ); /**@}*/ /** * @defgroup mouse_joint Mouse Joint * @brief Functions for the mouse joint. - * + * * The mouse joint is designed for use in the samples application, but you may find it useful in applications where * the user moves a rigid body with a cursor. * @{ @@ -778,38 +778,38 @@ B2_API float b2MotorJoint_GetCorrectionFactor(b2JointId jointId); /// Create a mouse joint /// @see b2MouseJointDef for details -B2_API b2JointId b2CreateMouseJoint(b2WorldId worldId, const b2MouseJointDef* def); +B2_API b2JointId b2CreateMouseJoint( b2WorldId worldId, const b2MouseJointDef* def ); /// Set the mouse joint target -B2_API void b2MouseJoint_SetTarget(b2JointId jointId, b2Vec2 target); +B2_API void b2MouseJoint_SetTarget( b2JointId jointId, b2Vec2 target ); /// Get the mouse joint target -B2_API b2Vec2 b2MouseJoint_GetTarget(b2JointId jointId); +B2_API b2Vec2 b2MouseJoint_GetTarget( b2JointId jointId ); /// Set the mouse joint spring stiffness in Hertz -B2_API void b2MouseJoint_SetSpringHertz(b2JointId jointId, float hertz); +B2_API void b2MouseJoint_SetSpringHertz( b2JointId jointId, float hertz ); /// Get the mouse joint spring stiffness in Hertz -B2_API float b2MouseJoint_GetSpringHertz(b2JointId jointId); +B2_API float b2MouseJoint_GetSpringHertz( b2JointId jointId ); /// Set the mouse joint spring damping ratio, non-dimensional -B2_API void b2MouseJoint_SetSpringDampingRatio(b2JointId jointId, float dampingRatio); +B2_API void b2MouseJoint_SetSpringDampingRatio( b2JointId jointId, float dampingRatio ); /// Get the mouse joint damping ratio, non-dimensional -B2_API float b2MouseJoint_GetSpringDampingRatio(b2JointId jointId); +B2_API float b2MouseJoint_GetSpringDampingRatio( b2JointId jointId ); /// Set the mouse joint maximum force, typically in newtons -B2_API void b2MouseJoint_SetMaxForce(b2JointId jointId, float maxForce); +B2_API void b2MouseJoint_SetMaxForce( b2JointId jointId, float maxForce ); /// Get the mouse joint maximum force, typically in newtons -B2_API float b2MouseJoint_GetMaxForce(b2JointId jointId); +B2_API float b2MouseJoint_GetMaxForce( b2JointId jointId ); /**@}*/ /** * @defgroup prismatic_joint Prismatic Joint * @brief A prismatic joint allows for translation along a single axis with no rotation. - * + * * The prismatic joint is useful for things like pistons and moving platforms, where you want a body to translate * along an axis and have no rotation. Also called a *slider* joint. * @{ @@ -817,70 +817,70 @@ B2_API float b2MouseJoint_GetMaxForce(b2JointId jointId); /// Create a prismatic (slider) joint. /// @see b2PrismaticJointDef for details -B2_API b2JointId b2CreatePrismaticJoint(b2WorldId worldId, const b2PrismaticJointDef* def); +B2_API b2JointId b2CreatePrismaticJoint( b2WorldId worldId, const b2PrismaticJointDef* def ); /// Enable/disable the joint spring. -B2_API void b2PrismaticJoint_EnableSpring(b2JointId jointId, bool enableSpring); +B2_API void b2PrismaticJoint_EnableSpring( b2JointId jointId, bool enableSpring ); /// Is the prismatic joint spring enabled or not? -B2_API bool b2PrismaticJoint_IsSpringEnabled(b2JointId jointId); +B2_API bool b2PrismaticJoint_IsSpringEnabled( b2JointId jointId ); /// Set the prismatic joint stiffness in Hertz. /// This should usually be less than a quarter of the simulation rate. For example, if the simulation /// runs at 60Hz then the joint stiffness should be 15Hz or less. -B2_API void b2PrismaticJoint_SetSpringHertz(b2JointId jointId, float hertz); +B2_API void b2PrismaticJoint_SetSpringHertz( b2JointId jointId, float hertz ); /// Get the prismatic joint stiffness in Hertz -B2_API float b2PrismaticJoint_GetSpringHertz(b2JointId jointId); +B2_API float b2PrismaticJoint_GetSpringHertz( b2JointId jointId ); /// Set the prismatic joint damping ratio (non-dimensional) -B2_API void b2PrismaticJoint_SetSpringDampingRatio(b2JointId jointId, float dampingRatio); +B2_API void b2PrismaticJoint_SetSpringDampingRatio( b2JointId jointId, float dampingRatio ); /// Get the prismatic spring damping ratio (non-dimensional) -B2_API float b2PrismaticJoint_GetSpringDampingRatio(b2JointId jointId); +B2_API float b2PrismaticJoint_GetSpringDampingRatio( b2JointId jointId ); /// Enable/disable a prismatic joint limit -B2_API void b2PrismaticJoint_EnableLimit(b2JointId jointId, bool enableLimit); +B2_API void b2PrismaticJoint_EnableLimit( b2JointId jointId, bool enableLimit ); /// Is the prismatic joint limit enabled? -B2_API bool b2PrismaticJoint_IsLimitEnabled(b2JointId jointId); +B2_API bool b2PrismaticJoint_IsLimitEnabled( b2JointId jointId ); /// Get the prismatic joint lower limit -B2_API float b2PrismaticJoint_GetLowerLimit(b2JointId jointId); +B2_API float b2PrismaticJoint_GetLowerLimit( b2JointId jointId ); /// Get the prismatic joint upper limit -B2_API float b2PrismaticJoint_GetUpperLimit(b2JointId jointId); +B2_API float b2PrismaticJoint_GetUpperLimit( b2JointId jointId ); /// Set the prismatic joint limits -B2_API void b2PrismaticJoint_SetLimits(b2JointId jointId, float lower, float upper); +B2_API void b2PrismaticJoint_SetLimits( b2JointId jointId, float lower, float upper ); /// Enable/disable a prismatic joint motor -B2_API void b2PrismaticJoint_EnableMotor(b2JointId jointId, bool enableMotor); +B2_API void b2PrismaticJoint_EnableMotor( b2JointId jointId, bool enableMotor ); /// Is the prismatic joint motor enabled? -B2_API bool b2PrismaticJoint_IsMotorEnabled(b2JointId jointId); +B2_API bool b2PrismaticJoint_IsMotorEnabled( b2JointId jointId ); /// Set the prismatic joint motor speed, typically in meters per second -B2_API void b2PrismaticJoint_SetMotorSpeed(b2JointId jointId, float motorSpeed); +B2_API void b2PrismaticJoint_SetMotorSpeed( b2JointId jointId, float motorSpeed ); /// Get the prismatic joint motor speed, typically in meters per second -B2_API float b2PrismaticJoint_GetMotorSpeed(b2JointId jointId); +B2_API float b2PrismaticJoint_GetMotorSpeed( b2JointId jointId ); /// Set the prismatic joint maximum motor force, typically in newtons -B2_API void b2PrismaticJoint_SetMaxMotorForce(b2JointId jointId, float force); +B2_API void b2PrismaticJoint_SetMaxMotorForce( b2JointId jointId, float force ); /// Get the prismatic joint maximum motor force, typically in newtons -B2_API float b2PrismaticJoint_GetMaxMotorForce(b2JointId jointId); +B2_API float b2PrismaticJoint_GetMaxMotorForce( b2JointId jointId ); /// Get the prismatic joint current motor force, typically in newtons -B2_API float b2PrismaticJoint_GetMotorForce(b2JointId jointId); +B2_API float b2PrismaticJoint_GetMotorForce( b2JointId jointId ); /** @} */ /** * @defgroup revolute_joint Revolute Joint * @brief A revolute joint allows for relative rotation in the 2D plane with no relative translation. - * + * * The revolute joint is probably the most common joint. It can be used for ragdolls and chains. * Also called a *hinge* or *pin* joint. * @{ @@ -888,69 +888,69 @@ B2_API float b2PrismaticJoint_GetMotorForce(b2JointId jointId); /// Create a revolute joint /// @see b2RevoluteJointDef for details -B2_API b2JointId b2CreateRevoluteJoint(b2WorldId worldId, const b2RevoluteJointDef* def); +B2_API b2JointId b2CreateRevoluteJoint( b2WorldId worldId, const b2RevoluteJointDef* def ); /// Enable/disable the revolute joint spring -B2_API void b2RevoluteJoint_EnableSpring(b2JointId jointId, bool enableSpring); +B2_API void b2RevoluteJoint_EnableSpring( b2JointId jointId, bool enableSpring ); /// Set the revolute joint spring stiffness in Hertz -B2_API void b2RevoluteJoint_SetSpringHertz(b2JointId jointId, float hertz); +B2_API void b2RevoluteJoint_SetSpringHertz( b2JointId jointId, float hertz ); /// Get the revolute joint spring stiffness in Hertz -B2_API float b2RevoluteJoint_GetSpringHertz(b2JointId jointId); +B2_API float b2RevoluteJoint_GetSpringHertz( b2JointId jointId ); /// Set the revolute joint spring damping ratio, non-dimensional -B2_API void b2RevoluteJoint_SetSpringDampingRatio(b2JointId jointId, float dampingRatio); +B2_API void b2RevoluteJoint_SetSpringDampingRatio( b2JointId jointId, float dampingRatio ); /// Get the revolute joint spring damping ratio, non-dimensional -B2_API float b2RevoluteJoint_GetSpringDampingRatio(b2JointId jointId); +B2_API float b2RevoluteJoint_GetSpringDampingRatio( b2JointId jointId ); /// Get the revolute joint current angle in radians relative to the reference angle /// @see b2RevoluteJointDef::referenceAngle -B2_API float b2RevoluteJoint_GetAngle(b2JointId jointId); +B2_API float b2RevoluteJoint_GetAngle( b2JointId jointId ); /// Enable/disable the revolute joint limit -B2_API void b2RevoluteJoint_EnableLimit(b2JointId jointId, bool enableLimit); +B2_API void b2RevoluteJoint_EnableLimit( b2JointId jointId, bool enableLimit ); /// Is the revolute joint limit enabled? -B2_API bool b2RevoluteJoint_IsLimitEnabled(b2JointId jointId); +B2_API bool b2RevoluteJoint_IsLimitEnabled( b2JointId jointId ); /// Get the revolute joint lower limit in radians -B2_API float b2RevoluteJoint_GetLowerLimit(b2JointId jointId); +B2_API float b2RevoluteJoint_GetLowerLimit( b2JointId jointId ); /// Get the revolute joint upper limit in radians -B2_API float b2RevoluteJoint_GetUpperLimit(b2JointId jointId); +B2_API float b2RevoluteJoint_GetUpperLimit( b2JointId jointId ); /// Set the revolute joint limits in radians -B2_API void b2RevoluteJoint_SetLimits(b2JointId jointId, float lower, float upper); +B2_API void b2RevoluteJoint_SetLimits( b2JointId jointId, float lower, float upper ); /// Enable/disable a revolute joint motor -B2_API void b2RevoluteJoint_EnableMotor(b2JointId jointId, bool enableMotor); +B2_API void b2RevoluteJoint_EnableMotor( b2JointId jointId, bool enableMotor ); /// Is the revolute joint motor enabled? -B2_API bool b2RevoluteJoint_IsMotorEnabled(b2JointId jointId); +B2_API bool b2RevoluteJoint_IsMotorEnabled( b2JointId jointId ); /// Set the revolute joint motor speed in radians per second -B2_API void b2RevoluteJoint_SetMotorSpeed(b2JointId jointId, float motorSpeed); +B2_API void b2RevoluteJoint_SetMotorSpeed( b2JointId jointId, float motorSpeed ); /// Get the revolute joint motor speed in radians per second -B2_API float b2RevoluteJoint_GetMotorSpeed(b2JointId jointId); +B2_API float b2RevoluteJoint_GetMotorSpeed( b2JointId jointId ); /// Get the revolute joint current motor torque, typically in newton-meters -B2_API float b2RevoluteJoint_GetMotorTorque(b2JointId jointId); +B2_API float b2RevoluteJoint_GetMotorTorque( b2JointId jointId ); /// Set the revolute joint maximum motor torque, typically in newton-meters -B2_API void b2RevoluteJoint_SetMaxMotorTorque(b2JointId jointId, float torque); +B2_API void b2RevoluteJoint_SetMaxMotorTorque( b2JointId jointId, float torque ); /// Get the revolute joint maximum motor torque, typically in newton-meters -B2_API float b2RevoluteJoint_GetMaxMotorTorque(b2JointId jointId); +B2_API float b2RevoluteJoint_GetMaxMotorTorque( b2JointId jointId ); /**@}*/ /** * @defgroup weld_joint Weld Joint * @brief A weld joint fully constrains the relative transform between two bodies while allowing for springiness - * + * * A weld joint constrains the relative rotation and translation between two bodies. Both rotation and translation * can have damped springs. * @@ -960,31 +960,31 @@ B2_API float b2RevoluteJoint_GetMaxMotorTorque(b2JointId jointId); /// Create a weld joint /// @see b2WeldJointDef for details -B2_API b2JointId b2CreateWeldJoint(b2WorldId worldId, const b2WeldJointDef* def); +B2_API b2JointId b2CreateWeldJoint( b2WorldId worldId, const b2WeldJointDef* def ); /// Set the weld joint linear stiffness in Hertz. 0 is rigid. -B2_API void b2WeldJoint_SetLinearHertz(b2JointId jointId, float hertz); +B2_API void b2WeldJoint_SetLinearHertz( b2JointId jointId, float hertz ); /// Get the weld joint linear stiffness in Hertz -B2_API float b2WeldJoint_GetLinearHertz(b2JointId jointId); +B2_API float b2WeldJoint_GetLinearHertz( b2JointId jointId ); /// Set the weld joint linear damping ratio (non-dimensional) -B2_API void b2WeldJoint_SetLinearDampingRatio(b2JointId jointId, float dampingRatio); +B2_API void b2WeldJoint_SetLinearDampingRatio( b2JointId jointId, float dampingRatio ); /// Get the weld joint linear damping ratio (non-dimensional) -B2_API float b2WeldJoint_GetLinearDampingRatio(b2JointId jointId); +B2_API float b2WeldJoint_GetLinearDampingRatio( b2JointId jointId ); /// Set the weld joint angular stiffness in Hertz. 0 is rigid. -B2_API void b2WeldJoint_SetAngularHertz(b2JointId jointId, float hertz); +B2_API void b2WeldJoint_SetAngularHertz( b2JointId jointId, float hertz ); /// Get the weld joint angular stiffness in Hertz -B2_API float b2WeldJoint_GetAngularHertz(b2JointId jointId); +B2_API float b2WeldJoint_GetAngularHertz( b2JointId jointId ); /// Set weld joint angular damping ratio, non-dimensional -B2_API void b2WeldJoint_SetAngularDampingRatio(b2JointId jointId, float dampingRatio); +B2_API void b2WeldJoint_SetAngularDampingRatio( b2JointId jointId, float dampingRatio ); /// Get the weld joint angular damping ratio, non-dimensional -B2_API float b2WeldJoint_GetAngularDampingRatio(b2JointId jointId); +B2_API float b2WeldJoint_GetAngularDampingRatio( b2JointId jointId ); /** @} */ @@ -1000,61 +1000,61 @@ B2_API float b2WeldJoint_GetAngularDampingRatio(b2JointId jointId); /// Create a wheel joint /// @see b2WheelJointDef for details -B2_API b2JointId b2CreateWheelJoint(b2WorldId worldId, const b2WheelJointDef* def); +B2_API b2JointId b2CreateWheelJoint( b2WorldId worldId, const b2WheelJointDef* def ); /// Enable/disable the wheel joint spring -B2_API void b2WheelJoint_EnableSpring(b2JointId jointId, bool enableSpring); +B2_API void b2WheelJoint_EnableSpring( b2JointId jointId, bool enableSpring ); /// Is the wheel joint spring enabled? -B2_API bool b2WheelJoint_IsSpringEnabled(b2JointId jointId); +B2_API bool b2WheelJoint_IsSpringEnabled( b2JointId jointId ); /// Set the wheel joint stiffness in Hertz -B2_API void b2WheelJoint_SetSpringHertz(b2JointId jointId, float hertz); +B2_API void b2WheelJoint_SetSpringHertz( b2JointId jointId, float hertz ); /// Get the wheel joint stiffness in Hertz -B2_API float b2WheelJoint_GetSpringHertz(b2JointId jointId); +B2_API float b2WheelJoint_GetSpringHertz( b2JointId jointId ); /// Set the wheel joint damping ratio, non-dimensional -B2_API void b2WheelJoint_SetSpringDampingRatio(b2JointId jointId, float dampingRatio); +B2_API void b2WheelJoint_SetSpringDampingRatio( b2JointId jointId, float dampingRatio ); /// Get the wheel joint damping ratio, non-dimensional -B2_API float b2WheelJoint_GetSpringDampingRatio(b2JointId jointId); +B2_API float b2WheelJoint_GetSpringDampingRatio( b2JointId jointId ); /// Enable/disable the wheel joint limit -B2_API void b2WheelJoint_EnableLimit(b2JointId jointId, bool enableLimit); +B2_API void b2WheelJoint_EnableLimit( b2JointId jointId, bool enableLimit ); /// Is the wheel joint limit enabled? -B2_API bool b2WheelJoint_IsLimitEnabled(b2JointId jointId); +B2_API bool b2WheelJoint_IsLimitEnabled( b2JointId jointId ); /// Get the wheel joint lower limit -B2_API float b2WheelJoint_GetLowerLimit(b2JointId jointId); +B2_API float b2WheelJoint_GetLowerLimit( b2JointId jointId ); /// Get the wheel joint upper limit -B2_API float b2WheelJoint_GetUpperLimit(b2JointId jointId); +B2_API float b2WheelJoint_GetUpperLimit( b2JointId jointId ); /// Set the wheel joint limits -B2_API void b2WheelJoint_SetLimits(b2JointId jointId, float lower, float upper); +B2_API void b2WheelJoint_SetLimits( b2JointId jointId, float lower, float upper ); /// Enable/disable the wheel joint motor -B2_API void b2WheelJoint_EnableMotor(b2JointId jointId, bool enableMotor); +B2_API void b2WheelJoint_EnableMotor( b2JointId jointId, bool enableMotor ); /// Is the wheel joint motor enabled? -B2_API bool b2WheelJoint_IsMotorEnabled(b2JointId jointId); +B2_API bool b2WheelJoint_IsMotorEnabled( b2JointId jointId ); /// Set the wheel joint motor speed in radians per second -B2_API void b2WheelJoint_SetMotorSpeed(b2JointId jointId, float motorSpeed); +B2_API void b2WheelJoint_SetMotorSpeed( b2JointId jointId, float motorSpeed ); /// Get the wheel joint motor speed in radians per second -B2_API float b2WheelJoint_GetMotorSpeed(b2JointId jointId); +B2_API float b2WheelJoint_GetMotorSpeed( b2JointId jointId ); /// Set the wheel joint maximum motor torque, typically in newton-meters -B2_API void b2WheelJoint_SetMaxMotorTorque(b2JointId jointId, float torque); +B2_API void b2WheelJoint_SetMaxMotorTorque( b2JointId jointId, float torque ); /// Get the wheel joint maximum motor torque, typically in newton-meters -B2_API float b2WheelJoint_GetMaxMotorTorque(b2JointId jointId); +B2_API float b2WheelJoint_GetMaxMotorTorque( b2JointId jointId ); /// Get the wheel joint current motor torque, typically in newton-meters -B2_API float b2WheelJoint_GetMotorTorque(b2JointId jointId); +B2_API float b2WheelJoint_GetMotorTorque( b2JointId jointId ); /**@}*/ diff --git a/include/box2d/collision.h b/include/box2d/collision.h index 0dc83764..61c7d12f 100644 --- a/include/box2d/collision.h +++ b/include/box2d/collision.h @@ -111,7 +111,7 @@ typedef struct b2Capsule { /// Local center of the first semicircle b2Vec2 center1; - + /// Local center of the second semicircle b2Vec2 center2; @@ -172,85 +172,85 @@ typedef struct b2SmoothSegment } b2SmoothSegment; /// Validate ray cast input data (NaN, etc) -B2_API bool b2IsValidRay(const b2RayCastInput* input); +B2_API bool b2IsValidRay( const b2RayCastInput* input ); /// Make a convex polygon from a convex hull. This will assert if the hull is not valid. /// @warning Do not manually fill in the hull data, it must come directly from b2ComputeHull -B2_API b2Polygon b2MakePolygon(const b2Hull* hull, float radius); +B2_API b2Polygon b2MakePolygon( const b2Hull* hull, float radius ); /// Make an offset convex polygon from a convex hull. This will assert if the hull is not valid. /// @warning Do not manually fill in the hull data, it must come directly from b2ComputeHull -B2_API b2Polygon b2MakeOffsetPolygon(const b2Hull* hull, float radius, b2Transform transform); +B2_API b2Polygon b2MakeOffsetPolygon( const b2Hull* hull, float radius, b2Transform transform ); /// Make a square polygon, bypassing the need for a convex hull. -B2_API b2Polygon b2MakeSquare(float h); +B2_API b2Polygon b2MakeSquare( float h ); /// Make a box (rectangle) polygon, bypassing the need for a convex hull. -B2_API b2Polygon b2MakeBox(float hx, float hy); +B2_API b2Polygon b2MakeBox( float hx, float hy ); /// Make a rounded box, bypassing the need for a convex hull. -B2_API b2Polygon b2MakeRoundedBox(float hx, float hy, float radius); +B2_API b2Polygon b2MakeRoundedBox( float hx, float hy, float radius ); /// Make an offset box, bypassing the need for a convex hull. -B2_API b2Polygon b2MakeOffsetBox(float hx, float hy, b2Vec2 center, float angle); +B2_API b2Polygon b2MakeOffsetBox( float hx, float hy, b2Vec2 center, float angle ); /// Transform a polygon. This is useful for transferring a shape from one body to another. -B2_API b2Polygon b2TransformPolygon(b2Transform transform, const b2Polygon* polygon); +B2_API b2Polygon b2TransformPolygon( b2Transform transform, const b2Polygon* polygon ); /// Compute mass properties of a circle -B2_API b2MassData b2ComputeCircleMass(const b2Circle* shape, float density); +B2_API b2MassData b2ComputeCircleMass( const b2Circle* shape, float density ); /// Compute mass properties of a capsule -B2_API b2MassData b2ComputeCapsuleMass(const b2Capsule* shape, float density); +B2_API b2MassData b2ComputeCapsuleMass( const b2Capsule* shape, float density ); /// Compute mass properties of a polygon -B2_API b2MassData b2ComputePolygonMass(const b2Polygon* shape, float density); +B2_API b2MassData b2ComputePolygonMass( const b2Polygon* shape, float density ); /// Compute the bounding box of a transformed circle -B2_API b2AABB b2ComputeCircleAABB(const b2Circle* shape, b2Transform transform); +B2_API b2AABB b2ComputeCircleAABB( const b2Circle* shape, b2Transform transform ); /// Compute the bounding box of a transformed capsule -B2_API b2AABB b2ComputeCapsuleAABB(const b2Capsule* shape, b2Transform transform); +B2_API b2AABB b2ComputeCapsuleAABB( const b2Capsule* shape, b2Transform transform ); /// Compute the bounding box of a transformed polygon -B2_API b2AABB b2ComputePolygonAABB(const b2Polygon* shape, b2Transform transform); +B2_API b2AABB b2ComputePolygonAABB( const b2Polygon* shape, b2Transform transform ); /// Compute the bounding box of a transformed line segment -B2_API b2AABB b2ComputeSegmentAABB(const b2Segment* shape, b2Transform transform); +B2_API b2AABB b2ComputeSegmentAABB( const b2Segment* shape, b2Transform transform ); /// Test a point for overlap with a circle in local space -B2_API bool b2PointInCircle(b2Vec2 point, const b2Circle* shape); +B2_API bool b2PointInCircle( b2Vec2 point, const b2Circle* shape ); /// Test a point for overlap with a capsule in local space -B2_API bool b2PointInCapsule(b2Vec2 point, const b2Capsule* shape); +B2_API bool b2PointInCapsule( b2Vec2 point, const b2Capsule* shape ); /// Test a point for overlap with a convex polygon in local space -B2_API bool b2PointInPolygon(b2Vec2 point, const b2Polygon* shape); +B2_API bool b2PointInPolygon( b2Vec2 point, const b2Polygon* shape ); /// Ray cast versus circle in shape local space. Initial overlap is treated as a miss. -B2_API b2CastOutput b2RayCastCircle(const b2RayCastInput* input, const b2Circle* shape); +B2_API b2CastOutput b2RayCastCircle( const b2RayCastInput* input, const b2Circle* shape ); /// Ray cast versus capsule in shape local space. Initial overlap is treated as a miss. -B2_API b2CastOutput b2RayCastCapsule(const b2RayCastInput* input, const b2Capsule* shape); +B2_API b2CastOutput b2RayCastCapsule( const b2RayCastInput* input, const b2Capsule* shape ); /// Ray cast versus segment in shape local space. Optionally treat the segment as one-sided with hits from /// the left side being treated as a miss. -B2_API b2CastOutput b2RayCastSegment(const b2RayCastInput* input, const b2Segment* shape, bool oneSided); +B2_API b2CastOutput b2RayCastSegment( const b2RayCastInput* input, const b2Segment* shape, bool oneSided ); /// Ray cast versus polygon in shape local space. Initial overlap is treated as a miss. -B2_API b2CastOutput b2RayCastPolygon(const b2RayCastInput* input, const b2Polygon* shape); +B2_API b2CastOutput b2RayCastPolygon( const b2RayCastInput* input, const b2Polygon* shape ); /// Shape cast versus a circle. Initial overlap is treated as a miss. -B2_API b2CastOutput b2ShapeCastCircle(const b2ShapeCastInput* input, const b2Circle* shape); +B2_API b2CastOutput b2ShapeCastCircle( const b2ShapeCastInput* input, const b2Circle* shape ); /// Shape cast versus a capsule. Initial overlap is treated as a miss. -B2_API b2CastOutput b2ShapeCastCapsule(const b2ShapeCastInput* input, const b2Capsule* shape); +B2_API b2CastOutput b2ShapeCastCapsule( const b2ShapeCastInput* input, const b2Capsule* shape ); /// Shape cast versus a line segment. Initial overlap is treated as a miss. -B2_API b2CastOutput b2ShapeCastSegment(const b2ShapeCastInput* input, const b2Segment* shape); +B2_API b2CastOutput b2ShapeCastSegment( const b2ShapeCastInput* input, const b2Segment* shape ); /// Shape cast versus a convex polygon. Initial overlap is treated as a miss. -B2_API b2CastOutput b2ShapeCastPolygon(const b2ShapeCastInput* input, const b2Polygon* shape); +B2_API b2CastOutput b2ShapeCastPolygon( const b2ShapeCastInput* input, const b2Polygon* shape ); /// A convex hull. Used to create convex polygons. /// @warning Do not modify these values directly, instead use b2ComputeHull() @@ -271,13 +271,13 @@ typedef struct b2Hull /// - more than b2_maxPolygonVertices points /// This welds close points and removes collinear points. /// @warning Do not modify a hull once it has been computed -B2_API b2Hull b2ComputeHull(const b2Vec2* points, int32_t count); +B2_API b2Hull b2ComputeHull( const b2Vec2* points, int32_t count ); /// This determines if a hull is valid. Checks for: /// - convexity /// - collinear points /// This is expensive and should not be called at runtime. -B2_API bool b2ValidateHull(const b2Hull* hull); +B2_API bool b2ValidateHull( const b2Hull* hull ); /**@}*/ @@ -311,7 +311,7 @@ typedef struct b2SegmentDistanceResult } b2SegmentDistanceResult; /// Compute the distance between two line segments, clamping at the end points if needed. -B2_API b2SegmentDistanceResult b2SegmentDistance(b2Vec2 p1, b2Vec2 q1, b2Vec2 p2, b2Vec2 q2); +B2_API b2SegmentDistanceResult b2SegmentDistance( b2Vec2 p1, b2Vec2 q1, b2Vec2 p2, b2Vec2 q2 ); /// A distance proxy is used by the GJK algorithm. It encapsulates any shape. typedef struct b2DistanceProxy @@ -364,20 +364,20 @@ typedef struct b2DistanceInput /// Output for b2ShapeDistance typedef struct b2DistanceOutput { - b2Vec2 pointA; ///< Closest point on shapeA - b2Vec2 pointB; ///< Closest point on shapeB - float distance; ///< The final distance, zero if overlapped - int32_t iterations; ///< Number of GJK iterations used + b2Vec2 pointA; ///< Closest point on shapeA + b2Vec2 pointB; ///< Closest point on shapeB + float distance; ///< The final distance, zero if overlapped + int32_t iterations; ///< Number of GJK iterations used int32_t simplexCount; ///< The number of simplexes stored in the simplex array } b2DistanceOutput; /// Simplex vertex for debugging the GJK algorithm typedef struct b2SimplexVertex { - b2Vec2 wA; ///< support point in proxyA - b2Vec2 wB; ///< support point in proxyB - b2Vec2 w; ///< wB - wA - float a; ///< barycentric coordinate for closest point + b2Vec2 wA; ///< support point in proxyA + b2Vec2 wB; ///< support point in proxyB + b2Vec2 w; ///< wB - wA + float a; ///< barycentric coordinate for closest point int32_t indexA; ///< wA index int32_t indexB; ///< wB index } b2SimplexVertex; @@ -386,13 +386,14 @@ typedef struct b2SimplexVertex typedef struct b2Simplex { b2SimplexVertex v1, v2, v3; ///< vertices - int32_t count; ///< number of valid vertices + int32_t count; ///< number of valid vertices } b2Simplex; /// Compute the closest points between two shapes represented as point clouds. /// b2DistanceCache cache is input/output. On the first call set b2DistanceCache.count to zero. /// The underlying GJK algorithm may be debugged by passing in debug simplexes and capacity. You may pass in NULL and 0 for these. -B2_API b2DistanceOutput b2ShapeDistance(b2DistanceCache* cache, const b2DistanceInput* input, b2Simplex* simplexes, int simplexCapacity); +B2_API b2DistanceOutput b2ShapeDistance( b2DistanceCache* cache, const b2DistanceInput* input, b2Simplex* simplexes, + int simplexCapacity ); /// Input parameters for b2ShapeCast typedef struct b2ShapeCastPairInput @@ -401,15 +402,15 @@ typedef struct b2ShapeCastPairInput b2DistanceProxy proxyB; ///< The proxy for shape B b2Transform transformA; ///< The world transform for shape A b2Transform transformB; ///< The world transform for shape B - b2Vec2 translationB; ///< The translation of shape B - float maxFraction; ///< The fraction of the translation to consider, typically 1 + b2Vec2 translationB; ///< The translation of shape B + float maxFraction; ///< The fraction of the translation to consider, typically 1 } b2ShapeCastPairInput; /// Perform a linear shape cast of shape B moving and shape A fixed. Determines the hit point, normal, and translation fraction. -B2_API b2CastOutput b2ShapeCast(const b2ShapeCastPairInput* input); +B2_API b2CastOutput b2ShapeCast( const b2ShapeCastPairInput* input ); /// Make a proxy for use in GJK and related functions. -B2_API b2DistanceProxy b2MakeProxy(const b2Vec2* vertices, int32_t count, float radius); +B2_API b2DistanceProxy b2MakeProxy( const b2Vec2* vertices, int32_t count, float radius ); /// This describes the motion of a body/shape for TOI computation. Shapes are defined with respect to the body origin, /// which may not coincide with the center of mass. However, to support dynamics we must interpolate the center of mass @@ -417,23 +418,23 @@ B2_API b2DistanceProxy b2MakeProxy(const b2Vec2* vertices, int32_t count, float typedef struct b2Sweep { b2Vec2 localCenter; ///< Local center of mass position - b2Vec2 c1; ///< Starting center of mass world position - b2Vec2 c2; ///< Ending center of mass world position - b2Rot q1; ///< Starting world rotation - b2Rot q2; ///< Ending world rotation + b2Vec2 c1; ///< Starting center of mass world position + b2Vec2 c2; ///< Ending center of mass world position + b2Rot q1; ///< Starting world rotation + b2Rot q2; ///< Ending world rotation } b2Sweep; /// Evaluate the transform sweep at a specific time. -B2_API b2Transform b2GetSweepTransform(const b2Sweep* sweep, float time); +B2_API b2Transform b2GetSweepTransform( const b2Sweep* sweep, float time ); /// Input parameters for b2TimeOfImpact typedef struct b2TOIInput { b2DistanceProxy proxyA; ///< The proxy for shape A b2DistanceProxy proxyB; ///< The proxy for shape B - b2Sweep sweepA; ///< The movement of shape A - b2Sweep sweepB; ///< The movement of shape B - float tMax; ///< Defines the sweep interval [0, tMax] + b2Sweep sweepA; ///< The movement of shape A + b2Sweep sweepB; ///< The movement of shape B + float tMax; ///< Defines the sweep interval [0, tMax] } b2TOIInput; /// Describes the TOI output @@ -450,14 +451,14 @@ typedef enum b2TOIState typedef struct b2TOIOutput { b2TOIState state; ///< The type of result - float t; ///< The time of the collision + float t; ///< The time of the collision } b2TOIOutput; /// 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. -B2_API b2TOIOutput b2TimeOfImpact(const b2TOIInput* input); +B2_API b2TOIOutput b2TimeOfImpact( const b2TOIInput* input ); /**@}*/ @@ -521,43 +522,49 @@ typedef struct b2Manifold } b2Manifold; /// Compute the contact manifold between two circles -B2_API b2Manifold b2CollideCircles(const b2Circle* circleA, b2Transform xfA, const b2Circle* circleB, b2Transform xfB); +B2_API b2Manifold b2CollideCircles( const b2Circle* circleA, b2Transform xfA, const b2Circle* circleB, b2Transform xfB ); /// Compute the contact manifold between a capsule and circle -B2_API b2Manifold b2CollideCapsuleAndCircle(const b2Capsule* capsuleA, b2Transform xfA, const b2Circle* circleB, b2Transform xfB); +B2_API b2Manifold b2CollideCapsuleAndCircle( const b2Capsule* capsuleA, b2Transform xfA, const b2Circle* circleB, + b2Transform xfB ); /// Compute the contact manifold between an segment and a circle -B2_API b2Manifold b2CollideSegmentAndCircle(const b2Segment* segmentA, b2Transform xfA, const b2Circle* circleB, b2Transform xfB); +B2_API b2Manifold b2CollideSegmentAndCircle( const b2Segment* segmentA, b2Transform xfA, const b2Circle* circleB, + b2Transform xfB ); /// Compute the contact manifold between a polygon and a circle -B2_API b2Manifold b2CollidePolygonAndCircle(const b2Polygon* polygonA, b2Transform xfA, const b2Circle* circleB, b2Transform xfB); +B2_API b2Manifold b2CollidePolygonAndCircle( const b2Polygon* polygonA, b2Transform xfA, const b2Circle* circleB, + b2Transform xfB ); /// Compute the contact manifold between a capsule and circle -B2_API b2Manifold b2CollideCapsules(const b2Capsule* capsuleA, b2Transform xfA, const b2Capsule* capsuleB, b2Transform xfB); +B2_API b2Manifold b2CollideCapsules( const b2Capsule* capsuleA, b2Transform xfA, const b2Capsule* capsuleB, b2Transform xfB ); /// Compute the contact manifold between an segment and a capsule -B2_API b2Manifold b2CollideSegmentAndCapsule(const b2Segment* segmentA, b2Transform xfA, const b2Capsule* capsuleB, b2Transform xfB); +B2_API b2Manifold b2CollideSegmentAndCapsule( const b2Segment* segmentA, b2Transform xfA, const b2Capsule* capsuleB, + b2Transform xfB ); /// Compute the contact manifold between a polygon and capsule -B2_API b2Manifold b2CollidePolygonAndCapsule(const b2Polygon* polygonA, b2Transform xfA, const b2Capsule* capsuleB, b2Transform xfB); +B2_API b2Manifold b2CollidePolygonAndCapsule( const b2Polygon* polygonA, b2Transform xfA, const b2Capsule* capsuleB, + b2Transform xfB ); /// Compute the contact manifold between two polygons -B2_API b2Manifold b2CollidePolygons(const b2Polygon* polygonA, b2Transform xfA, const b2Polygon* polygonB, b2Transform xfB); +B2_API b2Manifold b2CollidePolygons( const b2Polygon* polygonA, b2Transform xfA, const b2Polygon* polygonB, b2Transform xfB ); /// Compute the contact manifold between an segment and a polygon -B2_API b2Manifold b2CollideSegmentAndPolygon(const b2Segment* segmentA, b2Transform xfA, const b2Polygon* polygonB, b2Transform xfB); +B2_API b2Manifold b2CollideSegmentAndPolygon( const b2Segment* segmentA, b2Transform xfA, const b2Polygon* polygonB, + b2Transform xfB ); /// Compute the contact manifold between a smooth segment and a circle -B2_API b2Manifold b2CollideSmoothSegmentAndCircle(const b2SmoothSegment* smoothSegmentA, b2Transform xfA, const b2Circle* circleB, - b2Transform xfB); +B2_API b2Manifold b2CollideSmoothSegmentAndCircle( const b2SmoothSegment* smoothSegmentA, b2Transform xfA, + const b2Circle* circleB, b2Transform xfB ); /// Compute the contact manifold between an segment and a capsule -B2_API b2Manifold b2CollideSmoothSegmentAndCapsule(const b2SmoothSegment* smoothSegmentA, b2Transform xfA, - const b2Capsule* capsuleB, b2Transform xfB, b2DistanceCache* cache); +B2_API b2Manifold b2CollideSmoothSegmentAndCapsule( const b2SmoothSegment* smoothSegmentA, b2Transform xfA, + const b2Capsule* capsuleB, b2Transform xfB, b2DistanceCache* cache ); /// Compute the contact manifold between a smooth segment and a rounded polygon -B2_API b2Manifold b2CollideSmoothSegmentAndPolygon(const b2SmoothSegment* smoothSegmentA, b2Transform xfA, - const b2Polygon* polygonB, b2Transform xfB, b2DistanceCache* cache); +B2_API b2Manifold b2CollideSmoothSegmentAndPolygon( const b2SmoothSegment* smoothSegmentA, b2Transform xfA, + const b2Polygon* polygonB, b2Transform xfB, b2DistanceCache* cache ); /**@}*/ @@ -582,11 +589,11 @@ B2_API b2Manifold b2CollideSmoothSegmentAndPolygon(const b2SmoothSegment* smooth */ /// The default category bit for a tree proxy. Used for collision filtering. -#define b2_defaultCategoryBits (0x00000001) +#define b2_defaultCategoryBits ( 0x00000001 ) /// Convenience mask bits to use when you don't need collision filtering and just want /// all results. -#define b2_defaultMaskBits (0xFFFFFFFF) +#define b2_defaultMaskBits ( 0xFFFFFFFF ) /// A node in the dynamic tree. This is private data placed here for performance reasons. /// 16 + 16 + 8 + pad(8) @@ -613,7 +620,7 @@ typedef struct b2TreeNode /// Child 2 index int32_t child2; // 4 - /// User data + /// User data // todo could be union with child index int32_t userData; // 4 @@ -666,38 +673,38 @@ typedef struct b2DynamicTree } b2DynamicTree; /// Constructing the tree initializes the node pool. -B2_API b2DynamicTree b2DynamicTree_Create(void); +B2_API b2DynamicTree b2DynamicTree_Create( void ); /// Destroy the tree, freeing the node pool. -B2_API void b2DynamicTree_Destroy(b2DynamicTree* tree); +B2_API void b2DynamicTree_Destroy( b2DynamicTree* tree ); /// Create a proxy. Provide an AABB and a userData value. -B2_API int32_t b2DynamicTree_CreateProxy(b2DynamicTree* tree, b2AABB aabb, uint32_t categoryBits, int32_t userData); +B2_API int32_t b2DynamicTree_CreateProxy( b2DynamicTree* tree, b2AABB aabb, uint32_t categoryBits, int32_t userData ); /// Destroy a proxy. This asserts if the id is invalid. -B2_API void b2DynamicTree_DestroyProxy(b2DynamicTree* tree, int32_t proxyId); +B2_API void b2DynamicTree_DestroyProxy( b2DynamicTree* tree, int32_t proxyId ); /// Move a proxy to a new AABB by removing and reinserting into the tree. -B2_API void b2DynamicTree_MoveProxy(b2DynamicTree* tree, int32_t proxyId, b2AABB aabb); +B2_API void b2DynamicTree_MoveProxy( b2DynamicTree* tree, int32_t proxyId, b2AABB aabb ); /// Enlarge a proxy and enlarge ancestors as necessary. -B2_API void b2DynamicTree_EnlargeProxy(b2DynamicTree* tree, int32_t proxyId, b2AABB aabb); +B2_API void b2DynamicTree_EnlargeProxy( b2DynamicTree* tree, int32_t proxyId, b2AABB aabb ); /// This function receives proxies found in the AABB query. /// @return true if the query should continue -typedef bool b2TreeQueryCallbackFcn(int32_t proxyId, int32_t userData, void* context); +typedef bool b2TreeQueryCallbackFcn( int32_t proxyId, int32_t userData, void* context ); /// Query an AABB for overlapping proxies. The callback class /// is called for each proxy that overlaps the supplied AABB. -B2_API void b2DynamicTree_Query(const b2DynamicTree* tree, b2AABB aabb, uint32_t maskBits, - b2TreeQueryCallbackFcn* callback, void* context); +B2_API void b2DynamicTree_Query( const b2DynamicTree* tree, b2AABB aabb, uint32_t maskBits, b2TreeQueryCallbackFcn* callback, + void* context ); /// This function receives clipped raycast input for a proxy. The function /// returns the new ray fraction. /// - return a value of 0 to terminate the ray cast /// - return a value less than input->maxFraction to clip the ray /// - return a value of input->maxFraction to continue the ray cast without clipping -typedef float b2TreeRayCastCallbackFcn(const b2RayCastInput* input, int32_t proxyId, int32_t userData, void* context); +typedef float b2TreeRayCastCallbackFcn( const b2RayCastInput* input, int32_t proxyId, int32_t userData, void* context ); /// Ray-cast against the proxies in the tree. This relies on the callback /// to perform a exact ray-cast in the case were the proxy contains a shape. @@ -710,15 +717,15 @@ typedef float b2TreeRayCastCallbackFcn(const b2RayCastInput* input, int32_t prox /// @param maskBits filter bits: `bool accept = (maskBits & node->categoryBits) != 0;` /// @param callback a callback class that is called for each proxy that is hit by the ray /// @param context user context that is passed to the callback -B2_API void b2DynamicTree_RayCast(const b2DynamicTree* tree, const b2RayCastInput* input, uint32_t maskBits, - b2TreeRayCastCallbackFcn* callback, void* context); +B2_API void b2DynamicTree_RayCast( const b2DynamicTree* tree, const b2RayCastInput* input, uint32_t maskBits, + b2TreeRayCastCallbackFcn* callback, void* context ); /// This function receives clipped ray-cast input for a proxy. The function /// returns the new ray fraction. /// - return a value of 0 to terminate the ray-cast /// - return a value less than input->maxFraction to clip the ray /// - return a value of input->maxFraction to continue the ray cast without clipping -typedef float b2TreeShapeCastCallbackFcn(const b2ShapeCastInput* input, int32_t proxyId, int32_t userData, void* context); +typedef float b2TreeShapeCastCallbackFcn( const b2ShapeCastInput* input, int32_t proxyId, int32_t userData, void* context ); /// Ray-cast against the proxies in the tree. This relies on the callback /// to perform a exact ray-cast in the case were the proxy contains a shape. @@ -730,49 +737,49 @@ typedef float b2TreeShapeCastCallbackFcn(const b2ShapeCastInput* input, int32_t /// @param maskBits filter bits: `bool accept = (maskBits & node->categoryBits) != 0;` /// @param callback a callback class that is called for each proxy that is hit by the shape /// @param context user context that is passed to the callback -B2_API void b2DynamicTree_ShapeCast(const b2DynamicTree* tree, const b2ShapeCastInput* input, uint32_t maskBits, - b2TreeShapeCastCallbackFcn* callback, void* context); +B2_API void b2DynamicTree_ShapeCast( const b2DynamicTree* tree, const b2ShapeCastInput* input, uint32_t maskBits, + b2TreeShapeCastCallbackFcn* callback, void* context ); /// Validate this tree. For testing. -B2_API void b2DynamicTree_Validate(const b2DynamicTree* tree); +B2_API void b2DynamicTree_Validate( const b2DynamicTree* tree ); /// Compute the height of the binary tree in O(N) time. Should not be /// called often. -B2_API int b2DynamicTree_GetHeight(const b2DynamicTree* tree); +B2_API int b2DynamicTree_GetHeight( const b2DynamicTree* tree ); /// Get the maximum balance of the tree. The balance is the difference in height of the two children of a node. -B2_API int b2DynamicTree_GetMaxBalance(const b2DynamicTree* tree); +B2_API int b2DynamicTree_GetMaxBalance( const b2DynamicTree* tree ); /// Get the ratio of the sum of the node areas to the root area. -B2_API float b2DynamicTree_GetAreaRatio(const b2DynamicTree* tree); +B2_API float b2DynamicTree_GetAreaRatio( const b2DynamicTree* tree ); /// Build an optimal tree. Very expensive. For testing. -B2_API void b2DynamicTree_RebuildBottomUp(b2DynamicTree* tree); +B2_API void b2DynamicTree_RebuildBottomUp( b2DynamicTree* tree ); /// Get the number of proxies created -B2_API int b2DynamicTree_GetProxyCount(const b2DynamicTree* tree); +B2_API int b2DynamicTree_GetProxyCount( const b2DynamicTree* tree ); /// Rebuild the tree while retaining subtrees that haven't changed. Returns the number of boxes sorted. -B2_API int b2DynamicTree_Rebuild(b2DynamicTree* tree, bool fullBuild); +B2_API int b2DynamicTree_Rebuild( b2DynamicTree* tree, bool fullBuild ); /// Shift the world origin. Useful for large worlds. /// The shift formula is: position -= newOrigin /// @param tree the tree to shift /// @param newOrigin the new origin with respect to the old origin -B2_API void b2DynamicTree_ShiftOrigin(b2DynamicTree* tree, b2Vec2 newOrigin); +B2_API void b2DynamicTree_ShiftOrigin( b2DynamicTree* tree, b2Vec2 newOrigin ); /// Get the number of bytes used by this tree -B2_API int b2DynamicTree_GetByteCount(const b2DynamicTree* tree); +B2_API int b2DynamicTree_GetByteCount( const b2DynamicTree* tree ); /// Get proxy user data /// @return the proxy user data or 0 if the id is invalid -B2_INLINE int32_t b2DynamicTree_GetUserData(const b2DynamicTree* tree, int32_t proxyId) +B2_INLINE int32_t b2DynamicTree_GetUserData( const b2DynamicTree* tree, int32_t proxyId ) { return tree->nodes[proxyId].userData; } /// Get the AABB of a proxy -B2_INLINE b2AABB b2DynamicTree_GetAABB(const b2DynamicTree* tree, int32_t proxyId) +B2_INLINE b2AABB b2DynamicTree_GetAABB( const b2DynamicTree* tree, int32_t proxyId ) { return tree->nodes[proxyId].aabb; } diff --git a/include/box2d/id.h b/include/box2d/id.h index f06078f6..72c31f62 100644 --- a/include/box2d/id.h +++ b/include/box2d/id.h @@ -28,6 +28,7 @@ * * 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 Box2D. Do not access files within the src folder. Such usage is unsupported. * @{ */ @@ -80,12 +81,12 @@ static const b2JointId b2_nullJointId = B2_ZERO_INIT; static const b2ChainId b2_nullChainId = B2_ZERO_INIT; /// Macro to determine if any id is null. -#define B2_IS_NULL(id) (id.index1 == 0) +#define B2_IS_NULL( id ) ( id.index1 == 0 ) /// Macro to determine if any id is non-null. -#define B2_IS_NON_NULL(id) (id.index1 != 0) +#define B2_IS_NON_NULL( id ) ( id.index1 != 0 ) /// Compare two ids for equality. Doesn't work for b2WorldId. -#define B2_ID_EQUALS(id1, id2) (id1.index1 == id2.index1 && id1.world0 == id2.world0 && id1.revision == id2.revision) +#define B2_ID_EQUALS( id1, id2 ) ( id1.index1 == id2.index1 && id1.world0 == id2.world0 && id1.revision == id2.revision ) /**@}*/ diff --git a/include/box2d/math_functions.h b/include/box2d/math_functions.h index 9177e2ee..31955f3e 100644 --- a/include/box2d/math_functions.h +++ b/include/box2d/math_functions.h @@ -61,226 +61,226 @@ typedef struct b2AABB * @{ */ -static const b2Vec2 b2Vec2_zero = {0.0f, 0.0f}; -static const b2Rot b2Rot_identity = {1.0f, 0.0f}; -static const b2Transform b2Transform_identity = {{0.0f, 0.0f}, {1.0f, 0.0f}}; -static const b2Mat22 b2Mat22_zero = {{0.0f, 0.0f}, {0.0f, 0.0f}}; +static const b2Vec2 b2Vec2_zero = { 0.0f, 0.0f }; +static const b2Rot b2Rot_identity = { 1.0f, 0.0f }; +static const b2Transform b2Transform_identity = { { 0.0f, 0.0f }, { 1.0f, 0.0f } }; +static const b2Mat22 b2Mat22_zero = { { 0.0f, 0.0f }, { 0.0f, 0.0f } }; /// @return the minimum of two floats -B2_INLINE float b2MinFloat(float a, float b) +B2_INLINE float b2MinFloat( float a, float b ) { return a < b ? a : b; } /// @return the maximum of two floats -B2_INLINE float b2MaxFloat(float a, float b) +B2_INLINE float b2MaxFloat( float a, float b ) { return a > b ? a : b; } /// @return the absolute value of a float -B2_INLINE float b2AbsFloat(float a) +B2_INLINE float b2AbsFloat( float a ) { return a < 0 ? -a : a; } /// @return a float clamped between a lower and upper bound -B2_INLINE float b2ClampFloat(float a, float lower, float upper) +B2_INLINE float b2ClampFloat( float a, float lower, float upper ) { - return a < lower ? lower : (a > upper ? upper : a); + return a < lower ? lower : ( a > upper ? upper : a ); } /// @return the minimum of two integers -B2_INLINE int b2MinInt(int a, int b) +B2_INLINE int b2MinInt( int a, int b ) { return a < b ? a : b; } /// @return the maximum of two integers -B2_INLINE int b2MaxInt(int a, int b) +B2_INLINE int b2MaxInt( int a, int b ) { return a > b ? a : b; } /// @return the absolute value of an integer -B2_INLINE int b2AbsInt(int a) +B2_INLINE int b2AbsInt( int a ) { return a < 0 ? -a : a; } /// @return an integer clamped between a lower and upper bound -B2_INLINE int b2ClampInt(int a, int lower, int upper) +B2_INLINE int b2ClampInt( int a, int lower, int upper ) { - return a < lower ? lower : (a > upper ? upper : a); + return a < lower ? lower : ( a > upper ? upper : a ); } /// Vector dot product -B2_INLINE float b2Dot(b2Vec2 a, b2Vec2 b) +B2_INLINE float b2Dot( b2Vec2 a, b2Vec2 b ) { return a.x * b.x + a.y * b.y; } /// Vector cross product. In 2D this yields a scalar. -B2_INLINE float b2Cross(b2Vec2 a, b2Vec2 b) +B2_INLINE float b2Cross( b2Vec2 a, b2Vec2 b ) { return a.x * b.y - a.y * b.x; } /// Perform the cross product on a vector and a scalar. In 2D this produces a vector. -B2_INLINE b2Vec2 b2CrossVS(b2Vec2 v, float s) +B2_INLINE b2Vec2 b2CrossVS( b2Vec2 v, float s ) { - return B2_LITERAL(b2Vec2){s * v.y, -s * v.x}; + return B2_LITERAL( b2Vec2 ){ s * v.y, -s * v.x }; } /// Perform the cross product on a scalar and a vector. In 2D this produces a vector. -B2_INLINE b2Vec2 b2CrossSV(float s, b2Vec2 v) +B2_INLINE b2Vec2 b2CrossSV( float s, b2Vec2 v ) { - return B2_LITERAL(b2Vec2){-s * v.y, s * v.x}; + return B2_LITERAL( b2Vec2 ){ -s * v.y, s * v.x }; } /// Get a left pointing perpendicular vector. Equivalent to b2CrossSV(1.0f, v) -B2_INLINE b2Vec2 b2LeftPerp(b2Vec2 v) +B2_INLINE b2Vec2 b2LeftPerp( b2Vec2 v ) { - return B2_LITERAL(b2Vec2){-v.y, v.x}; + return B2_LITERAL( b2Vec2 ){ -v.y, v.x }; } /// Get a right pointing perpendicular vector. Equivalent to b2CrossVS(v, 1.0f) -B2_INLINE b2Vec2 b2RightPerp(b2Vec2 v) +B2_INLINE b2Vec2 b2RightPerp( b2Vec2 v ) { - return B2_LITERAL(b2Vec2){v.y, -v.x}; + return B2_LITERAL( b2Vec2 ){ v.y, -v.x }; } /// Vector addition -B2_INLINE b2Vec2 b2Add(b2Vec2 a, b2Vec2 b) +B2_INLINE b2Vec2 b2Add( b2Vec2 a, b2Vec2 b ) { - return B2_LITERAL(b2Vec2){a.x + b.x, a.y + b.y}; + return B2_LITERAL( b2Vec2 ){ a.x + b.x, a.y + b.y }; } /// Vector subtraction -B2_INLINE b2Vec2 b2Sub(b2Vec2 a, b2Vec2 b) +B2_INLINE b2Vec2 b2Sub( b2Vec2 a, b2Vec2 b ) { - return B2_LITERAL(b2Vec2){a.x - b.x, a.y - b.y}; + return B2_LITERAL( b2Vec2 ){ a.x - b.x, a.y - b.y }; } /// Vector negation -B2_INLINE b2Vec2 b2Neg(b2Vec2 a) +B2_INLINE b2Vec2 b2Neg( b2Vec2 a ) { - return B2_LITERAL(b2Vec2){-a.x, -a.y}; + return B2_LITERAL( b2Vec2 ){ -a.x, -a.y }; } /// Vector linear interpolation /// https://fgiesen.wordpress.com/2012/08/15/linear-interpolation-past-present-and-future/ -B2_INLINE b2Vec2 b2Lerp(b2Vec2 a, b2Vec2 b, float t) +B2_INLINE b2Vec2 b2Lerp( b2Vec2 a, b2Vec2 b, float t ) { - return B2_LITERAL(b2Vec2){(1.0f - t) * a.x + t * b.x, (1.0f - t) * a.y + t * b.y}; + return B2_LITERAL( b2Vec2 ){ ( 1.0f - t ) * a.x + t * b.x, ( 1.0f - t ) * a.y + t * b.y }; } /// Component-wise multiplication -B2_INLINE b2Vec2 b2Mul(b2Vec2 a, b2Vec2 b) +B2_INLINE b2Vec2 b2Mul( b2Vec2 a, b2Vec2 b ) { - return B2_LITERAL(b2Vec2){a.x * b.x, a.y * b.y}; + return B2_LITERAL( b2Vec2 ){ a.x * b.x, a.y * b.y }; } /// Multiply a scalar and vector -B2_INLINE b2Vec2 b2MulSV(float s, b2Vec2 v) +B2_INLINE b2Vec2 b2MulSV( float s, b2Vec2 v ) { - return B2_LITERAL(b2Vec2){s * v.x, s * v.y}; + return B2_LITERAL( b2Vec2 ){ s * v.x, s * v.y }; } /// a + s * b -B2_INLINE b2Vec2 b2MulAdd(b2Vec2 a, float s, b2Vec2 b) +B2_INLINE b2Vec2 b2MulAdd( b2Vec2 a, float s, b2Vec2 b ) { - return B2_LITERAL(b2Vec2){a.x + s * b.x, a.y + s * b.y}; + return B2_LITERAL( b2Vec2 ){ a.x + s * b.x, a.y + s * b.y }; } /// a - s * b -B2_INLINE b2Vec2 b2MulSub(b2Vec2 a, float s, b2Vec2 b) +B2_INLINE b2Vec2 b2MulSub( b2Vec2 a, float s, b2Vec2 b ) { - return B2_LITERAL(b2Vec2){a.x - s * b.x, a.y - s * b.y}; + return B2_LITERAL( b2Vec2 ){ a.x - s * b.x, a.y - s * b.y }; } /// Component-wise absolute vector -B2_INLINE b2Vec2 b2Abs(b2Vec2 a) +B2_INLINE b2Vec2 b2Abs( b2Vec2 a ) { b2Vec2 b; - b.x = b2AbsFloat(a.x); - b.y = b2AbsFloat(a.y); + b.x = b2AbsFloat( a.x ); + b.y = b2AbsFloat( a.y ); return b; } /// Component-wise minimum vector -B2_INLINE b2Vec2 b2Min(b2Vec2 a, b2Vec2 b) +B2_INLINE b2Vec2 b2Min( b2Vec2 a, b2Vec2 b ) { b2Vec2 c; - c.x = b2MinFloat(a.x, b.x); - c.y = b2MinFloat(a.y, b.y); + c.x = b2MinFloat( a.x, b.x ); + c.y = b2MinFloat( a.y, b.y ); return c; } /// Component-wise maximum vector -B2_INLINE b2Vec2 b2Max(b2Vec2 a, b2Vec2 b) +B2_INLINE b2Vec2 b2Max( b2Vec2 a, b2Vec2 b ) { b2Vec2 c; - c.x = b2MaxFloat(a.x, b.x); - c.y = b2MaxFloat(a.y, b.y); + c.x = b2MaxFloat( a.x, b.x ); + c.y = b2MaxFloat( a.y, b.y ); return c; } /// Component-wise clamp vector v into the range [a, b] -B2_INLINE b2Vec2 b2Clamp(b2Vec2 v, b2Vec2 a, b2Vec2 b) +B2_INLINE b2Vec2 b2Clamp( b2Vec2 v, b2Vec2 a, b2Vec2 b ) { b2Vec2 c; - c.x = b2ClampFloat(v.x, a.x, b.x); - c.y = b2ClampFloat(v.y, a.y, b.y); + c.x = b2ClampFloat( v.x, a.x, b.x ); + c.y = b2ClampFloat( v.y, a.y, b.y ); return c; } /// Get the length of this vector (the norm) -B2_INLINE float b2Length(b2Vec2 v) +B2_INLINE float b2Length( b2Vec2 v ) { - return sqrtf(v.x * v.x + v.y * v.y); + return sqrtf( v.x * v.x + v.y * v.y ); } /// Get the length squared of this vector -B2_INLINE float b2LengthSquared(b2Vec2 v) +B2_INLINE float b2LengthSquared( b2Vec2 v ) { return v.x * v.x + v.y * v.y; } /// Get the distance between two points -B2_INLINE float b2Distance(b2Vec2 a, b2Vec2 b) +B2_INLINE float b2Distance( b2Vec2 a, b2Vec2 b ) { float dx = b.x - a.x; float dy = b.y - a.y; - return sqrtf(dx * dx + dy * dy); + return sqrtf( dx * dx + dy * dy ); } /// Get the distance squared between points -B2_INLINE float b2DistanceSquared(b2Vec2 a, b2Vec2 b) +B2_INLINE float b2DistanceSquared( b2Vec2 a, b2Vec2 b ) { - b2Vec2 c = {b.x - a.x, b.y - a.y}; + b2Vec2 c = { b.x - a.x, b.y - a.y }; return c.x * c.x + c.y * c.y; } /// Make a rotation using an angle in radians -B2_INLINE b2Rot b2MakeRot(float angle) +B2_INLINE b2Rot b2MakeRot( float angle ) { // todo determinism - b2Rot q = {cosf(angle), sinf(angle)}; + b2Rot q = { cosf( angle ), sinf( angle ) }; return q; } /// Normalize rotation -B2_INLINE b2Rot b2NormalizeRot(b2Rot q) +B2_INLINE b2Rot b2NormalizeRot( b2Rot q ) { - float mag = sqrtf(q.s * q.s + q.c * q.c); + float mag = sqrtf( q.s * q.s + q.c * q.c ); float invMag = mag > 0.0 ? 1.0f / mag : 0.0f; - b2Rot qn = {q.c * invMag, q.s * invMag}; + b2Rot qn = { q.c * invMag, q.s * invMag }; return qn; } /// Is this rotation normalized? -B2_INLINE bool b2IsNormalized(b2Rot q) +B2_INLINE bool b2IsNormalized( b2Rot q ) { // larger tolerance due to failure on mingw 32-bit float qq = q.s * q.s + q.c * q.c; @@ -289,7 +289,7 @@ B2_INLINE bool b2IsNormalized(b2Rot q) /// Normalized linear interpolation /// https://fgiesen.wordpress.com/2012/08/15/linear-interpolation-past-present-and-future/ -B2_INLINE b2Rot b2NLerp(b2Rot q1, b2Rot q2, float t) +B2_INLINE b2Rot b2NLerp( b2Rot q1, b2Rot q2, float t ) { float omt = 1.0f - t; b2Rot q = { @@ -297,22 +297,22 @@ B2_INLINE b2Rot b2NLerp(b2Rot q1, b2Rot q2, float t) omt * q1.s + t * q2.s, }; - return b2NormalizeRot(q); + return b2NormalizeRot( q ); } /// Integration rotation from angular velocity /// @param q1 initial rotation /// @param deltaAngle the angular displacement in radians -B2_INLINE b2Rot b2IntegrateRotation(b2Rot q1, float deltaAngle) +B2_INLINE b2Rot b2IntegrateRotation( b2Rot q1, float deltaAngle ) { // dc/dt = -omega * sin(t) // ds/dt = omega * cos(t) // c2 = c1 - omega * h * s1 // s2 = s1 + omega * h * c1 - b2Rot q2 = {q1.c - deltaAngle * q1.s, q1.s + deltaAngle * q1.c}; - float mag = sqrtf(q2.s * q2.s + q2.c * q2.c); + b2Rot q2 = { q1.c - deltaAngle * q1.s, q1.s + deltaAngle * q1.c }; + float mag = sqrtf( q2.s * q2.s + q2.c * q2.c ); float invMag = mag > 0.0 ? 1.0f / mag : 0.0f; - b2Rot qn = {q2.c * invMag, q2.s * invMag}; + b2Rot qn = { q2.c * invMag, q2.s * invMag }; return qn; } @@ -320,7 +320,7 @@ B2_INLINE b2Rot b2IntegrateRotation(b2Rot q1, float deltaAngle) /// @param q1 initial rotation /// @param q2 final rotation /// @param inv_h inverse time step -B2_INLINE float b2ComputeAngularVelocity(b2Rot q1, b2Rot q2, float inv_h) +B2_INLINE float b2ComputeAngularVelocity( b2Rot q1, b2Rot q2, float inv_h ) { // ds/dt = omega * cos(t) // dc/dt = -omega * sin(t) @@ -332,33 +332,33 @@ B2_INLINE float b2ComputeAngularVelocity(b2Rot q1, b2Rot q2, float inv_h) // omega * h = (c1 - c2) * s1 + (s2 - s1) * c1; // omega * h = s1 * c1 - c2 * s1 + s2 * c1 - s1 * c1 // omega * h = s2 * c1 - c2 * s1 = sin(a2 - a1) ~= a2 - a1 for small delta - float omega = inv_h * (q2.s * q1.c - q2.c * q1.s); + float omega = inv_h * ( q2.s * q1.c - q2.c * q1.s ); return omega; } /// Get the angle in radians in the range [-pi, pi] -B2_INLINE float b2Rot_GetAngle(b2Rot q) +B2_INLINE float b2Rot_GetAngle( b2Rot q ) { // todo determinism - return atan2f(q.s, q.c); + return atan2f( q.s, q.c ); } /// Get the x-axis -B2_INLINE b2Vec2 b2Rot_GetXAxis(b2Rot q) +B2_INLINE b2Vec2 b2Rot_GetXAxis( b2Rot q ) { - b2Vec2 v = {q.c, q.s}; + b2Vec2 v = { q.c, q.s }; return v; } /// Get the y-axis -B2_INLINE b2Vec2 b2Rot_GetYAxis(b2Rot q) +B2_INLINE b2Vec2 b2Rot_GetYAxis( b2Rot q ) { - b2Vec2 v = {-q.s, q.c}; + b2Vec2 v = { -q.s, q.c }; return v; } /// Multiply two rotations: q * r -B2_INLINE b2Rot b2MulRot(b2Rot q, b2Rot r) +B2_INLINE b2Rot b2MulRot( b2Rot q, b2Rot r ) { // [qc -qs] * [rc -rs] = [qc*rc-qs*rs -qc*rs-qs*rc] // [qs qc] [rs rc] [qs*rc+qc*rs -qs*rs+qc*rc] @@ -371,7 +371,7 @@ B2_INLINE b2Rot b2MulRot(b2Rot q, b2Rot r) } /// Transpose multiply two rotations: qT * r -B2_INLINE b2Rot b2InvMulRot(b2Rot q, b2Rot r) +B2_INLINE b2Rot b2InvMulRot( b2Rot q, b2Rot r ) { // [ qc qs] * [rc -rs] = [qc*rc+qs*rs -qc*rs+qs*rc] // [-qs qc] [rs rc] [-qs*rc+qc*rs qs*rs+qc*rc] @@ -384,23 +384,23 @@ B2_INLINE b2Rot b2InvMulRot(b2Rot q, b2Rot r) } /// relative angle between b and a (rot_b * inv(rot_a)) -B2_INLINE float b2RelativeAngle(b2Rot b, b2Rot a) +B2_INLINE float b2RelativeAngle( b2Rot b, b2Rot a ) { // sin(b - a) = bs * ac - bc * as // cos(b - a) = bc * ac + bs * as float s = b.s * a.c - b.c * a.s; float c = b.c * a.c + b.s * a.s; - return atan2f(s, c); + return atan2f( s, c ); } /// Convert an angle in the range [-2*pi, 2*pi] into the range [-pi, pi] -B2_INLINE float b2UnwindAngle(float angle) +B2_INLINE float b2UnwindAngle( float angle ) { - if (angle < -b2_pi) + if ( angle < -b2_pi ) { return angle + 2.0f * b2_pi; } - else if (angle > b2_pi) + else if ( angle > b2_pi ) { return angle - 2.0f * b2_pi; } @@ -409,56 +409,56 @@ B2_INLINE float b2UnwindAngle(float angle) } /// Rotate a vector -B2_INLINE b2Vec2 b2RotateVector(b2Rot q, b2Vec2 v) +B2_INLINE b2Vec2 b2RotateVector( b2Rot q, b2Vec2 v ) { - return B2_LITERAL(b2Vec2){q.c * v.x - q.s * v.y, q.s * v.x + q.c * v.y}; + return B2_LITERAL( b2Vec2 ){ q.c * v.x - q.s * v.y, q.s * v.x + q.c * v.y }; } /// Inverse rotate a vector -B2_INLINE b2Vec2 b2InvRotateVector(b2Rot q, b2Vec2 v) +B2_INLINE b2Vec2 b2InvRotateVector( b2Rot q, b2Vec2 v ) { - return B2_LITERAL(b2Vec2){q.c * v.x + q.s * v.y, -q.s * v.x + q.c * v.y}; + return B2_LITERAL( b2Vec2 ){ q.c * v.x + q.s * v.y, -q.s * v.x + q.c * v.y }; } /// Transform a point (e.g. local space to world space) -B2_INLINE b2Vec2 b2TransformPoint(b2Transform t, const b2Vec2 p) +B2_INLINE b2Vec2 b2TransformPoint( b2Transform t, const b2Vec2 p ) { - float x = (t.q.c * p.x - t.q.s * p.y) + t.p.x; - float y = (t.q.s * p.x + t.q.c * p.y) + t.p.y; + float x = ( t.q.c * p.x - t.q.s * p.y ) + t.p.x; + float y = ( t.q.s * p.x + t.q.c * p.y ) + t.p.y; - return B2_LITERAL(b2Vec2){x, y}; + return B2_LITERAL( b2Vec2 ){ x, y }; } /// Inverse transform a point (e.g. world space to local space) -B2_INLINE b2Vec2 b2InvTransformPoint(b2Transform t, const b2Vec2 p) +B2_INLINE b2Vec2 b2InvTransformPoint( b2Transform t, const b2Vec2 p ) { float vx = p.x - t.p.x; float vy = p.y - t.p.y; - return B2_LITERAL(b2Vec2){t.q.c * vx + t.q.s * vy, -t.q.s * vx + t.q.c * vy}; + return B2_LITERAL( b2Vec2 ){ t.q.c * vx + t.q.s * vy, -t.q.s * vx + t.q.c * vy }; } /// v2 = A.q.Rot(B.q.Rot(v1) + B.p) + A.p /// = (A.q * B.q).Rot(v1) + A.q.Rot(B.p) + A.p -B2_INLINE b2Transform b2MulTransforms(b2Transform A, b2Transform B) +B2_INLINE b2Transform b2MulTransforms( b2Transform A, b2Transform B ) { b2Transform C; - C.q = b2MulRot(A.q, B.q); - C.p = b2Add(b2RotateVector(A.q, B.p), A.p); + C.q = b2MulRot( A.q, B.q ); + C.p = b2Add( b2RotateVector( A.q, B.p ), A.p ); return C; } /// v2 = A.q' * (B.q * v1 + B.p - A.p) /// = A.q' * B.q * v1 + A.q' * (B.p - A.p) -B2_INLINE b2Transform b2InvMulTransforms(b2Transform A, b2Transform B) +B2_INLINE b2Transform b2InvMulTransforms( b2Transform A, b2Transform B ) { b2Transform C; - C.q = b2InvMulRot(A.q, B.q); - C.p = b2InvRotateVector(A.q, b2Sub(B.p, A.p)); + C.q = b2InvMulRot( A.q, B.q ); + C.p = b2InvRotateVector( A.q, b2Sub( B.p, A.p ) ); return C; } /// Multiply a 2-by-2 matrix times a 2D vector -B2_INLINE b2Vec2 b2MulMV(b2Mat22 A, b2Vec2 v) +B2_INLINE b2Vec2 b2MulMV( b2Mat22 A, b2Vec2 v ) { b2Vec2 u = { A.cx.x * v.x + A.cy.x * v.y, @@ -468,38 +468,38 @@ B2_INLINE b2Vec2 b2MulMV(b2Mat22 A, b2Vec2 v) } /// Get the inverse of a 2-by-2 matrix -B2_INLINE b2Mat22 b2GetInverse22(b2Mat22 A) +B2_INLINE b2Mat22 b2GetInverse22( b2Mat22 A ) { float a = A.cx.x, b = A.cy.x, c = A.cx.y, d = A.cy.y; float det = a * d - b * c; - if (det != 0.0f) + if ( det != 0.0f ) { det = 1.0f / det; } b2Mat22 B = { - {det * d, -det * c}, - {-det * b, det * a}, + { det * d, -det * c }, + { -det * b, det * a }, }; return B; } /// Solve A * x = b, where b is a column vector. This is more efficient /// than computing the inverse in one-shot cases. -B2_INLINE b2Vec2 b2Solve22(b2Mat22 A, b2Vec2 b) +B2_INLINE b2Vec2 b2Solve22( b2Mat22 A, b2Vec2 b ) { float a11 = A.cx.x, a12 = A.cy.x, a21 = A.cx.y, a22 = A.cy.y; float det = a11 * a22 - a12 * a21; - if (det != 0.0f) + if ( det != 0.0f ) { det = 1.0f / det; } - b2Vec2 x = {det * (a22 * b.x - a12 * b.y), det * (a11 * b.y - a21 * b.x)}; + b2Vec2 x = { det * ( a22 * b.x - a12 * b.y ), det * ( a11 * b.y - a21 * b.x ) }; return x; } /// Does a fully contain b -B2_INLINE bool b2AABB_Contains(b2AABB a, b2AABB b) +B2_INLINE bool b2AABB_Contains( b2AABB a, b2AABB b ) { bool s = true; s = s && a.lowerBound.x <= b.lowerBound.x; @@ -510,60 +510,60 @@ B2_INLINE bool b2AABB_Contains(b2AABB a, b2AABB b) } /// Get the center of the AABB. -B2_INLINE b2Vec2 b2AABB_Center(b2AABB a) +B2_INLINE b2Vec2 b2AABB_Center( b2AABB a ) { - b2Vec2 b = {0.5f * (a.lowerBound.x + a.upperBound.x), 0.5f * (a.lowerBound.y + a.upperBound.y)}; + b2Vec2 b = { 0.5f * ( a.lowerBound.x + a.upperBound.x ), 0.5f * ( a.lowerBound.y + a.upperBound.y ) }; return b; } /// Get the extents of the AABB (half-widths). -B2_INLINE b2Vec2 b2AABB_Extents(b2AABB a) +B2_INLINE b2Vec2 b2AABB_Extents( b2AABB a ) { - b2Vec2 b = {0.5f * (a.upperBound.x - a.lowerBound.x), 0.5f * (a.upperBound.y - a.lowerBound.y)}; + b2Vec2 b = { 0.5f * ( a.upperBound.x - a.lowerBound.x ), 0.5f * ( a.upperBound.y - a.lowerBound.y ) }; return b; } /// Union of two AABBs -B2_INLINE b2AABB b2AABB_Union(b2AABB a, b2AABB b) +B2_INLINE b2AABB b2AABB_Union( b2AABB a, b2AABB b ) { b2AABB c; - c.lowerBound.x = b2MinFloat(a.lowerBound.x, b.lowerBound.x); - c.lowerBound.y = b2MinFloat(a.lowerBound.y, b.lowerBound.y); - c.upperBound.x = b2MaxFloat(a.upperBound.x, b.upperBound.x); - c.upperBound.y = b2MaxFloat(a.upperBound.y, b.upperBound.y); + c.lowerBound.x = b2MinFloat( a.lowerBound.x, b.lowerBound.x ); + c.lowerBound.y = b2MinFloat( a.lowerBound.y, b.lowerBound.y ); + c.upperBound.x = b2MaxFloat( a.upperBound.x, b.upperBound.x ); + c.upperBound.y = b2MaxFloat( a.upperBound.y, b.upperBound.y ); return c; } /// Is this a valid number? Not NaN or infinity. -B2_API bool b2IsValid(float a); +B2_API bool b2IsValid( float a ); /// Is this a valid vector? Not NaN or infinity. -B2_API bool b2Vec2_IsValid(b2Vec2 v); +B2_API bool b2Vec2_IsValid( b2Vec2 v ); /// Is this a valid rotation? Not NaN or infinity. Is normalized. -B2_API bool b2Rot_IsValid(b2Rot q); +B2_API bool b2Rot_IsValid( b2Rot q ); /// Is this a valid bounding box? Not Nan or infinity. Upper bound greater than or equal to lower bound. -B2_API bool b2AABB_IsValid(b2AABB aabb); +B2_API bool b2AABB_IsValid( b2AABB aabb ); /// Convert a vector into a unit vector if possible, otherwise returns the zero vector. -B2_API b2Vec2 b2Normalize(b2Vec2 v); +B2_API b2Vec2 b2Normalize( b2Vec2 v ); /// Convert a vector into a unit vector if possible, otherwise asserts. -B2_API b2Vec2 b2NormalizeChecked(b2Vec2 v); +B2_API b2Vec2 b2NormalizeChecked( b2Vec2 v ); /// Convert a vector into a unit vector if possible, otherwise returns the zero vector. Also /// outputs the length. -B2_API b2Vec2 b2GetLengthAndNormalize(float* length, b2Vec2 v); +B2_API b2Vec2 b2GetLengthAndNormalize( float* length, b2Vec2 v ); /// Box2D 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 Box2D -B2_API void b2SetLengthUnitsPerMeter(float lengthUnits); +B2_API void b2SetLengthUnitsPerMeter( float lengthUnits ); /// Get the current length units per meter. -B2_API float b2GetLengthUnitsPerMeter(void); +B2_API float b2GetLengthUnitsPerMeter( void ); /**@}*/ @@ -578,64 +578,64 @@ B2_API float b2GetLengthUnitsPerMeter(void); #ifdef __cplusplus /// Unary add one vector to another -inline void operator+=(b2Vec2& a, b2Vec2 b) +inline void operator+=( b2Vec2& a, b2Vec2 b ) { a.x += b.x; a.y += b.y; } /// Unary subtract one vector from another -inline void operator-=(b2Vec2& a, b2Vec2 b) +inline void operator-=( b2Vec2& a, b2Vec2 b ) { a.x -= b.x; a.y -= b.y; } /// Unary multiply a vector by a scalar -inline void operator*=(b2Vec2& a, float b) +inline void operator*=( b2Vec2& a, float b ) { a.x *= b; a.y *= b; } /// Unary negate a vector -inline b2Vec2 operator-(b2Vec2 a) +inline b2Vec2 operator-( b2Vec2 a ) { - return {-a.x, -a.y}; + return { -a.x, -a.y }; } /// Binary vector addition -inline b2Vec2 operator+(b2Vec2 a, b2Vec2 b) +inline b2Vec2 operator+( b2Vec2 a, b2Vec2 b ) { - return {a.x + b.x, a.y + b.y}; + return { a.x + b.x, a.y + b.y }; } /// Binary vector subtraction -inline b2Vec2 operator-(b2Vec2 a, b2Vec2 b) +inline b2Vec2 operator-( b2Vec2 a, b2Vec2 b ) { - return {a.x - b.x, a.y - b.y}; + return { a.x - b.x, a.y - b.y }; } /// Binary scalar and vector multiplication -inline b2Vec2 operator*(float a, b2Vec2 b) +inline b2Vec2 operator*( float a, b2Vec2 b ) { - return {a * b.x, a * b.y}; + return { a * b.x, a * b.y }; } /// Binary scalar and vector multiplication -inline b2Vec2 operator*(b2Vec2 a, float b) +inline b2Vec2 operator*( b2Vec2 a, float b ) { - return {a.x * b, a.y * b}; + return { a.x * b, a.y * b }; } /// Binary vector equality -inline bool operator==(b2Vec2 a, b2Vec2 b) +inline bool operator==( b2Vec2 a, b2Vec2 b ) { return a.x == b.x && a.y == b.y; } /// Binary vector inequality -inline bool operator!=(b2Vec2 a, b2Vec2 b) +inline bool operator!=( b2Vec2 a, b2Vec2 b ) { return a.x != b.x || a.y != b.y; } diff --git a/include/box2d/types.h b/include/box2d/types.h index 5aa94095..3cd6421e 100644 --- a/include/box2d/types.h +++ b/include/box2d/types.h @@ -27,7 +27,7 @@ /// } /// @endcode /// @ingroup world -typedef void b2TaskCallback(int32_t startIndex, int32_t endIndex, uint32_t workerIndex, void* taskContext); +typedef void b2TaskCallback( int32_t startIndex, int32_t endIndex, uint32_t workerIndex, void* taskContext ); /// 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 @@ -40,12 +40,12 @@ typedef void b2TaskCallback(int32_t startIndex, int32_t endIndex, uint32_t worke /// endIndex - startIndex >= minRange /// The exception of course is when itemCount < minRange. /// @ingroup world -typedef void* b2EnqueueTaskCallback(b2TaskCallback* task, int32_t itemCount, int32_t minRange, void* taskContext, - void* userContext); +typedef void* b2EnqueueTaskCallback( b2TaskCallback* task, int32_t itemCount, int32_t minRange, void* taskContext, + void* userContext ); /// Finishes a user task object that wraps a Box2D task. /// @ingroup world -typedef void b2FinishTaskCallback(void* userTask, void* userContext); +typedef void b2FinishTaskCallback( void* userTask, void* userContext ); /// Result from b2World_RayCastClosest /// @ingroup world @@ -114,7 +114,7 @@ typedef struct b2WorldDef /// Use this to initialize your world definition /// @ingroup world -B2_API b2WorldDef b2DefaultWorldDef(void); +B2_API b2WorldDef b2DefaultWorldDef( void ); /// The body simulation type. /// Each body is one of these three types. The type determines how the body behaves in the simulation. @@ -208,7 +208,7 @@ typedef struct b2BodyDef /// Use this to initialize your body definition /// @ingroup body -B2_API b2BodyDef b2DefaultBodyDef(void); +B2_API b2BodyDef b2DefaultBodyDef( void ); /// This is used to filter collision on shapes. It affects shape-vs-shape collision /// and shape-versus-query collision (such as b2World_CastRay). @@ -249,7 +249,7 @@ typedef struct b2Filter /// Use this to initialize your filter /// @ingroup shape -B2_API b2Filter b2DefaultFilter(void); +B2_API b2Filter b2DefaultFilter( void ); /// The query filter is used to filter collisions between queries and shapes. For example, /// you may want a ray-cast representing a projectile to hit players and the static environment @@ -267,7 +267,7 @@ typedef struct b2QueryFilter /// Use this to initialize your query filter /// @ingroup shape -B2_API b2QueryFilter b2DefaultQueryFilter(void); +B2_API b2QueryFilter b2DefaultQueryFilter( void ); /// Shape type /// @ingroup shape @@ -314,6 +314,9 @@ typedef struct b2ShapeDef /// Collision filtering data. b2Filter filter; + /// Custom debug draw color. + uint32_t customColor; + /// A sensor shape generates overlap events but never generates a collision response. bool isSensor; @@ -341,7 +344,7 @@ typedef struct b2ShapeDef /// Use this to initialize your shape definition /// @ingroup shape -B2_API b2ShapeDef b2DefaultShapeDef(void); +B2_API b2ShapeDef b2DefaultShapeDef( void ); /// Used to create a chain of edges. This is designed to eliminate ghost collisions with some limitations. /// - chains are one-sided @@ -387,7 +390,7 @@ typedef struct b2ChainDef /// Use this to initialize your chain definition /// @ingroup shape -B2_API b2ChainDef b2DefaultChainDef(void); +B2_API b2ChainDef b2DefaultChainDef( void ); //! @cond /// Profiling data. Times are in milliseconds. @@ -515,7 +518,7 @@ typedef struct b2DistanceJointDef /// Use this to initialize your joint definition /// @ingroup distance_joint -B2_API b2DistanceJointDef b2DefaultDistanceJointDef(void); +B2_API b2DistanceJointDef b2DefaultDistanceJointDef( void ); /// A motor joint is used to control the relative motion between two bodies /// @@ -556,7 +559,7 @@ typedef struct b2MotorJointDef /// Use this to initialize your joint definition /// @ingroup motor_joint -B2_API b2MotorJointDef b2DefaultMotorJointDef(void); +B2_API b2MotorJointDef b2DefaultMotorJointDef( void ); /// A mouse joint is used to make a point on a body track a specified world point. /// @@ -595,7 +598,7 @@ typedef struct b2MouseJointDef /// Use this to initialize your joint definition /// @ingroup mouse_joint -B2_API b2MouseJointDef b2DefaultMouseJointDef(void); +B2_API b2MouseJointDef b2DefaultMouseJointDef( void ); /// Prismatic joint definition /// @@ -663,7 +666,7 @@ typedef struct b2PrismaticJointDef /// Use this to initialize your joint definition /// @ingroupd prismatic_joint -B2_API b2PrismaticJointDef b2DefaultPrismaticJointDef(void); +B2_API b2PrismaticJointDef b2DefaultPrismaticJointDef( void ); /// Revolute joint definition /// @@ -737,7 +740,7 @@ typedef struct b2RevoluteJointDef /// Use this to initialize your joint definition. /// @ingroup revolute_joint -B2_API b2RevoluteJointDef b2DefaultRevoluteJointDef(void); +B2_API b2RevoluteJointDef b2DefaultRevoluteJointDef( void ); /// Weld joint definition /// @@ -786,7 +789,7 @@ typedef struct b2WeldJointDef /// Use this to initialize your joint definition /// @ingroup weld_joint -B2_API b2WeldJointDef b2DefaultWeldJointDef(void); +B2_API b2WeldJointDef b2DefaultWeldJointDef( void ); /// Wheel joint definition /// @@ -851,7 +854,7 @@ typedef struct b2WheelJointDef /// Use this to initialize your joint definition /// @ingroup wheel_joint -B2_API b2WheelJointDef b2DefaultWheelJointDef(void); +B2_API b2WheelJointDef b2DefaultWheelJointDef( void ); /** * @defgroup events Events @@ -1024,7 +1027,7 @@ typedef struct b2ContactData /// Return false if you want to disable the collision /// @warning Do not attempt to modify the world inside this callback /// @ingroup world -typedef bool b2CustomFilterFcn(b2ShapeId shapeIdA, b2ShapeId shapeIdB, void* context); +typedef bool b2CustomFilterFcn( b2ShapeId shapeIdA, b2ShapeId shapeIdB, void* context ); /// Prototype for a pre-solve callback. /// This is called after a contact is updated. This allows you to inspect a @@ -1032,21 +1035,21 @@ typedef bool b2CustomFilterFcn(b2ShapeId shapeIdA, b2ShapeId shapeIdB, void* con /// contact manifold (e.g. modify the normal). /// Notes: /// - this function must be thread-safe -/// - this is only called if the shape has enabled presolve events +/// - this is only called if the shape has enabled pre-solve events /// - this is called only for awake dynamic bodies /// - this is not called for sensors /// - the supplied manifold has impulse values from the previous step /// Return false if you want to disable the contact this step /// @warning Do not attempt to modify the world inside this callback /// @ingroup world -typedef bool b2PreSolveFcn(b2ShapeId shapeIdA, b2ShapeId shapeIdB, b2Manifold* manifold, void* context); +typedef bool b2PreSolveFcn( b2ShapeId shapeIdA, b2ShapeId shapeIdB, b2Manifold* manifold, void* context ); /// Prototype callback for overlap queries. /// Called for each shape found in the query. /// @see b2World_QueryAABB /// @return false to terminate the query. /// @ingroup world -typedef bool b2OverlapResultFcn(b2ShapeId shapeId, void* context); +typedef bool b2OverlapResultFcn( b2ShapeId shapeId, void* context ); /// Prototype callback for ray casts. /// Called for each shape found in the query. You control how the ray cast @@ -1063,9 +1066,10 @@ typedef bool b2OverlapResultFcn(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 b2CastResultFcn(b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* context); +typedef float b2CastResultFcn( b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* context ); /// These colors are used for debug draw. +/// See https://www.rapidtables.com/web/color/index.html typedef enum b2HexColor { b2_colorAliceBlue = 0xf0f8ff, @@ -1222,6 +1226,10 @@ typedef enum b2HexColor b2_colorWhiteSmoke = 0xf5f5f5, b2_colorYellow = 0xffff00, b2_colorYellowGreen = 0x9acd32, + b2_colorBox2DRed = 0xdc3132, + b2_colorBox2DBlue = 0x30aebf, + b2_colorBox2DGreen = 0x8cc924, + b2_colorBox2DYellow = 0xffee8c } b2HexColor; /// This struct holds callbacks you can implement to draw a Box2D world. @@ -1229,35 +1237,35 @@ typedef enum b2HexColor typedef struct b2DebugDraw { /// Draw a closed polygon provided in CCW order. - void (*DrawPolygon)(const b2Vec2* vertices, int vertexCount, b2HexColor color, void* context); + void ( *DrawPolygon )( const b2Vec2* vertices, int vertexCount, b2HexColor color, void* context ); /// Draw a solid closed polygon provided in CCW order. - void (*DrawSolidPolygon)(b2Transform transform, const b2Vec2* vertices, int vertexCount, float radius, b2HexColor color, - void* context); + void ( *DrawSolidPolygon )( b2Transform transform, const b2Vec2* vertices, int vertexCount, float radius, b2HexColor color, + void* context ); /// Draw a circle. - void (*DrawCircle)(b2Vec2 center, float radius, b2HexColor color, void* context); + void ( *DrawCircle )( b2Vec2 center, float radius, b2HexColor color, void* context ); /// Draw a solid circle. - void (*DrawSolidCircle)(b2Transform transform, float radius, b2HexColor color, void* context); + void ( *DrawSolidCircle )( b2Transform transform, float radius, b2HexColor color, void* context ); /// Draw a capsule. - void (*DrawCapsule)(b2Vec2 p1, b2Vec2 p2, float radius, b2HexColor color, void* context); + void ( *DrawCapsule )( b2Vec2 p1, b2Vec2 p2, float radius, b2HexColor color, void* context ); /// Draw a solid capsule. - void (*DrawSolidCapsule)(b2Vec2 p1, b2Vec2 p2, float radius, b2HexColor color, void* context); + void ( *DrawSolidCapsule )( b2Vec2 p1, b2Vec2 p2, float radius, b2HexColor color, void* context ); /// Draw a line segment. - void (*DrawSegment)(b2Vec2 p1, b2Vec2 p2, b2HexColor color, void* context); + void ( *DrawSegment )( b2Vec2 p1, b2Vec2 p2, b2HexColor color, void* context ); /// Draw a transform. Choose your own length scale. - void (*DrawTransform)(b2Transform transform, void* context); + void ( *DrawTransform )( b2Transform transform, void* context ); /// Draw a point. - void (*DrawPoint)(b2Vec2 p, float size, b2HexColor color, void* context); + void ( *DrawPoint )( b2Vec2 p, float size, b2HexColor color, void* context ); /// Draw a string. - void (*DrawString)(b2Vec2 p, const char* s, void* context); + void ( *DrawString )( b2Vec2 p, const char* s, void* context ); /// Bounds to use if restricting drawing to a rectangular region b2AABB drawingBounds; diff --git a/samples/car.cpp b/samples/car.cpp index 9bf8fcf6..51b7978d 100644 --- a/samples/car.cpp +++ b/samples/car.cpp @@ -18,67 +18,66 @@ Car::Car() m_isSpawned = false; } -void Car::Spawn(b2WorldId worldId, b2Vec2 position, float scale, float hertz, - float dampingRatio, float torque, void* userData) +void Car::Spawn( b2WorldId worldId, b2Vec2 position, float scale, float hertz, float dampingRatio, float torque, void* userData ) { - assert(m_isSpawned == false); + assert( m_isSpawned == false ); - assert(B2_IS_NULL(m_chassisId)); - assert(B2_IS_NULL(m_frontWheelId)); - assert(B2_IS_NULL(m_rearWheelId)); + assert( B2_IS_NULL( m_chassisId ) ); + assert( B2_IS_NULL( m_frontWheelId ) ); + assert( B2_IS_NULL( m_rearWheelId ) ); b2Vec2 vertices[6] = { - {-1.5f, -0.5f}, {1.5f, -0.5f}, {1.5f, 0.0f}, {0.0f, 0.9f}, {-1.15f, 0.9f}, {-1.5f, 0.2f}, + { -1.5f, -0.5f }, { 1.5f, -0.5f }, { 1.5f, 0.0f }, { 0.0f, 0.9f }, { -1.15f, 0.9f }, { -1.5f, 0.2f }, }; - for (int i = 0; i < 6; ++i) + for ( int i = 0; i < 6; ++i ) { vertices[i].x *= 0.85f * scale; vertices[i].y *= 0.85f * scale; } - b2Hull hull = b2ComputeHull(vertices, 6); - b2Polygon chassis = b2MakePolygon(&hull, 0.15f * scale); + b2Hull hull = b2ComputeHull( vertices, 6 ); + b2Polygon chassis = b2MakePolygon( &hull, 0.15f * scale ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f / scale; shapeDef.friction = 0.2f; - b2Circle circle = {{0.0f, 0.0f}, 0.4f * scale}; + b2Circle circle = { { 0.0f, 0.0f }, 0.4f * scale }; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = b2Add({0.0f, 1.0f * scale}, position); - m_chassisId = b2CreateBody(worldId, &bodyDef); - b2CreatePolygonShape(m_chassisId, &shapeDef, &chassis); + bodyDef.position = b2Add( { 0.0f, 1.0f * scale }, position ); + m_chassisId = b2CreateBody( worldId, &bodyDef ); + b2CreatePolygonShape( m_chassisId, &shapeDef, &chassis ); shapeDef.density = 2.0f / scale; shapeDef.friction = 1.5f; - bodyDef.position = b2Add({-1.0f * scale, 0.35f * scale}, position); - m_rearWheelId = b2CreateBody(worldId, &bodyDef); - b2CreateCircleShape(m_rearWheelId, &shapeDef, &circle); + bodyDef.position = b2Add( { -1.0f * scale, 0.35f * scale }, position ); + m_rearWheelId = b2CreateBody( worldId, &bodyDef ); + b2CreateCircleShape( m_rearWheelId, &shapeDef, &circle ); - bodyDef.position = b2Add({1.0f * scale, 0.4f * scale}, position); - m_frontWheelId = b2CreateBody(worldId, &bodyDef); - b2CreateCircleShape(m_frontWheelId, &shapeDef, &circle); + bodyDef.position = b2Add( { 1.0f * scale, 0.4f * scale }, position ); + m_frontWheelId = b2CreateBody( worldId, &bodyDef ); + b2CreateCircleShape( m_frontWheelId, &shapeDef, &circle ); - b2Vec2 axis = {0.0f, 1.0f}; - b2Vec2 pivot = b2Body_GetPosition(m_rearWheelId); + b2Vec2 axis = { 0.0f, 1.0f }; + b2Vec2 pivot = b2Body_GetPosition( m_rearWheelId ); // float throttle = 0.0f; // float speed = 35.0f; - //float torque = 2.5f * scale; - //float hertz = 5.0f; - //float dampingRatio = 0.7f; + // float torque = 2.5f * scale; + // float hertz = 5.0f; + // float dampingRatio = 0.7f; b2WheelJointDef jointDef = b2DefaultWheelJointDef(); jointDef.bodyIdA = m_chassisId; jointDef.bodyIdB = m_rearWheelId; - jointDef.localAxisA = b2Body_GetLocalVector(jointDef.bodyIdA, axis); - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); + jointDef.localAxisA = b2Body_GetLocalVector( jointDef.bodyIdA, axis ); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); jointDef.motorSpeed = 0.0f; jointDef.maxMotorTorque = torque; jointDef.enableMotor = true; @@ -87,14 +86,14 @@ void Car::Spawn(b2WorldId worldId, b2Vec2 position, float scale, float hertz, jointDef.lowerTranslation = -0.25f * scale; jointDef.upperTranslation = 0.25f * scale; jointDef.enableLimit = true; - m_rearAxleId = b2CreateWheelJoint(worldId, &jointDef); + m_rearAxleId = b2CreateWheelJoint( worldId, &jointDef ); - pivot = b2Body_GetPosition(m_frontWheelId); + pivot = b2Body_GetPosition( m_frontWheelId ); jointDef.bodyIdA = m_chassisId; jointDef.bodyIdB = m_frontWheelId; - jointDef.localAxisA = b2Body_GetLocalVector(jointDef.bodyIdA, axis); - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); + jointDef.localAxisA = b2Body_GetLocalVector( jointDef.bodyIdA, axis ); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); jointDef.motorSpeed = 0.0f; jointDef.maxMotorTorque = torque; jointDef.enableMotor = true; @@ -103,43 +102,192 @@ void Car::Spawn(b2WorldId worldId, b2Vec2 position, float scale, float hertz, jointDef.lowerTranslation = -0.25f * scale; jointDef.upperTranslation = 0.25f * scale; jointDef.enableLimit = true; - m_frontAxleId = b2CreateWheelJoint(worldId, &jointDef); + m_frontAxleId = b2CreateWheelJoint( worldId, &jointDef ); } void Car::Despawn() { - assert(m_isSpawned == true); + assert( m_isSpawned == true ); - b2DestroyJoint(m_rearAxleId); - b2DestroyJoint(m_frontAxleId); - b2DestroyBody(m_rearWheelId); - b2DestroyBody(m_frontWheelId); - b2DestroyBody(m_chassisId); + b2DestroyJoint( m_rearAxleId ); + b2DestroyJoint( m_frontAxleId ); + b2DestroyBody( m_rearWheelId ); + b2DestroyBody( m_frontWheelId ); + b2DestroyBody( m_chassisId ); m_isSpawned = false; } -void Car::SetSpeed(float speed) +void Car::SetSpeed( float speed ) { - b2WheelJoint_SetMotorSpeed(m_rearAxleId, speed); - b2WheelJoint_SetMotorSpeed(m_frontAxleId, speed); - b2Joint_WakeBodies(m_rearAxleId); + b2WheelJoint_SetMotorSpeed( m_rearAxleId, speed ); + b2WheelJoint_SetMotorSpeed( m_frontAxleId, speed ); + b2Joint_WakeBodies( m_rearAxleId ); } -void Car::SetTorque(float torque) +void Car::SetTorque( float torque ) { - b2WheelJoint_SetMaxMotorTorque(m_rearAxleId, torque); - b2WheelJoint_SetMaxMotorTorque(m_frontAxleId, torque); + b2WheelJoint_SetMaxMotorTorque( m_rearAxleId, torque ); + b2WheelJoint_SetMaxMotorTorque( m_frontAxleId, torque ); } -void Car::SetHertz(float hertz) +void Car::SetHertz( float hertz ) { - b2WheelJoint_SetSpringHertz(m_rearAxleId, hertz); - b2WheelJoint_SetSpringHertz(m_frontAxleId, hertz); + b2WheelJoint_SetSpringHertz( m_rearAxleId, hertz ); + b2WheelJoint_SetSpringHertz( m_frontAxleId, hertz ); } -void Car::SetDampingRadio(float dampingRatio) +void Car::SetDampingRadio( float dampingRatio ) { - b2WheelJoint_SetSpringDampingRatio(m_rearAxleId, dampingRatio); - b2WheelJoint_SetSpringDampingRatio(m_frontAxleId, dampingRatio); + b2WheelJoint_SetSpringDampingRatio( m_rearAxleId, dampingRatio ); + b2WheelJoint_SetSpringDampingRatio( m_frontAxleId, dampingRatio ); +} + +Truck::Truck() +{ + m_chassisId = {}; + m_rearWheelId = {}; + m_frontWheelId = {}; + m_rearAxleId = {}; + m_frontAxleId = {}; + m_isSpawned = false; +} + +void Truck::Spawn( b2WorldId worldId, b2Vec2 position, float scale, float hertz, float dampingRatio, float torque, float density, + void* userData ) +{ + assert( m_isSpawned == false ); + + assert( B2_IS_NULL( m_chassisId ) ); + assert( B2_IS_NULL( m_frontWheelId ) ); + assert( B2_IS_NULL( m_rearWheelId ) ); + + // b2Vec2 vertices[6] = { + // { -1.5f, -0.5f }, { 1.5f, -0.5f }, { 1.5f, 0.0f }, { 0.0f, 0.9f }, { -1.15f, 0.9f }, { -1.5f, 0.2f }, + // }; + + b2Vec2 vertices[5] = { + { -0.65f, -0.4f }, { 1.5f, -0.4f }, { 1.5f, 0.0f }, { 0.0f, 0.9f }, { -0.65f, 0.9f }, + }; + + for ( int i = 0; i < 5; ++i ) + { + vertices[i].x *= 0.85f * scale; + vertices[i].y *= 0.85f * scale; + } + + b2Hull hull = b2ComputeHull( vertices, 5 ); + b2Polygon chassis = b2MakePolygon( &hull, 0.15f * scale ); + + b2ShapeDef shapeDef = b2DefaultShapeDef(); + shapeDef.density = density; + shapeDef.friction = 0.2f; + shapeDef.customColor = b2_colorHotPink; + + b2BodyDef bodyDef = b2DefaultBodyDef(); + bodyDef.type = b2_dynamicBody; + bodyDef.position = b2Add( { 0.0f, 1.0f * scale }, position ); + m_chassisId = b2CreateBody( worldId, &bodyDef ); + b2CreatePolygonShape( m_chassisId, &shapeDef, &chassis ); + + b2Polygon box = b2MakeOffsetBox( 1.25f * scale, 0.1f * scale, { -2.05f * scale, -0.275f * scale }, 0.0f ); + box.radius = 0.1f * scale; + b2CreatePolygonShape( m_chassisId, &shapeDef, &box ); + + box = b2MakeOffsetBox( 0.05f * scale, 0.35f * scale, { -3.25f * scale, 0.375f * scale }, 0.0f ); + box.radius = 0.1f * scale; + b2CreatePolygonShape( m_chassisId, &shapeDef, &box ); + + shapeDef.density = 2.0f * density; + shapeDef.friction = 2.5f; + shapeDef.customColor = b2_colorSilver; + + b2Circle circle = { { 0.0f, 0.0f }, 0.4f * scale }; + bodyDef.position = b2Add( { -2.75f * scale, 0.3f * scale }, position ); + m_rearWheelId = b2CreateBody( worldId, &bodyDef ); + b2CreateCircleShape( m_rearWheelId, &shapeDef, &circle ); + + bodyDef.position = b2Add( { 0.8f * scale, 0.3f * scale }, position ); + m_frontWheelId = b2CreateBody( worldId, &bodyDef ); + b2CreateCircleShape( m_frontWheelId, &shapeDef, &circle ); + + b2Vec2 axis = { 0.0f, 1.0f }; + b2Vec2 pivot = b2Body_GetPosition( m_rearWheelId ); + + // float throttle = 0.0f; + // float speed = 35.0f; + // float torque = 2.5f * scale; + // float hertz = 5.0f; + // float dampingRatio = 0.7f; + + b2WheelJointDef jointDef = b2DefaultWheelJointDef(); + + jointDef.bodyIdA = m_chassisId; + jointDef.bodyIdB = m_rearWheelId; + jointDef.localAxisA = b2Body_GetLocalVector( jointDef.bodyIdA, axis ); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); + jointDef.motorSpeed = 0.0f; + jointDef.maxMotorTorque = torque; + jointDef.enableMotor = true; + jointDef.hertz = hertz; + jointDef.dampingRatio = dampingRatio; + jointDef.lowerTranslation = -0.25f * scale; + jointDef.upperTranslation = 0.25f * scale; + jointDef.enableLimit = true; + m_rearAxleId = b2CreateWheelJoint( worldId, &jointDef ); + + pivot = b2Body_GetPosition( m_frontWheelId ); + jointDef.bodyIdA = m_chassisId; + jointDef.bodyIdB = m_frontWheelId; + jointDef.localAxisA = b2Body_GetLocalVector( jointDef.bodyIdA, axis ); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); + jointDef.motorSpeed = 0.0f; + jointDef.maxMotorTorque = torque; + jointDef.enableMotor = true; + jointDef.hertz = hertz; + jointDef.dampingRatio = dampingRatio; + jointDef.lowerTranslation = -0.25f * scale; + jointDef.upperTranslation = 0.25f * scale; + jointDef.enableLimit = true; + m_frontAxleId = b2CreateWheelJoint( worldId, &jointDef ); +} + +void Truck::Despawn() +{ + assert( m_isSpawned == true ); + + b2DestroyJoint( m_rearAxleId ); + b2DestroyJoint( m_frontAxleId ); + b2DestroyBody( m_rearWheelId ); + b2DestroyBody( m_frontWheelId ); + b2DestroyBody( m_chassisId ); + + m_isSpawned = false; +} + +void Truck::SetSpeed( float speed ) +{ + b2WheelJoint_SetMotorSpeed( m_rearAxleId, speed ); + b2WheelJoint_SetMotorSpeed( m_frontAxleId, speed ); + b2Joint_WakeBodies( m_rearAxleId ); +} + +void Truck::SetTorque( float torque ) +{ + b2WheelJoint_SetMaxMotorTorque( m_rearAxleId, torque ); + b2WheelJoint_SetMaxMotorTorque( m_frontAxleId, torque ); +} + +void Truck::SetHertz( float hertz ) +{ + b2WheelJoint_SetSpringHertz( m_rearAxleId, hertz ); + b2WheelJoint_SetSpringHertz( m_frontAxleId, hertz ); +} + +void Truck::SetDampingRadio( float dampingRatio ) +{ + b2WheelJoint_SetSpringDampingRatio( m_rearAxleId, dampingRatio ); + b2WheelJoint_SetSpringDampingRatio( m_frontAxleId, dampingRatio ); } diff --git a/samples/car.h b/samples/car.h index 54a843c6..8013d1c0 100644 --- a/samples/car.h +++ b/samples/car.h @@ -10,14 +10,35 @@ class Car public: Car(); - void Spawn(b2WorldId worldId, b2Vec2 position, float scale, float hertz, - float dampingRatio, float torque, void* userData); + void Spawn( b2WorldId worldId, b2Vec2 position, float scale, float hertz, float dampingRatio, float torque, void* userData ); void Despawn(); - void SetSpeed(float speed); - void SetTorque(float torque); - void SetHertz(float hertz); - void SetDampingRadio(float dampingRatio); + void SetSpeed( float speed ); + void SetTorque( float torque ); + void SetHertz( float hertz ); + void SetDampingRadio( float dampingRatio ); + + b2BodyId m_chassisId; + b2BodyId m_rearWheelId; + b2BodyId m_frontWheelId; + b2JointId m_rearAxleId; + b2JointId m_frontAxleId; + bool m_isSpawned; +}; + +class Truck +{ +public: + Truck(); + + void Spawn( b2WorldId worldId, b2Vec2 position, float scale, float hertz, float dampingRatio, float torque, float density, + void* userData ); + void Despawn(); + + void SetSpeed( float speed ); + void SetTorque( float torque ); + void SetHertz( float hertz ); + void SetDampingRadio( float dampingRatio ); b2BodyId m_chassisId; b2BodyId m_rearWheelId; diff --git a/samples/data/background.fs b/samples/data/background.fs new file mode 100644 index 00000000..247fadcf --- /dev/null +++ b/samples/data/background.fs @@ -0,0 +1,33 @@ +// SPDX-FileCopyrightText: 2024 Erin Catto +// SPDX-License-Identifier: MIT + +#version 330 + +out vec4 FragColor; + +uniform float time; +uniform vec2 resolution; +uniform vec3 baseColor; + +// A simple pseudo-random function +float random(vec2 st) +{ + return fract(sin(dot(st.xy, vec2(12.9898, 78.233))) * 43758.5453123); +} + +void main() +{ + vec2 uv = gl_FragCoord.xy / resolution.xy; + + // Create some noise + float noise = random(uv + time * 0.1); + + // Adjust these values to control the intensity and color of the grain + float grainIntensity = 0.04; + + // Mix the base color with the noise + vec3 color = baseColor + vec3(noise * grainIntensity); + + FragColor = vec4(color, 1.0); +} + diff --git a/samples/data/background.vs b/samples/data/background.vs new file mode 100644 index 00000000..1ea9a850 --- /dev/null +++ b/samples/data/background.vs @@ -0,0 +1,10 @@ +// SPDX-FileCopyrightText: 2024 Erin Catto +// SPDX-License-Identifier: MIT +#version 330 + +layout(location = 0) in vec2 v_position; + +void main(void) +{ + gl_Position = vec4(v_position, 0.0f, 1.0f); +} diff --git a/samples/donut.cpp b/samples/donut.cpp index 80f650db..48c3f65a 100644 --- a/samples/donut.cpp +++ b/samples/donut.cpp @@ -10,7 +10,7 @@ Donut::Donut() { - for (int i = 0; i < e_sides; ++i) + for ( int i = 0; i < e_sides; ++i ) { m_bodyIds[i] = b2_nullBodyId; m_jointIds[i] = b2_nullJointId; @@ -19,21 +19,21 @@ Donut::Donut() m_isSpawned = false; } -void Donut::Spawn(b2WorldId worldId, b2Vec2 position, float scale, int groupIndex, void* userData) +void Donut::Spawn( b2WorldId worldId, b2Vec2 position, float scale, int groupIndex, void* userData ) { - assert(m_isSpawned == false); + assert( m_isSpawned == false ); - for (int i = 0; i < e_sides; ++i) + for ( int i = 0; i < e_sides; ++i ) { - assert(B2_IS_NULL(m_bodyIds[i])); - assert(B2_IS_NULL(m_jointIds[i])); + assert( B2_IS_NULL( m_bodyIds[i] ) ); + assert( B2_IS_NULL( m_jointIds[i] ) ); } float radius = 1.0f * scale; float deltaAngle = 2.0f * b2_pi / e_sides; float length = 2.0f * b2_pi * radius / e_sides; - b2Capsule capsule = {{0.0f, -0.5f * length}, {0.0f, 0.5f * length}, 0.25f * scale}; + b2Capsule capsule = { { 0.0f, -0.5f * length }, { 0.0f, 0.5f * length }, 0.25f * scale }; b2Vec2 center = position; @@ -48,13 +48,13 @@ void Donut::Spawn(b2WorldId worldId, b2Vec2 position, float scale, int groupInde // Create bodies float angle = 0.0f; - for (int i = 0; i < e_sides; ++i) + for ( int i = 0; i < e_sides; ++i ) { - bodyDef.position = {radius * cosf(angle) + center.x, radius * sinf(angle) + center.y}; - bodyDef.rotation = b2MakeRot(angle); + bodyDef.position = { radius * cosf( angle ) + center.x, radius * sinf( angle ) + center.y }; + bodyDef.rotation = b2MakeRot( angle ); - m_bodyIds[i] = b2CreateBody(worldId, &bodyDef); - b2CreateCapsuleShape(m_bodyIds[i], &shapeDef, &capsule); + m_bodyIds[i] = b2CreateBody( worldId, &bodyDef ); + b2CreateCapsuleShape( m_bodyIds[i], &shapeDef, &capsule ); angle += deltaAngle; } @@ -63,18 +63,18 @@ void Donut::Spawn(b2WorldId worldId, b2Vec2 position, float scale, int groupInde b2WeldJointDef weldDef = b2DefaultWeldJointDef(); weldDef.angularHertz = 5.0f; weldDef.angularDampingRatio = 0.0f; - weldDef.localAnchorA = {0.0f, 0.5f * length}; - weldDef.localAnchorB = {0.0f, -0.5f * length}; + weldDef.localAnchorA = { 0.0f, 0.5f * length }; + weldDef.localAnchorB = { 0.0f, -0.5f * length }; b2BodyId prevBodyId = m_bodyIds[e_sides - 1]; - for (int i = 0; i < e_sides; ++i) + for ( int i = 0; i < e_sides; ++i ) { weldDef.bodyIdA = prevBodyId; weldDef.bodyIdB = m_bodyIds[i]; - b2Rot rotA = b2Body_GetRotation(prevBodyId); - b2Rot rotB = b2Body_GetRotation(m_bodyIds[i]); - weldDef.referenceAngle = b2RelativeAngle(rotB, rotA); - m_jointIds[i] = b2CreateWeldJoint(worldId, &weldDef); + b2Rot rotA = b2Body_GetRotation( prevBodyId ); + b2Rot rotB = b2Body_GetRotation( m_bodyIds[i] ); + weldDef.referenceAngle = b2RelativeAngle( rotB, rotA ); + m_jointIds[i] = b2CreateWeldJoint( worldId, &weldDef ); prevBodyId = weldDef.bodyIdB; } @@ -83,11 +83,11 @@ void Donut::Spawn(b2WorldId worldId, b2Vec2 position, float scale, int groupInde void Donut::Despawn() { - assert(m_isSpawned == true); + assert( m_isSpawned == true ); - for (int i = 0; i < e_sides; ++i) + for ( int i = 0; i < e_sides; ++i ) { - b2DestroyBody(m_bodyIds[i]); + b2DestroyBody( m_bodyIds[i] ); m_bodyIds[i] = b2_nullBodyId; m_jointIds[i] = b2_nullJointId; } diff --git a/samples/donut.h b/samples/donut.h index 55694c4d..aecc016c 100644 --- a/samples/donut.h +++ b/samples/donut.h @@ -15,7 +15,7 @@ class Donut public: Donut(); - void Spawn(b2WorldId worldId, b2Vec2 position, float scale, int groupIndex, void* userData); + void Spawn( b2WorldId worldId, b2Vec2 position, float scale, int groupIndex, void* userData ); void Despawn(); b2BodyId m_bodyIds[e_sides]; diff --git a/samples/doohickey.cpp b/samples/doohickey.cpp index 7e05650e..89ac2daf 100644 --- a/samples/doohickey.cpp +++ b/samples/doohickey.cpp @@ -22,57 +22,57 @@ Doohickey::Doohickey() m_isSpawned = false; } -void Doohickey::Spawn(b2WorldId worldId, b2Vec2 position, float scale) +void Doohickey::Spawn( b2WorldId worldId, b2Vec2 position, float scale ) { - assert(m_isSpawned == false); + assert( m_isSpawned == false ); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Circle circle = {{0.0f, 0.0f}, 1.0f * scale}; - b2Capsule capsule = {{-3.5f * scale, 0.0f}, {3.5f * scale, 0.0f}, 0.15f * scale}; + b2Circle circle = { { 0.0f, 0.0f }, 1.0f * scale }; + b2Capsule capsule = { { -3.5f * scale, 0.0f }, { 3.5f * scale, 0.0f }, 0.15f * scale }; - bodyDef.position = b2MulAdd(position, scale, {-5.0f, 3.0f}); - m_wheelId1 = b2CreateBody(worldId, &bodyDef); - b2CreateCircleShape(m_wheelId1, &shapeDef, &circle); + bodyDef.position = b2MulAdd( position, scale, { -5.0f, 3.0f } ); + m_wheelId1 = b2CreateBody( worldId, &bodyDef ); + b2CreateCircleShape( m_wheelId1, &shapeDef, &circle ); - bodyDef.position = b2MulAdd(position, scale, {5.0f, 3.0f}); - m_wheelId2 = b2CreateBody(worldId, &bodyDef); - b2CreateCircleShape(m_wheelId2, &shapeDef, &circle); + bodyDef.position = b2MulAdd( position, scale, { 5.0f, 3.0f } ); + m_wheelId2 = b2CreateBody( worldId, &bodyDef ); + b2CreateCircleShape( m_wheelId2, &shapeDef, &circle ); - bodyDef.position = b2MulAdd(position, scale, {-1.5f, 3.0f}); - m_barId1 = b2CreateBody(worldId, &bodyDef); - b2CreateCapsuleShape(m_barId1, &shapeDef, &capsule); + bodyDef.position = b2MulAdd( position, scale, { -1.5f, 3.0f } ); + m_barId1 = b2CreateBody( worldId, &bodyDef ); + b2CreateCapsuleShape( m_barId1, &shapeDef, &capsule ); - bodyDef.position = b2MulAdd(position, scale, {1.5f, 3.0f}); - m_barId2 = b2CreateBody(worldId, &bodyDef); - b2CreateCapsuleShape(m_barId2, &shapeDef, &capsule); + bodyDef.position = b2MulAdd( position, scale, { 1.5f, 3.0f } ); + m_barId2 = b2CreateBody( worldId, &bodyDef ); + b2CreateCapsuleShape( m_barId2, &shapeDef, &capsule ); b2RevoluteJointDef revoluteDef = b2DefaultRevoluteJointDef(); revoluteDef.bodyIdA = m_wheelId1; revoluteDef.bodyIdB = m_barId1; - revoluteDef.localAnchorA = {0.0f, 0.0f}; - revoluteDef.localAnchorB = {-3.5f * scale, 0.0f}; + revoluteDef.localAnchorA = { 0.0f, 0.0f }; + revoluteDef.localAnchorB = { -3.5f * scale, 0.0f }; revoluteDef.enableMotor = true; revoluteDef.maxMotorTorque = 2.0f * scale; - b2CreateRevoluteJoint(worldId, &revoluteDef); + b2CreateRevoluteJoint( worldId, &revoluteDef ); revoluteDef.bodyIdA = m_wheelId2; revoluteDef.bodyIdB = m_barId2; - revoluteDef.localAnchorA = {0.0f, 0.0f}; - revoluteDef.localAnchorB = {3.5f * scale, 0.0f}; + revoluteDef.localAnchorA = { 0.0f, 0.0f }; + revoluteDef.localAnchorB = { 3.5f * scale, 0.0f }; revoluteDef.enableMotor = true; revoluteDef.maxMotorTorque = 2.0f * scale; - b2CreateRevoluteJoint(worldId, &revoluteDef); + b2CreateRevoluteJoint( worldId, &revoluteDef ); b2PrismaticJointDef prismaticDef = b2DefaultPrismaticJointDef(); prismaticDef.bodyIdA = m_barId1; prismaticDef.bodyIdB = m_barId2; - prismaticDef.localAxisA = {1.0f, 0.0f}; - prismaticDef.localAnchorA = {2.0f * scale, 0.0f}; - prismaticDef.localAnchorB = {-2.0f * scale, 0.0f}; + prismaticDef.localAxisA = { 1.0f, 0.0f }; + prismaticDef.localAnchorA = { 2.0f * scale, 0.0f }; + prismaticDef.localAnchorB = { -2.0f * scale, 0.0f }; prismaticDef.lowerTranslation = -2.0f * scale; prismaticDef.upperTranslation = 2.0f * scale; prismaticDef.enableLimit = true; @@ -81,21 +81,21 @@ void Doohickey::Spawn(b2WorldId worldId, b2Vec2 position, float scale) prismaticDef.enableSpring = true; prismaticDef.hertz = 1.0f; prismaticDef.dampingRatio = 0.5; - b2CreatePrismaticJoint(worldId, &prismaticDef); + b2CreatePrismaticJoint( worldId, &prismaticDef ); } void Doohickey::Despawn() { - assert(m_isSpawned == true); + assert( m_isSpawned == true ); - b2DestroyJoint(m_axleId1); - b2DestroyJoint(m_axleId2); - b2DestroyJoint(m_sliderId); + b2DestroyJoint( m_axleId1 ); + b2DestroyJoint( m_axleId2 ); + b2DestroyJoint( m_sliderId ); - b2DestroyBody(m_wheelId1); - b2DestroyBody(m_wheelId2); - b2DestroyBody(m_barId1); - b2DestroyBody(m_barId2); + b2DestroyBody( m_wheelId1 ); + b2DestroyBody( m_wheelId2 ); + b2DestroyBody( m_barId1 ); + b2DestroyBody( m_barId2 ); m_isSpawned = false; } diff --git a/samples/doohickey.h b/samples/doohickey.h index 2fe7c321..0db7345f 100644 --- a/samples/doohickey.h +++ b/samples/doohickey.h @@ -7,10 +7,10 @@ class Doohickey { - public: +public: Doohickey(); - void Spawn(b2WorldId worldId, b2Vec2 position, float scale); + void Spawn( b2WorldId worldId, b2Vec2 position, float scale ); void Despawn(); b2BodyId m_wheelId1; diff --git a/samples/draw.cpp b/samples/draw.cpp index b27d2179..b134b8ad 100644 --- a/samples/draw.cpp +++ b/samples/draw.cpp @@ -2,15 +2,16 @@ // SPDX-License-Identifier: MIT #include "draw.h" + #include "shader.h" #include "box2d/math_functions.h" -#include #include #include +#include -#if defined(_WIN32) +#if defined( _WIN32 ) #define _CRTDBG_MAP_ALLOC #include #include @@ -19,20 +20,22 @@ #endif #include +// Keep glad.h before glfw3.h +#include #include -#define BUFFER_OFFSET(x) ((const void*)(x)) +#define BUFFER_OFFSET( x ) ( (const void*)( x ) ) -#define SHADER_TEXT(x) "#version 330\n" #x +#define SHADER_TEXT( x ) "#version 330\n" #x struct RGBA8 { uint8_t r, g, b, a; }; -static inline RGBA8 MakeRGBA8(b2HexColor c, float alpha) +static inline RGBA8 MakeRGBA8( b2HexColor c, float alpha ) { - return {uint8_t((c >> 16) & 0xFF), uint8_t((c >> 8) & 0xFF), uint8_t(c & 0xFF), uint8_t(0xFF * alpha)}; + return { uint8_t( ( c >> 16 ) & 0xFF ), uint8_t( ( c >> 8 ) & 0xFF ), uint8_t( c & 0xFF ), uint8_t( 0xFF * alpha ) }; } Draw g_draw; @@ -47,55 +50,55 @@ Camera::Camera() void Camera::ResetView() { - m_center = {0.0f, 20.0f}; + m_center = { 0.0f, 20.0f }; m_zoom = 1.0f; } -b2Vec2 Camera::ConvertScreenToWorld(b2Vec2 ps) +b2Vec2 Camera::ConvertScreenToWorld( b2Vec2 ps ) { - float w = float(m_width); - float h = float(m_height); + float w = float( m_width ); + float h = float( m_height ); float u = ps.x / w; - float v = (h - ps.y) / h; + float v = ( h - ps.y ) / h; float ratio = w / h; - b2Vec2 extents = {m_zoom * ratio, m_zoom}; + b2Vec2 extents = { m_zoom * ratio, m_zoom }; - b2Vec2 lower = b2Sub(m_center, extents); - b2Vec2 upper = b2Add(m_center, extents); + b2Vec2 lower = b2Sub( m_center, extents ); + b2Vec2 upper = b2Add( m_center, extents ); - b2Vec2 pw = {(1.0f - u) * lower.x + u * upper.x, (1.0f - v) * lower.y + v * upper.y}; + b2Vec2 pw = { ( 1.0f - u ) * lower.x + u * upper.x, ( 1.0f - v ) * lower.y + v * upper.y }; return pw; } -b2Vec2 Camera::ConvertWorldToScreen(b2Vec2 pw) +b2Vec2 Camera::ConvertWorldToScreen( b2Vec2 pw ) { - float w = float(m_width); - float h = float(m_height); + float w = float( m_width ); + float h = float( m_height ); float ratio = w / h; - b2Vec2 extents = {m_zoom * ratio, m_zoom}; + b2Vec2 extents = { m_zoom * ratio, m_zoom }; - b2Vec2 lower = b2Sub(m_center, extents); - b2Vec2 upper = b2Add(m_center, extents); + b2Vec2 lower = b2Sub( m_center, extents ); + b2Vec2 upper = b2Add( m_center, extents ); - float u = (pw.x - lower.x) / (upper.x - lower.x); - float v = (pw.y - lower.y) / (upper.y - lower.y); + float u = ( pw.x - lower.x ) / ( upper.x - lower.x ); + float v = ( pw.y - lower.y ) / ( upper.y - lower.y ); - b2Vec2 ps = {u * w, (1.0f - v) * h}; + b2Vec2 ps = { u * w, ( 1.0f - v ) * h }; return ps; } // Convert from world coordinates to normalized device coordinates. // http://www.songho.ca/opengl/gl_projectionmatrix.html // This also includes the view transform -void Camera::BuildProjectionMatrix(float* m, float zBias) +void Camera::BuildProjectionMatrix( float* m, float zBias ) { - float ratio = float(m_width) / float(m_height); - b2Vec2 extents = {m_zoom * ratio, m_zoom}; + float ratio = float( m_width ) / float( m_height ); + b2Vec2 extents = { m_zoom * ratio, m_zoom }; - b2Vec2 lower = b2Sub(m_center, extents); - b2Vec2 upper = b2Add(m_center, extents); + b2Vec2 lower = b2Sub( m_center, extents ); + b2Vec2 upper = b2Add( m_center, extents ); float w = upper.x - lower.x; float h = upper.y - lower.y; @@ -123,11 +126,87 @@ void Camera::BuildProjectionMatrix(float* m, float zBias) b2AABB Camera::GetViewBounds() { b2AABB bounds; - bounds.lowerBound = ConvertScreenToWorld({0.0f, (float)m_height}); - bounds.upperBound = ConvertScreenToWorld({(float)m_width, 0.0f}); + bounds.lowerBound = ConvertScreenToWorld( { 0.0f, (float)m_height } ); + bounds.upperBound = ConvertScreenToWorld( { (float)m_width, 0.0f } ); return bounds; } +struct GLBackground +{ + void Create() + { + m_programId = CreateProgramFromFiles( "samples/data/background.vs", "samples/data/background.fs" ); + m_timeUniform = glGetUniformLocation( m_programId, "time" ); + m_resolutionUniform = glGetUniformLocation( m_programId, "resolution" ); + m_baseColorUniform = glGetUniformLocation( m_programId, "baseColor" ); + int vertexAttribute = 0; + + // Generate + glGenVertexArrays( 1, &m_vaoId ); + glGenBuffers( 1, &m_vboId ); + + glBindVertexArray( m_vaoId ); + glEnableVertexAttribArray( vertexAttribute ); + + // Single quad + b2Vec2 vertices[] = { { -1.0f, 1.0f }, { -1.0f, -1.0f }, { 1.0f, 1.0f }, { 1.0f, -1.0f } }; + glBindBuffer( GL_ARRAY_BUFFER, m_vboId ); + glBufferData( GL_ARRAY_BUFFER, sizeof( vertices ), vertices, GL_STATIC_DRAW ); + glVertexAttribPointer( vertexAttribute, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET( 0 ) ); + + CheckErrorGL(); + + // Cleanup + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindVertexArray( 0 ); + } + + void Destroy() + { + if ( m_vaoId ) + { + glDeleteVertexArrays( 1, &m_vaoId ); + glDeleteBuffers( 1, &m_vboId ); + m_vaoId = 0; + m_vboId = 0; + } + + if ( m_programId ) + { + glDeleteProgram( m_programId ); + m_programId = 0; + } + } + + void Draw() + { + glUseProgram( m_programId ); + + float time = (float)glfwGetTime(); + glUniform1f( m_timeUniform, time ); + glUniform2f( m_resolutionUniform, (float)g_camera.m_width, (float)g_camera.m_height ); + + // struct RGBA8 c8 = MakeRGBA8( b2_colorGray2, 1.0f ); + // glUniform3f(m_baseColorUniform, c8.r/255.0f, c8.g/255.0f, c8.b/255.0f); + glUniform3f( m_baseColorUniform, 0.2f, 0.2f, 0.2f ); + + glBindVertexArray( m_vaoId ); + + glBindBuffer( GL_ARRAY_BUFFER, m_vboId ); + glDrawArrays( GL_TRIANGLE_STRIP, 0, 4 ); + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindVertexArray( 0 ); + glUseProgram( 0 ); + } + + GLuint m_vaoId; + GLuint m_vboId; + GLuint m_programId; + GLint m_timeUniform; + GLint m_resolutionUniform; + GLint m_baseColorUniform; +}; + struct PointData { b2Vec2 position; @@ -160,50 +239,52 @@ struct GLPoints " color = f_color;\n" "}\n"; - m_programId = CreateProgramFromStrings(vs, fs); - m_projectionUniform = glGetUniformLocation(m_programId, "projectionMatrix"); + m_programId = CreateProgramFromStrings( vs, fs ); + m_projectionUniform = glGetUniformLocation( m_programId, "projectionMatrix" ); int vertexAttribute = 0; int sizeAttribute = 1; int colorAttribute = 2; // Generate - glGenVertexArrays(1, &m_vaoId); - glGenBuffers(1, &m_vboId); + glGenVertexArrays( 1, &m_vaoId ); + glGenBuffers( 1, &m_vboId ); - glBindVertexArray(m_vaoId); - glEnableVertexAttribArray(vertexAttribute); - glEnableVertexAttribArray(sizeAttribute); - glEnableVertexAttribArray(colorAttribute); + glBindVertexArray( m_vaoId ); + glEnableVertexAttribArray( vertexAttribute ); + glEnableVertexAttribArray( sizeAttribute ); + glEnableVertexAttribArray( colorAttribute ); // Vertex buffer - glBindBuffer(GL_ARRAY_BUFFER, m_vboId); - glBufferData(GL_ARRAY_BUFFER, e_maxCount * sizeof(PointData), NULL, GL_DYNAMIC_DRAW); + glBindBuffer( GL_ARRAY_BUFFER, m_vboId ); + glBufferData( GL_ARRAY_BUFFER, e_maxCount * sizeof( PointData ), NULL, GL_DYNAMIC_DRAW ); - glVertexAttribPointer(vertexAttribute, 2, GL_FLOAT, GL_FALSE, sizeof(PointData), (void*)offsetof(PointData, position)); - glVertexAttribPointer(sizeAttribute, 1, GL_FLOAT, GL_FALSE, sizeof(PointData), (void*)offsetof(PointData, size)); + glVertexAttribPointer( vertexAttribute, 2, GL_FLOAT, GL_FALSE, sizeof( PointData ), + (void*)offsetof( PointData, position ) ); + glVertexAttribPointer( sizeAttribute, 1, GL_FLOAT, GL_FALSE, sizeof( PointData ), (void*)offsetof( PointData, size ) ); // color will get automatically expanded to floats in the shader - glVertexAttribPointer(colorAttribute, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(PointData), (void*)offsetof(PointData, rgba)); + glVertexAttribPointer( colorAttribute, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( PointData ), + (void*)offsetof( PointData, rgba ) ); CheckErrorGL(); // Cleanup - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindVertexArray(0); + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindVertexArray( 0 ); } void Destroy() { - if (m_vaoId) + if ( m_vaoId ) { - glDeleteVertexArrays(1, &m_vaoId); - glDeleteBuffers(1, &m_vboId); + glDeleteVertexArrays( 1, &m_vaoId ); + glDeleteBuffers( 1, &m_vboId ); m_vaoId = 0; m_vboId = 0; } - if (m_programId) + if ( m_programId ) { - glDeleteProgram(m_programId); + glDeleteProgram( m_programId ); m_programId = 0; } } @@ -211,48 +292,48 @@ struct GLPoints // todo instead of flushing, keep a growable array of data // this will prevent sorting problems. - void AddPoint(b2Vec2 v, float size, b2HexColor c) + void AddPoint( b2Vec2 v, float size, b2HexColor c ) { - RGBA8 rgba = MakeRGBA8(c, 1.0f); - m_points.push_back({v, size, rgba}); + RGBA8 rgba = MakeRGBA8( c, 1.0f ); + m_points.push_back( { v, size, rgba } ); } void Flush() { int count = (int)m_points.size(); - if (count == 0) + if ( count == 0 ) { return; } - glUseProgram(m_programId); + glUseProgram( m_programId ); - float proj[16] = {0.0f}; - g_camera.BuildProjectionMatrix(proj, 0.0f); + float proj[16] = { 0.0f }; + g_camera.BuildProjectionMatrix( proj, 0.0f ); - glUniformMatrix4fv(m_projectionUniform, 1, GL_FALSE, proj); - glBindVertexArray(m_vaoId); + glUniformMatrix4fv( m_projectionUniform, 1, GL_FALSE, proj ); + glBindVertexArray( m_vaoId ); - glBindBuffer(GL_ARRAY_BUFFER, m_vboId); - glEnable(GL_PROGRAM_POINT_SIZE); + glBindBuffer( GL_ARRAY_BUFFER, m_vboId ); + glEnable( GL_PROGRAM_POINT_SIZE ); int base = 0; - while (count > 0) + while ( count > 0 ) { - int batchCount = b2MinInt(count, e_maxCount); - glBufferSubData(GL_ARRAY_BUFFER, 0, batchCount * sizeof(PointData), &m_points[base]); - glDrawArrays(GL_POINTS, 0, batchCount); + int batchCount = b2MinInt( count, e_maxCount ); + glBufferSubData( GL_ARRAY_BUFFER, 0, batchCount * sizeof( PointData ), &m_points[base] ); + glDrawArrays( GL_POINTS, 0, batchCount ); CheckErrorGL(); - + count -= e_maxCount; base += e_maxCount; } - glDisable(GL_PROGRAM_POINT_SIZE); - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindVertexArray(0); - glUseProgram(0); + glDisable( GL_PROGRAM_POINT_SIZE ); + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindVertexArray( 0 ); + glUseProgram( 0 ); m_points.clear(); } @@ -299,87 +380,88 @@ struct GLLines " color = f_color;\n" "}\n"; - m_programId = CreateProgramFromStrings(vs, fs); - m_projectionUniform = glGetUniformLocation(m_programId, "projectionMatrix"); + m_programId = CreateProgramFromStrings( vs, fs ); + m_projectionUniform = glGetUniformLocation( m_programId, "projectionMatrix" ); int vertexAttribute = 0; int colorAttribute = 1; // Generate - glGenVertexArrays(1, &m_vaoId); - glGenBuffers(1, &m_vboId); + glGenVertexArrays( 1, &m_vaoId ); + glGenBuffers( 1, &m_vboId ); - glBindVertexArray(m_vaoId); - glEnableVertexAttribArray(vertexAttribute); - glEnableVertexAttribArray(colorAttribute); + glBindVertexArray( m_vaoId ); + glEnableVertexAttribArray( vertexAttribute ); + glEnableVertexAttribArray( colorAttribute ); // Vertex buffer - glBindBuffer(GL_ARRAY_BUFFER, m_vboId); - glBufferData(GL_ARRAY_BUFFER, e_maxCount * sizeof(VertexData), NULL, GL_DYNAMIC_DRAW); + glBindBuffer( GL_ARRAY_BUFFER, m_vboId ); + glBufferData( GL_ARRAY_BUFFER, e_maxCount * sizeof( VertexData ), NULL, GL_DYNAMIC_DRAW ); - glVertexAttribPointer(vertexAttribute, 2, GL_FLOAT, GL_FALSE, sizeof(VertexData), (void*)offsetof(VertexData, position)); + glVertexAttribPointer( vertexAttribute, 2, GL_FLOAT, GL_FALSE, sizeof( VertexData ), + (void*)offsetof( VertexData, position ) ); // color will get automatically expanded to floats in the shader - glVertexAttribPointer(colorAttribute, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(VertexData), - (void*)offsetof(VertexData, rgba)); + glVertexAttribPointer( colorAttribute, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( VertexData ), + (void*)offsetof( VertexData, rgba ) ); CheckErrorGL(); // Cleanup - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindVertexArray(0); + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindVertexArray( 0 ); } void Destroy() { - if (m_vaoId) + if ( m_vaoId ) { - glDeleteVertexArrays(1, &m_vaoId); - glDeleteBuffers(1, &m_vboId); + glDeleteVertexArrays( 1, &m_vaoId ); + glDeleteBuffers( 1, &m_vboId ); m_vaoId = 0; m_vboId = 0; } - if (m_programId) + if ( m_programId ) { - glDeleteProgram(m_programId); + glDeleteProgram( m_programId ); m_programId = 0; } } - void AddLine(b2Vec2 p1, b2Vec2 p2, b2HexColor c) + void AddLine( b2Vec2 p1, b2Vec2 p2, b2HexColor c ) { - RGBA8 rgba = MakeRGBA8(c, 1.0f); - m_points.push_back({p1, rgba}); - m_points.push_back({p2, rgba}); + RGBA8 rgba = MakeRGBA8( c, 1.0f ); + m_points.push_back( { p1, rgba } ); + m_points.push_back( { p2, rgba } ); } void Flush() { int count = (int)m_points.size(); - if (count == 0) + if ( count == 0 ) { return; } - assert(count % 2 == 0); + assert( count % 2 == 0 ); - glUseProgram(m_programId); + glUseProgram( m_programId ); - float proj[16] = {0.0f}; - g_camera.BuildProjectionMatrix(proj, 0.1f); + float proj[16] = { 0.0f }; + g_camera.BuildProjectionMatrix( proj, 0.1f ); - glUniformMatrix4fv(m_projectionUniform, 1, GL_FALSE, proj); + glUniformMatrix4fv( m_projectionUniform, 1, GL_FALSE, proj ); - glBindVertexArray(m_vaoId); + glBindVertexArray( m_vaoId ); - glBindBuffer(GL_ARRAY_BUFFER, m_vboId); + glBindBuffer( GL_ARRAY_BUFFER, m_vboId ); int base = 0; - while (count > 0) + while ( count > 0 ) { - int batchCount = b2MinInt(count, e_maxCount); - glBufferSubData(GL_ARRAY_BUFFER, 0, batchCount * sizeof(VertexData), &m_points[base]); + int batchCount = b2MinInt( count, e_maxCount ); + glBufferSubData( GL_ARRAY_BUFFER, 0, batchCount * sizeof( VertexData ), &m_points[base] ); - glDrawArrays(GL_LINES, 0, batchCount); + glDrawArrays( GL_LINES, 0, batchCount ); CheckErrorGL(); @@ -387,9 +469,9 @@ struct GLLines base += e_maxCount; } - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindVertexArray(0); - glUseProgram(0); + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindVertexArray( 0 ); + glUseProgram( 0 ); m_points.clear(); } @@ -434,90 +516,91 @@ struct GLTriangles " color = f_color;\n" "}\n"; - m_programId = CreateProgramFromStrings(vs, fs); - m_projectionUniform = glGetUniformLocation(m_programId, "projectionMatrix"); + m_programId = CreateProgramFromStrings( vs, fs ); + m_projectionUniform = glGetUniformLocation( m_programId, "projectionMatrix" ); int vertexAttribute = 0; int colorAttribute = 1; // Generate - glGenVertexArrays(1, &m_vaoId); - glGenBuffers(1, &m_vboId); + glGenVertexArrays( 1, &m_vaoId ); + glGenBuffers( 1, &m_vboId ); - glBindVertexArray(m_vaoId); - glEnableVertexAttribArray(vertexAttribute); - glEnableVertexAttribArray(colorAttribute); + glBindVertexArray( m_vaoId ); + glEnableVertexAttribArray( vertexAttribute ); + glEnableVertexAttribArray( colorAttribute ); // Vertex buffer - glBindBuffer(GL_ARRAY_BUFFER, m_vboId); - glBufferData(GL_ARRAY_BUFFER, e_maxCount * sizeof(VertexData), NULL, GL_DYNAMIC_DRAW); + glBindBuffer( GL_ARRAY_BUFFER, m_vboId ); + glBufferData( GL_ARRAY_BUFFER, e_maxCount * sizeof( VertexData ), NULL, GL_DYNAMIC_DRAW ); - glVertexAttribPointer(vertexAttribute, 2, GL_FLOAT, GL_FALSE, sizeof(VertexData), (void*)offsetof(VertexData, position)); + glVertexAttribPointer( vertexAttribute, 2, GL_FLOAT, GL_FALSE, sizeof( VertexData ), + (void*)offsetof( VertexData, position ) ); // color will get automatically expanded to floats in the shader - glVertexAttribPointer(colorAttribute, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(VertexData), - (void*)offsetof(VertexData, rgba)); + glVertexAttribPointer( colorAttribute, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( VertexData ), + (void*)offsetof( VertexData, rgba ) ); CheckErrorGL(); // Cleanup - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindVertexArray(0); + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindVertexArray( 0 ); } void Destroy() { - if (m_vaoId) + if ( m_vaoId ) { - glDeleteVertexArrays(1, &m_vaoId); - glDeleteBuffers(1, &m_vboId); + glDeleteVertexArrays( 1, &m_vaoId ); + glDeleteBuffers( 1, &m_vboId ); m_vaoId = 0; m_vboId = 0; } - if (m_programId) + if ( m_programId ) { - glDeleteProgram(m_programId); + glDeleteProgram( m_programId ); m_programId = 0; } } - void AddTriangle(b2Vec2 p1, b2Vec2 p2, b2Vec2 p3, b2HexColor c) + void AddTriangle( b2Vec2 p1, b2Vec2 p2, b2Vec2 p3, b2HexColor c ) { - RGBA8 rgba = MakeRGBA8(c, 1.0f); - m_points.push_back({p1, rgba}); - m_points.push_back({p2, rgba}); - m_points.push_back({p3, rgba}); + RGBA8 rgba = MakeRGBA8( c, 1.0f ); + m_points.push_back( { p1, rgba } ); + m_points.push_back( { p2, rgba } ); + m_points.push_back( { p3, rgba } ); } void Flush() { int count = (int)m_points.size(); - if (count == 0) + if ( count == 0 ) { return; } - assert(count % 3 == 0); + assert( count % 3 == 0 ); - glUseProgram(m_programId); + glUseProgram( m_programId ); - float proj[16] = {0.0f}; - g_camera.BuildProjectionMatrix(proj, 0.2f); + float proj[16] = { 0.0f }; + g_camera.BuildProjectionMatrix( proj, 0.2f ); - glUniformMatrix4fv(m_projectionUniform, 1, GL_FALSE, proj); + glUniformMatrix4fv( m_projectionUniform, 1, GL_FALSE, proj ); - glBindVertexArray(m_vaoId); + glBindVertexArray( m_vaoId ); - glBindBuffer(GL_ARRAY_BUFFER, m_vboId); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glBindBuffer( GL_ARRAY_BUFFER, m_vboId ); + glEnable( GL_BLEND ); + glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); int base = 0; - while (count > 0) + while ( count > 0 ) { - int batchCount = b2MinInt(count, e_maxCount); + int batchCount = b2MinInt( count, e_maxCount ); - glBufferSubData(GL_ARRAY_BUFFER, 0, batchCount * sizeof(VertexData), &m_points[base]); - glDrawArrays(GL_TRIANGLES, 0, batchCount); + glBufferSubData( GL_ARRAY_BUFFER, 0, batchCount * sizeof( VertexData ), &m_points[base] ); + glDrawArrays( GL_TRIANGLES, 0, batchCount ); CheckErrorGL(); @@ -525,11 +608,11 @@ struct GLTriangles base += e_maxCount; } - glDisable(GL_BLEND); + glDisable( GL_BLEND ); - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindVertexArray(0); - glUseProgram(0); + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindVertexArray( 0 ); + glUseProgram( 0 ); m_points.clear(); } @@ -564,104 +647,106 @@ struct GLCircles { void Create() { - m_programId = CreateProgramFromFiles("samples/data/circle.vs", "samples/data/circle.fs"); - m_projectionUniform = glGetUniformLocation(m_programId, "projectionMatrix"); - m_pixelScaleUniform = glGetUniformLocation(m_programId, "pixelScale"); + m_programId = CreateProgramFromFiles( "samples/data/circle.vs", "samples/data/circle.fs" ); + m_projectionUniform = glGetUniformLocation( m_programId, "projectionMatrix" ); + m_pixelScaleUniform = glGetUniformLocation( m_programId, "pixelScale" ); int vertexAttribute = 0; int positionInstance = 1; int radiusInstance = 2; int colorInstance = 3; // Generate - glGenVertexArrays(1, &m_vaoId); - glGenBuffers(2, m_vboIds); + glGenVertexArrays( 1, &m_vaoId ); + glGenBuffers( 2, m_vboIds ); - glBindVertexArray(m_vaoId); - glEnableVertexAttribArray(vertexAttribute); - glEnableVertexAttribArray(positionInstance); - glEnableVertexAttribArray(radiusInstance); - glEnableVertexAttribArray(colorInstance); + glBindVertexArray( m_vaoId ); + glEnableVertexAttribArray( vertexAttribute ); + glEnableVertexAttribArray( positionInstance ); + glEnableVertexAttribArray( radiusInstance ); + glEnableVertexAttribArray( colorInstance ); // Vertex buffer for single quad float a = 1.1f; - b2Vec2 vertices[] = {{-a, -a}, {a, -a}, {-a, a}, {a, -a}, {a, a}, {-a, a}}; - glBindBuffer(GL_ARRAY_BUFFER, m_vboIds[0]); - glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); - glVertexAttribPointer(vertexAttribute, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0)); + b2Vec2 vertices[] = { { -a, -a }, { a, -a }, { -a, a }, { a, -a }, { a, a }, { -a, a } }; + glBindBuffer( GL_ARRAY_BUFFER, m_vboIds[0] ); + glBufferData( GL_ARRAY_BUFFER, sizeof( vertices ), vertices, GL_STATIC_DRAW ); + glVertexAttribPointer( vertexAttribute, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET( 0 ) ); // Circle buffer - glBindBuffer(GL_ARRAY_BUFFER, m_vboIds[1]); - glBufferData(GL_ARRAY_BUFFER, e_maxCount * sizeof(CircleData), NULL, GL_DYNAMIC_DRAW); + glBindBuffer( GL_ARRAY_BUFFER, m_vboIds[1] ); + glBufferData( GL_ARRAY_BUFFER, e_maxCount * sizeof( CircleData ), NULL, GL_DYNAMIC_DRAW ); - glVertexAttribPointer(positionInstance, 2, GL_FLOAT, GL_FALSE, sizeof(CircleData), - (void*)offsetof(CircleData, position)); - glVertexAttribPointer(radiusInstance, 1, GL_FLOAT, GL_FALSE, sizeof(CircleData), (void*)offsetof(CircleData, radius)); - glVertexAttribPointer(colorInstance, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(CircleData), (void*)offsetof(CircleData, rgba)); + glVertexAttribPointer( positionInstance, 2, GL_FLOAT, GL_FALSE, sizeof( CircleData ), + (void*)offsetof( CircleData, position ) ); + glVertexAttribPointer( radiusInstance, 1, GL_FLOAT, GL_FALSE, sizeof( CircleData ), + (void*)offsetof( CircleData, radius ) ); + glVertexAttribPointer( colorInstance, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( CircleData ), + (void*)offsetof( CircleData, rgba ) ); - glVertexAttribDivisor(positionInstance, 1); - glVertexAttribDivisor(radiusInstance, 1); - glVertexAttribDivisor(colorInstance, 1); + glVertexAttribDivisor( positionInstance, 1 ); + glVertexAttribDivisor( radiusInstance, 1 ); + glVertexAttribDivisor( colorInstance, 1 ); CheckErrorGL(); // Cleanup - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindVertexArray(0); + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindVertexArray( 0 ); } void Destroy() { - if (m_vaoId) + if ( m_vaoId ) { - glDeleteVertexArrays(1, &m_vaoId); - glDeleteBuffers(2, m_vboIds); + glDeleteVertexArrays( 1, &m_vaoId ); + glDeleteBuffers( 2, m_vboIds ); m_vaoId = 0; m_vboIds[0] = 0; m_vboIds[1] = 0; } - if (m_programId) + if ( m_programId ) { - glDeleteProgram(m_programId); + glDeleteProgram( m_programId ); m_programId = 0; } } - void AddCircle(b2Vec2 center, float radius, b2HexColor color) + void AddCircle( b2Vec2 center, float radius, b2HexColor color ) { - RGBA8 rgba = MakeRGBA8(color, 1.0f); - m_circles.push_back({center, radius, rgba}); + RGBA8 rgba = MakeRGBA8( color, 1.0f ); + m_circles.push_back( { center, radius, rgba } ); } void Flush() { int count = (int)m_circles.size(); - if (count == 0) + if ( count == 0 ) { return; } - glUseProgram(m_programId); + glUseProgram( m_programId ); - float proj[16] = {0.0f}; - g_camera.BuildProjectionMatrix(proj, 0.2f); + float proj[16] = { 0.0f }; + g_camera.BuildProjectionMatrix( proj, 0.2f ); - glUniformMatrix4fv(m_projectionUniform, 1, GL_FALSE, proj); - glUniform1f(m_pixelScaleUniform, g_camera.m_height / g_camera.m_zoom); + glUniformMatrix4fv( m_projectionUniform, 1, GL_FALSE, proj ); + glUniform1f( m_pixelScaleUniform, g_camera.m_height / g_camera.m_zoom ); - glBindVertexArray(m_vaoId); + glBindVertexArray( m_vaoId ); - glBindBuffer(GL_ARRAY_BUFFER, m_vboIds[1]); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glBindBuffer( GL_ARRAY_BUFFER, m_vboIds[1] ); + glEnable( GL_BLEND ); + glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); int base = 0; - while (count > 0) + while ( count > 0 ) { - int batchCount = b2MinInt(count, e_maxCount); + int batchCount = b2MinInt( count, e_maxCount ); - glBufferSubData(GL_ARRAY_BUFFER, 0, batchCount * sizeof(CircleData), &m_circles[base]); - glDrawArraysInstanced(GL_TRIANGLES, 0, 6, batchCount); + glBufferSubData( GL_ARRAY_BUFFER, 0, batchCount * sizeof( CircleData ), &m_circles[base] ); + glDrawArraysInstanced( GL_TRIANGLES, 0, 6, batchCount ); CheckErrorGL(); @@ -669,11 +754,11 @@ struct GLCircles base += e_maxCount; } - glDisable(GL_BLEND); + glDisable( GL_BLEND ); - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindVertexArray(0); - glUseProgram(0); + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindVertexArray( 0 ); + glUseProgram( 0 ); m_circles.clear(); } @@ -706,106 +791,107 @@ struct GLSolidCircles { void Create() { - m_programId = CreateProgramFromFiles("samples/data/solid_circle.vs", "samples/data/solid_circle.fs"); - m_projectionUniform = glGetUniformLocation(m_programId, "projectionMatrix"); - m_pixelScaleUniform = glGetUniformLocation(m_programId, "pixelScale"); - + m_programId = CreateProgramFromFiles( "samples/data/solid_circle.vs", "samples/data/solid_circle.fs" ); + m_projectionUniform = glGetUniformLocation( m_programId, "projectionMatrix" ); + m_pixelScaleUniform = glGetUniformLocation( m_programId, "pixelScale" ); // Generate - glGenVertexArrays(1, &m_vaoId); - glGenBuffers(2, m_vboIds); + glGenVertexArrays( 1, &m_vaoId ); + glGenBuffers( 2, m_vboIds ); - glBindVertexArray(m_vaoId); + glBindVertexArray( m_vaoId ); int vertexAttribute = 0; int transformInstance = 1; int radiusInstance = 2; int colorInstance = 3; - glEnableVertexAttribArray(vertexAttribute); - glEnableVertexAttribArray(transformInstance); - glEnableVertexAttribArray(radiusInstance); - glEnableVertexAttribArray(colorInstance); + glEnableVertexAttribArray( vertexAttribute ); + glEnableVertexAttribArray( transformInstance ); + glEnableVertexAttribArray( radiusInstance ); + glEnableVertexAttribArray( colorInstance ); // Vertex buffer for single quad float a = 1.1f; - b2Vec2 vertices[] = {{-a, -a}, {a, -a}, {-a, a}, {a, -a}, {a, a}, {-a, a}}; - glBindBuffer(GL_ARRAY_BUFFER, m_vboIds[0]); - glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); - glVertexAttribPointer(vertexAttribute, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0)); + b2Vec2 vertices[] = { { -a, -a }, { a, -a }, { -a, a }, { a, -a }, { a, a }, { -a, a } }; + glBindBuffer( GL_ARRAY_BUFFER, m_vboIds[0] ); + glBufferData( GL_ARRAY_BUFFER, sizeof( vertices ), vertices, GL_STATIC_DRAW ); + glVertexAttribPointer( vertexAttribute, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET( 0 ) ); // Circle buffer - glBindBuffer(GL_ARRAY_BUFFER, m_vboIds[1]); - glBufferData(GL_ARRAY_BUFFER, e_maxCount * sizeof(SolidCircleData), NULL, GL_DYNAMIC_DRAW); + glBindBuffer( GL_ARRAY_BUFFER, m_vboIds[1] ); + glBufferData( GL_ARRAY_BUFFER, e_maxCount * sizeof( SolidCircleData ), NULL, GL_DYNAMIC_DRAW ); - glVertexAttribPointer(transformInstance, 4, GL_FLOAT, GL_FALSE, sizeof(SolidCircleData), - (void*)offsetof(SolidCircleData, transform)); - glVertexAttribPointer(radiusInstance, 1, GL_FLOAT, GL_FALSE, sizeof(SolidCircleData), (void*)offsetof(SolidCircleData, radius)); - glVertexAttribPointer(colorInstance, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(SolidCircleData), (void*)offsetof(SolidCircleData, rgba)); + glVertexAttribPointer( transformInstance, 4, GL_FLOAT, GL_FALSE, sizeof( SolidCircleData ), + (void*)offsetof( SolidCircleData, transform ) ); + glVertexAttribPointer( radiusInstance, 1, GL_FLOAT, GL_FALSE, sizeof( SolidCircleData ), + (void*)offsetof( SolidCircleData, radius ) ); + glVertexAttribPointer( colorInstance, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( SolidCircleData ), + (void*)offsetof( SolidCircleData, rgba ) ); - glVertexAttribDivisor(transformInstance, 1); - glVertexAttribDivisor(radiusInstance, 1); - glVertexAttribDivisor(colorInstance, 1); + glVertexAttribDivisor( transformInstance, 1 ); + glVertexAttribDivisor( radiusInstance, 1 ); + glVertexAttribDivisor( colorInstance, 1 ); CheckErrorGL(); // Cleanup - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindVertexArray(0); + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindVertexArray( 0 ); } void Destroy() { - if (m_vaoId) + if ( m_vaoId ) { - glDeleteVertexArrays(1, &m_vaoId); - glDeleteBuffers(2, m_vboIds); + glDeleteVertexArrays( 1, &m_vaoId ); + glDeleteBuffers( 2, m_vboIds ); m_vaoId = 0; m_vboIds[0] = 0; m_vboIds[1] = 0; } - if (m_programId) + if ( m_programId ) { - glDeleteProgram(m_programId); + glDeleteProgram( m_programId ); m_programId = 0; } } - void AddCircle(const b2Transform& transform, float radius, b2HexColor color) + void AddCircle( const b2Transform& transform, float radius, b2HexColor color ) { - RGBA8 rgba = MakeRGBA8(color, 1.0f); - m_circles.push_back({{transform.p.x, transform.p.y, transform.q.c, transform.q.s}, radius, rgba}); + RGBA8 rgba = MakeRGBA8( color, 1.0f ); + m_circles.push_back( { { transform.p.x, transform.p.y, transform.q.c, transform.q.s }, radius, rgba } ); } void Flush() { int count = (int)m_circles.size(); - if (count == 0) + if ( count == 0 ) { return; } - glUseProgram(m_programId); + glUseProgram( m_programId ); - float proj[16] = {0.0f}; - g_camera.BuildProjectionMatrix(proj, 0.2f); + float proj[16] = { 0.0f }; + g_camera.BuildProjectionMatrix( proj, 0.2f ); - glUniformMatrix4fv(m_projectionUniform, 1, GL_FALSE, proj); - glUniform1f(m_pixelScaleUniform, g_camera.m_height / g_camera.m_zoom); + glUniformMatrix4fv( m_projectionUniform, 1, GL_FALSE, proj ); + glUniform1f( m_pixelScaleUniform, g_camera.m_height / g_camera.m_zoom ); - glBindVertexArray(m_vaoId); + glBindVertexArray( m_vaoId ); - glBindBuffer(GL_ARRAY_BUFFER, m_vboIds[1]); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glBindBuffer( GL_ARRAY_BUFFER, m_vboIds[1] ); + glEnable( GL_BLEND ); + glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); int base = 0; - while (count > 0) + while ( count > 0 ) { - int batchCount = b2MinInt(count, e_maxCount); + int batchCount = b2MinInt( count, e_maxCount ); - glBufferSubData(GL_ARRAY_BUFFER, 0, batchCount * sizeof(SolidCircleData), &m_circles[base]); - glDrawArraysInstanced(GL_TRIANGLES, 0, 6, batchCount); + glBufferSubData( GL_ARRAY_BUFFER, 0, batchCount * sizeof( SolidCircleData ), &m_circles[base] ); + glDrawArraysInstanced( GL_TRIANGLES, 0, 6, batchCount ); CheckErrorGL(); @@ -813,11 +899,11 @@ struct GLSolidCircles base += e_maxCount; } - glDisable(GL_BLEND); + glDisable( GL_BLEND ); - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindVertexArray(0); - glUseProgram(0); + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindVertexArray( 0 ); + glUseProgram( 0 ); m_circles.clear(); } @@ -849,10 +935,10 @@ struct GLSolidCapsules { void Create() { - m_programId = CreateProgramFromFiles("samples/data/solid_capsule.vs", "samples/data/solid_capsule.fs"); + m_programId = CreateProgramFromFiles( "samples/data/solid_capsule.vs", "samples/data/solid_capsule.fs" ); - m_projectionUniform = glGetUniformLocation(m_programId, "projectionMatrix"); - m_pixelScaleUniform = glGetUniformLocation(m_programId, "pixelScale"); + m_projectionUniform = glGetUniformLocation( m_programId, "projectionMatrix" ); + m_pixelScaleUniform = glGetUniformLocation( m_programId, "pixelScale" ); int vertexAttribute = 0; int transformInstance = 1; @@ -861,114 +947,116 @@ struct GLSolidCapsules int colorInstance = 4; // Generate - glGenVertexArrays(1, &m_vaoId); - glGenBuffers(2, m_vboIds); + glGenVertexArrays( 1, &m_vaoId ); + glGenBuffers( 2, m_vboIds ); - glBindVertexArray(m_vaoId); - glEnableVertexAttribArray(vertexAttribute); - glEnableVertexAttribArray(transformInstance); - glEnableVertexAttribArray(radiusInstance); - glEnableVertexAttribArray(lengthInstance); - glEnableVertexAttribArray(colorInstance); + glBindVertexArray( m_vaoId ); + glEnableVertexAttribArray( vertexAttribute ); + glEnableVertexAttribArray( transformInstance ); + glEnableVertexAttribArray( radiusInstance ); + glEnableVertexAttribArray( lengthInstance ); + glEnableVertexAttribArray( colorInstance ); // Vertex buffer for single quad float a = 1.1f; - b2Vec2 vertices[] = {{-a, -a}, {a, -a}, {-a, a}, {a, -a}, {a, a}, {-a, a}}; - glBindBuffer(GL_ARRAY_BUFFER, m_vboIds[0]); - glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); - glVertexAttribPointer(vertexAttribute, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0)); + b2Vec2 vertices[] = { { -a, -a }, { a, -a }, { -a, a }, { a, -a }, { a, a }, { -a, a } }; + glBindBuffer( GL_ARRAY_BUFFER, m_vboIds[0] ); + glBufferData( GL_ARRAY_BUFFER, sizeof( vertices ), vertices, GL_STATIC_DRAW ); + glVertexAttribPointer( vertexAttribute, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET( 0 ) ); // Capsule buffer - glBindBuffer(GL_ARRAY_BUFFER, m_vboIds[1]); - glBufferData(GL_ARRAY_BUFFER, e_maxCount * sizeof(CapsuleData), NULL, GL_DYNAMIC_DRAW); - - glVertexAttribPointer(transformInstance, 4, GL_FLOAT, GL_FALSE, sizeof(CapsuleData), - (void*)offsetof(CapsuleData, transform)); - glVertexAttribPointer(radiusInstance, 1, GL_FLOAT, GL_FALSE, sizeof(CapsuleData), (void*)offsetof(CapsuleData, radius)); - glVertexAttribPointer(lengthInstance, 1, GL_FLOAT, GL_FALSE, sizeof(CapsuleData), (void*)offsetof(CapsuleData, length)); - glVertexAttribPointer(colorInstance, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(CapsuleData), - (void*)offsetof(CapsuleData, rgba)); - - glVertexAttribDivisor(transformInstance, 1); - glVertexAttribDivisor(radiusInstance, 1); - glVertexAttribDivisor(lengthInstance, 1); - glVertexAttribDivisor(colorInstance, 1); + glBindBuffer( GL_ARRAY_BUFFER, m_vboIds[1] ); + glBufferData( GL_ARRAY_BUFFER, e_maxCount * sizeof( CapsuleData ), NULL, GL_DYNAMIC_DRAW ); + + glVertexAttribPointer( transformInstance, 4, GL_FLOAT, GL_FALSE, sizeof( CapsuleData ), + (void*)offsetof( CapsuleData, transform ) ); + glVertexAttribPointer( radiusInstance, 1, GL_FLOAT, GL_FALSE, sizeof( CapsuleData ), + (void*)offsetof( CapsuleData, radius ) ); + glVertexAttribPointer( lengthInstance, 1, GL_FLOAT, GL_FALSE, sizeof( CapsuleData ), + (void*)offsetof( CapsuleData, length ) ); + glVertexAttribPointer( colorInstance, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( CapsuleData ), + (void*)offsetof( CapsuleData, rgba ) ); + + glVertexAttribDivisor( transformInstance, 1 ); + glVertexAttribDivisor( radiusInstance, 1 ); + glVertexAttribDivisor( lengthInstance, 1 ); + glVertexAttribDivisor( colorInstance, 1 ); CheckErrorGL(); // Cleanup - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindVertexArray(0); + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindVertexArray( 0 ); } void Destroy() { - if (m_vaoId) + if ( m_vaoId ) { - glDeleteVertexArrays(1, &m_vaoId); - glDeleteBuffers(2, m_vboIds); + glDeleteVertexArrays( 1, &m_vaoId ); + glDeleteBuffers( 2, m_vboIds ); m_vaoId = 0; m_vboIds[0] = 0; m_vboIds[1] = 0; } - if (m_programId) + if ( m_programId ) { - glDeleteProgram(m_programId); + glDeleteProgram( m_programId ); m_programId = 0; } } - void AddCapsule(b2Vec2 p1, b2Vec2 p2, float radius, b2HexColor c) + void AddCapsule( b2Vec2 p1, b2Vec2 p2, float radius, b2HexColor c ) { b2Vec2 d = p2 - p1; - float length = b2Length(d); - if (length < 0.001f) + float length = b2Length( d ); + if ( length < 0.001f ) { - printf("WARNING: sample app: capsule too short!\n"); + printf( "WARNING: sample app: capsule too short!\n" ); return; } - b2Vec2 axis = {d.x / length, d.y / length}; + b2Vec2 axis = { d.x / length, d.y / length }; b2Transform transform; - transform.p = 0.5f * (p1 + p2); + transform.p = 0.5f * ( p1 + p2 ); transform.q.c = axis.x; transform.q.s = axis.y; - RGBA8 rgba = MakeRGBA8(c, 1.0f); + RGBA8 rgba = MakeRGBA8( c, 1.0f ); - m_capsules.push_back({{transform.p.x, transform.p.y, transform.q.c, transform.q.s}, radius, length, rgba}); + m_capsules.push_back( { { transform.p.x, transform.p.y, transform.q.c, transform.q.s }, radius, length, rgba } ); } void Flush() { int count = (int)m_capsules.size(); - if (count == 0) + if ( count == 0 ) { return; } - glUseProgram(m_programId); + glUseProgram( m_programId ); - float proj[16] = {0.0f}; - g_camera.BuildProjectionMatrix(proj, 0.2f); + float proj[16] = { 0.0f }; + g_camera.BuildProjectionMatrix( proj, 0.2f ); - glUniformMatrix4fv(m_projectionUniform, 1, GL_FALSE, proj); - glUniform1f(m_pixelScaleUniform, g_camera.m_height / g_camera.m_zoom); + glUniformMatrix4fv( m_projectionUniform, 1, GL_FALSE, proj ); + glUniform1f( m_pixelScaleUniform, g_camera.m_height / g_camera.m_zoom ); - glBindVertexArray(m_vaoId); + glBindVertexArray( m_vaoId ); - glBindBuffer(GL_ARRAY_BUFFER, m_vboIds[1]); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glBindBuffer( GL_ARRAY_BUFFER, m_vboIds[1] ); + glEnable( GL_BLEND ); + glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); int base = 0; - while (count > 0) + while ( count > 0 ) { - int batchCount = b2MinInt(count, e_maxCount); + int batchCount = b2MinInt( count, e_maxCount ); - glBufferSubData(GL_ARRAY_BUFFER, 0, batchCount * sizeof(CapsuleData), &m_capsules[base]); - glDrawArraysInstanced(GL_TRIANGLES, 0, 6, batchCount); + glBufferSubData( GL_ARRAY_BUFFER, 0, batchCount * sizeof( CapsuleData ), &m_capsules[base] ); + glDrawArraysInstanced( GL_TRIANGLES, 0, 6, batchCount ); CheckErrorGL(); @@ -976,11 +1064,11 @@ struct GLSolidCapsules base += e_maxCount; } - glDisable(GL_BLEND); + glDisable( GL_BLEND ); - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindVertexArray(0); - glUseProgram(0); + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindVertexArray( 0 ); + glUseProgram( 0 ); m_capsules.clear(); } @@ -1015,10 +1103,10 @@ struct GLSolidPolygons { void Create() { - m_programId = CreateProgramFromFiles("samples/data/solid_polygon.vs", "samples/data/solid_polygon.fs"); + m_programId = CreateProgramFromFiles( "samples/data/solid_polygon.vs", "samples/data/solid_polygon.fs" ); - m_projectionUniform = glGetUniformLocation(m_programId, "projectionMatrix"); - m_pixelScaleUniform = glGetUniformLocation(m_programId, "pixelScale"); + m_projectionUniform = glGetUniformLocation( m_programId, "projectionMatrix" ); + m_pixelScaleUniform = glGetUniformLocation( m_programId, "pixelScale" ); int vertexAttribute = 0; int instanceTransform = 1; int instancePoint12 = 2; @@ -1030,134 +1118,139 @@ struct GLSolidPolygons int instanceColor = 8; // Generate - glGenVertexArrays(1, &m_vaoId); - glGenBuffers(2, m_vboIds); - - glBindVertexArray(m_vaoId); - glEnableVertexAttribArray(vertexAttribute); - glEnableVertexAttribArray(instanceTransform); - glEnableVertexAttribArray(instancePoint12); - glEnableVertexAttribArray(instancePoint34); - glEnableVertexAttribArray(instancePoint56); - glEnableVertexAttribArray(instancePoint78); - glEnableVertexAttribArray(instancePointCount); - glEnableVertexAttribArray(instanceRadius); - glEnableVertexAttribArray(instanceColor); + glGenVertexArrays( 1, &m_vaoId ); + glGenBuffers( 2, m_vboIds ); + + glBindVertexArray( m_vaoId ); + glEnableVertexAttribArray( vertexAttribute ); + glEnableVertexAttribArray( instanceTransform ); + glEnableVertexAttribArray( instancePoint12 ); + glEnableVertexAttribArray( instancePoint34 ); + glEnableVertexAttribArray( instancePoint56 ); + glEnableVertexAttribArray( instancePoint78 ); + glEnableVertexAttribArray( instancePointCount ); + glEnableVertexAttribArray( instanceRadius ); + glEnableVertexAttribArray( instanceColor ); // Vertex buffer for single quad float a = 1.1f; - b2Vec2 vertices[] = {{-a, -a}, {a, -a}, {-a, a}, {a, -a}, {a, a}, {-a, a}}; - glBindBuffer(GL_ARRAY_BUFFER, m_vboIds[0]); - glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); - glVertexAttribPointer(vertexAttribute, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0)); + b2Vec2 vertices[] = { { -a, -a }, { a, -a }, { -a, a }, { a, -a }, { a, a }, { -a, a } }; + glBindBuffer( GL_ARRAY_BUFFER, m_vboIds[0] ); + glBufferData( GL_ARRAY_BUFFER, sizeof( vertices ), vertices, GL_STATIC_DRAW ); + glVertexAttribPointer( vertexAttribute, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET( 0 ) ); // Polygon buffer - glBindBuffer(GL_ARRAY_BUFFER, m_vboIds[1]); - glBufferData(GL_ARRAY_BUFFER, e_maxCount * sizeof(PolygonData), NULL, GL_DYNAMIC_DRAW); - glVertexAttribPointer(instanceTransform, 4, GL_FLOAT, GL_FALSE, sizeof(PolygonData), - (void*)offsetof(PolygonData, transform)); - glVertexAttribPointer(instancePoint12, 4, GL_FLOAT, GL_FALSE, sizeof(PolygonData), (void*)offsetof(PolygonData, p1)); - glVertexAttribPointer(instancePoint34, 4, GL_FLOAT, GL_FALSE, sizeof(PolygonData), (void*)offsetof(PolygonData, p3)); - glVertexAttribPointer(instancePoint56, 4, GL_FLOAT, GL_FALSE, sizeof(PolygonData), (void*)offsetof(PolygonData, p5)); - glVertexAttribPointer(instancePoint78, 4, GL_FLOAT, GL_FALSE, sizeof(PolygonData), (void*)offsetof(PolygonData, p7)); - glVertexAttribIPointer(instancePointCount, 1, GL_INT, sizeof(PolygonData), (void*)offsetof(PolygonData, count)); - glVertexAttribPointer(instanceRadius, 1, GL_FLOAT, GL_FALSE, sizeof(PolygonData), (void*)offsetof(PolygonData, radius)); + glBindBuffer( GL_ARRAY_BUFFER, m_vboIds[1] ); + glBufferData( GL_ARRAY_BUFFER, e_maxCount * sizeof( PolygonData ), NULL, GL_DYNAMIC_DRAW ); + glVertexAttribPointer( instanceTransform, 4, GL_FLOAT, GL_FALSE, sizeof( PolygonData ), + (void*)offsetof( PolygonData, transform ) ); + glVertexAttribPointer( instancePoint12, 4, GL_FLOAT, GL_FALSE, sizeof( PolygonData ), + (void*)offsetof( PolygonData, p1 ) ); + glVertexAttribPointer( instancePoint34, 4, GL_FLOAT, GL_FALSE, sizeof( PolygonData ), + (void*)offsetof( PolygonData, p3 ) ); + glVertexAttribPointer( instancePoint56, 4, GL_FLOAT, GL_FALSE, sizeof( PolygonData ), + (void*)offsetof( PolygonData, p5 ) ); + glVertexAttribPointer( instancePoint78, 4, GL_FLOAT, GL_FALSE, sizeof( PolygonData ), + (void*)offsetof( PolygonData, p7 ) ); + glVertexAttribIPointer( instancePointCount, 1, GL_INT, sizeof( PolygonData ), (void*)offsetof( PolygonData, count ) ); + glVertexAttribPointer( instanceRadius, 1, GL_FLOAT, GL_FALSE, sizeof( PolygonData ), + (void*)offsetof( PolygonData, radius ) ); // color will get automatically expanded to floats in the shader - glVertexAttribPointer(instanceColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(PolygonData), - (void*)offsetof(PolygonData, color)); + glVertexAttribPointer( instanceColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( PolygonData ), + (void*)offsetof( PolygonData, color ) ); // These divisors tell glsl how to distribute per instance data - glVertexAttribDivisor(instanceTransform, 1); - glVertexAttribDivisor(instancePoint12, 1); - glVertexAttribDivisor(instancePoint34, 1); - glVertexAttribDivisor(instancePoint56, 1); - glVertexAttribDivisor(instancePoint78, 1); - glVertexAttribDivisor(instancePointCount, 1); - glVertexAttribDivisor(instanceRadius, 1); - glVertexAttribDivisor(instanceColor, 1); + glVertexAttribDivisor( instanceTransform, 1 ); + glVertexAttribDivisor( instancePoint12, 1 ); + glVertexAttribDivisor( instancePoint34, 1 ); + glVertexAttribDivisor( instancePoint56, 1 ); + glVertexAttribDivisor( instancePoint78, 1 ); + glVertexAttribDivisor( instancePointCount, 1 ); + glVertexAttribDivisor( instanceRadius, 1 ); + glVertexAttribDivisor( instanceColor, 1 ); CheckErrorGL(); // Cleanup - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindVertexArray(0); + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindVertexArray( 0 ); } void Destroy() { - if (m_vaoId) + if ( m_vaoId ) { - glDeleteVertexArrays(1, &m_vaoId); - glDeleteBuffers(2, m_vboIds); + glDeleteVertexArrays( 1, &m_vaoId ); + glDeleteBuffers( 2, m_vboIds ); m_vaoId = 0; } - if (m_programId) + if ( m_programId ) { - glDeleteProgram(m_programId); + glDeleteProgram( m_programId ); m_programId = 0; } } - void AddPolygon(const b2Transform& transform, const b2Vec2* points, int count, float radius, b2HexColor color) + void AddPolygon( const b2Transform& transform, const b2Vec2* points, int count, float radius, b2HexColor color ) { PolygonData data = {}; data.transform = transform; int n = count < 8 ? count : 8; b2Vec2* ps = &data.p1; - for (int i = 0; i < n; ++i) + for ( int i = 0; i < n; ++i ) { ps[i] = points[i]; } data.count = n; data.radius = radius; - data.color = MakeRGBA8(color, 1.0f); + data.color = MakeRGBA8( color, 1.0f ); - m_polygons.push_back(data); + m_polygons.push_back( data ); } void Flush() { int count = (int)m_polygons.size(); - if (count == 0) + if ( count == 0 ) { return; } - glUseProgram(m_programId); + glUseProgram( m_programId ); - float proj[16] = {0.0f}; - g_camera.BuildProjectionMatrix(proj, 0.2f); + float proj[16] = { 0.0f }; + g_camera.BuildProjectionMatrix( proj, 0.2f ); - glUniformMatrix4fv(m_projectionUniform, 1, GL_FALSE, proj); - glUniform1f(m_pixelScaleUniform, g_camera.m_height / g_camera.m_zoom); + glUniformMatrix4fv( m_projectionUniform, 1, GL_FALSE, proj ); + glUniform1f( m_pixelScaleUniform, g_camera.m_height / g_camera.m_zoom ); - glBindVertexArray(m_vaoId); - glBindBuffer(GL_ARRAY_BUFFER, m_vboIds[1]); + glBindVertexArray( m_vaoId ); + glBindBuffer( GL_ARRAY_BUFFER, m_vboIds[1] ); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glEnable( GL_BLEND ); + glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); int base = 0; - while (count > 0) + while ( count > 0 ) { - int batchCount = b2MinInt(count, e_maxCount); + int batchCount = b2MinInt( count, e_maxCount ); - glBufferSubData(GL_ARRAY_BUFFER, 0, batchCount * sizeof(PolygonData), &m_polygons[base]); - glDrawArraysInstanced(GL_TRIANGLES, 0, 6, batchCount); + glBufferSubData( GL_ARRAY_BUFFER, 0, batchCount * sizeof( PolygonData ), &m_polygons[base] ); + glDrawArraysInstanced( GL_TRIANGLES, 0, 6, batchCount ); CheckErrorGL(); count -= e_maxCount; base += e_maxCount; } - glDisable(GL_BLEND); + glDisable( GL_BLEND ); - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindVertexArray(0); - glUseProgram(0); + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindVertexArray( 0 ); + glUseProgram( 0 ); m_polygons.clear(); } @@ -1176,55 +1269,55 @@ struct GLSolidPolygons GLint m_pixelScaleUniform; }; -void DrawPolygonFcn(const b2Vec2* vertices, int vertexCount, b2HexColor color, void* context) +void DrawPolygonFcn( const b2Vec2* vertices, int vertexCount, b2HexColor color, void* context ) { - static_cast(context)->DrawPolygon(vertices, vertexCount, color); + static_cast( context )->DrawPolygon( vertices, vertexCount, color ); } -void DrawSolidPolygonFcn(b2Transform transform, const b2Vec2* vertices, int vertexCount, float radius, b2HexColor color, - void* context) +void DrawSolidPolygonFcn( b2Transform transform, const b2Vec2* vertices, int vertexCount, float radius, b2HexColor color, + void* context ) { - static_cast(context)->DrawSolidPolygon(transform, vertices, vertexCount, radius, color); + static_cast( context )->DrawSolidPolygon( transform, vertices, vertexCount, radius, color ); } -void DrawCircleFcn(b2Vec2 center, float radius, b2HexColor color, void* context) +void DrawCircleFcn( b2Vec2 center, float radius, b2HexColor color, void* context ) { - static_cast(context)->DrawCircle(center, radius, color); + static_cast( context )->DrawCircle( center, radius, color ); } -void DrawSolidCircleFcn(b2Transform transform, float radius, b2HexColor color, void* context) +void DrawSolidCircleFcn( b2Transform transform, float radius, b2HexColor color, void* context ) { - static_cast(context)->DrawSolidCircle(transform, b2Vec2_zero, radius, color); + static_cast( context )->DrawSolidCircle( transform, b2Vec2_zero, radius, color ); } -void DrawCapsuleFcn(b2Vec2 p1, b2Vec2 p2, float radius, b2HexColor color, void* context) +void DrawCapsuleFcn( b2Vec2 p1, b2Vec2 p2, float radius, b2HexColor color, void* context ) { - static_cast(context)->DrawCapsule(p1, p2, radius, color); + static_cast( context )->DrawCapsule( p1, p2, radius, color ); } -void DrawSolidCapsuleFcn(b2Vec2 p1, b2Vec2 p2, float radius, b2HexColor color, void* context) +void DrawSolidCapsuleFcn( b2Vec2 p1, b2Vec2 p2, float radius, b2HexColor color, void* context ) { - static_cast(context)->DrawSolidCapsule(p1, p2, radius, color); + static_cast( context )->DrawSolidCapsule( p1, p2, radius, color ); } -void DrawSegmentFcn(b2Vec2 p1, b2Vec2 p2, b2HexColor color, void* context) +void DrawSegmentFcn( b2Vec2 p1, b2Vec2 p2, b2HexColor color, void* context ) { - static_cast(context)->DrawSegment(p1, p2, color); + static_cast( context )->DrawSegment( p1, p2, color ); } -void DrawTransformFcn(b2Transform transform, void* context) +void DrawTransformFcn( b2Transform transform, void* context ) { - static_cast(context)->DrawTransform(transform); + static_cast( context )->DrawTransform( transform ); } -void DrawPointFcn(b2Vec2 p, float size, b2HexColor color, void* context) +void DrawPointFcn( b2Vec2 p, float size, b2HexColor color, void* context ) { - static_cast(context)->DrawPoint(p, size, color); + static_cast( context )->DrawPoint( p, size, color ); } -void DrawStringFcn(b2Vec2 p, const char* s, void* context) +void DrawStringFcn( b2Vec2 p, const char* s, void* context ) { - static_cast(context)->DrawString(p, s); + static_cast( context )->DrawString( p, s ); } Draw::Draw() @@ -1242,17 +1335,19 @@ Draw::Draw() Draw::~Draw() { - assert(m_points == nullptr); - assert(m_lines == nullptr); - assert(m_triangles == nullptr); - assert(m_circles == nullptr); - assert(m_solidCircles == nullptr); - assert(m_solidCapsules == nullptr); - assert(m_solidPolygons == nullptr); + assert( m_points == nullptr ); + assert( m_lines == nullptr ); + assert( m_triangles == nullptr ); + assert( m_circles == nullptr ); + assert( m_solidCircles == nullptr ); + assert( m_solidCapsules == nullptr ); + assert( m_solidPolygons == nullptr ); } void Draw::Create() { + m_background = new GLBackground; + m_background->Create(); m_points = new GLPoints; m_points->Create(); m_lines = new GLLines; @@ -1268,35 +1363,39 @@ void Draw::Create() m_solidPolygons = new GLSolidPolygons; m_solidPolygons->Create(); - b2AABB bounds = {{-FLT_MAX, -FLT_MAX}, {FLT_MAX, FLT_MAX}}; - - m_debugDraw = {DrawPolygonFcn, - DrawSolidPolygonFcn, - DrawCircleFcn, - DrawSolidCircleFcn, - DrawCapsuleFcn, - DrawSolidCapsuleFcn, - DrawSegmentFcn, - DrawTransformFcn, - DrawPointFcn, - DrawStringFcn, - bounds, - false, // drawUsingBounds - true, // shapes - true, // joints - false, // joint extras - false, // aabbs - false, // mass - false, // contacts - false, // colors - false, // normals - false, // impulse - false, // friction - this}; + b2AABB bounds = { { -FLT_MAX, -FLT_MAX }, { FLT_MAX, FLT_MAX } }; + + m_debugDraw = { DrawPolygonFcn, + DrawSolidPolygonFcn, + DrawCircleFcn, + DrawSolidCircleFcn, + DrawCapsuleFcn, + DrawSolidCapsuleFcn, + DrawSegmentFcn, + DrawTransformFcn, + DrawPointFcn, + DrawStringFcn, + bounds, + false, // drawUsingBounds + true, // shapes + true, // joints + false, // joint extras + false, // aabbs + false, // mass + false, // contacts + false, // colors + false, // normals + false, // impulse + false, // friction + this }; } void Draw::Destroy() { + m_background->Destroy(); + delete m_background; + m_background = nullptr; + m_points->Destroy(); delete m_points; m_points = nullptr; @@ -1326,114 +1425,114 @@ void Draw::Destroy() m_solidPolygons = nullptr; } -void Draw::DrawPolygon(const b2Vec2* vertices, int vertexCount, b2HexColor color) +void Draw::DrawPolygon( const b2Vec2* vertices, int vertexCount, b2HexColor color ) { b2Vec2 p1 = vertices[vertexCount - 1]; - for (int i = 0; i < vertexCount; ++i) + for ( int i = 0; i < vertexCount; ++i ) { b2Vec2 p2 = vertices[i]; - m_lines->AddLine(p1, p2, color); + m_lines->AddLine( p1, p2, color ); p1 = p2; } } -void Draw::DrawSolidPolygon(b2Transform transform, const b2Vec2* vertices, int vertexCount, float radius, b2HexColor color) +void Draw::DrawSolidPolygon( b2Transform transform, const b2Vec2* vertices, int vertexCount, float radius, b2HexColor color ) { - m_solidPolygons->AddPolygon(transform, vertices, vertexCount, radius, color); + m_solidPolygons->AddPolygon( transform, vertices, vertexCount, radius, color ); } -void Draw::DrawCircle(b2Vec2 center, float radius, b2HexColor color) +void Draw::DrawCircle( b2Vec2 center, float radius, b2HexColor color ) { - m_circles->AddCircle(center, radius, color); + m_circles->AddCircle( center, radius, color ); } -void Draw::DrawSolidCircle(b2Transform transform, b2Vec2 center, float radius, b2HexColor color) +void Draw::DrawSolidCircle( b2Transform transform, b2Vec2 center, float radius, b2HexColor color ) { - transform.p = b2TransformPoint(transform, center); - m_solidCircles->AddCircle(transform, radius, color); + transform.p = b2TransformPoint( transform, center ); + m_solidCircles->AddCircle( transform, radius, color ); } // todo this is not used -void Draw::DrawCapsule(b2Vec2 p1, b2Vec2 p2, float radius, b2HexColor color) +void Draw::DrawCapsule( b2Vec2 p1, b2Vec2 p2, float radius, b2HexColor color ) { float length; - b2Vec2 axis = b2GetLengthAndNormalize(&length, b2Sub(p2, p1)); + b2Vec2 axis = b2GetLengthAndNormalize( &length, b2Sub( p2, p1 ) ); - if (length == 0.0f) + if ( length == 0.0f ) { - DrawCircle(p1, radius, color); + DrawCircle( p1, radius, color ); } const float k_segments = 16.0f; const float k_increment = b2_pi / k_segments; - float sinInc = sinf(k_increment); - float cosInc = cosf(k_increment); + float sinInc = sinf( k_increment ); + float cosInc = cosf( k_increment ); - b2Vec2 r1 = {-axis.y, axis.x}; - b2Vec2 v1 = b2MulAdd(p1, radius, r1); + b2Vec2 r1 = { -axis.y, axis.x }; + b2Vec2 v1 = b2MulAdd( p1, radius, r1 ); b2Vec2 a = v1; - for (int i = 0; i < k_segments; ++i) + for ( int i = 0; i < k_segments; ++i ) { // Perform rotation to avoid additional trigonometry. b2Vec2 r2; r2.x = cosInc * r1.x - sinInc * r1.y; r2.y = sinInc * r1.x + cosInc * r1.y; - b2Vec2 v2 = b2MulAdd(p1, radius, r2); - m_lines->AddLine(v1, v2, color); + b2Vec2 v2 = b2MulAdd( p1, radius, r2 ); + m_lines->AddLine( v1, v2, color ); r1 = r2; v1 = v2; } b2Vec2 b = v1; - r1 = {axis.y, -axis.x}; - v1 = b2MulAdd(p2, radius, r1); + r1 = { axis.y, -axis.x }; + v1 = b2MulAdd( p2, radius, r1 ); b2Vec2 c = v1; - for (int i = 0; i < k_segments; ++i) + for ( int i = 0; i < k_segments; ++i ) { // Perform rotation to avoid additional trigonometry. b2Vec2 r2; r2.x = cosInc * r1.x - sinInc * r1.y; r2.y = sinInc * r1.x + cosInc * r1.y; - b2Vec2 v2 = b2MulAdd(p2, radius, r2); - m_lines->AddLine(v1, v2, color); + b2Vec2 v2 = b2MulAdd( p2, radius, r2 ); + m_lines->AddLine( v1, v2, color ); r1 = r2; v1 = v2; } b2Vec2 d = v1; - m_lines->AddLine(a, d, color); - m_lines->AddLine(b, c, color); - m_lines->AddLine(p1, p2, color); + m_lines->AddLine( a, d, color ); + m_lines->AddLine( b, c, color ); + m_lines->AddLine( p1, p2, color ); } -void Draw::DrawSolidCapsule(b2Vec2 p1, b2Vec2 p2, float radius, b2HexColor color) +void Draw::DrawSolidCapsule( b2Vec2 p1, b2Vec2 p2, float radius, b2HexColor color ) { - m_solidCapsules->AddCapsule(p1, p2, radius, color); + m_solidCapsules->AddCapsule( p1, p2, radius, color ); } -void Draw::DrawSegment(b2Vec2 p1, b2Vec2 p2, b2HexColor color) +void Draw::DrawSegment( b2Vec2 p1, b2Vec2 p2, b2HexColor color ) { - m_lines->AddLine(p1, p2, color); + m_lines->AddLine( p1, p2, color ); } -void Draw::DrawTransform(b2Transform transform) +void Draw::DrawTransform( b2Transform transform ) { const float k_axisScale = 0.2f; b2Vec2 p1 = transform.p; - b2Vec2 p2 = b2MulAdd(p1, k_axisScale, b2Rot_GetXAxis(transform.q)); - m_lines->AddLine(p1, p2, b2_colorRed); + b2Vec2 p2 = b2MulAdd( p1, k_axisScale, b2Rot_GetXAxis( transform.q ) ); + m_lines->AddLine( p1, p2, b2_colorRed ); - p2 = b2MulAdd(p1, k_axisScale, b2Rot_GetYAxis(transform.q)); - m_lines->AddLine(p1, p2, b2_colorGreen); + p2 = b2MulAdd( p1, k_axisScale, b2Rot_GetYAxis( transform.q ) ); + m_lines->AddLine( p1, p2, b2_colorGreen ); } -void Draw::DrawPoint(b2Vec2 p, float size, b2HexColor color) +void Draw::DrawPoint( b2Vec2 p, float size, b2HexColor color ) { - m_points->AddPoint(p, size, color); + m_points->AddPoint( p, size, color ); } -void Draw::DrawString(int x, int y, const char* string, ...) +void Draw::DrawString( int x, int y, const char* string, ... ) { // if (m_showUI == false) //{ @@ -1441,42 +1540,42 @@ void Draw::DrawString(int x, int y, const char* string, ...) // } va_list arg; - va_start(arg, string); - ImGui::Begin("Overlay", nullptr, - ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | - ImGuiWindowFlags_NoScrollbar); - ImGui::SetCursorPos(ImVec2(float(x), float(y))); - ImGui::TextColoredV(ImColor(230, 153, 153, 255), string, arg); + va_start( arg, string ); + ImGui::Begin( "Overlay", nullptr, + ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | + ImGuiWindowFlags_NoScrollbar ); + ImGui::SetCursorPos( ImVec2( float( x ), float( y ) ) ); + ImGui::TextColoredV( ImColor( 230, 153, 153, 255 ), string, arg ); ImGui::End(); - va_end(arg); + va_end( arg ); } -void Draw::DrawString(b2Vec2 p, const char* string, ...) +void Draw::DrawString( b2Vec2 p, const char* string, ... ) { - b2Vec2 ps = g_camera.ConvertWorldToScreen(p); + b2Vec2 ps = g_camera.ConvertWorldToScreen( p ); va_list arg; - va_start(arg, string); - ImGui::Begin("Overlay", nullptr, - ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | - ImGuiWindowFlags_NoScrollbar); - ImGui::SetCursorPos(ImVec2(ps.x, ps.y)); - ImGui::TextColoredV(ImColor(230, 230, 230, 255), string, arg); + va_start( arg, string ); + ImGui::Begin( "Overlay", nullptr, + ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | + ImGuiWindowFlags_NoScrollbar ); + ImGui::SetCursorPos( ImVec2( ps.x, ps.y ) ); + ImGui::TextColoredV( ImColor( 230, 230, 230, 255 ), string, arg ); ImGui::End(); - va_end(arg); + va_end( arg ); } -void Draw::DrawAABB(b2AABB aabb, b2HexColor c) +void Draw::DrawAABB( b2AABB aabb, b2HexColor c ) { b2Vec2 p1 = aabb.lowerBound; - b2Vec2 p2 = {aabb.upperBound.x, aabb.lowerBound.y}; + b2Vec2 p2 = { aabb.upperBound.x, aabb.lowerBound.y }; b2Vec2 p3 = aabb.upperBound; - b2Vec2 p4 = {aabb.lowerBound.x, aabb.upperBound.y}; + b2Vec2 p4 = { aabb.lowerBound.x, aabb.upperBound.y }; - m_lines->AddLine(p1, p2, c); - m_lines->AddLine(p2, p3, c); - m_lines->AddLine(p3, p4, c); - m_lines->AddLine(p4, p1, c); + m_lines->AddLine( p1, p2, c ); + m_lines->AddLine( p2, p3, c ); + m_lines->AddLine( p3, p4, c ); + m_lines->AddLine( p4, p1, c ); } void Draw::Flush() @@ -1490,3 +1589,8 @@ void Draw::Flush() m_points->Flush(); CheckErrorGL(); } + +void Draw::DrawBackground() +{ + m_background->Draw(); +} diff --git a/samples/draw.h b/samples/draw.h index 521bc01e..b52f4a06 100644 --- a/samples/draw.h +++ b/samples/draw.h @@ -11,9 +11,9 @@ struct Camera Camera(); void ResetView(); - b2Vec2 ConvertScreenToWorld(b2Vec2 screenPoint); - b2Vec2 ConvertWorldToScreen(b2Vec2 worldPoint); - void BuildProjectionMatrix(float* m, float zBias); + b2Vec2 ConvertScreenToWorld( b2Vec2 screenPoint ); + b2Vec2 ConvertWorldToScreen( b2Vec2 worldPoint ); + void BuildProjectionMatrix( float* m, float zBias ); b2AABB GetViewBounds(); b2Vec2 m_center; @@ -32,30 +32,32 @@ class Draw void Create(); void Destroy(); - void DrawPolygon(const b2Vec2* vertices, int32_t vertexCount, b2HexColor color); - void DrawSolidPolygon(b2Transform transform, const b2Vec2* vertices, int32_t vertexCount, float radius, b2HexColor color); + void DrawPolygon( const b2Vec2* vertices, int32_t vertexCount, b2HexColor color ); + void DrawSolidPolygon( b2Transform transform, const b2Vec2* vertices, int32_t vertexCount, float radius, b2HexColor color ); - void DrawCircle(b2Vec2 center, float radius, b2HexColor color); - void DrawSolidCircle(b2Transform transform, b2Vec2 center, float radius, b2HexColor color); + void DrawCircle( b2Vec2 center, float radius, b2HexColor color ); + void DrawSolidCircle( b2Transform transform, b2Vec2 center, float radius, b2HexColor color ); - void DrawCapsule(b2Vec2 p1, b2Vec2 p2, float radius, b2HexColor color); - void DrawSolidCapsule(b2Vec2 p1, b2Vec2 p2, float radius, b2HexColor color); + void DrawCapsule( b2Vec2 p1, b2Vec2 p2, float radius, b2HexColor color ); + void DrawSolidCapsule( b2Vec2 p1, b2Vec2 p2, float radius, b2HexColor color ); - void DrawSegment(b2Vec2 p1, b2Vec2 p2, b2HexColor color); + void DrawSegment( b2Vec2 p1, b2Vec2 p2, b2HexColor color ); - void DrawTransform(b2Transform transform); + void DrawTransform( b2Transform transform ); - void DrawPoint(b2Vec2 p, float size, b2HexColor color); + void DrawPoint( b2Vec2 p, float size, b2HexColor color ); - void DrawString(int x, int y, const char* string, ...); + void DrawString( int x, int y, const char* string, ... ); - void DrawString(b2Vec2 p, const char* string, ...); + void DrawString( b2Vec2 p, const char* string, ... ); - void DrawAABB(b2AABB aabb, b2HexColor color); + void DrawAABB( b2AABB aabb, b2HexColor color ); void Flush(); + void DrawBackground(); bool m_showUI; + struct GLBackground* m_background; struct GLPoints* m_points; struct GLLines* m_lines; struct GLTriangles* m_triangles; diff --git a/samples/human.cpp b/samples/human.cpp index ce03f865..70912a92 100644 --- a/samples/human.cpp +++ b/samples/human.cpp @@ -3,6 +3,8 @@ #include "human.h" +#include "sample.h" + #include "box2d/box2d.h" #include "box2d/math_functions.h" @@ -10,19 +12,22 @@ Human::Human() { - for (int i = 0; i < Bone::e_count; ++i) + for ( int i = 0; i < Bone::e_count; ++i ) { m_bones[i].bodyId = b2_nullBodyId; m_bones[i].jointId = b2_nullJointId; + m_bones[i].frictionScale = 1.0f; m_bones[i].parentIndex = -1; } + m_scale = 1.0f; m_isSpawned = false; } -void Human::Spawn(b2WorldId worldId, b2Vec2 position, float scale, int groupIndex, void* userData) +void Human::Spawn( b2WorldId worldId, b2Vec2 position, float scale, float frictionTorque, float hertz, float dampingRatio, + int groupIndex, void* userData, bool colorize ) { - assert(m_isSpawned == false); + assert( m_isSpawned == false ); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; @@ -32,146 +37,206 @@ void Human::Spawn(b2WorldId worldId, b2Vec2 position, float scale, int groupInde b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.friction = 0.2f; shapeDef.filter.groupIndex = -groupIndex; + shapeDef.filter.maskBits = 1; b2ShapeDef footShapeDef = shapeDef; footShapeDef.friction = 0.05f; + if ( colorize ) + { + footShapeDef.customColor = b2_colorSaddleBrown; + } + + m_scale = scale; float s = scale; - float maxTorque = 0.05f * s; + float maxTorque = frictionTorque * s; bool enableMotor = true; bool enableLimit = true; float drawSize = 0.05f; + b2HexColor shirtColor = b2_colorMediumTurquoise; + b2HexColor pantColor = b2_colorDodgerBlue; + + b2HexColor skinColors[4] = { b2_colorNavajoWhite, b2_colorLightYellow, b2_colorPeru, b2_colorTan }; + b2HexColor skinColor = skinColors[groupIndex % 4]; + // hip { Bone* bone = m_bones + Bone::e_hip; bone->parentIndex = -1; - - bodyDef.position = b2Add({0.0f, 0.95f * s}, position); - bone->bodyId = b2CreateBody(worldId, &bodyDef); - b2Capsule capsule = {{0.0f, -0.02f * s}, {0.0f, 0.02f * s}, 0.095f * s}; - b2CreateCapsuleShape(bone->bodyId, &shapeDef, &capsule); + bodyDef.position = b2Add( { 0.0f, 0.95f * s }, position ); + bodyDef.linearDamping = 0.0f; + bone->bodyId = b2CreateBody( worldId, &bodyDef ); + + if ( colorize ) + { + shapeDef.customColor = pantColor; + } + + b2Capsule capsule = { { 0.0f, -0.02f * s }, { 0.0f, 0.02f * s }, 0.095f * s }; + b2CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); } // torso { Bone* bone = m_bones + Bone::e_torso; bone->parentIndex = Bone::e_hip; - - bodyDef.position = b2Add({0.0f, 1.2f * s}, position); - //bodyDef.type = b2_staticBody; - bone->bodyId = b2CreateBody(worldId, &bodyDef); + + bodyDef.position = b2Add( { 0.0f, 1.2f * s }, position ); + bodyDef.linearDamping = 0.0f; + // bodyDef.type = b2_staticBody; + bone->bodyId = b2CreateBody( worldId, &bodyDef ); + bone->frictionScale = 0.5f; bodyDef.type = b2_dynamicBody; - b2Capsule capsule = {{0.0f, -0.135f * s}, {0.0f, 0.135f * s}, 0.09f * s}; - b2CreateCapsuleShape(bone->bodyId, &shapeDef, &capsule); + if ( colorize ) + { + shapeDef.customColor = shirtColor; + } + + b2Capsule capsule = { { 0.0f, -0.135f * s }, { 0.0f, 0.135f * s }, 0.09f * s }; + b2CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); - b2Vec2 pivot = b2Add({0.0f, 1.0f * s}, position); + b2Vec2 pivot = b2Add( { 0.0f, 1.0f * s }, position ); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.bodyIdA = m_bones[bone->parentIndex].bodyId; jointDef.bodyIdB = bone->bodyId; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); jointDef.enableLimit = enableLimit; jointDef.lowerAngle = -0.25f * b2_pi; jointDef.upperAngle = 0.0f; jointDef.enableMotor = enableMotor; - jointDef.maxMotorTorque = 0.5f * maxTorque; + jointDef.maxMotorTorque = bone->frictionScale * maxTorque; + jointDef.enableSpring = hertz > 0.0f; + jointDef.hertz = hertz; + jointDef.dampingRatio = dampingRatio; jointDef.drawSize = drawSize; - bone->jointId = b2CreateRevoluteJoint(worldId, &jointDef); + bone->jointId = b2CreateRevoluteJoint( worldId, &jointDef ); } // head { Bone* bone = m_bones + Bone::e_head; bone->parentIndex = Bone::e_torso; - - bodyDef.position = b2Add({0.0f * s, 1.5f * s}, position); - bone->bodyId = b2CreateBody(worldId, &bodyDef); - b2Capsule capsule = {{0.0f, -0.0325f * s}, {0.0f, 0.0325f * s}, 0.08f * s}; - b2CreateCapsuleShape(bone->bodyId, &shapeDef, &capsule); + bodyDef.position = b2Add( { 0.0f * s, 1.5f * s }, position ); + bodyDef.linearDamping = 0.1f; + + bone->bodyId = b2CreateBody( worldId, &bodyDef ); + bone->frictionScale = 0.25f; + + if ( colorize ) + { + shapeDef.customColor = skinColor; + } + + b2Capsule capsule = { { 0.0f, -0.0325f * s }, { 0.0f, 0.0325f * s }, 0.08f * s }; + b2CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); // neck - capsule = {{0.0f, -0.12f * s}, {0.0f, -0.08f * s}, 0.05f * s}; - b2CreateCapsuleShape(bone->bodyId, &shapeDef, &capsule); + capsule = { { 0.0f, -0.12f * s }, { 0.0f, -0.08f * s }, 0.05f * s }; + b2CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); - b2Vec2 pivot = b2Add({0.0f, 1.4f * s}, position); + b2Vec2 pivot = b2Add( { 0.0f, 1.4f * s }, position ); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.bodyIdA = m_bones[bone->parentIndex].bodyId; jointDef.bodyIdB = bone->bodyId; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); jointDef.enableLimit = enableLimit; jointDef.lowerAngle = -0.3f * b2_pi; jointDef.upperAngle = 0.1f * b2_pi; jointDef.enableMotor = enableMotor; - jointDef.maxMotorTorque = 0.25f * maxTorque; + jointDef.maxMotorTorque = bone->frictionScale * maxTorque; + jointDef.enableSpring = hertz > 0.0f; + jointDef.hertz = hertz; + jointDef.dampingRatio = dampingRatio; jointDef.drawSize = drawSize; - bone->jointId = b2CreateRevoluteJoint(worldId, &jointDef); + bone->jointId = b2CreateRevoluteJoint( worldId, &jointDef ); } // upper left leg { Bone* bone = m_bones + Bone::e_upperLeftLeg; bone->parentIndex = Bone::e_hip; - - bodyDef.position = b2Add({0.0f, 0.775f * s}, position); - bone->bodyId = b2CreateBody(worldId, &bodyDef); - b2Capsule capsule = {{0.0f, -0.125f * s}, {0.0f, 0.125f * s}, 0.06f * s}; - b2CreateCapsuleShape(bone->bodyId, &shapeDef, &capsule); + bodyDef.position = b2Add( { 0.0f, 0.775f * s }, position ); + bodyDef.linearDamping = 0.0f; + bone->bodyId = b2CreateBody( worldId, &bodyDef ); + bone->frictionScale = 1.0f; + + if ( colorize ) + { + shapeDef.customColor = pantColor; + } + + b2Capsule capsule = { { 0.0f, -0.125f * s }, { 0.0f, 0.125f * s }, 0.06f * s }; + b2CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); - b2Vec2 pivot = b2Add({0.0f, 0.9f * s}, position); + b2Vec2 pivot = b2Add( { 0.0f, 0.9f * s }, position ); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.bodyIdA = m_bones[bone->parentIndex].bodyId; jointDef.bodyIdB = bone->bodyId; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); jointDef.enableLimit = enableLimit; jointDef.lowerAngle = -0.05f * b2_pi; jointDef.upperAngle = 0.4f * b2_pi; jointDef.enableMotor = enableMotor; - jointDef.maxMotorTorque = maxTorque; + jointDef.maxMotorTorque = bone->frictionScale * maxTorque; + jointDef.enableSpring = hertz > 0.0f; + jointDef.hertz = hertz; + jointDef.dampingRatio = dampingRatio; jointDef.drawSize = drawSize; - bone->jointId = b2CreateRevoluteJoint(worldId, &jointDef); + bone->jointId = b2CreateRevoluteJoint( worldId, &jointDef ); } // lower left leg { Bone* bone = m_bones + Bone::e_lowerLeftLeg; bone->parentIndex = Bone::e_upperLeftLeg; - - bodyDef.position = b2Add({0.0f, 0.475f * s}, position); - bone->bodyId = b2CreateBody(worldId, &bodyDef); - b2Capsule capsule = {{0.0f, -0.14f * s}, {0.0f, 0.125f * s}, 0.05f * s}; - b2CreateCapsuleShape(bone->bodyId, &shapeDef, &capsule); + bodyDef.position = b2Add( { 0.0f, 0.475f * s }, position ); + bodyDef.linearDamping = 0.0f; + bone->bodyId = b2CreateBody( worldId, &bodyDef ); + bone->frictionScale = 0.5f; + + if ( colorize ) + { + shapeDef.customColor = pantColor; + } + + b2Capsule capsule = { { 0.0f, -0.14f * s }, { 0.0f, 0.125f * s }, 0.05f * s }; + b2CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); - //b2Polygon box = b2MakeOffsetBox(0.1f * s, 0.03f * s, {0.05f * s, -0.175f * s}, 0.0f); - //b2CreatePolygonShape(bone->bodyId, &shapeDef, &box); + // b2Polygon box = b2MakeOffsetBox(0.1f * s, 0.03f * s, {0.05f * s, -0.175f * s}, 0.0f); + // b2CreatePolygonShape(bone->bodyId, &shapeDef, &box); - capsule = {{-0.02f * s, -0.175f * s}, {0.13f * s, -0.175f * s}, 0.03f * s}; - b2CreateCapsuleShape(bone->bodyId, &footShapeDef, &capsule); + capsule = { { -0.02f * s, -0.175f * s }, { 0.13f * s, -0.175f * s }, 0.03f * s }; + b2CreateCapsuleShape( bone->bodyId, &footShapeDef, &capsule ); - b2Vec2 pivot = b2Add({0.0f, 0.625f * s}, position); + b2Vec2 pivot = b2Add( { 0.0f, 0.625f * s }, position ); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.bodyIdA = m_bones[bone->parentIndex].bodyId; jointDef.bodyIdB = bone->bodyId; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); jointDef.enableLimit = enableLimit; jointDef.lowerAngle = -0.5f * b2_pi; jointDef.upperAngle = -0.02f * b2_pi; jointDef.enableMotor = enableMotor; - jointDef.maxMotorTorque = 0.5f * maxTorque; + jointDef.maxMotorTorque = bone->frictionScale * maxTorque; + jointDef.enableSpring = hertz > 0.0f; + jointDef.hertz = hertz; + jointDef.dampingRatio = dampingRatio; jointDef.drawSize = drawSize; - bone->jointId = b2CreateRevoluteJoint(worldId, &jointDef); + bone->jointId = b2CreateRevoluteJoint( worldId, &jointDef ); } // upper right leg @@ -179,26 +244,36 @@ void Human::Spawn(b2WorldId worldId, b2Vec2 position, float scale, int groupInde Bone* bone = m_bones + Bone::e_upperRightLeg; bone->parentIndex = Bone::e_hip; - bodyDef.position = b2Add({0.0f, 0.775f * s}, position); - bone->bodyId = b2CreateBody(worldId, &bodyDef); + bodyDef.position = b2Add( { 0.0f, 0.775f * s }, position ); + bodyDef.linearDamping = 0.0f; + bone->bodyId = b2CreateBody( worldId, &bodyDef ); + bone->frictionScale = 1.0f; - b2Capsule capsule = {{0.0f, -0.125f * s}, {0.0f, 0.125f * s}, 0.06f * s}; - b2CreateCapsuleShape(bone->bodyId, &shapeDef, &capsule); + if ( colorize ) + { + shapeDef.customColor = pantColor; + } + + b2Capsule capsule = { { 0.0f, -0.125f * s }, { 0.0f, 0.125f * s }, 0.06f * s }; + b2CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); - b2Vec2 pivot = b2Add({0.0f, 0.9f * s}, position); + b2Vec2 pivot = b2Add( { 0.0f, 0.9f * s }, position ); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.bodyIdA = m_bones[bone->parentIndex].bodyId; jointDef.bodyIdB = bone->bodyId; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); jointDef.enableLimit = enableLimit; jointDef.lowerAngle = -0.05f * b2_pi; jointDef.upperAngle = 0.4f * b2_pi; jointDef.enableMotor = enableMotor; - jointDef.maxMotorTorque = maxTorque; + jointDef.maxMotorTorque = bone->frictionScale * maxTorque; + jointDef.enableSpring = hertz > 0.0f; + jointDef.hertz = hertz; + jointDef.dampingRatio = dampingRatio; jointDef.drawSize = drawSize; - bone->jointId = b2CreateRevoluteJoint(worldId, &jointDef); + bone->jointId = b2CreateRevoluteJoint( worldId, &jointDef ); } // lower right leg @@ -206,59 +281,79 @@ void Human::Spawn(b2WorldId worldId, b2Vec2 position, float scale, int groupInde Bone* bone = m_bones + Bone::e_lowerRightLeg; bone->parentIndex = Bone::e_upperRightLeg; - bodyDef.position = b2Add({0.0f, 0.475f * s}, position); - bone->bodyId = b2CreateBody(worldId, &bodyDef); + bodyDef.position = b2Add( { 0.0f, 0.475f * s }, position ); + bodyDef.linearDamping = 0.0f; + bone->bodyId = b2CreateBody( worldId, &bodyDef ); + bone->frictionScale = 0.5f; + + if ( colorize ) + { + shapeDef.customColor = pantColor; + } - b2Capsule capsule = {{0.0f, -0.14f * s}, {0.0f, 0.125f * s}, 0.05f * s}; - b2CreateCapsuleShape(bone->bodyId, &shapeDef, &capsule); + b2Capsule capsule = { { 0.0f, -0.14f * s }, { 0.0f, 0.125f * s }, 0.05f * s }; + b2CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); - //b2Polygon box = b2MakeOffsetBox(0.1f * s, 0.03f * s, {0.05f * s, -0.175f * s}, 0.0f); - //b2CreatePolygonShape(bone->bodyId, &shapeDef, &box); + // b2Polygon box = b2MakeOffsetBox(0.1f * s, 0.03f * s, {0.05f * s, -0.175f * s}, 0.0f); + // b2CreatePolygonShape(bone->bodyId, &shapeDef, &box); - capsule = {{-0.02f * s, -0.175f * s}, {0.13f * s, -0.175f * s}, 0.03f * s}; - b2CreateCapsuleShape(bone->bodyId, &footShapeDef, &capsule); + capsule = { { -0.02f * s, -0.175f * s }, { 0.13f * s, -0.175f * s }, 0.03f * s }; + b2CreateCapsuleShape( bone->bodyId, &footShapeDef, &capsule ); - b2Vec2 pivot = b2Add({0.0f, 0.625f * s}, position); + b2Vec2 pivot = b2Add( { 0.0f, 0.625f * s }, position ); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.bodyIdA = m_bones[bone->parentIndex].bodyId; jointDef.bodyIdB = bone->bodyId; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); jointDef.enableLimit = enableLimit; jointDef.lowerAngle = -0.5f * b2_pi; jointDef.upperAngle = -0.02f * b2_pi; jointDef.enableMotor = enableMotor; - jointDef.maxMotorTorque = 0.5f * maxTorque; + jointDef.maxMotorTorque = bone->frictionScale * maxTorque; + jointDef.enableSpring = hertz > 0.0f; + jointDef.hertz = hertz; + jointDef.dampingRatio = dampingRatio; jointDef.drawSize = drawSize; - bone->jointId = b2CreateRevoluteJoint(worldId, &jointDef); + bone->jointId = b2CreateRevoluteJoint( worldId, &jointDef ); } // upper left arm { Bone* bone = m_bones + Bone::e_upperLeftArm; bone->parentIndex = Bone::e_torso; + bone->frictionScale = 0.5f; - bodyDef.position = b2Add({0.0f, 1.225f * s}, position); - bone->bodyId = b2CreateBody(worldId, &bodyDef); + bodyDef.position = b2Add( { 0.0f, 1.225f * s }, position ); + bodyDef.linearDamping = 0.0f; + bone->bodyId = b2CreateBody( worldId, &bodyDef ); - b2Capsule capsule = {{0.0f, -0.125f * s}, {0.0f, 0.125f * s}, 0.035f * s}; - b2CreateCapsuleShape(bone->bodyId, &shapeDef, &capsule); + if ( colorize ) + { + shapeDef.customColor = shirtColor; + } + + b2Capsule capsule = { { 0.0f, -0.125f * s }, { 0.0f, 0.125f * s }, 0.035f * s }; + b2CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); - b2Vec2 pivot = b2Add({0.0f, 1.35f * s}, position); + b2Vec2 pivot = b2Add( { 0.0f, 1.35f * s }, position ); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.bodyIdA = m_bones[bone->parentIndex].bodyId; jointDef.bodyIdB = bone->bodyId; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); jointDef.enableLimit = enableLimit; - jointDef.lowerAngle = 0.05f * b2_pi; + jointDef.lowerAngle = -0.1f * b2_pi; jointDef.upperAngle = 0.8f * b2_pi; jointDef.enableMotor = enableMotor; - jointDef.maxMotorTorque = 0.5f * maxTorque; + jointDef.maxMotorTorque = bone->frictionScale * maxTorque; + jointDef.enableSpring = hertz > 0.0f; + jointDef.hertz = hertz; + jointDef.dampingRatio = dampingRatio; jointDef.drawSize = drawSize; - bone->jointId = b2CreateRevoluteJoint(worldId, &jointDef); + bone->jointId = b2CreateRevoluteJoint( worldId, &jointDef ); } // lower left arm @@ -266,26 +361,36 @@ void Human::Spawn(b2WorldId worldId, b2Vec2 position, float scale, int groupInde Bone* bone = m_bones + Bone::e_lowerLeftArm; bone->parentIndex = Bone::e_upperLeftArm; - bodyDef.position = b2Add({0.0f, 0.975f * s}, position); - bone->bodyId = b2CreateBody(worldId, &bodyDef); + bodyDef.position = b2Add( { 0.0f, 0.975f * s }, position ); + bodyDef.linearDamping = 0.1f; + bone->bodyId = b2CreateBody( worldId, &bodyDef ); + bone->frictionScale = 0.1f; + + if ( colorize ) + { + shapeDef.customColor = skinColor; + } - b2Capsule capsule = {{0.0f, -0.125f * s}, {0.0f, 0.125f * s}, 0.03f * s}; - b2CreateCapsuleShape(bone->bodyId, &shapeDef, &capsule); + b2Capsule capsule = { { 0.0f, -0.125f * s }, { 0.0f, 0.125f * s }, 0.03f * s }; + b2CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); - b2Vec2 pivot = b2Add({0.0f, 1.1f * s}, position); + b2Vec2 pivot = b2Add( { 0.0f, 1.1f * s }, position ); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.bodyIdA = m_bones[bone->parentIndex].bodyId; jointDef.bodyIdB = bone->bodyId; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); jointDef.enableLimit = enableLimit; jointDef.lowerAngle = 0.01f * b2_pi; jointDef.upperAngle = 0.5f * b2_pi; jointDef.enableMotor = enableMotor; - jointDef.maxMotorTorque = 0.1f * maxTorque; + jointDef.maxMotorTorque = bone->frictionScale * maxTorque; + jointDef.enableSpring = hertz > 0.0f; + jointDef.hertz = hertz; + jointDef.dampingRatio = dampingRatio; jointDef.drawSize = drawSize; - bone->jointId = b2CreateRevoluteJoint(worldId, &jointDef); + bone->jointId = b2CreateRevoluteJoint( worldId, &jointDef ); } // upper right arm @@ -293,26 +398,36 @@ void Human::Spawn(b2WorldId worldId, b2Vec2 position, float scale, int groupInde Bone* bone = m_bones + Bone::e_upperRightArm; bone->parentIndex = Bone::e_torso; - bodyDef.position = b2Add({0.0f, 1.225f * s}, position); - bone->bodyId = b2CreateBody(worldId, &bodyDef); + bodyDef.position = b2Add( { 0.0f, 1.225f * s }, position ); + bodyDef.linearDamping = 0.0f; + bone->bodyId = b2CreateBody( worldId, &bodyDef ); + bone->frictionScale = 0.5f; - b2Capsule capsule = {{0.0f, -0.125f * s}, {0.0f, 0.125f * s}, 0.035f * s}; - b2CreateCapsuleShape(bone->bodyId, &shapeDef, &capsule); + if ( colorize ) + { + shapeDef.customColor = shirtColor; + } + + b2Capsule capsule = { { 0.0f, -0.125f * s }, { 0.0f, 0.125f * s }, 0.035f * s }; + b2CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); - b2Vec2 pivot = b2Add({0.0f, 1.35f * s}, position); + b2Vec2 pivot = b2Add( { 0.0f, 1.35f * s }, position ); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.bodyIdA = m_bones[bone->parentIndex].bodyId; jointDef.bodyIdB = bone->bodyId; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); jointDef.enableLimit = enableLimit; - jointDef.lowerAngle = 0.05f * b2_pi; + jointDef.lowerAngle = -0.1f * b2_pi; jointDef.upperAngle = 0.8f * b2_pi; jointDef.enableMotor = enableMotor; - jointDef.maxMotorTorque = 0.5f * maxTorque; + jointDef.maxMotorTorque = bone->frictionScale * maxTorque; + jointDef.enableSpring = hertz > 0.0f; + jointDef.hertz = hertz; + jointDef.dampingRatio = dampingRatio; jointDef.drawSize = drawSize; - bone->jointId = b2CreateRevoluteJoint(worldId, &jointDef); + bone->jointId = b2CreateRevoluteJoint( worldId, &jointDef ); } // lower right arm @@ -320,26 +435,36 @@ void Human::Spawn(b2WorldId worldId, b2Vec2 position, float scale, int groupInde Bone* bone = m_bones + Bone::e_lowerRightArm; bone->parentIndex = Bone::e_upperRightArm; - bodyDef.position = b2Add({0.0f, 0.975f * s}, position); - bone->bodyId = b2CreateBody(worldId, &bodyDef); + bodyDef.position = b2Add( { 0.0f, 0.975f * s }, position ); + bodyDef.linearDamping = 0.1f; + bone->bodyId = b2CreateBody( worldId, &bodyDef ); + bone->frictionScale = 0.1f; - b2Capsule capsule = {{0.0f, -0.125f * s}, {0.0f, 0.125f * s}, 0.03f * s}; - b2CreateCapsuleShape(bone->bodyId, &shapeDef, &capsule); + if ( colorize ) + { + shapeDef.customColor = skinColor; + } - b2Vec2 pivot = b2Add({0.0f, 1.1f * s}, position); + b2Capsule capsule = { { 0.0f, -0.125f * s }, { 0.0f, 0.125f * s }, 0.03f * s }; + b2CreateCapsuleShape( bone->bodyId, &shapeDef, &capsule ); + + b2Vec2 pivot = b2Add( { 0.0f, 1.1f * s }, position ); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.bodyIdA = m_bones[bone->parentIndex].bodyId; jointDef.bodyIdB = bone->bodyId; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); jointDef.enableLimit = enableLimit; jointDef.lowerAngle = 0.01f * b2_pi; jointDef.upperAngle = 0.5f * b2_pi; jointDef.enableMotor = enableMotor; - jointDef.maxMotorTorque = 0.1f * maxTorque; + jointDef.maxMotorTorque = bone->frictionScale * maxTorque; + jointDef.enableSpring = hertz > 0.0f; + jointDef.hertz = hertz; + jointDef.dampingRatio = dampingRatio; jointDef.drawSize = drawSize; - bone->jointId = b2CreateRevoluteJoint(worldId, &jointDef); + bone->jointId = b2CreateRevoluteJoint( worldId, &jointDef ); } m_isSpawned = true; @@ -347,29 +472,102 @@ void Human::Spawn(b2WorldId worldId, b2Vec2 position, float scale, int groupInde void Human::Despawn() { - assert(m_isSpawned == true); + assert( m_isSpawned == true ); - for (int i = 0; i < Bone::e_count; ++i) + for ( int i = 0; i < Bone::e_count; ++i ) { - if (B2_IS_NULL(m_bones[i].jointId)) + if ( B2_IS_NULL( m_bones[i].jointId ) ) { continue; } - b2DestroyJoint(m_bones[i].jointId); + b2DestroyJoint( m_bones[i].jointId ); m_bones[i].jointId = b2_nullJointId; } - for (int i = 0; i < Bone::e_count; ++i) + for ( int i = 0; i < Bone::e_count; ++i ) { - if (B2_IS_NULL(m_bones[i].bodyId)) + if ( B2_IS_NULL( m_bones[i].bodyId ) ) { continue; } - b2DestroyBody(m_bones[i].bodyId); + b2DestroyBody( m_bones[i].bodyId ); m_bones[i].bodyId = b2_nullBodyId; } m_isSpawned = false; } + +void Human::ApplyRandomAngularImpulse( float magnitude ) +{ + if ( m_isSpawned == false ) + { + return; + } + + float impulse = RandomFloat( -magnitude, magnitude ); + b2Body_ApplyAngularImpulse( m_bones[Bone::e_torso].bodyId, impulse, true ); +} + +void Human::SetJointFrictionTorque( float torque ) +{ + if ( m_isSpawned == false ) + { + return; + } + + if ( torque == 0.0f ) + { + for ( int i = 1; i < Bone::e_count; ++i ) + { + b2RevoluteJoint_EnableMotor( m_bones[i].jointId, false ); + } + } + else + { + for ( int i = 1; i < Bone::e_count; ++i ) + { + b2RevoluteJoint_EnableMotor( m_bones[i].jointId, true ); + float scale = m_scale * m_bones[i].frictionScale; + b2RevoluteJoint_SetMaxMotorTorque( m_bones[i].jointId, scale * torque ); + } + } +} + +void Human::SetJointSpringHertz( float hertz ) +{ + if ( m_isSpawned == false ) + { + return; + } + + if ( hertz == 0.0f ) + { + for ( int i = 1; i < Bone::e_count; ++i ) + { + b2RevoluteJoint_EnableSpring( m_bones[i].jointId, false ); + } + } + else + { + for ( int i = 1; i < Bone::e_count; ++i ) + { + b2RevoluteJoint_EnableSpring( m_bones[i].jointId, true ); + b2RevoluteJoint_SetSpringHertz( m_bones[i].jointId, hertz ); + } + } +} + +void Human::SetJointDampingRatio( float dampingRatio ) +{ + if ( m_isSpawned == false ) + { + return; + } + + for ( int i = 1; i < Bone::e_count; ++i ) + { + b2RevoluteJoint_SetSpringDampingRatio( m_bones[i].jointId, dampingRatio ); + } +} diff --git a/samples/human.h b/samples/human.h index c5e46d5f..306a867d 100644 --- a/samples/human.h +++ b/samples/human.h @@ -25,17 +25,25 @@ struct Bone b2BodyId bodyId; b2JointId jointId; + float frictionScale; int parentIndex; }; class Human { - public: +public: Human(); - void Spawn(b2WorldId worldId, b2Vec2 position, float scale, int groupIndex, void* userData); + void Spawn( b2WorldId worldId, b2Vec2 position, float scale, float frictionTorque, float hertz, float dampingRatio, + int groupIndex, void* userData, bool colorize ); void Despawn(); + void ApplyRandomAngularImpulse( float magnitude ); + void SetJointFrictionTorque( float torque ); + void SetJointSpringHertz( float hertz ); + void SetJointDampingRatio( float dampingRatio ); + Bone m_bones[Bone::e_count]; + float m_scale; bool m_isSpawned; }; diff --git a/samples/main.cpp b/samples/main.cpp index 09bbc11d..576b4d1c 100644 --- a/samples/main.cpp +++ b/samples/main.cpp @@ -28,14 +28,14 @@ #define FrameMark #endif -#if defined(_WIN32) +#if defined( _WIN32 ) #include -static int MyAllocHook(int allocType, void* userData, size_t size, int blockType, long requestNumber, - const unsigned char* filename, int lineNumber) +static int MyAllocHook( int allocType, void* userData, size_t size, int blockType, long requestNumber, + const unsigned char* filename, int lineNumber ) { // This hook can help find leaks - if (size == 143) + if ( size == 143 ) { size += 0; } @@ -53,57 +53,57 @@ static b2Vec2 s_clickPointWS = b2Vec2_zero; static float s_windowScale = 1.0f; static float s_framebufferScale = 1.0f; -inline bool IsPowerOfTwo(int32_t x) +inline bool IsPowerOfTwo( int32_t x ) { - return (x != 0) && ((x & (x - 1)) == 0); + return ( x != 0 ) && ( ( x & ( x - 1 ) ) == 0 ); } -void* AllocFcn(uint32_t size, int32_t alignment) +void* AllocFcn( uint32_t size, int32_t alignment ) { // Allocation must be a multiple of alignment or risk a seg fault // https://en.cppreference.com/w/c/memory/aligned_alloc - assert(IsPowerOfTwo(alignment)); - size_t sizeAligned = ((size - 1) | (alignment - 1)) + 1; - assert((sizeAligned & (alignment - 1)) == 0); + assert( IsPowerOfTwo( alignment ) ); + size_t sizeAligned = ( ( size - 1 ) | ( alignment - 1 ) ) + 1; + assert( ( sizeAligned & ( alignment - 1 ) ) == 0 ); -#if defined(_WIN64) - void* ptr = _aligned_malloc(sizeAligned, alignment); +#if defined( _WIN64 ) + void* ptr = _aligned_malloc( sizeAligned, alignment ); #else - void* ptr = aligned_alloc(alignment, sizeAligned); + void* ptr = aligned_alloc( alignment, sizeAligned ); #endif - assert(ptr != nullptr); + assert( ptr != nullptr ); return ptr; } -void FreeFcn(void* mem) +void FreeFcn( void* mem ) { -#if defined(_WIN64) - _aligned_free(mem); +#if defined( _WIN64 ) + _aligned_free( mem ); #else - free(mem); + free( mem ); #endif } -int AssertFcn(const char* condition, const char* fileName, int lineNumber) +int AssertFcn( const char* condition, const char* fileName, int lineNumber ) { - printf("SAMPLE ASSERTION: %s, %s, line %d\n", condition, fileName, lineNumber); + printf( "SAMPLE ASSERTION: %s, %s, line %d\n", condition, fileName, lineNumber ); return 1; } -void glfwErrorCallback(int error, const char* description) +void glfwErrorCallback( int error, const char* description ) { - fprintf(stderr, "GLFW error occurred. Code: %d. Description: %s\n", error, description); + fprintf( stderr, "GLFW error occurred. Code: %d. Description: %s\n", error, description ); } -static inline int CompareSamples(const void* a, const void* b) +static inline int CompareSamples( const void* a, const void* b ) { SampleEntry* sa = (SampleEntry*)a; SampleEntry* sb = (SampleEntry*)b; - int result = strcmp(sa->category, sb->category); - if (result == 0) + int result = strcmp( sa->category, sb->category ); + if ( result == 0 ) { - result = strcmp(sa->name, sb->name); + result = strcmp( sa->name, sb->name ); } return result; @@ -111,7 +111,7 @@ static inline int CompareSamples(const void* a, const void* b) static void SortTests() { - qsort(g_sampleEntries, g_sampleCount, sizeof(SampleEntry), CompareSamples); + qsort( g_sampleEntries, g_sampleCount, sizeof( SampleEntry ), CompareSamples ); } static void RestartSample() @@ -119,45 +119,45 @@ static void RestartSample() delete s_sample; s_sample = nullptr; s_settings.restart = true; - s_sample = g_sampleEntries[s_settings.sampleIndex].createFcn(s_settings); + s_sample = g_sampleEntries[s_settings.sampleIndex].createFcn( s_settings ); s_settings.restart = false; } -static void CreateUI(GLFWwindow* window, const char* glslVersion) +static void CreateUI( GLFWwindow* window, const char* glslVersion ) { IMGUI_CHECKVERSION(); ImGui::CreateContext(); - bool success = ImGui_ImplGlfw_InitForOpenGL(window, false); - if (success == false) + bool success = ImGui_ImplGlfw_InitForOpenGL( window, false ); + if ( success == false ) { - printf("ImGui_ImplGlfw_InitForOpenGL failed\n"); - assert(false); + printf( "ImGui_ImplGlfw_InitForOpenGL failed\n" ); + assert( false ); } - success = ImGui_ImplOpenGL3_Init(glslVersion); - if (success == false) + success = ImGui_ImplOpenGL3_Init( glslVersion ); + if ( success == false ) { - printf("ImGui_ImplOpenGL3_Init failed\n"); - assert(false); + printf( "ImGui_ImplOpenGL3_Init failed\n" ); + assert( false ); } // this doesn't look that good // Search for font file const char* fontPath = "samples/data/droid_sans.ttf"; - FILE* file = fopen(fontPath, "rb"); + FILE* file = fopen( fontPath, "rb" ); - if (file != NULL) + if ( file != NULL ) { ImFontConfig fontConfig; fontConfig.RasterizerMultiply = s_windowScale * s_framebufferScale; - ImGui::GetIO().Fonts->AddFontFromFileTTF(fontPath, 14.0f, &fontConfig); - ImGui::GetIO().Fonts->AddFontFromFileTTF(fontPath, 128.0f, &fontConfig); + ImGui::GetIO().Fonts->AddFontFromFileTTF( fontPath, 14.0f, &fontConfig ); + ImGui::GetIO().Fonts->AddFontFromFileTTF( fontPath, 48.0f, &fontConfig ); } else { - printf("\n\nERROR: the Box2D samples working directory must be the top level Box2D directory (same as README.md)\n\n"); - exit(EXIT_FAILURE); + printf( "\n\nERROR: the Box2D samples working directory must be the top level Box2D directory (same as README.md)\n\n" ); + exit( EXIT_FAILURE ); } } @@ -168,37 +168,37 @@ static void DestroyUI() ImGui::DestroyContext(); } -static void ResizeWindowCallback(GLFWwindow*, int width, int height) +static void ResizeWindowCallback( GLFWwindow*, int width, int height ) { - g_camera.m_width = int(width / s_windowScale); - g_camera.m_height = int(height / s_windowScale); - s_settings.windowWidth = int(width / s_windowScale); - s_settings.windowHeight = int(height / s_windowScale); + g_camera.m_width = int( width / s_windowScale ); + g_camera.m_height = int( height / s_windowScale ); + s_settings.windowWidth = int( width / s_windowScale ); + s_settings.windowHeight = int( height / s_windowScale ); } -static void KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) +static void KeyCallback( GLFWwindow* window, int key, int scancode, int action, int mods ) { - ImGui_ImplGlfw_KeyCallback(window, key, scancode, action, mods); - if (ImGui::GetIO().WantCaptureKeyboard) + ImGui_ImplGlfw_KeyCallback( window, key, scancode, action, mods ); + if ( ImGui::GetIO().WantCaptureKeyboard ) { return; } - if (action == GLFW_PRESS) + if ( action == GLFW_PRESS ) { - switch (key) + switch ( key ) { case GLFW_KEY_ESCAPE: // Quit - glfwSetWindowShouldClose(g_mainWindow, GL_TRUE); + glfwSetWindowShouldClose( g_mainWindow, GL_TRUE ); break; case GLFW_KEY_LEFT: // Pan left - if (mods == GLFW_MOD_CONTROL) + if ( mods == GLFW_MOD_CONTROL ) { - b2Vec2 newOrigin = {2.0f, 0.0f}; - s_sample->ShiftOrigin(newOrigin); + b2Vec2 newOrigin = { 2.0f, 0.0f }; + s_sample->ShiftOrigin( newOrigin ); } else { @@ -208,10 +208,10 @@ static void KeyCallback(GLFWwindow* window, int key, int scancode, int action, i case GLFW_KEY_RIGHT: // Pan right - if (mods == GLFW_MOD_CONTROL) + if ( mods == GLFW_MOD_CONTROL ) { - b2Vec2 newOrigin = {-2.0f, 0.0f}; - s_sample->ShiftOrigin(newOrigin); + b2Vec2 newOrigin = { -2.0f, 0.0f }; + s_sample->ShiftOrigin( newOrigin ); } else { @@ -221,10 +221,10 @@ static void KeyCallback(GLFWwindow* window, int key, int scancode, int action, i case GLFW_KEY_DOWN: // Pan down - if (mods == GLFW_MOD_CONTROL) + if ( mods == GLFW_MOD_CONTROL ) { - b2Vec2 newOrigin = {0.0f, 2.0f}; - s_sample->ShiftOrigin(newOrigin); + b2Vec2 newOrigin = { 0.0f, 2.0f }; + s_sample->ShiftOrigin( newOrigin ); } else { @@ -234,10 +234,10 @@ static void KeyCallback(GLFWwindow* window, int key, int scancode, int action, i case GLFW_KEY_UP: // Pan up - if (mods == GLFW_MOD_CONTROL) + if ( mods == GLFW_MOD_CONTROL ) { - b2Vec2 newOrigin = {0.0f, -2.0f}; - s_sample->ShiftOrigin(newOrigin); + b2Vec2 newOrigin = { 0.0f, -2.0f }; + s_sample->ShiftOrigin( newOrigin ); } else { @@ -264,7 +264,7 @@ static void KeyCallback(GLFWwindow* window, int key, int scancode, int action, i case GLFW_KEY_LEFT_BRACKET: // Switch to previous test --s_selection; - if (s_selection < 0) + if ( s_selection < 0 ) { s_selection = g_sampleCount - 1; } @@ -273,7 +273,7 @@ static void KeyCallback(GLFWwindow* window, int key, int scancode, int action, i case GLFW_KEY_RIGHT_BRACKET: // Switch to next test ++s_selection; - if (s_selection == g_sampleCount) + if ( s_selection == g_sampleCount ) { s_selection = 0; } @@ -283,88 +283,88 @@ static void KeyCallback(GLFWwindow* window, int key, int scancode, int action, i g_draw.m_showUI = !g_draw.m_showUI; default: - if (s_sample) + if ( s_sample ) { - s_sample->Keyboard(key); + s_sample->Keyboard( key ); } } } } -static void CharCallback(GLFWwindow* window, unsigned int c) +static void CharCallback( GLFWwindow* window, unsigned int c ) { - ImGui_ImplGlfw_CharCallback(window, c); + ImGui_ImplGlfw_CharCallback( window, c ); } -static void MouseButtonCallback(GLFWwindow* window, int32_t button, int32_t action, int32_t mods) +static void MouseButtonCallback( GLFWwindow* window, int32_t button, int32_t action, int32_t mods ) { - ImGui_ImplGlfw_MouseButtonCallback(window, button, action, mods); + ImGui_ImplGlfw_MouseButtonCallback( window, button, action, mods ); - if (ImGui::GetIO().WantCaptureMouse) + if ( ImGui::GetIO().WantCaptureMouse ) { return; } double xd, yd; - glfwGetCursorPos(g_mainWindow, &xd, &yd); - b2Vec2 ps = {float(xd) / s_windowScale, float(yd) / s_windowScale}; + glfwGetCursorPos( g_mainWindow, &xd, &yd ); + b2Vec2 ps = { float( xd ) / s_windowScale, float( yd ) / s_windowScale }; // Use the mouse to move things around. - if (button == GLFW_MOUSE_BUTTON_1) + if ( button == GLFW_MOUSE_BUTTON_1 ) { - b2Vec2 pw = g_camera.ConvertScreenToWorld(ps); - if (action == GLFW_PRESS) + b2Vec2 pw = g_camera.ConvertScreenToWorld( ps ); + if ( action == GLFW_PRESS ) { - s_sample->MouseDown(pw, button, mods); + s_sample->MouseDown( pw, button, mods ); } - if (action == GLFW_RELEASE) + if ( action == GLFW_RELEASE ) { - s_sample->MouseUp(pw, button); + s_sample->MouseUp( pw, button ); } } - else if (button == GLFW_MOUSE_BUTTON_2) + else if ( button == GLFW_MOUSE_BUTTON_2 ) { - if (action == GLFW_PRESS) + if ( action == GLFW_PRESS ) { - s_clickPointWS = g_camera.ConvertScreenToWorld(ps); + s_clickPointWS = g_camera.ConvertScreenToWorld( ps ); s_rightMouseDown = true; } - if (action == GLFW_RELEASE) + if ( action == GLFW_RELEASE ) { s_rightMouseDown = false; } } } -static void MouseMotionCallback(GLFWwindow* window, double xd, double yd) +static void MouseMotionCallback( GLFWwindow* window, double xd, double yd ) { - b2Vec2 ps = {float(xd) / s_windowScale, float(yd) / s_windowScale}; + b2Vec2 ps = { float( xd ) / s_windowScale, float( yd ) / s_windowScale }; - ImGui_ImplGlfw_CursorPosCallback(window, ps.x, ps.y); + ImGui_ImplGlfw_CursorPosCallback( window, ps.x, ps.y ); - b2Vec2 pw = g_camera.ConvertScreenToWorld(ps); - s_sample->MouseMove(pw); + b2Vec2 pw = g_camera.ConvertScreenToWorld( ps ); + s_sample->MouseMove( pw ); - if (s_rightMouseDown) + if ( s_rightMouseDown ) { - b2Vec2 diff = b2Sub(pw, s_clickPointWS); + b2Vec2 diff = b2Sub( pw, s_clickPointWS ); g_camera.m_center.x -= diff.x; g_camera.m_center.y -= diff.y; - s_clickPointWS = g_camera.ConvertScreenToWorld(ps); + s_clickPointWS = g_camera.ConvertScreenToWorld( ps ); } } -static void ScrollCallback(GLFWwindow* window, double dx, double dy) +static void ScrollCallback( GLFWwindow* window, double dx, double dy ) { - ImGui_ImplGlfw_ScrollCallback(window, dx, dy); - if (ImGui::GetIO().WantCaptureMouse) + ImGui_ImplGlfw_ScrollCallback( window, dx, dy ); + if ( ImGui::GetIO().WantCaptureMouse ) { return; } - if (dy > 0) + if ( dy > 0 ) { g_camera.m_zoom /= 1.1f; } @@ -379,79 +379,79 @@ static void UpdateUI() int maxWorkers = enki::GetNumHardwareThreads(); float menuWidth = 180.0f; - if (g_draw.m_showUI) + if ( g_draw.m_showUI ) { - ImGui::SetNextWindowPos({g_camera.m_width - menuWidth - 10.0f, 10.0f}); - ImGui::SetNextWindowSize({menuWidth, g_camera.m_height - 20.0f}); + ImGui::SetNextWindowPos( { g_camera.m_width - menuWidth - 10.0f, 10.0f } ); + ImGui::SetNextWindowSize( { menuWidth, g_camera.m_height - 20.0f } ); - ImGui::Begin("Tools", &g_draw.m_showUI, - ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse); + ImGui::Begin( "Tools", &g_draw.m_showUI, + ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse ); - if (ImGui::BeginTabBar("ControlTabs", ImGuiTabBarFlags_None)) + if ( ImGui::BeginTabBar( "ControlTabs", ImGuiTabBarFlags_None ) ) { - if (ImGui::BeginTabItem("Controls")) + if ( ImGui::BeginTabItem( "Controls" ) ) { - ImGui::PushItemWidth(100.0f); - ImGui::SliderInt("Sub-steps", &s_settings.subStepCount, 1, 50); - ImGui::SliderFloat("Hertz", &s_settings.hertz, 5.0f, 120.0f, "%.0f hz"); + ImGui::PushItemWidth( 100.0f ); + ImGui::SliderInt( "Sub-steps", &s_settings.subStepCount, 1, 50 ); + ImGui::SliderFloat( "Hertz", &s_settings.hertz, 5.0f, 120.0f, "%.0f hz" ); - if (ImGui::SliderInt("Workers", &s_settings.workerCount, 1, maxWorkers)) + if ( ImGui::SliderInt( "Workers", &s_settings.workerCount, 1, maxWorkers ) ) { - s_settings.workerCount = b2ClampInt(s_settings.workerCount, 1, maxWorkers); + s_settings.workerCount = b2ClampInt( s_settings.workerCount, 1, maxWorkers ); RestartSample(); } ImGui::PopItemWidth(); ImGui::Separator(); - ImGui::Checkbox("Sleep", &s_settings.enableSleep); - ImGui::Checkbox("Warm Starting", &s_settings.enableWarmStarting); - ImGui::Checkbox("Continuous", &s_settings.enableContinuous); + ImGui::Checkbox( "Sleep", &s_settings.enableSleep ); + ImGui::Checkbox( "Warm Starting", &s_settings.enableWarmStarting ); + ImGui::Checkbox( "Continuous", &s_settings.enableContinuous ); ImGui::Separator(); - ImGui::Checkbox("Shapes", &s_settings.drawShapes); - ImGui::Checkbox("Joints", &s_settings.drawJoints); - ImGui::Checkbox("Joint Extras", &s_settings.drawJointExtras); - ImGui::Checkbox("AABBs", &s_settings.drawAABBs); - ImGui::Checkbox("Contact Points", &s_settings.drawContactPoints); - ImGui::Checkbox("Contact Normals", &s_settings.drawContactNormals); - ImGui::Checkbox("Contact Impulses", &s_settings.drawContactImpulses); - ImGui::Checkbox("Friction Impulses", &s_settings.drawFrictionImpulses); - ImGui::Checkbox("Center of Masses", &s_settings.drawMass); - ImGui::Checkbox("Graph Colors", &s_settings.drawGraphColors); - ImGui::Checkbox("Counters", &s_settings.drawCounters); - ImGui::Checkbox("Profile", &s_settings.drawProfile); - - ImVec2 button_sz = ImVec2(-1, 0); - if (ImGui::Button("Pause (P)", button_sz)) + ImGui::Checkbox( "Shapes", &s_settings.drawShapes ); + ImGui::Checkbox( "Joints", &s_settings.drawJoints ); + ImGui::Checkbox( "Joint Extras", &s_settings.drawJointExtras ); + ImGui::Checkbox( "AABBs", &s_settings.drawAABBs ); + ImGui::Checkbox( "Contact Points", &s_settings.drawContactPoints ); + ImGui::Checkbox( "Contact Normals", &s_settings.drawContactNormals ); + ImGui::Checkbox( "Contact Impulses", &s_settings.drawContactImpulses ); + ImGui::Checkbox( "Friction Impulses", &s_settings.drawFrictionImpulses ); + ImGui::Checkbox( "Center of Masses", &s_settings.drawMass ); + ImGui::Checkbox( "Graph Colors", &s_settings.drawGraphColors ); + ImGui::Checkbox( "Counters", &s_settings.drawCounters ); + ImGui::Checkbox( "Profile", &s_settings.drawProfile ); + + ImVec2 button_sz = ImVec2( -1, 0 ); + if ( ImGui::Button( "Pause (P)", button_sz ) ) { s_settings.pause = !s_settings.pause; } - if (ImGui::Button("Single Step (O)", button_sz)) + if ( ImGui::Button( "Single Step (O)", button_sz ) ) { s_settings.singleStep = !s_settings.singleStep; } - if (ImGui::Button("Dump Mem Stats", button_sz)) + if ( ImGui::Button( "Dump Mem Stats", button_sz ) ) { - b2World_DumpMemoryStats(s_sample->m_worldId); + b2World_DumpMemoryStats( s_sample->m_worldId ); } - if (ImGui::Button("Reset Profile", button_sz)) + if ( ImGui::Button( "Reset Profile", button_sz ) ) { s_sample->ResetProfile(); } - if (ImGui::Button("Restart (R)", button_sz)) + if ( ImGui::Button( "Restart (R)", button_sz ) ) { RestartSample(); } - if (ImGui::Button("Quit", button_sz)) + if ( ImGui::Button( "Quit", button_sz ) ) { - glfwSetWindowShouldClose(g_mainWindow, GL_TRUE); + glfwSetWindowShouldClose( g_mainWindow, GL_TRUE ); } ImGui::EndTabItem(); @@ -462,28 +462,29 @@ static void UpdateUI() ImGuiTreeNodeFlags nodeFlags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; - if (ImGui::BeginTabItem("Tests")) + if ( ImGui::BeginTabItem( "Tests" ) ) { int categoryIndex = 0; const char* category = g_sampleEntries[categoryIndex].category; int i = 0; - while (i < g_sampleCount) + while ( i < g_sampleCount ) { - bool categorySelected = strcmp(category, g_sampleEntries[s_settings.sampleIndex].category) == 0; + bool categorySelected = strcmp( category, g_sampleEntries[s_settings.sampleIndex].category ) == 0; ImGuiTreeNodeFlags nodeSelectionFlags = categorySelected ? ImGuiTreeNodeFlags_Selected : 0; - bool nodeOpen = ImGui::TreeNodeEx(category, nodeFlags | nodeSelectionFlags); + bool nodeOpen = ImGui::TreeNodeEx( category, nodeFlags | nodeSelectionFlags ); - if (nodeOpen) + if ( nodeOpen ) { - while (i < g_sampleCount && strcmp(category, g_sampleEntries[i].category) == 0) + while ( i < g_sampleCount && strcmp( category, g_sampleEntries[i].category ) == 0 ) { ImGuiTreeNodeFlags selectionFlags = 0; - if (s_settings.sampleIndex == i) + if ( s_settings.sampleIndex == i ) { selectionFlags = ImGuiTreeNodeFlags_Selected; } - ImGui::TreeNodeEx((void*)(intptr_t)i, leafNodeFlags | selectionFlags, "%s", g_sampleEntries[i].name); - if (ImGui::IsItemClicked()) + ImGui::TreeNodeEx( (void*)(intptr_t)i, leafNodeFlags | selectionFlags, "%s", + g_sampleEntries[i].name ); + if ( ImGui::IsItemClicked() ) { s_selection = i; } @@ -493,13 +494,13 @@ static void UpdateUI() } else { - while (i < g_sampleCount && strcmp(category, g_sampleEntries[i].category) == 0) + while ( i < g_sampleCount && strcmp( category, g_sampleEntries[i].category ) == 0 ) { ++i; } } - if (i < g_sampleCount) + if ( i < g_sampleCount ) { category = g_sampleEntries[i].category; categoryIndex = i; @@ -517,12 +518,12 @@ static void UpdateUI() } // -int main(int, char**) +int main( int, char** ) { -#if defined(_WIN32) +#if defined( _WIN32 ) // Enable memory-leak reports - _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE); - _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT); + _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE ); + _CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDOUT ); //_CrtSetAllocHook(MyAllocHook); // How to break at the leaking allocation, in the watch window enter this variable @@ -531,23 +532,23 @@ int main(int, char**) #endif // Install memory hooks - b2SetAllocator(AllocFcn, FreeFcn); - b2SetAssertFcn(AssertFcn); + b2SetAllocator( AllocFcn, FreeFcn ); + b2SetAssertFcn( AssertFcn ); char buffer[128]; s_settings.Load(); - s_settings.workerCount = b2MinInt(8, (int)enki::GetNumHardwareThreads() / 2); + s_settings.workerCount = b2MinInt( 8, (int)enki::GetNumHardwareThreads() / 2 ); SortTests(); - glfwSetErrorCallback(glfwErrorCallback); + glfwSetErrorCallback( glfwErrorCallback ); g_camera.m_width = s_settings.windowWidth; g_camera.m_height = s_settings.windowHeight; - if (glfwInit() == 0) + if ( glfwInit() == 0 ) { - fprintf(stderr, "Failed to initialize GLFW\n"); + fprintf( stderr, "Failed to initialize GLFW\n" ); return -1; } @@ -557,141 +558,148 @@ int main(int, char**) const char* glslVersion = nullptr; #endif - glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); - glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); - glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); - glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); + glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 3 ); + glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 3 ); + glfwWindowHint( GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE ); + glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE ); // MSAA - glfwWindowHint(GLFW_SAMPLES, 4); + glfwWindowHint( GLFW_SAMPLES, 4 ); b2Version version = b2GetVersion(); - snprintf(buffer, 128, "Box2D Version %d.%d.%d (beta)", version.major, version.minor, version.revision); + snprintf( buffer, 128, "Box2D Version %d.%d.%d", version.major, version.minor, version.revision ); - if (GLFWmonitor* primaryMonitor = glfwGetPrimaryMonitor()) + if ( GLFWmonitor* primaryMonitor = glfwGetPrimaryMonitor() ) { #ifdef __APPLE__ - glfwGetMonitorContentScale(primaryMonitor, &s_framebufferScale, &s_framebufferScale); + glfwGetMonitorContentScale( primaryMonitor, &s_framebufferScale, &s_framebufferScale ); #else - glfwGetMonitorContentScale(primaryMonitor, &s_windowScale, &s_windowScale); + glfwGetMonitorContentScale( primaryMonitor, &s_windowScale, &s_windowScale ); #endif } bool fullscreen = false; - if (fullscreen) + if ( fullscreen ) { - g_mainWindow = - glfwCreateWindow(int(1920 * s_windowScale), int(1080 * s_windowScale), buffer, glfwGetPrimaryMonitor(), nullptr); + g_mainWindow = glfwCreateWindow( int( 1920 * s_windowScale ), int( 1080 * s_windowScale ), buffer, + glfwGetPrimaryMonitor(), nullptr ); } else { - g_mainWindow = glfwCreateWindow(int(g_camera.m_width * s_windowScale), int(g_camera.m_height * s_windowScale), buffer, - nullptr, nullptr); + g_mainWindow = glfwCreateWindow( int( g_camera.m_width * s_windowScale ), int( g_camera.m_height * s_windowScale ), + buffer, nullptr, nullptr ); } - if (g_mainWindow == nullptr) + if ( g_mainWindow == nullptr ) { - fprintf(stderr, "Failed to open GLFW g_mainWindow.\n"); + fprintf( stderr, "Failed to open GLFW g_mainWindow.\n" ); glfwTerminate(); return -1; } #ifdef __APPLE__ - glfwGetWindowContentScale(g_mainWindow, &s_framebufferScale, &s_framebufferScale); + glfwGetWindowContentScale( g_mainWindow, &s_framebufferScale, &s_framebufferScale ); #else - glfwGetWindowContentScale(g_mainWindow, &s_windowScale, &s_windowScale); + glfwGetWindowContentScale( g_mainWindow, &s_windowScale, &s_windowScale ); #endif - glfwMakeContextCurrent(g_mainWindow); + glfwMakeContextCurrent( g_mainWindow ); // Load OpenGL functions using glad - if (!gladLoadGL()) + if ( !gladLoadGL() ) { - fprintf(stderr, "Failed to initialize glad\n"); + fprintf( stderr, "Failed to initialize glad\n" ); glfwTerminate(); return -1; } - printf("GL %d.%d\n", GLVersion.major, GLVersion.minor); - printf("OpenGL %s, GLSL %s\n", glGetString(GL_VERSION), glGetString(GL_SHADING_LANGUAGE_VERSION)); + printf( "GL %d.%d\n", GLVersion.major, GLVersion.minor ); + printf( "OpenGL %s, GLSL %s\n", glGetString( GL_VERSION ), glGetString( GL_SHADING_LANGUAGE_VERSION ) ); - glfwSetWindowSizeCallback(g_mainWindow, ResizeWindowCallback); - glfwSetKeyCallback(g_mainWindow, KeyCallback); - glfwSetCharCallback(g_mainWindow, CharCallback); - glfwSetMouseButtonCallback(g_mainWindow, MouseButtonCallback); - glfwSetCursorPosCallback(g_mainWindow, MouseMotionCallback); - glfwSetScrollCallback(g_mainWindow, ScrollCallback); + glfwSetWindowSizeCallback( g_mainWindow, ResizeWindowCallback ); + glfwSetKeyCallback( g_mainWindow, KeyCallback ); + glfwSetCharCallback( g_mainWindow, CharCallback ); + glfwSetMouseButtonCallback( g_mainWindow, MouseButtonCallback ); + glfwSetCursorPosCallback( g_mainWindow, MouseMotionCallback ); + glfwSetScrollCallback( g_mainWindow, ScrollCallback ); // todo put this in s_settings - CreateUI(g_mainWindow, glslVersion); + CreateUI( g_mainWindow, glslVersion ); g_draw.Create(); - s_settings.sampleIndex = b2ClampInt(s_settings.sampleIndex, 0, g_sampleCount - 1); + s_settings.sampleIndex = b2ClampInt( s_settings.sampleIndex, 0, g_sampleCount - 1 ); s_selection = s_settings.sampleIndex; - s_sample = g_sampleEntries[s_settings.sampleIndex].createFcn(s_settings); - glClearColor(0.2f, 0.2f, 0.2f, 1.0f); + glClearColor( 0.2f, 0.2f, 0.2f, 1.0f ); float frameTime = 0.0; int32_t frame = 0; - while (!glfwWindowShouldClose(g_mainWindow)) + while ( !glfwWindowShouldClose( g_mainWindow ) ) { double time1 = glfwGetTime(); - if (glfwGetKey(g_mainWindow, GLFW_KEY_Z) == GLFW_PRESS) + if ( glfwGetKey( g_mainWindow, GLFW_KEY_Z ) == GLFW_PRESS ) { // Zoom out - g_camera.m_zoom = b2MinFloat(1.005f * g_camera.m_zoom, 100.0f); + g_camera.m_zoom = b2MinFloat( 1.005f * g_camera.m_zoom, 100.0f ); } - else if (glfwGetKey(g_mainWindow, GLFW_KEY_X) == GLFW_PRESS) + else if ( glfwGetKey( g_mainWindow, GLFW_KEY_X ) == GLFW_PRESS ) { // Zoom in - g_camera.m_zoom = b2MaxFloat(0.995f * g_camera.m_zoom, 0.5f); + g_camera.m_zoom = b2MaxFloat( 0.995f * g_camera.m_zoom, 0.5f ); } - glfwGetWindowSize(g_mainWindow, &g_camera.m_width, &g_camera.m_height); - g_camera.m_width = int(g_camera.m_width / s_windowScale); - g_camera.m_height = int(g_camera.m_height / s_windowScale); + glfwGetWindowSize( g_mainWindow, &g_camera.m_width, &g_camera.m_height ); + g_camera.m_width = int( g_camera.m_width / s_windowScale ); + g_camera.m_height = int( g_camera.m_height / s_windowScale ); int bufferWidth, bufferHeight; - glfwGetFramebufferSize(g_mainWindow, &bufferWidth, &bufferHeight); - glViewport(0, 0, bufferWidth, bufferHeight); + glfwGetFramebufferSize( g_mainWindow, &bufferWidth, &bufferHeight ); + glViewport( 0, 0, bufferWidth, bufferHeight ); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); + + g_draw.DrawBackground(); double cursorPosX = 0, cursorPosY = 0; - glfwGetCursorPos(g_mainWindow, &cursorPosX, &cursorPosY); - ImGui_ImplGlfw_CursorPosCallback(g_mainWindow, cursorPosX / s_windowScale, cursorPosY / s_windowScale); + glfwGetCursorPos( g_mainWindow, &cursorPosX, &cursorPosY ); + ImGui_ImplGlfw_CursorPosCallback( g_mainWindow, cursorPosX / s_windowScale, cursorPosY / s_windowScale ); ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); - ImGui_ImplGlfw_CursorPosCallback(g_mainWindow, cursorPosX / s_windowScale, cursorPosY / s_windowScale); + ImGui_ImplGlfw_CursorPosCallback( g_mainWindow, cursorPosX / s_windowScale, cursorPosY / s_windowScale ); ImGuiIO& io = ImGui::GetIO(); - io.DisplaySize.x = float(g_camera.m_width); - io.DisplaySize.y = float(g_camera.m_height); - io.DisplayFramebufferScale.x = bufferWidth / float(g_camera.m_width); - io.DisplayFramebufferScale.y = bufferHeight / float(g_camera.m_height); + io.DisplaySize.x = float( g_camera.m_width ); + io.DisplaySize.y = float( g_camera.m_height ); + io.DisplayFramebufferScale.x = bufferWidth / float( g_camera.m_width ); + io.DisplayFramebufferScale.y = bufferHeight / float( g_camera.m_height ); ImGui::NewFrame(); - ImGui::SetNextWindowPos(ImVec2(0.0f, 0.0f)); - ImGui::SetNextWindowSize(ImVec2(float(g_camera.m_width), float(g_camera.m_height))); - ImGui::SetNextWindowBgAlpha(0.0f); - ImGui::Begin("Overlay", nullptr, - ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | - ImGuiWindowFlags_NoScrollbar); + ImGui::SetNextWindowPos( ImVec2( 0.0f, 0.0f ) ); + ImGui::SetNextWindowSize( ImVec2( float( g_camera.m_width ), float( g_camera.m_height ) ) ); + ImGui::SetNextWindowBgAlpha( 0.0f ); + ImGui::Begin( "Overlay", nullptr, + ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | + ImGuiWindowFlags_NoScrollbar ); ImGui::End(); - if (g_draw.m_showUI) + if ( s_sample == nullptr ) + { + // delayed creation because imgui doesn't create fonts until NewFrame() is called + s_sample = g_sampleEntries[s_settings.sampleIndex].createFcn( s_settings ); + } + + if ( g_draw.m_showUI ) { const SampleEntry& entry = g_sampleEntries[s_settings.sampleIndex]; - snprintf(buffer, 128, "%s : %s", entry.category, entry.name); - s_sample->DrawTitle(buffer); + snprintf( buffer, 128, "%s : %s", entry.category, entry.name ); + s_sample->DrawTitle( buffer ); } - s_sample->Step(s_settings); + s_sample->Step( s_settings ); g_draw.Flush(); @@ -701,25 +709,27 @@ int main(int, char**) // if (g_draw.m_showUI) { - snprintf(buffer, 128, "%.1f ms - step %d - camera (%g, %g, %g)", 1000.0f * frameTime, s_sample->m_stepCount, - g_camera.m_center.x, g_camera.m_center.y, g_camera.m_zoom); - - ImGui::Begin("Overlay", nullptr, - ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | - ImGuiWindowFlags_NoScrollbar); - ImGui::SetCursorPos(ImVec2(5.0f, g_camera.m_height - 20.0f)); - ImGui::TextColored(ImColor(153, 230, 153, 255), "%s", buffer); + snprintf( buffer, 128, "%.1f ms - step %d - camera (%g, %g, %g)", 1000.0f * frameTime, s_sample->m_stepCount, + g_camera.m_center.x, g_camera.m_center.y, g_camera.m_zoom ); + //snprintf( buffer, 128, "%.1f ms", 1000.0f * frameTime ); + + ImGui::Begin( "Overlay", nullptr, + ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | + ImGuiWindowFlags_NoScrollbar ); + ImGui::SetCursorPos( ImVec2( 5.0f, g_camera.m_height - 20.0f ) ); + ImGui::TextColored( ImColor( 153, 230, 153, 255 ), "%s", buffer ); ImGui::End(); } ImGui::Render(); - ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); + ImGui_ImplOpenGL3_RenderDrawData( ImGui::GetDrawData() ); - glfwSwapBuffers(g_mainWindow); + glfwSwapBuffers( g_mainWindow ); + // For the Tracy profiler FrameMark; - if (s_selection != s_settings.sampleIndex) + if ( s_selection != s_settings.sampleIndex ) { g_camera.ResetView(); s_settings.sampleIndex = s_selection; @@ -731,7 +741,7 @@ int main(int, char**) delete s_sample; s_sample = nullptr; - s_sample = g_sampleEntries[s_settings.sampleIndex].createFcn(s_settings); + s_sample = g_sampleEntries[s_settings.sampleIndex].createFcn( s_settings ); } glfwPollEvents(); @@ -740,14 +750,14 @@ int main(int, char**) double time2 = glfwGetTime(); double targetTime = time1 + 1.0f / 60.0f; int loopCount = 0; - while (time2 < targetTime) + while ( time2 < targetTime ) { b2Yield(); time2 = glfwGetTime(); ++loopCount; } - frameTime = (float)(time2 - time1); + frameTime = (float)( time2 - time1 ); // if (frame % 17 == 0) //{ // printf("loop count = %d, frame time = %.1f\n", loopCount, 1000.0f * frameTime); @@ -765,7 +775,7 @@ int main(int, char**) s_settings.Save(); -#if defined(_WIN32) +#if defined( _WIN32 ) _CrtDumpMemoryLeaks(); #endif diff --git a/samples/sample.cpp b/samples/sample.cpp index 7ddfa196..abdc781d 100644 --- a/samples/sample.cpp +++ b/samples/sample.cpp @@ -14,43 +14,43 @@ #include #include -static void* EnqueueTask(b2TaskCallback* task, int32_t itemCount, int32_t minRange, void* taskContext, void* userContext) +static void* EnqueueTask( b2TaskCallback* task, int32_t itemCount, int32_t minRange, void* taskContext, void* userContext ) { - Sample* sample = static_cast(userContext); - if (sample->m_taskCount < maxTasks) + Sample* sample = static_cast( userContext ); + if ( sample->m_taskCount < maxTasks ) { SampleTask& sampleTask = sample->m_tasks[sample->m_taskCount]; sampleTask.m_SetSize = itemCount; sampleTask.m_MinRange = minRange; sampleTask.m_task = task; sampleTask.m_taskContext = taskContext; - sample->m_scheduler.AddTaskSetToPipe(&sampleTask); + sample->m_scheduler.AddTaskSetToPipe( &sampleTask ); ++sample->m_taskCount; return &sampleTask; } else { // This is not fatal but the maxTasks should be increased - assert(false); - task(0, itemCount, 0, taskContext); + assert( false ); + task( 0, itemCount, 0, taskContext ); return nullptr; } } -static void FinishTask(void* taskPtr, void* userContext) +static void FinishTask( void* taskPtr, void* userContext ) { - if (taskPtr != nullptr) + if ( taskPtr != nullptr ) { - SampleTask* sampleTask = static_cast(taskPtr); - Sample* sample = static_cast(userContext); - sample->m_scheduler.WaitforTask(sampleTask); + SampleTask* sampleTask = static_cast( taskPtr ); + Sample* sample = static_cast( userContext ); + sample->m_scheduler.WaitforTask( sampleTask ); } } static void TestMathCpp() { - b2Vec2 a = {1.0f, 2.0f}; - b2Vec2 b = {3.0f, 4.0f}; + b2Vec2 a = { 1.0f, 2.0f }; + b2Vec2 b = { 3.0f, 4.0f }; b2Vec2 c = a; c += b; @@ -62,12 +62,12 @@ static void TestMathCpp() c = 2.0f * a; c = a * 2.0f; - if (b == a) + if ( b == a ) { c = a; } - if (b != a) + if ( b != a ) { c = b; } @@ -75,9 +75,9 @@ static void TestMathCpp() c += c; } -Sample::Sample(Settings& settings) +Sample::Sample( Settings& settings ) { - m_scheduler.Initialize(settings.workerCount); + m_scheduler.Initialize( settings.workerCount ); m_taskCount = 0; m_threadCount = 1 + settings.workerCount; @@ -89,7 +89,7 @@ Sample::Sample(Settings& settings) worldDef.userTaskContext = this; worldDef.enableSleep = settings.enableSleep; - m_worldId = b2CreateWorld(&worldDef); + m_worldId = b2CreateWorld( &worldDef ); m_textLine = 30; m_textIncrement = 18; m_mouseJointId = b2_nullJointId; @@ -107,13 +107,13 @@ Sample::Sample(Settings& settings) Sample::~Sample() { // By deleting the world, we delete the bomb, mouse joint, etc. - b2DestroyWorld(m_worldId); + b2DestroyWorld( m_worldId ); } -void Sample::DrawTitle(const char* string) +void Sample::DrawTitle( const char* string ) { - g_draw.DrawString(5, 5, string); - m_textLine = int(26.0f); + g_draw.DrawString( 5, 5, string ); + m_textLine = int( 26.0f ); } struct QueryContext @@ -122,20 +122,20 @@ struct QueryContext b2BodyId bodyId = b2_nullBodyId; }; -bool QueryCallback(b2ShapeId shapeId, void* context) +bool QueryCallback( b2ShapeId shapeId, void* context ) { - QueryContext* queryContext = static_cast(context); + QueryContext* queryContext = static_cast( context ); - b2BodyId bodyId = b2Shape_GetBody(shapeId); - b2BodyType bodyType = b2Body_GetType(bodyId); - if (bodyType != b2_dynamicBody) + b2BodyId bodyId = b2Shape_GetBody( shapeId ); + b2BodyType bodyType = b2Body_GetType( bodyId ); + if ( bodyType != b2_dynamicBody ) { // continue query return true; } - bool overlap = b2Shape_TestPoint(shapeId, queryContext->point); - if (overlap) + bool overlap = b2Shape_TestPoint( shapeId, queryContext->point ); + if ( overlap ) { // found shape queryContext->bodyId = bodyId; @@ -145,29 +145,29 @@ bool QueryCallback(b2ShapeId shapeId, void* context) return true; } -void Sample::MouseDown(b2Vec2 p, int button, int mod) +void Sample::MouseDown( b2Vec2 p, int button, int mod ) { - if (B2_IS_NON_NULL(m_mouseJointId)) + if ( B2_IS_NON_NULL( m_mouseJointId ) ) { return; } - if (button == GLFW_MOUSE_BUTTON_1) + if ( button == GLFW_MOUSE_BUTTON_1 ) { // Make a small box. b2AABB box; - b2Vec2 d = {0.001f, 0.001f}; - box.lowerBound = b2Sub(p, d); - box.upperBound = b2Add(p, d); + b2Vec2 d = { 0.001f, 0.001f }; + box.lowerBound = b2Sub( p, d ); + box.upperBound = b2Add( p, d ); // Query the world for overlapping shapes. - QueryContext queryContext = {p, b2_nullBodyId}; - b2World_OverlapAABB(m_worldId, box, b2DefaultQueryFilter(), QueryCallback, &queryContext); + QueryContext queryContext = { p, b2_nullBodyId }; + b2World_OverlapAABB( m_worldId, box, b2DefaultQueryFilter(), QueryCallback, &queryContext ); - if (B2_IS_NON_NULL(queryContext.bodyId)) + if ( B2_IS_NON_NULL( queryContext.bodyId ) ) { b2BodyDef bodyDef = b2DefaultBodyDef(); - m_groundBodyId = b2CreateBody(m_worldId, &bodyDef); + m_groundBodyId = b2CreateBody( m_worldId, &bodyDef ); b2MouseJointDef mouseDef = b2DefaultMouseJointDef(); mouseDef.bodyIdA = m_groundBodyId; @@ -175,45 +175,45 @@ void Sample::MouseDown(b2Vec2 p, int button, int mod) mouseDef.target = p; mouseDef.hertz = 5.0f; mouseDef.dampingRatio = 0.7f; - mouseDef.maxForce = 1000.0f * b2Body_GetMass(queryContext.bodyId); - m_mouseJointId = b2CreateMouseJoint(m_worldId, &mouseDef); + mouseDef.maxForce = 1000.0f * b2Body_GetMass( queryContext.bodyId ); + m_mouseJointId = b2CreateMouseJoint( m_worldId, &mouseDef ); - b2Body_SetAwake(queryContext.bodyId, true); + b2Body_SetAwake( queryContext.bodyId, true ); } } } -void Sample::MouseUp(b2Vec2 p, int button) +void Sample::MouseUp( b2Vec2 p, int button ) { - if (b2Joint_IsValid(m_mouseJointId) == false) + if ( b2Joint_IsValid( m_mouseJointId ) == false ) { // The world or attached body was destroyed. m_mouseJointId = b2_nullJointId; } - if (B2_IS_NON_NULL(m_mouseJointId) && button == GLFW_MOUSE_BUTTON_1) + if ( B2_IS_NON_NULL( m_mouseJointId ) && button == GLFW_MOUSE_BUTTON_1 ) { - b2DestroyJoint(m_mouseJointId); + b2DestroyJoint( m_mouseJointId ); m_mouseJointId = b2_nullJointId; - b2DestroyBody(m_groundBodyId); + b2DestroyBody( m_groundBodyId ); m_groundBodyId = b2_nullBodyId; } } -void Sample::MouseMove(b2Vec2 p) +void Sample::MouseMove( b2Vec2 p ) { - if (b2Joint_IsValid(m_mouseJointId) == false) + if ( b2Joint_IsValid( m_mouseJointId ) == false ) { // The world or attached body was destroyed. m_mouseJointId = b2_nullJointId; } - if (B2_IS_NON_NULL(m_mouseJointId)) + if ( B2_IS_NON_NULL( m_mouseJointId ) ) { - b2MouseJoint_SetTarget(m_mouseJointId, p); - b2BodyId bodyIdB = b2Joint_GetBodyB(m_mouseJointId); - b2Body_SetAwake(bodyIdB, true); + b2MouseJoint_SetTarget( m_mouseJointId, p ); + b2BodyId bodyIdB = b2Joint_GetBodyB( m_mouseJointId ); + b2Body_SetAwake( bodyIdB, true ); } } @@ -224,13 +224,13 @@ void Sample::ResetProfile() m_stepCount = 0; } -void Sample::Step(Settings& settings) +void Sample::Step( Settings& settings ) { float timeStep = settings.hertz > 0.0f ? 1.0f / settings.hertz : 0.0f; - if (settings.pause) + if ( settings.pause ) { - if (settings.singleStep) + if ( settings.singleStep ) { settings.singleStep = false; } @@ -239,7 +239,7 @@ void Sample::Step(Settings& settings) timeStep = 0.0f; } - g_draw.DrawString(5, m_textLine, "****PAUSED****"); + g_draw.DrawString( 5, m_textLine, "****PAUSED****" ); m_textLine += m_textIncrement; } @@ -247,10 +247,10 @@ void Sample::Step(Settings& settings) g_draw.m_debugDraw.useDrawingBounds = settings.useCameraBounds; // todo testing - //b2Transform t1 = {g_draw.m_debugDraw.drawingBounds.lowerBound, b2Rot_identity}; - //b2Transform t2 = {g_draw.m_debugDraw.drawingBounds.upperBound, b2Rot_identity}; - //g_draw.DrawSolidCircle(t1, b2Vec2_zero, 1.0f, {1.0f, 0.0f, 0.0f, 1.0f}); - //g_draw.DrawSolidCircle(t2, b2Vec2_zero, 1.0f, {1.0f, 0.0f, 0.0f, 1.0f}); + // b2Transform t1 = {g_draw.m_debugDraw.drawingBounds.lowerBound, b2Rot_identity}; + // b2Transform t2 = {g_draw.m_debugDraw.drawingBounds.upperBound, b2Rot_identity}; + // g_draw.DrawSolidCircle(t1, b2Vec2_zero, 1.0f, {1.0f, 0.0f, 0.0f, 1.0f}); + // g_draw.DrawSolidCircle(t2, b2Vec2_zero, 1.0f, {1.0f, 0.0f, 0.0f, 1.0f}); g_draw.m_debugDraw.drawShapes = settings.drawShapes; g_draw.m_debugDraw.drawJoints = settings.drawJoints; @@ -263,83 +263,83 @@ void Sample::Step(Settings& settings) g_draw.m_debugDraw.drawContactImpulses = settings.drawContactImpulses; g_draw.m_debugDraw.drawFrictionImpulses = settings.drawFrictionImpulses; - b2World_EnableSleeping(m_worldId, settings.enableSleep); - b2World_EnableWarmStarting(m_worldId, settings.enableWarmStarting); - b2World_EnableContinuous(m_worldId, settings.enableContinuous); + b2World_EnableSleeping( m_worldId, settings.enableSleep ); + b2World_EnableWarmStarting( m_worldId, settings.enableWarmStarting ); + b2World_EnableContinuous( m_worldId, settings.enableContinuous ); - for (int i = 0; i < 1; ++i) + for ( int i = 0; i < 1; ++i ) { - b2World_Step(m_worldId, timeStep, settings.subStepCount); + b2World_Step( m_worldId, timeStep, settings.subStepCount ); m_taskCount = 0; } - b2World_Draw(m_worldId, &g_draw.m_debugDraw); + b2World_Draw( m_worldId, &g_draw.m_debugDraw ); - if (timeStep > 0.0f) + if ( timeStep > 0.0f ) { ++m_stepCount; } - if (settings.drawCounters) + if ( settings.drawCounters ) { - b2Counters s = b2World_GetCounters(m_worldId); + b2Counters s = b2World_GetCounters( m_worldId ); - g_draw.DrawString(5, m_textLine, "bodies/shapes/contacts/joints = %d/%d/%d/%d", s.bodyCount, s.shapeCount, s.contactCount, - s.jointCount); + g_draw.DrawString( 5, m_textLine, "bodies/shapes/contacts/joints = %d/%d/%d/%d", s.bodyCount, s.shapeCount, + s.contactCount, s.jointCount ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "islands/tasks = %d/%d", s.islandCount, s.taskCount); + g_draw.DrawString( 5, m_textLine, "islands/tasks = %d/%d", s.islandCount, s.taskCount ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "tree height static/movable = %d/%d", s.staticTreeHeight, s.treeHeight); + g_draw.DrawString( 5, m_textLine, "tree height static/movable = %d/%d", s.staticTreeHeight, s.treeHeight ); m_textLine += m_textIncrement; int totalCount = 0; - char buffer[256] = {0}; - static_assert(std::size(s.colorCounts) == 12); + char buffer[256] = { 0 }; + static_assert( std::size( s.colorCounts ) == 12 ); - int offset = snprintf(buffer, 256, "colors: "); - for (int i = 0; i < 12; ++i) + int offset = snprintf( buffer, 256, "colors: " ); + for ( int i = 0; i < 12; ++i ) { - offset += snprintf(buffer + offset, 256 - offset, "%d/", s.colorCounts[i]); + offset += snprintf( buffer + offset, 256 - offset, "%d/", s.colorCounts[i] ); totalCount += s.colorCounts[i]; } - snprintf(buffer + offset, 256 - offset, "[%d]", totalCount); - g_draw.DrawString(5, m_textLine, buffer); + snprintf( buffer + offset, 256 - offset, "[%d]", totalCount ); + g_draw.DrawString( 5, m_textLine, buffer ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "stack allocator size = %d K", s.stackUsed / 1024); + g_draw.DrawString( 5, m_textLine, "stack allocator size = %d K", s.stackUsed / 1024 ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "total allocation = %d K", s.byteCount / 1024); + g_draw.DrawString( 5, m_textLine, "total allocation = %d K", s.byteCount / 1024 ); m_textLine += m_textIncrement; } // Track maximum profile times { - b2Profile p = b2World_GetProfile(m_worldId); - m_maxProfile.step = b2MaxFloat(m_maxProfile.step, p.step); - m_maxProfile.pairs = b2MaxFloat(m_maxProfile.pairs, p.pairs); - m_maxProfile.collide = b2MaxFloat(m_maxProfile.collide, p.collide); - m_maxProfile.solve = b2MaxFloat(m_maxProfile.solve, p.solve); - m_maxProfile.buildIslands = b2MaxFloat(m_maxProfile.buildIslands, p.buildIslands); - m_maxProfile.solveConstraints = b2MaxFloat(m_maxProfile.solveConstraints, p.solveConstraints); - m_maxProfile.prepareTasks = b2MaxFloat(m_maxProfile.prepareTasks, p.prepareTasks); - m_maxProfile.solverTasks = b2MaxFloat(m_maxProfile.solverTasks, p.solverTasks); - m_maxProfile.prepareConstraints = b2MaxFloat(m_maxProfile.prepareConstraints, p.prepareConstraints); - m_maxProfile.integrateVelocities = b2MaxFloat(m_maxProfile.integrateVelocities, p.integrateVelocities); - m_maxProfile.warmStart = b2MaxFloat(m_maxProfile.warmStart, p.warmStart); - m_maxProfile.solveVelocities = b2MaxFloat(m_maxProfile.solveVelocities, p.solveVelocities); - m_maxProfile.integratePositions = b2MaxFloat(m_maxProfile.integratePositions, p.integratePositions); - m_maxProfile.relaxVelocities = b2MaxFloat(m_maxProfile.relaxVelocities, p.relaxVelocities); - m_maxProfile.applyRestitution = b2MaxFloat(m_maxProfile.applyRestitution, p.applyRestitution); - m_maxProfile.storeImpulses = b2MaxFloat(m_maxProfile.storeImpulses, p.storeImpulses); - m_maxProfile.finalizeBodies = b2MaxFloat(m_maxProfile.finalizeBodies, p.finalizeBodies); - m_maxProfile.sleepIslands = b2MaxFloat(m_maxProfile.sleepIslands, p.sleepIslands); - m_maxProfile.splitIslands = b2MaxFloat(m_maxProfile.splitIslands, p.splitIslands); - m_maxProfile.hitEvents = b2MaxFloat(m_maxProfile.hitEvents, p.hitEvents); - m_maxProfile.broadphase = b2MaxFloat(m_maxProfile.broadphase, p.broadphase); - m_maxProfile.continuous = b2MaxFloat(m_maxProfile.continuous, p.continuous); + b2Profile p = b2World_GetProfile( m_worldId ); + m_maxProfile.step = b2MaxFloat( m_maxProfile.step, p.step ); + m_maxProfile.pairs = b2MaxFloat( m_maxProfile.pairs, p.pairs ); + m_maxProfile.collide = b2MaxFloat( m_maxProfile.collide, p.collide ); + m_maxProfile.solve = b2MaxFloat( m_maxProfile.solve, p.solve ); + m_maxProfile.buildIslands = b2MaxFloat( m_maxProfile.buildIslands, p.buildIslands ); + m_maxProfile.solveConstraints = b2MaxFloat( m_maxProfile.solveConstraints, p.solveConstraints ); + m_maxProfile.prepareTasks = b2MaxFloat( m_maxProfile.prepareTasks, p.prepareTasks ); + m_maxProfile.solverTasks = b2MaxFloat( m_maxProfile.solverTasks, p.solverTasks ); + m_maxProfile.prepareConstraints = b2MaxFloat( m_maxProfile.prepareConstraints, p.prepareConstraints ); + m_maxProfile.integrateVelocities = b2MaxFloat( m_maxProfile.integrateVelocities, p.integrateVelocities ); + m_maxProfile.warmStart = b2MaxFloat( m_maxProfile.warmStart, p.warmStart ); + m_maxProfile.solveVelocities = b2MaxFloat( m_maxProfile.solveVelocities, p.solveVelocities ); + m_maxProfile.integratePositions = b2MaxFloat( m_maxProfile.integratePositions, p.integratePositions ); + m_maxProfile.relaxVelocities = b2MaxFloat( m_maxProfile.relaxVelocities, p.relaxVelocities ); + m_maxProfile.applyRestitution = b2MaxFloat( m_maxProfile.applyRestitution, p.applyRestitution ); + m_maxProfile.storeImpulses = b2MaxFloat( m_maxProfile.storeImpulses, p.storeImpulses ); + m_maxProfile.finalizeBodies = b2MaxFloat( m_maxProfile.finalizeBodies, p.finalizeBodies ); + m_maxProfile.sleepIslands = b2MaxFloat( m_maxProfile.sleepIslands, p.sleepIslands ); + m_maxProfile.splitIslands = b2MaxFloat( m_maxProfile.splitIslands, p.splitIslands ); + m_maxProfile.hitEvents = b2MaxFloat( m_maxProfile.hitEvents, p.hitEvents ); + m_maxProfile.broadphase = b2MaxFloat( m_maxProfile.broadphase, p.broadphase ); + m_maxProfile.continuous = b2MaxFloat( m_maxProfile.continuous, p.continuous ); m_totalProfile.step += p.step; m_totalProfile.pairs += p.pairs; @@ -365,13 +365,13 @@ void Sample::Step(Settings& settings) m_totalProfile.continuous += p.continuous; } - if (settings.drawProfile) + if ( settings.drawProfile ) { - b2Profile p = b2World_GetProfile(m_worldId); + b2Profile p = b2World_GetProfile( m_worldId ); b2Profile aveProfile; - memset(&aveProfile, 0, sizeof(b2Profile)); - if (m_stepCount > 0) + memset( &aveProfile, 0, sizeof( b2Profile ) ); + if ( m_stepCount > 0 ) { float scale = 1.0f / m_stepCount; aveProfile.step = scale * m_totalProfile.step; @@ -398,75 +398,76 @@ void Sample::Step(Settings& settings) aveProfile.continuous = scale * m_totalProfile.continuous; } - g_draw.DrawString(5, m_textLine, "step [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.step, aveProfile.step, m_maxProfile.step); + g_draw.DrawString( 5, m_textLine, "step [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.step, aveProfile.step, + m_maxProfile.step ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "pairs [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.pairs, aveProfile.pairs, - m_maxProfile.pairs); + g_draw.DrawString( 5, m_textLine, "pairs [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.pairs, aveProfile.pairs, + m_maxProfile.pairs ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "collide [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.collide, aveProfile.collide, - m_maxProfile.collide); + g_draw.DrawString( 5, m_textLine, "collide [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.collide, aveProfile.collide, + m_maxProfile.collide ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "solve [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solve, aveProfile.solve, - m_maxProfile.solve); + g_draw.DrawString( 5, m_textLine, "solve [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solve, aveProfile.solve, + m_maxProfile.solve ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "builds island [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.buildIslands, - aveProfile.buildIslands, m_maxProfile.buildIslands); + g_draw.DrawString( 5, m_textLine, "builds island [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.buildIslands, + aveProfile.buildIslands, m_maxProfile.buildIslands ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "solve constraints [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveConstraints, - aveProfile.solveConstraints, m_maxProfile.solveConstraints); + g_draw.DrawString( 5, m_textLine, "solve constraints [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveConstraints, + aveProfile.solveConstraints, m_maxProfile.solveConstraints ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "prepare tasks [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.prepareTasks, - aveProfile.prepareTasks, m_maxProfile.prepareTasks); + g_draw.DrawString( 5, m_textLine, "prepare tasks [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.prepareTasks, + aveProfile.prepareTasks, m_maxProfile.prepareTasks ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "solver tasks [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solverTasks, - aveProfile.solverTasks, m_maxProfile.solverTasks); + g_draw.DrawString( 5, m_textLine, "solver tasks [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solverTasks, + aveProfile.solverTasks, m_maxProfile.solverTasks ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "prepare constraints [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.prepareConstraints, - aveProfile.prepareConstraints, m_maxProfile.prepareConstraints); + g_draw.DrawString( 5, m_textLine, "prepare constraints [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.prepareConstraints, + aveProfile.prepareConstraints, m_maxProfile.prepareConstraints ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "integrate velocities [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.integrateVelocities, - aveProfile.integrateVelocities, m_maxProfile.integrateVelocities); + g_draw.DrawString( 5, m_textLine, "integrate velocities [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.integrateVelocities, + aveProfile.integrateVelocities, m_maxProfile.integrateVelocities ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "warm start [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.warmStart, aveProfile.warmStart, - m_maxProfile.warmStart); + g_draw.DrawString( 5, m_textLine, "warm start [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.warmStart, aveProfile.warmStart, + m_maxProfile.warmStart ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "solve velocities [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveVelocities, - aveProfile.solveVelocities, m_maxProfile.solveVelocities); + g_draw.DrawString( 5, m_textLine, "solve velocities [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveVelocities, + aveProfile.solveVelocities, m_maxProfile.solveVelocities ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "integrate positions [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.integratePositions, - aveProfile.integratePositions, m_maxProfile.integratePositions); + g_draw.DrawString( 5, m_textLine, "integrate positions [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.integratePositions, + aveProfile.integratePositions, m_maxProfile.integratePositions ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "relax velocities [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.relaxVelocities, - aveProfile.relaxVelocities, m_maxProfile.relaxVelocities); + g_draw.DrawString( 5, m_textLine, "relax velocities [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.relaxVelocities, + aveProfile.relaxVelocities, m_maxProfile.relaxVelocities ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "apply restitution [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.applyRestitution, - aveProfile.applyRestitution, m_maxProfile.applyRestitution); + g_draw.DrawString( 5, m_textLine, "apply restitution [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.applyRestitution, + aveProfile.applyRestitution, m_maxProfile.applyRestitution ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "store impulses [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.storeImpulses, - aveProfile.storeImpulses, m_maxProfile.storeImpulses); + g_draw.DrawString( 5, m_textLine, "store impulses [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.storeImpulses, + aveProfile.storeImpulses, m_maxProfile.storeImpulses ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "finalize bodies [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.finalizeBodies, - aveProfile.finalizeBodies, m_maxProfile.finalizeBodies); + g_draw.DrawString( 5, m_textLine, "finalize bodies [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.finalizeBodies, + aveProfile.finalizeBodies, m_maxProfile.finalizeBodies ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "sleep islands [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.sleepIslands, - aveProfile.sleepIslands, m_maxProfile.sleepIslands); + g_draw.DrawString( 5, m_textLine, "sleep islands [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.sleepIslands, + aveProfile.sleepIslands, m_maxProfile.sleepIslands ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "split islands [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.splitIslands, - aveProfile.splitIslands, m_maxProfile.splitIslands); + g_draw.DrawString( 5, m_textLine, "split islands [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.splitIslands, + aveProfile.splitIslands, m_maxProfile.splitIslands ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "hit events [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.hitEvents, aveProfile.hitEvents, - m_maxProfile.hitEvents); + g_draw.DrawString( 5, m_textLine, "hit events [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.hitEvents, aveProfile.hitEvents, + m_maxProfile.hitEvents ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "broad-phase [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.broadphase, aveProfile.broadphase, - m_maxProfile.broadphase); + g_draw.DrawString( 5, m_textLine, "broad-phase [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.broadphase, aveProfile.broadphase, + m_maxProfile.broadphase ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "continuous collision [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.continuous, - aveProfile.continuous, m_maxProfile.continuous); + g_draw.DrawString( 5, m_textLine, "continuous collision [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.continuous, + aveProfile.continuous, m_maxProfile.continuous ); m_textLine += m_textIncrement; } } -void Sample::ShiftOrigin(b2Vec2 newOrigin) +void Sample::ShiftOrigin( b2Vec2 newOrigin ) { // m_world->ShiftOrigin(newOrigin); } @@ -474,12 +475,12 @@ void Sample::ShiftOrigin(b2Vec2 newOrigin) SampleEntry g_sampleEntries[MAX_SAMPLES] = {}; int g_sampleCount = 0; -int RegisterSample(const char* category, const char* name, SampleCreateFcn* fcn) +int RegisterSample( const char* category, const char* name, SampleCreateFcn* fcn ) { int index = g_sampleCount; - if (index < MAX_SAMPLES) + if ( index < MAX_SAMPLES ) { - g_sampleEntries[index] = {category, name, fcn}; + g_sampleEntries[index] = { category, name, fcn }; ++g_sampleCount; return index; } @@ -487,20 +488,20 @@ int RegisterSample(const char* category, const char* name, SampleCreateFcn* fcn) return -1; } -b2Polygon RandomPolygon(float extent) +b2Polygon RandomPolygon( float extent ) { b2Vec2 points[b2_maxPolygonVertices]; int count = 3 + rand() % 6; - for (int i = 0; i < count; ++i) + for ( int i = 0; i < count; ++i ) { - points[i] = RandomVec2(-extent, extent); + points[i] = RandomVec2( -extent, extent ); } - b2Hull hull = b2ComputeHull(points, count); - if (hull.count > 0) + b2Hull hull = b2ComputeHull( points, count ); + if ( hull.count > 0 ) { - return b2MakePolygon(&hull, 0.0f); + return b2MakePolygon( &hull, 0.0f ); } - return b2MakeSquare(extent); + return b2MakeSquare( extent ); } diff --git a/samples/sample.h b/samples/sample.h index 8539445f..fe4dfd11 100644 --- a/samples/sample.h +++ b/samples/sample.h @@ -3,8 +3,8 @@ #pragma once -#include "box2d/id.h" #include "box2d/collision.h" +#include "box2d/id.h" #include "box2d/types.h" // todo this include is slow @@ -12,7 +12,7 @@ #include -#define ARRAY_COUNT(A) (int)(sizeof(A) / sizeof(A[0])) +#define ARRAY_COUNT( A ) (int)( sizeof( A ) / sizeof( A[0] ) ) struct Settings; @@ -40,12 +40,12 @@ struct ContactPoint class SampleTask : public enki::ITaskSet { - public: +public: SampleTask() = default; - void ExecuteRange(enki::TaskSetPartition range, uint32_t threadIndex) override + void ExecuteRange( enki::TaskSetPartition range, uint32_t threadIndex ) override { - m_task(range.start, range.end, threadIndex, m_taskContext); + m_task( range.start, range.end, threadIndex, m_taskContext ); } b2TaskCallback* m_task = nullptr; @@ -57,24 +57,24 @@ constexpr int32_t maxThreads = 64; class Sample { - public: - explicit Sample(Settings& settings); +public: + explicit Sample( Settings& settings ); virtual ~Sample(); - void DrawTitle(const char* string); - virtual void Step(Settings& settings); + void DrawTitle( const char* string ); + virtual void Step( Settings& settings ); virtual void UpdateUI() { } - virtual void Keyboard(int) + virtual void Keyboard( int ) { } - virtual void MouseDown(b2Vec2 p, int button, int mod); - virtual void MouseUp(b2Vec2 p, int button); - virtual void MouseMove(b2Vec2 p); + virtual void MouseDown( b2Vec2 p, int button, int mod ); + virtual void MouseUp( b2Vec2 p, int button ); + virtual void MouseMove( b2Vec2 p ); void ResetProfile(); - void ShiftOrigin(b2Vec2 newOrigin); + void ShiftOrigin( b2Vec2 newOrigin ); friend class DestructionListener; friend class BoundaryListener; @@ -97,9 +97,9 @@ class Sample b2Profile m_totalProfile; }; -typedef Sample* SampleCreateFcn(Settings& settings); +typedef Sample* SampleCreateFcn( Settings& settings ); -int RegisterSample(const char* category, const char* name, SampleCreateFcn* fcn); +int RegisterSample( const char* category, const char* name, SampleCreateFcn* fcn ); struct SampleEntry { @@ -114,31 +114,37 @@ extern int g_sampleCount; #define RAND_LIMIT 32767 +/// Random integer in range [lo, hi) +inline float RandomInt( int lo, int hi ) +{ + return lo + rand() % ( hi - lo ); +} + /// Random number in range [-1,1] inline float RandomFloat() { - float r = (float)(rand() & (RAND_LIMIT)); + float r = (float)( rand() & ( RAND_LIMIT ) ); r /= RAND_LIMIT; r = 2.0f * r - 1.0f; return r; } /// Random floating point number in range [lo, hi] -inline float RandomFloat(float lo, float hi) +inline float RandomFloat( float lo, float hi ) { - float r = (float)(rand() & (RAND_LIMIT)); + float r = (float)( rand() & ( RAND_LIMIT ) ); r /= RAND_LIMIT; - r = (hi - lo) * r + lo; + r = ( hi - lo ) * r + lo; return r; } /// Random vector with coordinates in range [lo, hi] -inline b2Vec2 RandomVec2(float lo, float hi) +inline b2Vec2 RandomVec2( float lo, float hi ) { b2Vec2 v; - v.x = RandomFloat(lo, hi); - v.y = RandomFloat(lo, hi); + v.x = RandomFloat( lo, hi ); + v.y = RandomFloat( lo, hi ); return v; } -b2Polygon RandomPolygon(float extent); +b2Polygon RandomPolygon( float extent ); diff --git a/samples/sample_benchmark.cpp b/samples/sample_benchmark.cpp index 2e01372b..8878a0ad 100644 --- a/samples/sample_benchmark.cpp +++ b/samples/sample_benchmark.cpp @@ -31,12 +31,12 @@ class BenchmarkBarrel : public Sample e_maxRows = 130, }; - explicit BenchmarkBarrel(Settings& settings) - : Sample(settings) + explicit BenchmarkBarrel( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {8.0f, 53.0f}; + g_camera.m_center = { 8.0f, 53.0f }; g_camera.m_zoom = 25.0f * 2.35f; } @@ -46,23 +46,23 @@ class BenchmarkBarrel : public Sample { b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); - b2Polygon box = b2MakeBox(groundSize, 1.2f); + b2Polygon box = b2MakeBox( groundSize, 1.2f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreatePolygonShape(groundId, &shapeDef, &box); + b2CreatePolygonShape( groundId, &shapeDef, &box ); - box = b2MakeOffsetBox(1.2f, 2.0f * groundSize, {-groundSize, 2.0f * groundSize}, 0.0f); - b2CreatePolygonShape(groundId, &shapeDef, &box); + box = b2MakeOffsetBox( 1.2f, 2.0f * groundSize, { -groundSize, 2.0f * groundSize }, 0.0f ); + b2CreatePolygonShape( groundId, &shapeDef, &box ); - box = b2MakeOffsetBox(1.2f, 2.0f * groundSize, {groundSize, 2.0f * groundSize}, 0.0f); - b2CreatePolygonShape(groundId, &shapeDef, &box); + box = b2MakeOffsetBox( 1.2f, 2.0f * groundSize, { groundSize, 2.0f * groundSize }, 0.0f ); + b2CreatePolygonShape( groundId, &shapeDef, &box ); - box = b2MakeOffsetBox(800.0f, 10.0f, {0.0f, -80.0f}, 0.0f); - b2CreatePolygonShape(groundId, &shapeDef, &box); + box = b2MakeOffsetBox( 800.0f, 10.0f, { 0.0f, -80.0f }, 0.0f ); + b2CreatePolygonShape( groundId, &shapeDef, &box ); } - for (int i = 0; i < e_maxRows * e_maxColumns; ++i) + for ( int i = 0; i < e_maxRows * e_maxColumns; ++i ) { m_bodies[i] = b2_nullBodyId; } @@ -74,17 +74,17 @@ class BenchmarkBarrel : public Sample void CreateScene() { - srand(42); + srand( 42 ); - for (int i = 0; i < e_maxRows * e_maxColumns; ++i) + for ( int i = 0; i < e_maxRows * e_maxColumns; ++i ) { - if (B2_IS_NON_NULL(m_bodies[i])) + if ( B2_IS_NON_NULL( m_bodies[i] ) ) { - b2DestroyBody(m_bodies[i]); + b2DestroyBody( m_bodies[i] ); m_bodies[i] = b2_nullBodyId; } - if (m_humans[i].m_isSpawned) + if ( m_humans[i].m_isSpawned ) { m_humans[i].Despawn(); } @@ -93,16 +93,16 @@ class BenchmarkBarrel : public Sample m_columnCount = g_sampleDebug ? 10 : e_maxColumns; m_rowCount = g_sampleDebug ? 40 : e_maxRows; - if (m_shapeType == e_compoundShape) + if ( m_shapeType == e_compoundShape ) { - if constexpr (g_sampleDebug == false) + if constexpr ( g_sampleDebug == false ) { m_columnCount = 20; } } - else if (m_shapeType == e_humanShape) + else if ( m_shapeType == e_humanShape ) { - if constexpr (g_sampleDebug) + if constexpr ( g_sampleDebug ) { m_rowCount = 5; m_columnCount = 10; @@ -127,25 +127,25 @@ class BenchmarkBarrel : public Sample shapeDef.density = 1.0f; shapeDef.friction = 0.5f; - b2Capsule capsule = {{0.0f, -0.25f}, {0.0f, 0.25f}, rad}; - b2Circle circle = {{0.0f, 0.0f}, rad}; + b2Capsule capsule = { { 0.0f, -0.25f }, { 0.0f, 0.25f }, rad }; + b2Circle circle = { { 0.0f, 0.0f }, rad }; + + b2Vec2 points[3] = { { -0.1f, -0.5f }, { 0.1f, -0.5f }, { 0.0f, 0.5f } }; + b2Hull wedgeHull = b2ComputeHull( points, 3 ); + b2Polygon wedge = b2MakePolygon( &wedgeHull, 0.0f ); - b2Vec2 points[3] = {{-0.1f, -0.5f}, {0.1f, -0.5f}, {0.0f, 0.5f}}; - b2Hull wedgeHull = b2ComputeHull(points, 3); - b2Polygon wedge = b2MakePolygon(&wedgeHull, 0.0f); - b2Vec2 vertices[3]; - vertices[0] = {-1.0f, 0.0f}; - vertices[1] = {0.5f, 1.0f}; - vertices[2] = {0.0f, 2.0f}; - b2Hull hull = b2ComputeHull(vertices, 3); - b2Polygon left = b2MakePolygon(&hull, 0.0f); - - vertices[0] = {1.0f, 0.0f}; - vertices[1] = {-0.5f, 1.0f}; - vertices[2] = {0.0f, 2.0f}; - hull = b2ComputeHull(vertices, 3); - b2Polygon right = b2MakePolygon(&hull, 0.0f); + vertices[0] = { -1.0f, 0.0f }; + vertices[1] = { 0.5f, 1.0f }; + vertices[2] = { 0.0f, 2.0f }; + b2Hull hull = b2ComputeHull( vertices, 3 ); + b2Polygon left = b2MakePolygon( &hull, 0.0f ); + + vertices[0] = { 1.0f, 0.0f }; + vertices[1] = { -0.5f, 1.0f }; + vertices[2] = { 0.0f, 2.0f }; + hull = b2ComputeHull( vertices, 3 ); + b2Polygon right = b2MakePolygon( &hull, 0.0f ); // b2Polygon top = b2MakeOffsetBox(0.8f, 0.2f, {0.0f, 0.8f}, 0.0f); // b2Polygon leftLeg = b2MakeOffsetBox(0.2f, 0.5f, {-0.6f, 0.5f}, 0.0f); @@ -153,15 +153,15 @@ class BenchmarkBarrel : public Sample float side = -0.1f; float extray = 0.5f; - - if (m_shapeType == e_compoundShape) + + if ( m_shapeType == e_compoundShape ) { extray = 0.25f; side = 0.25f; shift = 2.0f; centerx = shift * m_columnCount / 2.0f - 1.0f; } - else if (m_shapeType == e_humanShape) + else if ( m_shapeType == e_humanShape ) { extray = 0.5f; side = 0.55f; @@ -171,80 +171,80 @@ class BenchmarkBarrel : public Sample int index = 0; - for (int i = 0; i < m_columnCount; ++i) + for ( int i = 0; i < m_columnCount; ++i ) { float x = i * shift - centerx; - for (int j = 0; j < m_rowCount; ++j) + for ( int j = 0; j < m_rowCount; ++j ) { - float y = j * (shift + extray) + centery + 2.0f; + float y = j * ( shift + extray ) + centery + 2.0f; - bodyDef.position = {x + side, y}; + bodyDef.position = { x + side, y }; side = -side; - if (m_shapeType == e_circleShape) + if ( m_shapeType == e_circleShape ) { - m_bodies[index] = b2CreateBody(m_worldId, &bodyDef); - circle.radius = RandomFloat(0.25f, 0.75f); - b2CreateCircleShape(m_bodies[index], &shapeDef, &circle); + m_bodies[index] = b2CreateBody( m_worldId, &bodyDef ); + circle.radius = RandomFloat( 0.25f, 0.75f ); + b2CreateCircleShape( m_bodies[index], &shapeDef, &circle ); } - else if (m_shapeType == e_caspuleShape) + else if ( m_shapeType == e_caspuleShape ) { - m_bodies[index] = b2CreateBody(m_worldId, &bodyDef); - capsule.radius = RandomFloat(0.25f, 0.5f); - float length = RandomFloat(0.25f, 1.0f); - capsule.center1 = {0.0f, -0.5f * length}; - capsule.center2 = {0.0f, 0.5f * length}; - b2CreateCapsuleShape(m_bodies[index], &shapeDef, &capsule); + m_bodies[index] = b2CreateBody( m_worldId, &bodyDef ); + capsule.radius = RandomFloat( 0.25f, 0.5f ); + float length = RandomFloat( 0.25f, 1.0f ); + capsule.center1 = { 0.0f, -0.5f * length }; + capsule.center2 = { 0.0f, 0.5f * length }; + b2CreateCapsuleShape( m_bodies[index], &shapeDef, &capsule ); } - else if (m_shapeType == e_mixShape) + else if ( m_shapeType == e_mixShape ) { - m_bodies[index] = b2CreateBody(m_worldId, &bodyDef); + m_bodies[index] = b2CreateBody( m_worldId, &bodyDef ); int mod = index % 3; - if (mod == 0) + if ( mod == 0 ) { - circle.radius = RandomFloat(0.25f, 0.75f); - b2CreateCircleShape(m_bodies[index], &shapeDef, &circle); + circle.radius = RandomFloat( 0.25f, 0.75f ); + b2CreateCircleShape( m_bodies[index], &shapeDef, &circle ); } - else if (mod == 1) + else if ( mod == 1 ) { - capsule.radius = RandomFloat(0.25f, 0.5f); - float length = RandomFloat(0.25f, 1.0f); - capsule.center1 = {0.0f, -0.5f * length}; - capsule.center2 = {0.0f, 0.5f * length}; - b2CreateCapsuleShape(m_bodies[index], &shapeDef, &capsule); + capsule.radius = RandomFloat( 0.25f, 0.5f ); + float length = RandomFloat( 0.25f, 1.0f ); + capsule.center1 = { 0.0f, -0.5f * length }; + capsule.center2 = { 0.0f, 0.5f * length }; + b2CreateCapsuleShape( m_bodies[index], &shapeDef, &capsule ); } - else if (mod == 2) + else if ( mod == 2 ) { - float width = RandomFloat(0.1f, 0.5f); - float height = RandomFloat(0.5f, 0.75f); - b2Polygon box = b2MakeBox(width, height); + float width = RandomFloat( 0.1f, 0.5f ); + float height = RandomFloat( 0.5f, 0.75f ); + b2Polygon box = b2MakeBox( width, height ); // Don't put a function call into a macro. - float value = RandomFloat(-1.0f, 1.0f); - box.radius = 0.25f * b2MaxFloat(0.0f, value); - b2CreatePolygonShape(m_bodies[index], &shapeDef, &box); + float value = RandomFloat( -1.0f, 1.0f ); + box.radius = 0.25f * b2MaxFloat( 0.0f, value ); + b2CreatePolygonShape( m_bodies[index], &shapeDef, &box ); } else { - wedge.radius = RandomFloat(0.1f, 0.25f); - b2CreatePolygonShape(m_bodies[index], &shapeDef, &wedge); + wedge.radius = RandomFloat( 0.1f, 0.25f ); + b2CreatePolygonShape( m_bodies[index], &shapeDef, &wedge ); } } - else if (m_shapeType == e_compoundShape) + else if ( m_shapeType == e_compoundShape ) { - m_bodies[index] = b2CreateBody(m_worldId, &bodyDef); + m_bodies[index] = b2CreateBody( m_worldId, &bodyDef ); - b2CreatePolygonShape(m_bodies[index], &shapeDef, &left); - b2CreatePolygonShape(m_bodies[index], &shapeDef, &right); + b2CreatePolygonShape( m_bodies[index], &shapeDef, &left ); + b2CreatePolygonShape( m_bodies[index], &shapeDef, &right ); // b2CreatePolygonShape(m_bodies[index], &shapeDef, &top); // b2CreatePolygonShape(m_bodies[index], &shapeDef, &leftLeg); // b2CreatePolygonShape(m_bodies[index], &shapeDef, &rightLeg); } - else if (m_shapeType == e_humanShape) + else if ( m_shapeType == e_humanShape ) { - m_humans[index].Spawn(m_worldId, bodyDef.position, 3.5f, index + 1, nullptr); + m_humans[index].Spawn( m_worldId, bodyDef.position, 3.5f, 0.05f, 0.0f, 0.0f, index + 1, nullptr, false ); } index += 1; @@ -255,20 +255,20 @@ class BenchmarkBarrel : public Sample void UpdateUI() override { float height = 80.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(220.0f, height)); - ImGui::Begin("Benchmark: Barrel", nullptr, ImGuiWindowFlags_NoResize); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 220.0f, height ) ); + ImGui::Begin( "Benchmark: Barrel", nullptr, ImGuiWindowFlags_NoResize ); bool changed = false; - const char* shapeTypes[] = {"Circle", "Capsule", "Mix", "Compound", "Human"}; + const char* shapeTypes[] = { "Circle", "Capsule", "Mix", "Compound", "Human" }; - int shapeType = int(m_shapeType); - changed = changed || ImGui::Combo("Shape", &shapeType, shapeTypes, IM_ARRAYSIZE(shapeTypes)); - m_shapeType = ShapeType(shapeType); + int shapeType = int( m_shapeType ); + changed = changed || ImGui::Combo( "Shape", &shapeType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ); + m_shapeType = ShapeType( shapeType ); - changed = changed || ImGui::Button("Reset Scene"); + changed = changed || ImGui::Button( "Reset Scene" ); - if (changed) + if ( changed ) { CreateScene(); } @@ -276,9 +276,9 @@ class BenchmarkBarrel : public Sample ImGui::End(); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new BenchmarkBarrel(settings); + return new BenchmarkBarrel( settings ); } b2BodyId m_bodies[e_maxRows * e_maxColumns]; @@ -289,45 +289,45 @@ class BenchmarkBarrel : public Sample ShapeType m_shapeType; }; -static int benchmarkBarrel = RegisterSample("Benchmark", "Barrel", BenchmarkBarrel::Create); +static int benchmarkBarrel = RegisterSample( "Benchmark", "Barrel", BenchmarkBarrel::Create ); class BenchmarkTumbler : public Sample { public: - explicit BenchmarkTumbler(Settings& settings) - : Sample(settings) + explicit BenchmarkTumbler( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {1.5f, 10.0f}; + g_camera.m_center = { 1.5f, 10.0f }; g_camera.m_zoom = 25.0f * 0.6f; } b2BodyId groundId; { b2BodyDef bodyDef = b2DefaultBodyDef(); - groundId = b2CreateBody(m_worldId, &bodyDef); + groundId = b2CreateBody( m_worldId, &bodyDef ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.enableSleep = true; - bodyDef.position = {0.0f, 10.0f}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { 0.0f, 10.0f }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 50.0f; b2Polygon polygon; - polygon = b2MakeOffsetBox(0.5f, 10.0f, {10.0f, 0.0f}, 0.0); - b2CreatePolygonShape(bodyId, &shapeDef, &polygon); - polygon = b2MakeOffsetBox(0.5f, 10.0f, {-10.0f, 0.0f}, 0.0); - b2CreatePolygonShape(bodyId, &shapeDef, &polygon); - polygon = b2MakeOffsetBox(10.0f, 0.5f, {0.0f, 10.0f}, 0.0); - b2CreatePolygonShape(bodyId, &shapeDef, &polygon); - polygon = b2MakeOffsetBox(10.0f, 0.5f, {0.0f, -10.0f}, 0.0); - b2CreatePolygonShape(bodyId, &shapeDef, &polygon); + polygon = b2MakeOffsetBox( 0.5f, 10.0f, { 10.0f, 0.0f }, 0.0 ); + b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); + polygon = b2MakeOffsetBox( 0.5f, 10.0f, { -10.0f, 0.0f }, 0.0 ); + b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); + polygon = b2MakeOffsetBox( 10.0f, 0.5f, { 0.0f, 10.0f }, 0.0 ); + b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); + polygon = b2MakeOffsetBox( 10.0f, 0.5f, { 0.0f, -10.0f }, 0.0 ); + b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); // m_motorSpeed = 9.0f; m_motorSpeed = 25.0f; @@ -335,33 +335,33 @@ class BenchmarkTumbler : public Sample b2RevoluteJointDef jd = b2DefaultRevoluteJointDef(); jd.bodyIdA = groundId; jd.bodyIdB = bodyId; - jd.localAnchorA = {0.0f, 10.0f}; - jd.localAnchorB = {0.0f, 0.0f}; + jd.localAnchorA = { 0.0f, 10.0f }; + jd.localAnchorB = { 0.0f, 0.0f }; jd.referenceAngle = 0.0f; - jd.motorSpeed = (b2_pi / 180.0f) * m_motorSpeed; + jd.motorSpeed = ( b2_pi / 180.0f ) * m_motorSpeed; jd.maxMotorTorque = 1e8f; jd.enableMotor = true; - m_jointId = b2CreateRevoluteJoint(m_worldId, &jd); + m_jointId = b2CreateRevoluteJoint( m_worldId, &jd ); } int gridCount = g_sampleDebug ? 20 : 45; - b2Polygon polygon = b2MakeBox(0.125f, 0.125f); + b2Polygon polygon = b2MakeBox( 0.125f, 0.125f ); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; b2ShapeDef shapeDef = b2DefaultShapeDef(); float y = -0.2f * gridCount + 10.0f; - for (int i = 0; i < gridCount; ++i) + for ( int i = 0; i < gridCount; ++i ) { float x = -0.2f * gridCount; - for (int j = 0; j < gridCount; ++j) + for ( int j = 0; j < gridCount; ++j ) { - bodyDef.position = {x, y}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { x, y }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); - b2CreatePolygonShape(bodyId, &shapeDef, &polygon); + b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); x += 0.4f; } @@ -373,18 +373,18 @@ class BenchmarkTumbler : public Sample void UpdateUI() override { float height = 60.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(200.0f, height)); - ImGui::Begin("Benchmark: Tumbler", nullptr, ImGuiWindowFlags_NoResize); - ImGui::PushItemWidth(120.0f); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 200.0f, height ) ); + ImGui::Begin( "Benchmark: Tumbler", nullptr, ImGuiWindowFlags_NoResize ); + ImGui::PushItemWidth( 120.0f ); - if (ImGui::SliderFloat("Speed", &m_motorSpeed, 0.0f, 100.0f, "%.f")) + if ( ImGui::SliderFloat( "Speed", &m_motorSpeed, 0.0f, 100.0f, "%.f" ) ) { - b2RevoluteJoint_SetMotorSpeed(m_jointId, (b2_pi / 180.0f) * m_motorSpeed); + b2RevoluteJoint_SetMotorSpeed( m_jointId, ( b2_pi / 180.0f ) * m_motorSpeed ); - if (m_motorSpeed > 0.0f) + if ( m_motorSpeed > 0.0f ) { - b2Joint_WakeBodies(m_jointId); + b2Joint_WakeBodies( m_jointId ); } } @@ -392,33 +392,33 @@ class BenchmarkTumbler : public Sample ImGui::End(); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new BenchmarkTumbler(settings); + return new BenchmarkTumbler( settings ); } b2JointId m_jointId; float m_motorSpeed; }; -static int benchmarkTumbler = RegisterSample("Benchmark", "Tumbler", BenchmarkTumbler::Create); +static int benchmarkTumbler = RegisterSample( "Benchmark", "Tumbler", BenchmarkTumbler::Create ); // todo try removing kinematics from graph coloring class BenchmarkManyTumblers : public Sample { public: - explicit BenchmarkManyTumblers(Settings& settings) - : Sample(settings) + explicit BenchmarkManyTumblers( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {1.0f, -5.5}; + g_camera.m_center = { 1.0f, -5.5 }; g_camera.m_zoom = 25.0f * 3.4f; settings.drawJoints = false; } b2BodyDef bodyDef = b2DefaultBodyDef(); - m_groundId = b2CreateBody(m_worldId, &bodyDef); + m_groundId = b2CreateBody( m_worldId, &bodyDef ); m_rowCount = g_sampleDebug ? 2 : 19; m_columnCount = g_sampleDebug ? 2 : 19; @@ -438,65 +438,65 @@ class BenchmarkManyTumblers : public Sample ~BenchmarkManyTumblers() override { - free(m_tumblerIds); - free(m_positions); - free(m_bodyIds); + free( m_tumblerIds ); + free( m_positions ); + free( m_bodyIds ); } - void CreateTumbler(b2Vec2 position, int index) + void CreateTumbler( b2Vec2 position, int index ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_kinematicBody; - bodyDef.position = {position.x, position.y}; - bodyDef.angularVelocity = (b2_pi / 180.0f) * m_angularSpeed; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { position.x, position.y }; + bodyDef.angularVelocity = ( b2_pi / 180.0f ) * m_angularSpeed; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); m_tumblerIds[index] = bodyId; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 50.0f; b2Polygon polygon; - polygon = b2MakeOffsetBox(0.25f, 2.0f, {2.0f, 0.0f}, 0.0); - b2CreatePolygonShape(bodyId, &shapeDef, &polygon); - polygon = b2MakeOffsetBox(0.25f, 2.0f, {-2.0f, 0.0f}, 0.0); - b2CreatePolygonShape(bodyId, &shapeDef, &polygon); - polygon = b2MakeOffsetBox(2.0f, 0.25f, {0.0f, 2.0f}, 0.0); - b2CreatePolygonShape(bodyId, &shapeDef, &polygon); - polygon = b2MakeOffsetBox(2.0f, 0.25f, {0.0f, -2.0f}, 0.0); - b2CreatePolygonShape(bodyId, &shapeDef, &polygon); + polygon = b2MakeOffsetBox( 0.25f, 2.0f, { 2.0f, 0.0f }, 0.0 ); + b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); + polygon = b2MakeOffsetBox( 0.25f, 2.0f, { -2.0f, 0.0f }, 0.0 ); + b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); + polygon = b2MakeOffsetBox( 2.0f, 0.25f, { 0.0f, 2.0f }, 0.0 ); + b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); + polygon = b2MakeOffsetBox( 2.0f, 0.25f, { 0.0f, -2.0f }, 0.0 ); + b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); } void CreateScene() { - for (int i = 0; i < m_bodyCount; ++i) + for ( int i = 0; i < m_bodyCount; ++i ) { - if (B2_IS_NON_NULL(m_bodyIds[i])) + if ( B2_IS_NON_NULL( m_bodyIds[i] ) ) { - b2DestroyBody(m_bodyIds[i]); + b2DestroyBody( m_bodyIds[i] ); } } - for (int i = 0; i < m_tumblerCount; ++i) + for ( int i = 0; i < m_tumblerCount; ++i ) { - b2DestroyBody(m_tumblerIds[i]); + b2DestroyBody( m_tumblerIds[i] ); } - free(m_tumblerIds); - free(m_positions); + free( m_tumblerIds ); + free( m_positions ); m_tumblerCount = m_rowCount * m_columnCount; - m_tumblerIds = static_cast(malloc(m_tumblerCount * sizeof(b2BodyId))); - m_positions = static_cast(malloc(m_tumblerCount * sizeof(b2Vec2))); + m_tumblerIds = static_cast( malloc( m_tumblerCount * sizeof( b2BodyId ) ) ); + m_positions = static_cast( malloc( m_tumblerCount * sizeof( b2Vec2 ) ) ); int index = 0; float x = -4.0f * m_rowCount; - for (int i = 0; i < m_rowCount; ++i) + for ( int i = 0; i < m_rowCount; ++i ) { float y = -4.0f * m_columnCount; - for (int j = 0; j < m_columnCount; ++j) + for ( int j = 0; j < m_columnCount; ++j ) { - m_positions[index] = {x, y}; - CreateTumbler(m_positions[index], index); + m_positions[index] = { x, y }; + CreateTumbler( m_positions[index], index ); ++index; y += 8.0f; } @@ -504,40 +504,40 @@ class BenchmarkManyTumblers : public Sample x += 8.0f; } - free(m_bodyIds); + free( m_bodyIds ); int bodiesPerTumbler = g_sampleDebug ? 8 : 50; m_bodyCount = bodiesPerTumbler * m_tumblerCount; - m_bodyIds = static_cast(malloc(m_bodyCount * sizeof(b2BodyId))); + m_bodyIds = static_cast( malloc( m_bodyCount * sizeof( b2BodyId ) ) ); - memset(m_bodyIds, 0, m_bodyCount * sizeof(b2BodyId)); + memset( m_bodyIds, 0, m_bodyCount * sizeof( b2BodyId ) ); m_bodyIndex = 0; } void UpdateUI() override { float height = 110.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(200.0f, height)); - ImGui::Begin("Benchmark: Many Tumblers", nullptr, ImGuiWindowFlags_NoResize); - ImGui::PushItemWidth(100.0f); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 200.0f, height ) ); + ImGui::Begin( "Benchmark: Many Tumblers", nullptr, ImGuiWindowFlags_NoResize ); + ImGui::PushItemWidth( 100.0f ); bool changed = false; - changed = changed || ImGui::SliderInt("Row Count", &m_rowCount, 1, 32); - changed = changed || ImGui::SliderInt("Column Count", &m_columnCount, 1, 32); + changed = changed || ImGui::SliderInt( "Row Count", &m_rowCount, 1, 32 ); + changed = changed || ImGui::SliderInt( "Column Count", &m_columnCount, 1, 32 ); - if (changed) + if ( changed ) { CreateScene(); } - if (ImGui::SliderFloat("Speed", &m_angularSpeed, 0.0f, 100.0f, "%.f")) + if ( ImGui::SliderFloat( "Speed", &m_angularSpeed, 0.0f, 100.0f, "%.f" ) ) { - for (int i = 0; i < m_tumblerCount; ++i) + for ( int i = 0; i < m_tumblerCount; ++i ) { - b2Body_SetAngularVelocity(m_tumblerIds[i], (b2_pi / 180.0f) * m_angularSpeed); - b2Body_SetAwake(m_tumblerIds[i], true); + b2Body_SetAngularVelocity( m_tumblerIds[i], ( b2_pi / 180.0f ) * m_angularSpeed ); + b2Body_SetAwake( m_tumblerIds[i], true ); } } @@ -545,34 +545,34 @@ class BenchmarkManyTumblers : public Sample ImGui::End(); } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - Sample::Step(settings); + Sample::Step( settings ); - if (m_bodyIndex < m_bodyCount && (m_stepCount & 0x7) == 0) + if ( m_bodyIndex < m_bodyCount && ( m_stepCount & 0x7 ) == 0 ) { b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Capsule capsule = {{-0.1f, 0.0f}, {0.1f, 0.0f}, 0.075f}; + b2Capsule capsule = { { -0.1f, 0.0f }, { 0.1f, 0.0f }, 0.075f }; - for (int i = 0; i < m_tumblerCount; ++i) + for ( int i = 0; i < m_tumblerCount; ++i ) { - assert(m_bodyIndex < m_bodyCount); + assert( m_bodyIndex < m_bodyCount ); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.position = m_positions[i]; - m_bodyIds[m_bodyIndex] = b2CreateBody(m_worldId, &bodyDef); - b2CreateCapsuleShape(m_bodyIds[m_bodyIndex], &shapeDef, &capsule); + m_bodyIds[m_bodyIndex] = b2CreateBody( m_worldId, &bodyDef ); + b2CreateCapsuleShape( m_bodyIds[m_bodyIndex], &shapeDef, &capsule ); m_bodyIndex += 1; } } } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new BenchmarkManyTumblers(settings); + return new BenchmarkManyTumblers( settings ); } b2BodyId m_groundId; @@ -591,17 +591,17 @@ class BenchmarkManyTumblers : public Sample float m_angularSpeed; }; -static int benchmarkManyTumblers = RegisterSample("Benchmark", "Many Tumblers", BenchmarkManyTumblers::Create); +static int benchmarkManyTumblers = RegisterSample( "Benchmark", "Many Tumblers", BenchmarkManyTumblers::Create ); class BenchmarkLargePyramid : public Sample { public: - explicit BenchmarkLargePyramid(Settings& settings) - : Sample(settings) + explicit BenchmarkLargePyramid( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 50.0f}; + g_camera.m_center = { 0.0f, 50.0f }; g_camera.m_zoom = 25.0f * 2.2f; } @@ -613,12 +613,12 @@ class BenchmarkLargePyramid : public Sample { b2BodyDef bodyDef = b2DefaultBodyDef(); - bodyDef.position = {0.0f, -1.0f}; - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { 0.0f, -1.0f }; + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); - b2Polygon box = b2MakeBox(100.0f, 1.0f); + b2Polygon box = b2MakeBox( 100.0f, 1.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreatePolygonShape(groundId, &shapeDef, &box); + b2CreatePolygonShape( groundId, &shapeDef, &box ); } b2BodyDef bodyDef = b2DefaultBodyDef(); @@ -628,43 +628,43 @@ class BenchmarkLargePyramid : public Sample shapeDef.density = 1.0f; float h = 0.5f; - b2Polygon box = b2MakeRoundedBox(h - 0.05f, h - 0.05f, 0.05f); + b2Polygon box = b2MakeRoundedBox( h - 0.05f, h - 0.05f, 0.05f ); float shift = 1.0f * h; - for (int i = 0; i < baseCount; ++i) + for ( int i = 0; i < baseCount; ++i ) { - float y = (2.0f * i + 1.0f) * shift; + float y = ( 2.0f * i + 1.0f ) * shift; - for (int j = i; j < baseCount; ++j) + for ( int j = i; j < baseCount; ++j ) { - float x = (i + 1.0f) * shift + 2.0f * (j - i) * shift - h * baseCount; + float x = ( i + 1.0f ) * shift + 2.0f * ( j - i ) * shift - h * baseCount; - bodyDef.position = {x, y}; + bodyDef.position = { x, y }; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); } } } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new BenchmarkLargePyramid(settings); + return new BenchmarkLargePyramid( settings ); } }; -static int benchmarkLargePyramid = RegisterSample("Benchmark", "Large Pyramid", BenchmarkLargePyramid::Create); +static int benchmarkLargePyramid = RegisterSample( "Benchmark", "Large Pyramid", BenchmarkLargePyramid::Create ); class BenchmarkManyPyramids : public Sample { public: - explicit BenchmarkManyPyramids(Settings& settings) - : Sample(settings) + explicit BenchmarkManyPyramids( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {16.0f, 110.0f}; + g_camera.m_center = { 16.0f, 110.0f }; g_camera.m_zoom = 25.0f * 5.0f; } @@ -683,10 +683,10 @@ class BenchmarkManyPyramids : public Sample ~BenchmarkManyPyramids() override { - free(m_bodyIds); + free( m_bodyIds ); } - void CreatePyramid(float centerX, float baseY) + void CreatePyramid( float centerX, float baseY ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; @@ -695,23 +695,23 @@ class BenchmarkManyPyramids : public Sample shapeDef.density = 1.0f; float h = m_extent - m_round; - b2Polygon box = b2MakeRoundedBox(h, h, m_round); + b2Polygon box = b2MakeRoundedBox( h, h, m_round ); float shift = 1.0f * h; - for (int i = 0; i < m_baseCount; ++i) + for ( int i = 0; i < m_baseCount; ++i ) { - float y = (2.0f * i + 1.0f) * shift + baseY; + float y = ( 2.0f * i + 1.0f ) * shift + baseY; - for (int j = i; j < m_baseCount; ++j) + for ( int j = i; j < m_baseCount; ++j ) { - float x = (i + 1.0f) * shift + 2.0f * (j - i) * shift + centerX - 0.5f; + float x = ( i + 1.0f ) * shift + 2.0f * ( j - i ) * shift + centerX - 0.5f; - bodyDef.position = {x, y}; + bodyDef.position = { x, y }; - assert(m_bodyIndex < m_bodyCount); - m_bodyIds[m_bodyIndex] = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(m_bodyIds[m_bodyIndex], &shapeDef, &box); + assert( m_bodyIndex < m_bodyCount ); + m_bodyIds[m_bodyIndex] = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( m_bodyIds[m_bodyIndex], &shapeDef, &box ); m_bodyIndex += 1; } @@ -720,73 +720,73 @@ class BenchmarkManyPyramids : public Sample void CreateScene() { - if (B2_IS_NON_NULL(m_groundId)) + if ( B2_IS_NON_NULL( m_groundId ) ) { - b2DestroyBody(m_groundId); + b2DestroyBody( m_groundId ); } - for (int i = 0; i < m_bodyCount; ++i) + for ( int i = 0; i < m_bodyCount; ++i ) { - b2DestroyBody(m_bodyIds[i]); + b2DestroyBody( m_bodyIds[i] ); } - free(m_bodyIds); + free( m_bodyIds ); - m_bodyCount = m_rowCount * m_columnCount * m_baseCount * (m_baseCount + 1) / 2; - m_bodyIds = (b2BodyId*)malloc(m_bodyCount * sizeof(b2BodyId)); + m_bodyCount = m_rowCount * m_columnCount * m_baseCount * ( m_baseCount + 1 ) / 2; + m_bodyIds = (b2BodyId*)malloc( m_bodyCount * sizeof( b2BodyId ) ); m_bodyIndex = 0; b2BodyDef bodyDef = b2DefaultBodyDef(); - m_groundId = b2CreateBody(m_worldId, &bodyDef); + m_groundId = b2CreateBody( m_worldId, &bodyDef ); - float groundDeltaY = 2.0f * m_extent * (m_baseCount + 1.0f); - float groundWidth = 2.0f * m_extent * m_columnCount * (m_baseCount + 1.0f); + float groundDeltaY = 2.0f * m_extent * ( m_baseCount + 1.0f ); + float groundWidth = 2.0f * m_extent * m_columnCount * ( m_baseCount + 1.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); float groundY = 0.0f; - for (int i = 0; i < m_rowCount; ++i) + for ( int i = 0; i < m_rowCount; ++i ) { // b2Segment segment = {{-0.5f * groundWidth, groundY}, {0.5f * groundWidth, groundY}}; - b2Segment segment = {{-0.5f * 2.0f * groundWidth, groundY}, {0.5f * 2.0f * groundWidth, groundY}}; - b2CreateSegmentShape(m_groundId, &shapeDef, &segment); + b2Segment segment = { { -0.5f * 2.0f * groundWidth, groundY }, { 0.5f * 2.0f * groundWidth, groundY } }; + b2CreateSegmentShape( m_groundId, &shapeDef, &segment ); groundY += groundDeltaY; } float baseWidth = 2.0f * m_extent * m_baseCount; float baseY = 0.0f; - for (int i = 0; i < m_rowCount; ++i) + for ( int i = 0; i < m_rowCount; ++i ) { - for (int j = 0; j < m_columnCount; ++j) + for ( int j = 0; j < m_columnCount; ++j ) { - float centerX = -0.5f * groundWidth + j * (baseWidth + 2.0f * m_extent) + m_extent; - CreatePyramid(centerX, baseY); + float centerX = -0.5f * groundWidth + j * ( baseWidth + 2.0f * m_extent ) + m_extent; + CreatePyramid( centerX, baseY ); } baseY += groundDeltaY; } - assert(m_bodyIndex == m_bodyCount); + assert( m_bodyIndex == m_bodyCount ); } void UpdateUI() override { float height = 160.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(200.0f, height)); - ImGui::Begin("Benchmark: Many Pyramids", nullptr, ImGuiWindowFlags_NoResize); - ImGui::PushItemWidth(100.0f); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 200.0f, height ) ); + ImGui::Begin( "Benchmark: Many Pyramids", nullptr, ImGuiWindowFlags_NoResize ); + ImGui::PushItemWidth( 100.0f ); bool changed = false; - changed = changed || ImGui::SliderInt("Row Count", &m_rowCount, 1, 32); - changed = changed || ImGui::SliderInt("Column Count", &m_columnCount, 1, 32); - changed = changed || ImGui::SliderInt("Base Count", &m_baseCount, 1, 30); + changed = changed || ImGui::SliderInt( "Row Count", &m_rowCount, 1, 32 ); + changed = changed || ImGui::SliderInt( "Column Count", &m_columnCount, 1, 32 ); + changed = changed || ImGui::SliderInt( "Base Count", &m_baseCount, 1, 30 ); - changed = changed || ImGui::SliderFloat("Round", &m_round, 0.0f, 0.4f, "%.1f"); - changed = changed || ImGui::Button("Reset Scene"); + changed = changed || ImGui::SliderFloat( "Round", &m_round, 0.0f, 0.4f, "%.1f" ); + changed = changed || ImGui::Button( "Reset Scene" ); - if (changed) + if ( changed ) { CreateScene(); } @@ -795,9 +795,9 @@ class BenchmarkManyPyramids : public Sample ImGui::End(); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new BenchmarkManyPyramids(settings); + return new BenchmarkManyPyramids( settings ); } b2BodyId m_groundId; @@ -811,7 +811,7 @@ class BenchmarkManyPyramids : public Sample float m_extent; }; -static int benchmarkManyPyramids = RegisterSample("Benchmark", "Many Pyramids", BenchmarkManyPyramids::Create); +static int benchmarkManyPyramids = RegisterSample( "Benchmark", "Many Pyramids", BenchmarkManyPyramids::Create ); class BenchmarkCreateDestroy : public Sample { @@ -819,28 +819,28 @@ class BenchmarkCreateDestroy : public Sample enum { e_maxBaseCount = 100, - e_maxBodyCount = e_maxBaseCount * (e_maxBaseCount + 1) / 2 + e_maxBodyCount = e_maxBaseCount * ( e_maxBaseCount + 1 ) / 2 }; - explicit BenchmarkCreateDestroy(Settings& settings) - : Sample(settings) + explicit BenchmarkCreateDestroy( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 50.0f}; + g_camera.m_center = { 0.0f, 50.0f }; g_camera.m_zoom = 25.0f * 2.2f; } float groundSize = 100.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); - b2Polygon box = b2MakeBox(groundSize, 1.0f); + b2Polygon box = b2MakeBox( groundSize, 1.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreatePolygonShape(groundId, &shapeDef, &box); + b2CreatePolygonShape( groundId, &shapeDef, &box ); - for (int i = 0; i < e_maxBodyCount; ++i) + for ( int i = 0; i < e_maxBodyCount; ++i ) { m_bodies[i] = b2_nullBodyId; } @@ -852,11 +852,11 @@ class BenchmarkCreateDestroy : public Sample void CreateScene() { - for (int i = 0; i < e_maxBodyCount; ++i) + for ( int i = 0; i < e_maxBodyCount; ++i ) { - if (B2_IS_NON_NULL(m_bodies[i])) + if ( B2_IS_NON_NULL( m_bodies[i] ) ) { - b2DestroyBody(m_bodies[i]); + b2DestroyBody( m_bodies[i] ); m_bodies[i] = b2_nullBodyId; } } @@ -875,22 +875,22 @@ class BenchmarkCreateDestroy : public Sample shapeDef.friction = 0.5f; float h = 0.5f; - b2Polygon box = b2MakeRoundedBox(h, h, 0.0f); + b2Polygon box = b2MakeRoundedBox( h, h, 0.0f ); int index = 0; - for (int i = 0; i < count; ++i) + for ( int i = 0; i < count; ++i ) { float y = i * shift + centery; - for (int j = i; j < count; ++j) + for ( int j = i; j < count; ++j ) { - float x = 0.5f * i * shift + (j - i) * shift - centerx; - bodyDef.position = {x, y}; + float x = 0.5f * i * shift + ( j - i ) * shift - centerx; + bodyDef.position = { x, y }; - assert(index < e_maxBodyCount); - m_bodies[index] = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(m_bodies[index], &shapeDef, &box); + assert( index < e_maxBodyCount ); + m_bodies[index] = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( m_bodies[index], &shapeDef, &box ); index += 1; } @@ -899,26 +899,26 @@ class BenchmarkCreateDestroy : public Sample m_bodyCount = index; } - void Step(Settings& settings) override + void Step( Settings& settings ) override { b2Timer timer = b2CreateTimer(); - for (int i = 0; i < m_iterations; ++i) + for ( int i = 0; i < m_iterations; ++i ) { CreateScene(); } - float ms = b2GetMilliseconds(&timer); + float ms = b2GetMilliseconds( &timer ); - g_draw.DrawString(5, m_textLine, "milliseconds = %g", ms); + g_draw.DrawString( 5, m_textLine, "milliseconds = %g", ms ); m_textLine += m_textIncrement; - Sample::Step(settings); + Sample::Step( settings ); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new BenchmarkCreateDestroy(settings); + return new BenchmarkCreateDestroy( settings ); } b2BodyId m_bodies[e_maxBodyCount]; @@ -927,7 +927,7 @@ class BenchmarkCreateDestroy : public Sample int m_iterations; }; -static int benchmarkCreateDestroy = RegisterSample("Benchmark", "CreateDestroy", BenchmarkCreateDestroy::Create); +static int benchmarkCreateDestroy = RegisterSample( "Benchmark", "CreateDestroy", BenchmarkCreateDestroy::Create ); class BenchmarkSleep : public Sample { @@ -935,28 +935,28 @@ class BenchmarkSleep : public Sample enum { e_maxBaseCount = 100, - e_maxBodyCount = e_maxBaseCount * (e_maxBaseCount + 1) / 2 + e_maxBodyCount = e_maxBaseCount * ( e_maxBaseCount + 1 ) / 2 }; - explicit BenchmarkSleep(Settings& settings) - : Sample(settings) + explicit BenchmarkSleep( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 50.0f}; + g_camera.m_center = { 0.0f, 50.0f }; g_camera.m_zoom = 25.0f * 2.2f; } float groundSize = 100.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); - b2Polygon box = b2MakeBox(groundSize, 1.0f); + b2Polygon box = b2MakeBox( groundSize, 1.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreatePolygonShape(groundId, &shapeDef, &box); + b2CreatePolygonShape( groundId, &shapeDef, &box ); - for (int i = 0; i < e_maxBodyCount; ++i) + for ( int i = 0; i < e_maxBodyCount; ++i ) { m_bodies[i] = b2_nullBodyId; } @@ -977,11 +977,11 @@ class BenchmarkSleep : public Sample void CreateScene() { - for (int i = 0; i < e_maxBodyCount; ++i) + for ( int i = 0; i < e_maxBodyCount; ++i ) { - if (B2_IS_NON_NULL(m_bodies[i])) + if ( B2_IS_NON_NULL( m_bodies[i] ) ) { - b2DestroyBody(m_bodies[i]); + b2DestroyBody( m_bodies[i] ); m_bodies[i] = b2_nullBodyId; } } @@ -1000,22 +1000,22 @@ class BenchmarkSleep : public Sample shapeDef.friction = 0.5f; float h = 0.5f; - b2Polygon box = b2MakeRoundedBox(h, h, 0.0f); + b2Polygon box = b2MakeRoundedBox( h, h, 0.0f ); int index = 0; - for (int i = 0; i < count; ++i) + for ( int i = 0; i < count; ++i ) { float y = i * shift + centery; - for (int j = i; j < count; ++j) + for ( int j = i; j < count; ++j ) { - float x = 0.5f * i * shift + (j - i) * shift - centerx; - bodyDef.position = {x, y}; + float x = 0.5f * i * shift + ( j - i ) * shift - centerx; + bodyDef.position = { x, y }; - assert(index < e_maxBodyCount); - m_bodies[index] = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(m_bodies[index], &shapeDef, &box); + assert( index < e_maxBodyCount ); + m_bodies[index] = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( m_bodies[index], &shapeDef, &box ); index += 1; } @@ -1024,46 +1024,46 @@ class BenchmarkSleep : public Sample m_bodyCount = index; } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - float timeStep = settings.hertz > 0.0f ? 1.0f / settings.hertz : float(0.0f); + float timeStep = settings.hertz > 0.0f ? 1.0f / settings.hertz : float( 0.0f ); b2Timer timer = b2CreateTimer(); - for (int i = 0; i < m_iterations; ++i) + for ( int i = 0; i < m_iterations; ++i ) { - b2Body_SetAwake(m_bodies[0], m_awake); - if (m_awake) + b2Body_SetAwake( m_bodies[0], m_awake ); + if ( m_awake ) { - m_wakeTotal += b2GetMillisecondsAndReset(&timer); + m_wakeTotal += b2GetMillisecondsAndReset( &timer ); m_wakeCount += 1; } else { - m_sleepTotal += b2GetMillisecondsAndReset(&timer); + m_sleepTotal += b2GetMillisecondsAndReset( &timer ); m_sleepCount += 1; } m_awake = !m_awake; } - if (m_wakeCount > 0) + if ( m_wakeCount > 0 ) { - g_draw.DrawString(5, m_textLine, "wake ave = %g ms", m_wakeTotal / m_wakeCount); + g_draw.DrawString( 5, m_textLine, "wake ave = %g ms", m_wakeTotal / m_wakeCount ); m_textLine += m_textIncrement; } - if (m_sleepCount > 0) + if ( m_sleepCount > 0 ) { - g_draw.DrawString(5, m_textLine, "sleep ave = %g ms", m_sleepTotal / m_sleepCount); + g_draw.DrawString( 5, m_textLine, "sleep ave = %g ms", m_sleepTotal / m_sleepCount ); m_textLine += m_textIncrement; } - Sample::Step(settings); + Sample::Step( settings ); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new BenchmarkSleep(settings); + return new BenchmarkSleep( settings ); } b2BodyId m_bodies[e_maxBodyCount]; @@ -1077,24 +1077,24 @@ class BenchmarkSleep : public Sample bool m_awake; }; -static int benchmarkSleep = RegisterSample("Benchmark", "Sleep", BenchmarkSleep::Create); +static int benchmarkSleep = RegisterSample( "Benchmark", "Sleep", BenchmarkSleep::Create ); class BenchmarkJointGrid : public Sample { public: - explicit BenchmarkJointGrid(Settings& settings) - : Sample(settings) + explicit BenchmarkJointGrid( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {60.0f, -57.0f}; + g_camera.m_center = { 60.0f, -57.0f }; g_camera.m_zoom = 25.0f * 2.5f; } constexpr int N = g_sampleDebug ? 10 : 100; // Allocate to avoid huge stack usage - b2BodyId* bodies = static_cast(malloc(N * N * sizeof(b2BodyId))); + b2BodyId* bodies = static_cast( malloc( N * N * sizeof( b2BodyId ) ) ); int index = 0; b2ShapeDef shapeDef = b2DefaultShapeDef(); @@ -1102,19 +1102,19 @@ class BenchmarkJointGrid : public Sample shapeDef.filter.categoryBits = 2; shapeDef.filter.maskBits = ~2u; - b2Circle circle = {{0.0f, 0.0f}, 0.4f}; + b2Circle circle = { { 0.0f, 0.0f }, 0.4f }; b2RevoluteJointDef jd = b2DefaultRevoluteJointDef(); b2BodyDef bodyDef = b2DefaultBodyDef(); - for (int k = 0; k < N; ++k) + for ( int k = 0; k < N; ++k ) { - for (int i = 0; i < N; ++i) + for ( int i = 0; i < N; ++i ) { float fk = (float)k; float fi = (float)i; - if (k >= N / 2 - 3 && k <= N / 2 + 3 && i == 0) + if ( k >= N / 2 - 3 && k <= N / 2 + 3 && i == 0 ) { bodyDef.type = b2_staticBody; } @@ -1123,35 +1123,35 @@ class BenchmarkJointGrid : public Sample bodyDef.type = b2_dynamicBody; } - bodyDef.position = {fk, -fi}; + bodyDef.position = { fk, -fi }; - b2BodyId body = b2CreateBody(m_worldId, &bodyDef); + b2BodyId body = b2CreateBody( m_worldId, &bodyDef ); - b2CreateCircleShape(body, &shapeDef, &circle); + b2CreateCircleShape( body, &shapeDef, &circle ); - if (i > 0) + if ( i > 0 ) { jd.bodyIdA = bodies[index - 1]; jd.bodyIdB = body; - jd.localAnchorA = {0.0f, -0.5f}; - jd.localAnchorB = {0.0f, 0.5f}; - b2CreateRevoluteJoint(m_worldId, &jd); + jd.localAnchorA = { 0.0f, -0.5f }; + jd.localAnchorB = { 0.0f, 0.5f }; + b2CreateRevoluteJoint( m_worldId, &jd ); } - if (k > 0) + if ( k > 0 ) { jd.bodyIdA = bodies[index - N]; jd.bodyIdB = body; - jd.localAnchorA = {0.5f, 0.0f}; - jd.localAnchorB = {-0.5f, 0.0f}; - b2CreateRevoluteJoint(m_worldId, &jd); + jd.localAnchorA = { 0.5f, 0.0f }; + jd.localAnchorB = { -0.5f, 0.0f }; + b2CreateRevoluteJoint( m_worldId, &jd ); } bodies[index++] = body; } } - free(bodies); + free( bodies ); m_gravity = 10.0f; } @@ -1159,54 +1159,54 @@ class BenchmarkJointGrid : public Sample void UpdateUI() override { float height = 60.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(240.0f, height)); - ImGui::Begin("Benchmark: Joint Grid", nullptr, ImGuiWindowFlags_NoResize); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); + ImGui::Begin( "Benchmark: Joint Grid", nullptr, ImGuiWindowFlags_NoResize ); - if (ImGui::SliderFloat("gravity", &m_gravity, 0.0f, 20.0f, "%.1f")) + if ( ImGui::SliderFloat( "gravity", &m_gravity, 0.0f, 20.0f, "%.1f" ) ) { - b2World_SetGravity(m_worldId, {0.0f, -m_gravity}); + b2World_SetGravity( m_worldId, { 0.0f, -m_gravity } ); } ImGui::End(); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new BenchmarkJointGrid(settings); + return new BenchmarkJointGrid( settings ); } float m_gravity; }; -static int benchmarkJointGridIndex = RegisterSample("Benchmark", "Joint Grid", BenchmarkJointGrid::Create); +static int benchmarkJointGridIndex = RegisterSample( "Benchmark", "Joint Grid", BenchmarkJointGrid::Create ); class BenchmarkSmash : public Sample { public: - explicit BenchmarkSmash(Settings& settings) - : Sample(settings) + explicit BenchmarkSmash( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {60.0f, 6.0f}; + g_camera.m_center = { 60.0f, 6.0f }; g_camera.m_zoom = 25.0f * 1.6f; } - b2World_SetGravity(m_worldId, b2Vec2_zero); + b2World_SetGravity( m_worldId, b2Vec2_zero ); { - b2Polygon box = b2MakeBox(4.0f, 4.0f); + b2Polygon box = b2MakeBox( 4.0f, 4.0f ); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {-20.0f, 0.0f}; - bodyDef.linearVelocity = {40.0f, 0.0f}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { -20.0f, 0.0f }; + bodyDef.linearVelocity = { 40.0f, 0.0f }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 8.0f; - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); } m_created = false; @@ -1215,7 +1215,7 @@ class BenchmarkSmash : public Sample void CreateScene1() { ImGuiIO& io = ImGui::GetIO(); - if (io.Fonts->Fonts.size() == 0) + if ( io.Fonts->Fonts.size() == 0 ) { return; } @@ -1233,22 +1233,22 @@ class BenchmarkSmash : public Sample b2ShapeDef shapeDef = b2DefaultShapeDef(); - for (int i = 0; i < height; ++i) + for ( int i = 0; i < height; ++i ) { - for (int j = 0; j < width; ++j) + for ( int j = 0; j < width; ++j ) { unsigned char value = pixels[i * width + j]; - if (value != 0 && value != 0xFF) + if ( value != 0 && value != 0xFF ) { value += 0; } - if (value > 50) + if ( value > 50 ) { - b2Polygon square = b2MakeSquare(0.95f * scale * (value / 255.0f)); - bodyDef.position = {2.0f * j * scale, 2.0f * (height - i) * scale - 10.0f}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &square); + b2Polygon square = b2MakeSquare( 0.95f * scale * ( value / 255.0f ) ); + bodyDef.position = { 2.0f * j * scale, 2.0f * ( height - i ) * scale - 10.0f }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &square ); } } } @@ -1259,7 +1259,7 @@ class BenchmarkSmash : public Sample void CreateScene2() { ImGuiIO& io = ImGui::GetIO(); - if (io.Fonts->Fonts.size() == 0) + if ( io.Fonts->Fonts.size() == 0 ) { return; } @@ -1279,13 +1279,13 @@ class BenchmarkSmash : public Sample b2ShapeDef shapeDef = b2DefaultShapeDef(); const char* text = "I"; - int n = (int)strlen(text); + int n = (int)strlen( text ); float zoom = 1.0f; float x = 0.0f; - for (int k = 0; k < n; ++k) + for ( int k = 0; k < n; ++k ) { - const ImFontGlyph* glyph = font->FindGlyph(text[k]); + const ImFontGlyph* glyph = font->FindGlyph( text[k] ); float x1 = glyph->X0; float x2 = glyph->X1; float y1 = glyph->Y0; @@ -1295,28 +1295,28 @@ class BenchmarkSmash : public Sample float u2 = glyph->U1; float v2 = glyph->V1; - float w = zoom * (x2 - x1); - float h = zoom * (y2 - y1); + float w = zoom * ( x2 - x1 ); + float h = zoom * ( y2 - y1 ); - int gridx = int(w); - int gridy = int(h); - for (int i = 0; i < gridy; ++i) + int gridx = int( w ); + int gridy = int( h ); + for ( int i = 0; i < gridy; ++i ) { - float v = v1 + i / h * (v2 - v1); - int iy = int(v * height); + float v = v1 + i / h * ( v2 - v1 ); + int iy = int( v * height ); - for (int j = 0; j < gridx; ++j) + for ( int j = 0; j < gridx; ++j ) { - float u = u1 + j / w * (u2 - u1); - int ix = int(u * width); + float u = u1 + j / w * ( u2 - u1 ); + int ix = int( u * width ); unsigned char value = pixels[iy * width + ix]; - if (value > 50) + if ( value > 50 ) { - b2Polygon square = b2MakeSquare(0.9f * scale * value / 255.0f); - bodyDef.position = {x + 2.0f * (zoom * x1 + j) * scale, -2.0f * (zoom * y1 + i) * scale + 13.0f}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &square); + b2Polygon square = b2MakeSquare( 0.9f * scale * value / 255.0f ); + bodyDef.position = { x + 2.0f * ( zoom * x1 + j ) * scale, -2.0f * ( zoom * y1 + i ) * scale + 13.0f }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &square ); } } } @@ -1330,7 +1330,7 @@ class BenchmarkSmash : public Sample void CreateScene3() { float d = 0.4f; - b2Polygon box = b2MakeSquare(0.5f * d); + b2Polygon box = b2MakeSquare( 0.5f * d ); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; @@ -1341,49 +1341,49 @@ class BenchmarkSmash : public Sample int columns = g_sampleDebug ? 20 : 120; int rows = g_sampleDebug ? 10 : 80; - for (int i = 0; i < columns; ++i) + for ( int i = 0; i < columns; ++i ) { - for (int j = 0; j < rows; ++j) + for ( int j = 0; j < rows; ++j ) { bodyDef.position.x = i * d + 30.0f; - bodyDef.position.y = (j - rows / 2.0f) * d; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &box); + bodyDef.position.y = ( j - rows / 2.0f ) * d; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); } } m_created = true; } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - Sample::Step(settings); + Sample::Step( settings ); - if (m_created == false) + if ( m_created == false ) { CreateScene3(); } } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new BenchmarkSmash(settings); + return new BenchmarkSmash( settings ); } bool m_created; }; -static int sampleSmash = RegisterSample("Benchmark", "Smash", BenchmarkSmash::Create); +static int sampleSmash = RegisterSample( "Benchmark", "Smash", BenchmarkSmash::Create ); class BenchmarkCompound : public Sample { public: - explicit BenchmarkCompound(Settings& settings) - : Sample(settings) + explicit BenchmarkCompound( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {18.0f, 115.0f}; + g_camera.m_center = { 18.0f, 115.0f }; g_camera.m_zoom = 25.0f * 5.5f; } @@ -1398,28 +1398,28 @@ class BenchmarkCompound : public Sample { b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - for (int i = 0; i < height; ++i) + for ( int i = 0; i < height; ++i ) { float y = grid * i; - for (int j = i; j < width; ++j) + for ( int j = i; j < width; ++j ) { float x = grid * j; - b2Polygon square = b2MakeOffsetBox(0.5f * grid, 0.5f * grid, {x, y}, 0.0f); - b2CreatePolygonShape(groundId, &shapeDef, &square); + b2Polygon square = b2MakeOffsetBox( 0.5f * grid, 0.5f * grid, { x, y }, 0.0f ); + b2CreatePolygonShape( groundId, &shapeDef, &square ); } } - for (int i = 0; i < height; ++i) + for ( int i = 0; i < height; ++i ) { float y = grid * i; - for (int j = i; j < width; ++j) + for ( int j = i; j < width; ++j ) { float x = -grid * j; - b2Polygon square = b2MakeOffsetBox(0.5f * grid, 0.5f * grid, {x, y}, 0.0f); - b2CreatePolygonShape(groundId, &shapeDef, &square); + b2Polygon square = b2MakeOffsetBox( 0.5f * grid, 0.5f * grid, { x, y }, 0.0f ); + b2CreatePolygonShape( groundId, &shapeDef, &square ); } } } @@ -1439,51 +1439,51 @@ class BenchmarkCompound : public Sample bodyDef.automaticMass = false; b2ShapeDef shapeDef = b2DefaultShapeDef(); - for (int m = 0; m < count; ++m) + for ( int m = 0; m < count; ++m ) { - float ybody = (100.0f + m * span) * grid; + float ybody = ( 100.0f + m * span ) * grid; - for (int n = 0; n < count; ++n) + for ( int n = 0; n < count; ++n ) { float xbody = -0.5f * grid * count * span + n * span * grid; - bodyDef.position = {xbody, ybody}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { xbody, ybody }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); - for (int i = 0; i < span; ++i) + for ( int i = 0; i < span; ++i ) { float y = i * grid; - for (int j = 0; j < span; ++j) + for ( int j = 0; j < span; ++j ) { float x = j * grid; - b2Polygon square = b2MakeOffsetBox(0.5f * grid, 0.5f * grid, {x, y}, 0.0f); - b2CreatePolygonShape(bodyId, &shapeDef, &square); + b2Polygon square = b2MakeOffsetBox( 0.5f * grid, 0.5f * grid, { x, y }, 0.0f ); + b2CreatePolygonShape( bodyId, &shapeDef, &square ); } } // All shapes have been added so I can efficiently compute the mass properties. - b2Body_ApplyMassFromShapes(bodyId); + b2Body_ApplyMassFromShapes( bodyId ); } } } } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new BenchmarkCompound(settings); + return new BenchmarkCompound( settings ); } }; -static int sampleCompound = RegisterSample("Benchmark", "Compound", BenchmarkCompound::Create); +static int sampleCompound = RegisterSample( "Benchmark", "Compound", BenchmarkCompound::Create ); class BenchmarkKinematic : public Sample { public: - explicit BenchmarkKinematic(Settings& settings) - : Sample(settings) + explicit BenchmarkKinematic( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 0.0f}; + g_camera.m_center = { 0.0f, 0.0f }; g_camera.m_zoom = 150.0f; } @@ -1505,27 +1505,27 @@ class BenchmarkKinematic : public Sample shapeDef.filter.categoryBits = 1; shapeDef.filter.maskBits = 2; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); - for (int i = -span; i < span; ++i) + for ( int i = -span; i < span; ++i ) { float y = i * grid; - for (int j = -span; j < span; ++j) + for ( int j = -span; j < span; ++j ) { float x = j * grid; - b2Polygon square = b2MakeOffsetBox(0.5f * grid, 0.5f * grid, {x, y}, 0.0f); - b2CreatePolygonShape(bodyId, &shapeDef, &square); + b2Polygon square = b2MakeOffsetBox( 0.5f * grid, 0.5f * grid, { x, y }, 0.0f ); + b2CreatePolygonShape( bodyId, &shapeDef, &square ); } } // All shapes have been added so I can efficiently compute the mass properties. - b2Body_ApplyMassFromShapes(bodyId); + b2Body_ApplyMassFromShapes( bodyId ); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new BenchmarkKinematic(settings); + return new BenchmarkKinematic( settings ); } }; -static int sampleKinematic = RegisterSample("Benchmark", "Kinematic", BenchmarkKinematic::Create); +static int sampleKinematic = RegisterSample( "Benchmark", "Kinematic", BenchmarkKinematic::Create ); diff --git a/samples/sample_bodies.cpp b/samples/sample_bodies.cpp index a85273f2..a08d368c 100644 --- a/samples/sample_bodies.cpp +++ b/samples/sample_bodies.cpp @@ -11,13 +11,13 @@ class BodyType : public Sample { - public: - explicit BodyType(Settings& settings) - : Sample(settings) +public: + explicit BodyType( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.8f, 6.4f}; + g_camera.m_center = { 0.8f, 6.4f }; g_camera.m_zoom = 25.0f * 0.4f; } @@ -27,24 +27,24 @@ class BodyType : public Sample b2BodyId groundId = b2_nullBodyId; { b2BodyDef bodyDef = b2DefaultBodyDef(); - groundId = b2CreateBody(m_worldId, &bodyDef); + groundId = b2CreateBody( m_worldId, &bodyDef ); - b2Segment segment = {{-20.0f, 0.0f}, {20.0f, 0.0f}}; + b2Segment segment = { { -20.0f, 0.0f }, { 20.0f, 0.0f } }; b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2CreateSegmentShape( groundId, &shapeDef, &segment ); } // Define attachment { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {-2.0f, 3.0f}; - m_attachmentId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { -2.0f, 3.0f }; + m_attachmentId = b2CreateBody( m_worldId, &bodyDef ); - b2Polygon box = b2MakeBox(0.5f, 2.0f); + b2Polygon box = b2MakeBox( 0.5f, 2.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; - b2CreatePolygonShape(m_attachmentId, &shapeDef, &box); + b2CreatePolygonShape( m_attachmentId, &shapeDef, &box ); } // Define second attachment @@ -52,13 +52,13 @@ class BodyType : public Sample b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = m_type; bodyDef.isEnabled = m_isEnabled; - bodyDef.position = {3.0f, 3.0f}; - m_secondAttachmentId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { 3.0f, 3.0f }; + m_secondAttachmentId = b2CreateBody( m_worldId, &bodyDef ); - b2Polygon box = b2MakeBox(0.5f, 2.0f); + b2Polygon box = b2MakeBox( 0.5f, 2.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; - b2CreatePolygonShape(m_secondAttachmentId, &shapeDef, &box); + b2CreatePolygonShape( m_secondAttachmentId, &shapeDef, &box ); } // Define platform @@ -66,42 +66,42 @@ class BodyType : public Sample b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = m_type; bodyDef.isEnabled = m_isEnabled; - bodyDef.position = {-4.0f, 5.0f}; - m_platformId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { -4.0f, 5.0f }; + m_platformId = b2CreateBody( m_worldId, &bodyDef ); - b2Polygon box = b2MakeOffsetBox(0.5f, 4.0f, {4.0f, 0.0f}, 0.5f * b2_pi); + b2Polygon box = b2MakeOffsetBox( 0.5f, 4.0f, { 4.0f, 0.0f }, 0.5f * b2_pi ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.friction = 0.6f; shapeDef.density = 2.0f; - b2CreatePolygonShape(m_platformId, &shapeDef, &box); + b2CreatePolygonShape( m_platformId, &shapeDef, &box ); b2RevoluteJointDef revoluteDef = b2DefaultRevoluteJointDef(); - b2Vec2 pivot = {-2.0f, 5.0f}; + b2Vec2 pivot = { -2.0f, 5.0f }; revoluteDef.bodyIdA = m_attachmentId; revoluteDef.bodyIdB = m_platformId; - revoluteDef.localAnchorA = b2Body_GetLocalPoint(m_attachmentId, pivot); - revoluteDef.localAnchorB = b2Body_GetLocalPoint(m_platformId, pivot); + revoluteDef.localAnchorA = b2Body_GetLocalPoint( m_attachmentId, pivot ); + revoluteDef.localAnchorB = b2Body_GetLocalPoint( m_platformId, pivot ); revoluteDef.maxMotorTorque = 50.0f; revoluteDef.enableMotor = true; - b2CreateRevoluteJoint(m_worldId, &revoluteDef); + b2CreateRevoluteJoint( m_worldId, &revoluteDef ); - pivot = {3.0f, 5.0f}; + pivot = { 3.0f, 5.0f }; revoluteDef.bodyIdA = m_secondAttachmentId; revoluteDef.bodyIdB = m_platformId; - revoluteDef.localAnchorA = b2Body_GetLocalPoint(m_secondAttachmentId, pivot); - revoluteDef.localAnchorB = b2Body_GetLocalPoint(m_platformId, pivot); + revoluteDef.localAnchorA = b2Body_GetLocalPoint( m_secondAttachmentId, pivot ); + revoluteDef.localAnchorB = b2Body_GetLocalPoint( m_platformId, pivot ); revoluteDef.maxMotorTorque = 50.0f; revoluteDef.enableMotor = true; - b2CreateRevoluteJoint(m_worldId, &revoluteDef); + b2CreateRevoluteJoint( m_worldId, &revoluteDef ); b2PrismaticJointDef prismaticDef = b2DefaultPrismaticJointDef(); - b2Vec2 anchor = {0.0f, 5.0f}; + b2Vec2 anchor = { 0.0f, 5.0f }; prismaticDef.bodyIdA = groundId; prismaticDef.bodyIdB = m_platformId; - prismaticDef.localAnchorA = b2Body_GetLocalPoint(groundId, anchor); - prismaticDef.localAnchorB = b2Body_GetLocalPoint(m_platformId, anchor); - prismaticDef.localAxisA = {1.0f, 0.0f}; + prismaticDef.localAnchorA = b2Body_GetLocalPoint( groundId, anchor ); + prismaticDef.localAnchorB = b2Body_GetLocalPoint( m_platformId, anchor ); + prismaticDef.localAxisA = { 1.0f, 0.0f }; prismaticDef.maxMotorForce = 1000.0f; prismaticDef.motorSpeed = 0.0f; prismaticDef.enableMotor = true; @@ -109,7 +109,7 @@ class BodyType : public Sample prismaticDef.upperTranslation = 10.0f; prismaticDef.enableLimit = true; - b2CreatePrismaticJoint(m_worldId, &prismaticDef); + b2CreatePrismaticJoint( m_worldId, &prismaticDef ); m_speed = 3.0f; } @@ -118,16 +118,16 @@ class BodyType : public Sample { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {-3.0f, 8.0f}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { -3.0f, 8.0f }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); - b2Polygon box = b2MakeBox(0.75f, 0.75f); + b2Polygon box = b2MakeBox( 0.75f, 0.75f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.friction = 0.6f; shapeDef.density = 2.0f; - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); } // Create a second payload @@ -135,16 +135,16 @@ class BodyType : public Sample b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = m_type; bodyDef.isEnabled = m_isEnabled; - bodyDef.position = {2.0f, 8.0f}; - m_secondPayloadId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { 2.0f, 8.0f }; + m_secondPayloadId = b2CreateBody( m_worldId, &bodyDef ); - b2Polygon box = b2MakeBox(0.75f, 0.75f); + b2Polygon box = b2MakeBox( 0.75f, 0.75f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.friction = 0.6f; shapeDef.density = 2.0f; - b2CreatePolygonShape(m_secondPayloadId, &shapeDef, &box); + b2CreatePolygonShape( m_secondPayloadId, &shapeDef, &box ); } // Create a separate body on the ground @@ -152,16 +152,16 @@ class BodyType : public Sample b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = m_type; bodyDef.isEnabled = m_isEnabled; - bodyDef.position = {8.0f, 0.2f}; - m_touchingBodyId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { 8.0f, 0.2f }; + m_touchingBodyId = b2CreateBody( m_worldId, &bodyDef ); - b2Capsule capsule = {{0.0f, 0.0f}, {1.0f, 0.0f}, 0.25f}; + b2Capsule capsule = { { 0.0f, 0.0f }, { 1.0f, 0.0f }, 0.25f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.friction = 0.6f; shapeDef.density = 2.0f; - b2CreateCapsuleShape(m_touchingBodyId, &shapeDef, &capsule); + b2CreateCapsuleShape( m_touchingBodyId, &shapeDef, &capsule ); } // Create a separate floating body @@ -169,109 +169,109 @@ class BodyType : public Sample b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = m_type; bodyDef.isEnabled = m_isEnabled; - bodyDef.position = {-8.0f, 12.0f}; + bodyDef.position = { -8.0f, 12.0f }; bodyDef.gravityScale = 0.0f; - m_floatingBodyId = b2CreateBody(m_worldId, &bodyDef); + m_floatingBodyId = b2CreateBody( m_worldId, &bodyDef ); - b2Circle circle = {{0.0f, 0.5f}, 0.25f}; + b2Circle circle = { { 0.0f, 0.5f }, 0.25f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.friction = 0.6f; shapeDef.density = 2.0f; - b2CreateCircleShape(m_floatingBodyId, &shapeDef, &circle); + b2CreateCircleShape( m_floatingBodyId, &shapeDef, &circle ); } } void UpdateUI() override { float height = 140.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(180.0f, height)); - ImGui::Begin("Body Type", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 180.0f, height ) ); + ImGui::Begin( "Body Type", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); - if (ImGui::RadioButton("Static", m_type == b2_staticBody)) + if ( ImGui::RadioButton( "Static", m_type == b2_staticBody ) ) { m_type = b2_staticBody; - b2Body_SetType(m_platformId, b2_staticBody); - b2Body_SetType(m_secondAttachmentId, b2_staticBody); - b2Body_SetType(m_secondPayloadId, b2_staticBody); - b2Body_SetType(m_touchingBodyId, b2_staticBody); - b2Body_SetType(m_floatingBodyId, b2_staticBody); + b2Body_SetType( m_platformId, b2_staticBody ); + b2Body_SetType( m_secondAttachmentId, b2_staticBody ); + b2Body_SetType( m_secondPayloadId, b2_staticBody ); + b2Body_SetType( m_touchingBodyId, b2_staticBody ); + b2Body_SetType( m_floatingBodyId, b2_staticBody ); } - if (ImGui::RadioButton("Kinematic", m_type == b2_kinematicBody)) + if ( ImGui::RadioButton( "Kinematic", m_type == b2_kinematicBody ) ) { m_type = b2_kinematicBody; - b2Body_SetType(m_platformId, b2_kinematicBody); - b2Body_SetLinearVelocity(m_platformId, {-m_speed, 0.0f}); - b2Body_SetAngularVelocity(m_platformId, 0.0f); - b2Body_SetType(m_secondAttachmentId, b2_kinematicBody); - b2Body_SetType(m_secondPayloadId, b2_kinematicBody); - b2Body_SetType(m_touchingBodyId, b2_kinematicBody); - b2Body_SetType(m_floatingBodyId, b2_kinematicBody); + b2Body_SetType( m_platformId, b2_kinematicBody ); + b2Body_SetLinearVelocity( m_platformId, { -m_speed, 0.0f } ); + b2Body_SetAngularVelocity( m_platformId, 0.0f ); + b2Body_SetType( m_secondAttachmentId, b2_kinematicBody ); + b2Body_SetType( m_secondPayloadId, b2_kinematicBody ); + b2Body_SetType( m_touchingBodyId, b2_kinematicBody ); + b2Body_SetType( m_floatingBodyId, b2_kinematicBody ); } - - if (ImGui::RadioButton("Dynamic", m_type == b2_dynamicBody)) + + if ( ImGui::RadioButton( "Dynamic", m_type == b2_dynamicBody ) ) { m_type = b2_dynamicBody; - b2Body_SetType(m_platformId, b2_dynamicBody); - b2Body_SetType(m_secondAttachmentId, b2_dynamicBody); - b2Body_SetType(m_secondPayloadId, b2_dynamicBody); - b2Body_SetType(m_touchingBodyId, b2_dynamicBody); - b2Body_SetType(m_floatingBodyId, b2_dynamicBody); + b2Body_SetType( m_platformId, b2_dynamicBody ); + b2Body_SetType( m_secondAttachmentId, b2_dynamicBody ); + b2Body_SetType( m_secondPayloadId, b2_dynamicBody ); + b2Body_SetType( m_touchingBodyId, b2_dynamicBody ); + b2Body_SetType( m_floatingBodyId, b2_dynamicBody ); } - if (ImGui::Checkbox("Enable", &m_isEnabled)) + if ( ImGui::Checkbox( "Enable", &m_isEnabled ) ) { - if (m_isEnabled) + if ( m_isEnabled ) { - b2Body_Enable(m_platformId); - b2Body_Enable(m_secondAttachmentId); - b2Body_Enable(m_secondPayloadId); - b2Body_Enable(m_touchingBodyId); - b2Body_Enable(m_floatingBodyId); + b2Body_Enable( m_platformId ); + b2Body_Enable( m_secondAttachmentId ); + b2Body_Enable( m_secondPayloadId ); + b2Body_Enable( m_touchingBodyId ); + b2Body_Enable( m_floatingBodyId ); - if (m_type == b2_kinematicBody) + if ( m_type == b2_kinematicBody ) { - b2Body_SetLinearVelocity(m_platformId, {-m_speed, 0.0f}); - b2Body_SetAngularVelocity(m_platformId, 0.0f); + b2Body_SetLinearVelocity( m_platformId, { -m_speed, 0.0f } ); + b2Body_SetAngularVelocity( m_platformId, 0.0f ); } } else { - b2Body_Disable(m_platformId); - b2Body_Disable(m_secondAttachmentId); - b2Body_Disable(m_secondPayloadId); - b2Body_Disable(m_touchingBodyId); - b2Body_Disable(m_floatingBodyId); + b2Body_Disable( m_platformId ); + b2Body_Disable( m_secondAttachmentId ); + b2Body_Disable( m_secondPayloadId ); + b2Body_Disable( m_touchingBodyId ); + b2Body_Disable( m_floatingBodyId ); } } ImGui::End(); } - void Step(Settings& settings) override + void Step( Settings& settings ) override { // Drive the kinematic body. - if (m_type == b2_kinematicBody) + if ( m_type == b2_kinematicBody ) { - b2Vec2 p = b2Body_GetPosition(m_platformId); - b2Vec2 v = b2Body_GetLinearVelocity(m_platformId); + b2Vec2 p = b2Body_GetPosition( m_platformId ); + b2Vec2 v = b2Body_GetLinearVelocity( m_platformId ); - if ((p.x < -14.0f && v.x < 0.0f) || (p.x > 6.0f && v.x > 0.0f)) + if ( ( p.x < -14.0f && v.x < 0.0f ) || ( p.x > 6.0f && v.x > 0.0f ) ) { v.x = -v.x; - b2Body_SetLinearVelocity(m_platformId, v); + b2Body_SetLinearVelocity( m_platformId, v ); } } - Sample::Step(settings); + Sample::Step( settings ); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new BodyType(settings); + return new BodyType( settings ); } b2BodyId m_attachmentId; @@ -285,8 +285,7 @@ class BodyType : public Sample bool m_isEnabled; }; -static int sampleBodyType = RegisterSample("Bodies", "Body Type", BodyType::Create); - +static int sampleBodyType = RegisterSample( "Bodies", "Body Type", BodyType::Create ); /// This is a test of typical character collision scenarios. This does not /// show how you should implement a character in your application. @@ -294,23 +293,23 @@ static int sampleBodyType = RegisterSample("Bodies", "Body Type", BodyType::Crea class Character : public Sample { public: - explicit Character(Settings& settings) - : Sample(settings) + explicit Character( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {-2.0f, 7.0f}; + g_camera.m_center = { -2.0f, 7.0f }; g_camera.m_zoom = 25.0f * 0.4f; } // Ground body { b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Segment segment = {{-20.0f, 0.0f}, {20.0f, 0.0f}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2Segment segment = { { -20.0f, 0.0f }, { 20.0f, 0.0f } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment ); } // Collinear edges with no adjacency information. @@ -318,32 +317,32 @@ class Character : public Sample // an internal vertex. { b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); - + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); + b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Segment segment1 = {{-8.0f, 1.0f}, {-6.0f, 1.0f}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment1); + b2Segment segment1 = { { -8.0f, 1.0f }, { -6.0f, 1.0f } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment1 ); - b2Segment segment2 = {{-6.0f, 1.0f}, {-4.0f, 1.0f}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment2); + b2Segment segment2 = { { -6.0f, 1.0f }, { -4.0f, 1.0f } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment2 ); - b2Segment segment3 = {{-4.0f, 1.0f}, {-2.0f, 1.0f}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment3); + b2Segment segment3 = { { -4.0f, 1.0f }, { -2.0f, 1.0f } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment3 ); } // Chain shape { b2BodyDef bodyDef = b2DefaultBodyDef(); - bodyDef.rotation = b2MakeRot(0.25f * b2_pi); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.rotation = b2MakeRot( 0.25f * b2_pi ); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); - b2Vec2 points[4] = {{8.0f, 7.0f}, {7.0f, 8.0f}, {6.0f, 8.0f}, {5.0f, 7.0f}}; + b2Vec2 points[4] = { { 8.0f, 7.0f }, { 7.0f, 8.0f }, { 6.0f, 8.0f }, { 5.0f, 7.0f } }; b2ChainDef chainDef = b2DefaultChainDef(); chainDef.points = points; chainDef.count = 4; chainDef.isLoop = true; - b2CreateChain(groundId, &chainDef); + b2CreateChain( groundId, &chainDef ); } // Square tiles. This shows that adjacency shapes may have non-smooth collision. Box2D has no solution @@ -351,117 +350,117 @@ class Character : public Sample // TODO_ERIN try this: https://briansemrau.github.io/dealing-with-ghost-collisions/ { b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Polygon box = b2MakeOffsetBox(1.0f, 1.0f, {4.0f, 3.0f}, 0.0f); - b2CreatePolygonShape(groundId, &shapeDef, &box); + b2Polygon box = b2MakeOffsetBox( 1.0f, 1.0f, { 4.0f, 3.0f }, 0.0f ); + b2CreatePolygonShape( groundId, &shapeDef, &box ); - box = b2MakeOffsetBox(1.0f, 1.0f, {6.0f, 3.0f}, 0.0f); - b2CreatePolygonShape(groundId, &shapeDef, &box); + box = b2MakeOffsetBox( 1.0f, 1.0f, { 6.0f, 3.0f }, 0.0f ); + b2CreatePolygonShape( groundId, &shapeDef, &box ); - box = b2MakeOffsetBox(1.0f, 1.0f, {8.0f, 3.0f}, 0.0f); - b2CreatePolygonShape(groundId, &shapeDef, &box); + box = b2MakeOffsetBox( 1.0f, 1.0f, { 8.0f, 3.0f }, 0.0f ); + b2CreatePolygonShape( groundId, &shapeDef, &box ); } // Square made from a chain loop. Collision should be smooth. { b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); - b2Vec2 points[4] = {{-1.0f, 3.0}, {1.0f, 3.0f}, {1.0f, 5.0f}, {-1.0f, 5.0}}; + b2Vec2 points[4] = { { -1.0f, 3.0 }, { 1.0f, 3.0f }, { 1.0f, 5.0f }, { -1.0f, 5.0 } }; b2ChainDef chainDef = b2DefaultChainDef(); chainDef.points = points; chainDef.count = 4; chainDef.isLoop = true; - b2CreateChain(groundId, &chainDef); + b2CreateChain( groundId, &chainDef ); } // Chain loop. Collision should be smooth. { b2BodyDef bodyDef = b2DefaultBodyDef(); - bodyDef.position = {-10.0f, 4.0f}; - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { -10.0f, 4.0f }; + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); - b2Vec2 points[10] = {{0.0f, 0.0f}, {6.0f, 0.0f}, {6.0f, 2.0f}, {4.0f, 1.0f}, {2.0f, 2.0f}, - {0.0f, 2.0f}, {-2.0f, 2.0f}, {-4.0f, 3.0f}, {-6.0f, 2.0f}, {-6.0f, 0.0f}}; + b2Vec2 points[10] = { { 0.0f, 0.0f }, { 6.0f, 0.0f }, { 6.0f, 2.0f }, { 4.0f, 1.0f }, { 2.0f, 2.0f }, + { 0.0f, 2.0f }, { -2.0f, 2.0f }, { -4.0f, 3.0f }, { -6.0f, 2.0f }, { -6.0f, 0.0f } }; b2ChainDef chainDef = b2DefaultChainDef(); chainDef.points = points; chainDef.count = 10; chainDef.isLoop = true; - b2CreateChain(groundId, &chainDef); + b2CreateChain( groundId, &chainDef ); } // Circle character { b2BodyDef bodyDef = b2DefaultBodyDef(); - bodyDef.position = {-7.0f, 6.0f}; + bodyDef.position = { -7.0f, 6.0f }; bodyDef.type = b2_dynamicBody; bodyDef.fixedRotation = true; bodyDef.enableSleep = false; - m_circleCharacterId = b2CreateBody(m_worldId, &bodyDef); + m_circleCharacterId = b2CreateBody( m_worldId, &bodyDef ); - b2Circle circle = {{0.0f, 0.0f}, 0.25f}; + b2Circle circle = { { 0.0f, 0.0f }, 0.25f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 20.0f; shapeDef.friction = 0.2f; - b2CreateCircleShape(m_circleCharacterId, &shapeDef, &circle); + b2CreateCircleShape( m_circleCharacterId, &shapeDef, &circle ); } // Capsule character { b2BodyDef bodyDef = b2DefaultBodyDef(); - bodyDef.position = {3.0f, 5.0f}; + bodyDef.position = { 3.0f, 5.0f }; bodyDef.type = b2_dynamicBody; bodyDef.fixedRotation = true; bodyDef.enableSleep = false; - m_capsuleCharacterId = b2CreateBody(m_worldId, &bodyDef); + m_capsuleCharacterId = b2CreateBody( m_worldId, &bodyDef ); - b2Capsule capsule = {{0.0f, 0.25f}, {0.0f, 0.75f}, 0.25f}; + b2Capsule capsule = { { 0.0f, 0.25f }, { 0.0f, 0.75f }, 0.25f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 20.0f; shapeDef.friction = 0.2f; - b2CreateCapsuleShape(m_capsuleCharacterId, &shapeDef, &capsule); + b2CreateCapsuleShape( m_capsuleCharacterId, &shapeDef, &capsule ); } // Square character { b2BodyDef bodyDef = b2DefaultBodyDef(); - bodyDef.position = {-3.0f, 8.0f}; + bodyDef.position = { -3.0f, 8.0f }; bodyDef.type = b2_dynamicBody; bodyDef.fixedRotation = true; bodyDef.enableSleep = false; - m_boxCharacterId = b2CreateBody(m_worldId, &bodyDef); + m_boxCharacterId = b2CreateBody( m_worldId, &bodyDef ); - b2Polygon box = b2MakeBox(0.4f, 0.4f); + b2Polygon box = b2MakeBox( 0.4f, 0.4f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 20.0f; shapeDef.friction = 0.2f; - b2CreatePolygonShape(m_boxCharacterId, &shapeDef, &box); + b2CreatePolygonShape( m_boxCharacterId, &shapeDef, &box ); } } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - Sample::Step(settings); + Sample::Step( settings ); - g_draw.DrawString(5, m_textLine, "This tests various character collision shapes."); + g_draw.DrawString( 5, m_textLine, "This tests various character collision shapes." ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "Limitation: square and hexagon can snag on aligned boxes."); + g_draw.DrawString( 5, m_textLine, "Limitation: square and hexagon can snag on aligned boxes." ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "Feature: edge chains have smooth collision inside and out."); + g_draw.DrawString( 5, m_textLine, "Feature: edge chains have smooth collision inside and out." ); m_textLine += m_textIncrement; } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new Character(settings); + return new Character( settings ); } b2BodyId m_circleCharacterId; @@ -469,56 +468,56 @@ class Character : public Sample b2BodyId m_boxCharacterId; }; -static int sampleCharacter = RegisterSample("Bodies", "Character", Character::Create); +static int sampleCharacter = RegisterSample( "Bodies", "Character", Character::Create ); class Weeble : public Sample { public: - explicit Weeble(Settings& settings) - : Sample(settings) + explicit Weeble( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {2.3f, 10.0f}; + g_camera.m_center = { 2.3f, 10.0f }; g_camera.m_zoom = 25.0f * 0.5f; } b2BodyId groundId = b2_nullBodyId; { b2BodyDef bodyDef = b2DefaultBodyDef(); - groundId = b2CreateBody(m_worldId, &bodyDef); + groundId = b2CreateBody( m_worldId, &bodyDef ); - b2Segment segment = {{-20.0f, 0.0f}, {20.0f, 0.0f}}; + b2Segment segment = { { -20.0f, 0.0f }, { 20.0f, 0.0f } }; b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2CreateSegmentShape( groundId, &shapeDef, &segment ); } // Build weeble { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {0.0f, 3.0f}; - bodyDef.rotation = b2MakeRot(0.25f * b2_pi); - m_weebleId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { 0.0f, 3.0f }; + bodyDef.rotation = b2MakeRot( 0.25f * b2_pi ); + m_weebleId = b2CreateBody( m_worldId, &bodyDef ); - b2Capsule capsule = {{0.0f, -1.0f}, {0.0f, 1.0f}, 1.0f}; + b2Capsule capsule = { { 0.0f, -1.0f }, { 0.0f, 1.0f }, 1.0f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; - b2CreateCapsuleShape(m_weebleId, &shapeDef, &capsule); + b2CreateCapsuleShape( m_weebleId, &shapeDef, &capsule ); + + float mass = b2Body_GetMass( m_weebleId ); + float inertiaTensor = b2Body_GetInertiaTensor( m_weebleId ); - float mass = b2Body_GetMass(m_weebleId); - float inertiaTensor = b2Body_GetInertiaTensor(m_weebleId); - float offset = 1.5f; // See: https://en.wikipedia.org/wiki/Parallel_axis_theorem inertiaTensor += mass * offset * offset; - b2MassData massData = {mass, {0.0f, -offset}, inertiaTensor}; - b2Body_SetMassData(m_weebleId, massData); + b2MassData massData = { mass, { 0.0f, -offset }, inertiaTensor }; + b2Body_SetMassData( m_weebleId, massData ); } - m_explosionPosition = {0.0f, 0.0f}; + m_explosionPosition = { 0.0f, 0.0f }; m_explosionRadius = 2.0f; m_explosionMagnitude = 8.0f; } @@ -526,36 +525,36 @@ class Weeble : public Sample void UpdateUI() override { float height = 120.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(200.0f, height)); - ImGui::Begin("Weeble", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize); - if (ImGui::Button("Teleport")) + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 200.0f, height ) ); + ImGui::Begin( "Weeble", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); + if ( ImGui::Button( "Teleport" ) ) { - b2Body_SetTransform(m_weebleId, {0.0f, 5.0f}, b2MakeRot(0.95 * b2_pi)); + b2Body_SetTransform( m_weebleId, { 0.0f, 5.0f }, b2MakeRot( 0.95 * b2_pi ) ); } - if (ImGui::Button("Explode")) + if ( ImGui::Button( "Explode" ) ) { - b2World_Explode(m_worldId, m_explosionPosition, m_explosionRadius, m_explosionMagnitude); + b2World_Explode( m_worldId, m_explosionPosition, m_explosionRadius, m_explosionMagnitude ); } - ImGui::PushItemWidth(100.0f); + ImGui::PushItemWidth( 100.0f ); - ImGui::SliderFloat("Magnitude", &m_explosionMagnitude, -100.0f, 100.0f, "%.1f"); + ImGui::SliderFloat( "Magnitude", &m_explosionMagnitude, -100.0f, 100.0f, "%.1f" ); ImGui::PopItemWidth(); ImGui::End(); } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - Sample::Step(settings); + Sample::Step( settings ); - g_draw.DrawCircle(m_explosionPosition, m_explosionRadius, b2_colorAzure); + g_draw.DrawCircle( m_explosionPosition, m_explosionRadius, b2_colorAzure ); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new Weeble(settings); + return new Weeble( settings ); } b2BodyId m_weebleId; @@ -564,47 +563,47 @@ class Weeble : public Sample float m_explosionMagnitude; }; -static int sampleWeeble = RegisterSample("Bodies", "Weeble", Weeble::Create); +static int sampleWeeble = RegisterSample( "Bodies", "Weeble", Weeble::Create ); class Sleep : public Sample { public: - explicit Sleep(Settings& settings) - : Sample(settings) + explicit Sleep( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {3.0f, 50.0f}; + g_camera.m_center = { 3.0f, 50.0f }; g_camera.m_zoom = 25.0f * 2.2f; } b2BodyId groundId = b2_nullBodyId; { b2BodyDef bodyDef = b2DefaultBodyDef(); - groundId = b2CreateBody(m_worldId, &bodyDef); + groundId = b2CreateBody( m_worldId, &bodyDef ); - b2Segment segment = {{-20.0f, 0.0f}, {20.0f, 0.0f}}; + b2Segment segment = { { -20.0f, 0.0f }, { 20.0f, 0.0f } }; b2ShapeDef shapeDef = b2DefaultShapeDef(); - m_groundShapeId = b2CreateSegmentShape(groundId, &shapeDef, &segment); + m_groundShapeId = b2CreateSegmentShape( groundId, &shapeDef, &segment ); } // Sleeping body with sensors - for (int i = 0; i < 2; ++i) + for ( int i = 0; i < 2; ++i ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {-4.0f, 3.0f + 2.0f * i}; + bodyDef.position = { -4.0f, 3.0f + 2.0f * i }; bodyDef.isAwake = false; bodyDef.enableSleep = true; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); - b2Capsule capsule = {{0.0f, 1.0f}, {1.0f, 1.0f}, 0.75f}; + b2Capsule capsule = { { 0.0f, 1.0f }, { 1.0f, 1.0f }, 0.75f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreateCapsuleShape(bodyId, &shapeDef, &capsule); + b2CreateCapsuleShape( bodyId, &shapeDef, &capsule ); shapeDef.isSensor = true; capsule.radius = 1.0f; - m_sensorIds[i] = b2CreateCapsuleShape(bodyId, &shapeDef, &capsule); + m_sensorIds[i] = b2CreateCapsuleShape( bodyId, &shapeDef, &capsule ); m_sensorTouching[i] = false; } @@ -612,89 +611,89 @@ class Sleep : public Sample { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {0.0f, 3.0f}; + bodyDef.position = { 0.0f, 3.0f }; bodyDef.isAwake = false; bodyDef.enableSleep = false; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); - b2Circle circle = {{1.0f, 1.0f}, 1.0f}; + b2Circle circle = { { 1.0f, 1.0f }, 1.0f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreateCircleShape(bodyId, &shapeDef, &circle); + b2CreateCircleShape( bodyId, &shapeDef, &circle ); } // Awake body and sleep is disabled { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {5.0f, 3.0f}; + bodyDef.position = { 5.0f, 3.0f }; bodyDef.isAwake = true; bodyDef.enableSleep = false; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); - b2Polygon box = b2MakeOffsetBox(1.0f, 1.0f, {0.0f, 1.0f}, 0.25f * b2_pi); + b2Polygon box = b2MakeOffsetBox( 1.0f, 1.0f, { 0.0f, 1.0f }, 0.25f * b2_pi ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); } // A sleeping body to test waking on collision { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {5.0f, 1.0f}; + bodyDef.position = { 5.0f, 1.0f }; bodyDef.isAwake = false; bodyDef.enableSleep = true; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); - b2Polygon box = b2MakeSquare(1.0f); + b2Polygon box = b2MakeSquare( 1.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); } // A long pendulum { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {0.0f, 100.0f}; + bodyDef.position = { 0.0f, 100.0f }; bodyDef.angularDamping = 0.5f; bodyDef.sleepThreshold = 0.05f; - m_pendulumId = b2CreateBody(m_worldId, &bodyDef); + m_pendulumId = b2CreateBody( m_worldId, &bodyDef ); - b2Capsule capsule = {{0.0f, 0.0f}, {90.0f, 0.0f}, 0.25f}; + b2Capsule capsule = { { 0.0f, 0.0f }, { 90.0f, 0.0f }, 0.25f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreateCapsuleShape(m_pendulumId, &shapeDef, &capsule); + b2CreateCapsuleShape( m_pendulumId, &shapeDef, &capsule ); b2Vec2 pivot = bodyDef.position; b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.bodyIdA = groundId; jointDef.bodyIdB = m_pendulumId; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); - b2CreateRevoluteJoint(m_worldId, &jointDef); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); + b2CreateRevoluteJoint( m_worldId, &jointDef ); } } void UpdateUI() override { float height = 100.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(240.0f, height)); - ImGui::Begin("Sleep", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); + ImGui::Begin( "Sleep", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); - ImGui::PushItemWidth(120.0f); + ImGui::PushItemWidth( 120.0f ); - ImGui::Text("Pendulum Tuning"); + ImGui::Text( "Pendulum Tuning" ); - float sleepVelocity = b2Body_GetSleepThreshold(m_pendulumId); - if (ImGui::SliderFloat("sleep velocity", &sleepVelocity, 0.0f, 1.0f, "%.2f")) + float sleepVelocity = b2Body_GetSleepThreshold( m_pendulumId ); + if ( ImGui::SliderFloat( "sleep velocity", &sleepVelocity, 0.0f, 1.0f, "%.2f" ) ) { - b2Body_SetSleepThreshold(m_pendulumId, sleepVelocity); - b2Body_SetAwake(m_pendulumId, true); + b2Body_SetSleepThreshold( m_pendulumId, sleepVelocity ); + b2Body_SetAwake( m_pendulumId, true ); } - float angularDamping = b2Body_GetAngularDamping(m_pendulumId); - if (ImGui::SliderFloat("angular damping", &angularDamping, 0.0f, 2.0f, "%.2f")) + float angularDamping = b2Body_GetAngularDamping( m_pendulumId ); + if ( ImGui::SliderFloat( "angular damping", &angularDamping, 0.0f, 2.0f, "%.2f" ) ) { - b2Body_SetAngularDamping(m_pendulumId, angularDamping); + b2Body_SetAngularDamping( m_pendulumId, angularDamping ); } ImGui::PopItemWidth(); @@ -702,55 +701,55 @@ class Sleep : public Sample ImGui::End(); } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - Sample::Step(settings); + Sample::Step( settings ); // Detect sensors touching the ground - b2SensorEvents sensorEvents = b2World_GetSensorEvents(m_worldId); + b2SensorEvents sensorEvents = b2World_GetSensorEvents( m_worldId ); - for (int i = 0; i < sensorEvents.beginCount; ++i) + for ( int i = 0; i < sensorEvents.beginCount; ++i ) { b2SensorBeginTouchEvent* event = sensorEvents.beginEvents + i; - if (B2_ID_EQUALS(event->visitorShapeId, m_groundShapeId)) + if ( B2_ID_EQUALS( event->visitorShapeId, m_groundShapeId ) ) { - if (B2_ID_EQUALS(event->sensorShapeId, m_sensorIds[0])) + if ( B2_ID_EQUALS( event->sensorShapeId, m_sensorIds[0] ) ) { m_sensorTouching[0] = true; } - else if (B2_ID_EQUALS(event->sensorShapeId, m_sensorIds[1])) + else if ( B2_ID_EQUALS( event->sensorShapeId, m_sensorIds[1] ) ) { m_sensorTouching[1] = true; } } } - for (int i = 0; i < sensorEvents.endCount; ++i) + for ( int i = 0; i < sensorEvents.endCount; ++i ) { b2SensorEndTouchEvent* event = sensorEvents.endEvents + i; - if (B2_ID_EQUALS(event->visitorShapeId, m_groundShapeId)) + if ( B2_ID_EQUALS( event->visitorShapeId, m_groundShapeId ) ) { - if (B2_ID_EQUALS(event->sensorShapeId, m_sensorIds[0])) + if ( B2_ID_EQUALS( event->sensorShapeId, m_sensorIds[0] ) ) { m_sensorTouching[0] = false; } - else if (B2_ID_EQUALS(event->sensorShapeId, m_sensorIds[1])) + else if ( B2_ID_EQUALS( event->sensorShapeId, m_sensorIds[1] ) ) { m_sensorTouching[1] = false; } } } - for (int i = 0; i < 2; ++i) + for ( int i = 0; i < 2; ++i ) { - g_draw.DrawString(5, m_textLine, "sensor touch %d = %s", i, m_sensorTouching[i] ? "true" : "false"); + g_draw.DrawString( 5, m_textLine, "sensor touch %d = %s", i, m_sensorTouching[i] ? "true" : "false" ); m_textLine += m_textIncrement; } } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new Sleep(settings); + return new Sleep( settings ); } b2BodyId m_pendulumId; @@ -759,84 +758,84 @@ class Sleep : public Sample bool m_sensorTouching[2]; }; -static int sampleSleep = RegisterSample("Bodies", "Sleep", Sleep::Create); +static int sampleSleep = RegisterSample( "Bodies", "Sleep", Sleep::Create ); class BadBody : public Sample { public: - explicit BadBody(Settings& settings) - : Sample(settings) + explicit BadBody( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {2.3f, 10.0f}; + g_camera.m_center = { 2.3f, 10.0f }; g_camera.m_zoom = 25.0f * 0.5f; } b2BodyId groundId = b2_nullBodyId; { b2BodyDef bodyDef = b2DefaultBodyDef(); - groundId = b2CreateBody(m_worldId, &bodyDef); + groundId = b2CreateBody( m_worldId, &bodyDef ); - b2Segment segment = {{-20.0f, 0.0f}, {20.0f, 0.0f}}; + b2Segment segment = { { -20.0f, 0.0f }, { 20.0f, 0.0f } }; b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2CreateSegmentShape( groundId, &shapeDef, &segment ); } // Build a bad body { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {0.0f, 3.0f}; + bodyDef.position = { 0.0f, 3.0f }; bodyDef.angularVelocity = 0.2f; - bodyDef.rotation = b2MakeRot(0.25f * b2_pi); + bodyDef.rotation = b2MakeRot( 0.25f * b2_pi ); - m_badBodyId = b2CreateBody(m_worldId, &bodyDef); + m_badBodyId = b2CreateBody( m_worldId, &bodyDef ); - b2Capsule capsule = {{0.0f, -1.0f}, {0.0f, 1.0f}, 1.0f}; + b2Capsule capsule = { { 0.0f, -1.0f }, { 0.0f, 1.0f }, 1.0f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); // density set to zero intentionally to create a bad body shapeDef.density = 0.0f; - b2CreateCapsuleShape(m_badBodyId, &shapeDef, &capsule); + b2CreateCapsuleShape( m_badBodyId, &shapeDef, &capsule ); } // Build a normal body { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {2.0f, 3.0f}; - bodyDef.rotation = b2MakeRot(0.25f * b2_pi); + bodyDef.position = { 2.0f, 3.0f }; + bodyDef.rotation = b2MakeRot( 0.25f * b2_pi ); - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); - b2Capsule capsule = {{0.0f, -1.0f}, {0.0f, 1.0f}, 1.0f}; + b2Capsule capsule = { { 0.0f, -1.0f }, { 0.0f, 1.0f }, 1.0f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreateCapsuleShape(bodyId, &shapeDef, &capsule); + b2CreateCapsuleShape( bodyId, &shapeDef, &capsule ); } } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - Sample::Step(settings); + Sample::Step( settings ); - g_draw.DrawString(5, m_textLine, "A bad body is a dynamic body with no mass and behaves like a kinematic body."); + g_draw.DrawString( 5, m_textLine, "A bad body is a dynamic body with no mass and behaves like a kinematic body." ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "Bad bodies are considered invalid and a user bug. Behavior is not guaranteed."); + g_draw.DrawString( 5, m_textLine, "Bad bodies are considered invalid and a user bug. Behavior is not guaranteed." ); m_textLine += m_textIncrement; // For science - b2Body_ApplyForceToCenter(m_badBodyId, {0.0f, 10.0f}, true); + b2Body_ApplyForceToCenter( m_badBodyId, { 0.0f, 10.0f }, true ); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new BadBody(settings); + return new BadBody( settings ); } b2BodyId m_badBodyId; }; -static int sampleBadBody = RegisterSample("Bodies", "Bad", BadBody::Create); +static int sampleBadBody = RegisterSample( "Bodies", "Bad", BadBody::Create ); diff --git a/samples/sample_collision.cpp b/samples/sample_collision.cpp index 97df0a78..ff07e528 100644 --- a/samples/sample_collision.cpp +++ b/samples/sample_collision.cpp @@ -25,33 +25,33 @@ class ShapeDistance : public Sample e_box }; - explicit ShapeDistance(Settings& settings) - : Sample(settings) + explicit ShapeDistance( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 0.0f}; + g_camera.m_center = { 0.0f, 0.0f }; g_camera.m_zoom = 3.0f; } m_point = b2Vec2_zero; - m_segment = {{-0.5f, 0.0f}, {0.5f, 0.0f}}; + m_segment = { { -0.5f, 0.0f }, { 0.5f, 0.0f } }; { - b2Vec2 points[3] = {{-0.5f, 0.0f}, {0.5f, 0.0f}, {0.0f, 1.0f}}; - b2Hull hull = b2ComputeHull(points, 3); - m_triangle = b2MakePolygon(&hull, 0.0f); + b2Vec2 points[3] = { { -0.5f, 0.0f }, { 0.5f, 0.0f }, { 0.0f, 1.0f } }; + b2Hull hull = b2ComputeHull( points, 3 ); + m_triangle = b2MakePolygon( &hull, 0.0f ); } - m_box = b2MakeBox(0.5f, 0.5f); + m_box = b2MakeBox( 0.5f, 0.5f ); - m_transform = {{1.5f, -1.5f}, b2Rot_identity}; + m_transform = { { 1.5f, -1.5f }, b2Rot_identity }; m_angle = 0.0f; m_cache = b2_emptyDistanceCache; m_simplexCount = 0; - m_startPoint = {0.0f, 0.0f}; - m_basePosition = {0.0f, 0.0f}; + m_startPoint = { 0.0f, 0.0f }; + m_basePosition = { 0.0f, 0.0f }; m_baseAngle = 0.0f; m_dragging = false; @@ -65,16 +65,16 @@ class ShapeDistance : public Sample m_radiusA = 0.0f; m_radiusB = 0.0f; - m_proxyA = MakeProxy(m_typeA, m_radiusA); - m_proxyB = MakeProxy(m_typeB, m_radiusB); + m_proxyA = MakeProxy( m_typeA, m_radiusA ); + m_proxyB = MakeProxy( m_typeB, m_radiusB ); } - b2DistanceProxy MakeProxy(ShapeType type, float radius) + b2DistanceProxy MakeProxy( ShapeType type, float radius ) { b2DistanceProxy proxy = {}; proxy.radius = radius; - switch (type) + switch ( type ) { case e_point: proxy.points[0] = b2Vec2_zero; @@ -103,134 +103,134 @@ class ShapeDistance : public Sample break; default: - assert(false); + assert( false ); } return proxy; } - void DrawShape(ShapeType type, b2Transform transform, float radius, b2HexColor color) + void DrawShape( ShapeType type, b2Transform transform, float radius, b2HexColor color ) { - switch (type) + switch ( type ) { case e_point: { - b2Vec2 p = b2TransformPoint(transform, m_point); - if (radius > 0.0f) + b2Vec2 p = b2TransformPoint( transform, m_point ); + if ( radius > 0.0f ) { - g_draw.DrawCircle(p, radius, color); + g_draw.DrawCircle( p, radius, color ); } else { - g_draw.DrawPoint(p, 5.0f, color); + g_draw.DrawPoint( p, 5.0f, color ); } } break; case e_segment: { - b2Vec2 p1 = b2TransformPoint(transform, m_segment.point1); - b2Vec2 p2 = b2TransformPoint(transform, m_segment.point2); + b2Vec2 p1 = b2TransformPoint( transform, m_segment.point1 ); + b2Vec2 p2 = b2TransformPoint( transform, m_segment.point2 ); - if (radius > 0.0f) + if ( radius > 0.0f ) { - g_draw.DrawCapsule(p1, p2, radius, color); + g_draw.DrawCapsule( p1, p2, radius, color ); } else { - g_draw.DrawSegment(p1, p2, color); + g_draw.DrawSegment( p1, p2, color ); } } break; case e_triangle: - g_draw.DrawSolidPolygon(transform, m_triangle.vertices, 3, radius, color); + g_draw.DrawSolidPolygon( transform, m_triangle.vertices, 3, radius, color ); break; case e_box: - g_draw.DrawSolidPolygon(transform, m_box.vertices, 4, radius, color); + g_draw.DrawSolidPolygon( transform, m_box.vertices, 4, radius, color ); break; default: - assert(false); + assert( false ); } } void UpdateUI() override { float height = 310.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(240.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); - ImGui::Begin("Shape Distance", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize); + ImGui::Begin( "Shape Distance", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); - const char* shapeTypes[] = {"point", "segment", "triangle", "box"}; - int shapeType = int(m_typeA); - if (ImGui::Combo("shape A", &shapeType, shapeTypes, IM_ARRAYSIZE(shapeTypes))) + const char* shapeTypes[] = { "point", "segment", "triangle", "box" }; + int shapeType = int( m_typeA ); + if ( ImGui::Combo( "shape A", &shapeType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ) ) { - m_typeA = ShapeType(shapeType); - m_proxyA = MakeProxy(m_typeA, m_radiusA); + m_typeA = ShapeType( shapeType ); + m_proxyA = MakeProxy( m_typeA, m_radiusA ); } - if (ImGui::SliderFloat("radius A", &m_radiusA, 0.0f, 0.5f, "%.2f")) + if ( ImGui::SliderFloat( "radius A", &m_radiusA, 0.0f, 0.5f, "%.2f" ) ) { m_proxyA.radius = m_radiusA; } - shapeType = int(m_typeB); - if (ImGui::Combo("shape B", &shapeType, shapeTypes, IM_ARRAYSIZE(shapeTypes))) + shapeType = int( m_typeB ); + if ( ImGui::Combo( "shape B", &shapeType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ) ) { - m_typeB = ShapeType(shapeType); - m_proxyB = MakeProxy(m_typeB, m_radiusB); + m_typeB = ShapeType( shapeType ); + m_proxyB = MakeProxy( m_typeB, m_radiusB ); } - if (ImGui::SliderFloat("radius B", &m_radiusB, 0.0f, 0.5f, "%.2f")) + if ( ImGui::SliderFloat( "radius B", &m_radiusB, 0.0f, 0.5f, "%.2f" ) ) { m_proxyB.radius = m_radiusB; } ImGui::Separator(); - ImGui::SliderFloat("x offset", &m_transform.p.x, -2.0f, 2.0f, "%.2f"); - ImGui::SliderFloat("y offset", &m_transform.p.y, -2.0f, 2.0f, "%.2f"); + ImGui::SliderFloat( "x offset", &m_transform.p.x, -2.0f, 2.0f, "%.2f" ); + ImGui::SliderFloat( "y offset", &m_transform.p.y, -2.0f, 2.0f, "%.2f" ); - if (ImGui::SliderFloat("angle", &m_angle, -b2_pi, b2_pi, "%.2f")) + if ( ImGui::SliderFloat( "angle", &m_angle, -b2_pi, b2_pi, "%.2f" ) ) { - m_transform.q = b2MakeRot(m_angle); + m_transform.q = b2MakeRot( m_angle ); } ImGui::Separator(); - ImGui::Checkbox("show indices", &m_showIndices); - ImGui::Checkbox("use cache", &m_useCache); + ImGui::Checkbox( "show indices", &m_showIndices ); + ImGui::Checkbox( "use cache", &m_useCache ); ImGui::Separator(); - if (ImGui::Checkbox("draw simplex", &m_drawSimplex)) + if ( ImGui::Checkbox( "draw simplex", &m_drawSimplex ) ) { m_simplexIndex = 0; } - if (m_drawSimplex) + if ( m_drawSimplex ) { - ImGui::SliderInt("index", &m_simplexIndex, 0, m_simplexCount - 1); - m_simplexIndex = b2ClampInt(m_simplexIndex, 0, m_simplexCount - 1); + ImGui::SliderInt( "index", &m_simplexIndex, 0, m_simplexCount - 1 ); + m_simplexIndex = b2ClampInt( m_simplexIndex, 0, m_simplexCount - 1 ); } ImGui::End(); } - void MouseDown(b2Vec2 p, int button, int mods) override + void MouseDown( b2Vec2 p, int button, int mods ) override { - if (button == GLFW_MOUSE_BUTTON_1) + if ( button == GLFW_MOUSE_BUTTON_1 ) { - if (mods == 0 && m_rotating == false) + if ( mods == 0 && m_rotating == false ) { m_dragging = true; m_startPoint = p; m_basePosition = m_transform.p; } - else if (mods == GLFW_MOD_SHIFT && m_dragging == false) + else if ( mods == GLFW_MOD_SHIFT && m_dragging == false ) { m_rotating = true; m_startPoint = p; @@ -239,46 +239,46 @@ class ShapeDistance : public Sample } } - void MouseUp(b2Vec2, int button) override + void MouseUp( b2Vec2, int button ) override { - if (button == GLFW_MOUSE_BUTTON_1) + if ( button == GLFW_MOUSE_BUTTON_1 ) { m_dragging = false; m_rotating = false; } } - void MouseMove(b2Vec2 p) override + void MouseMove( b2Vec2 p ) override { - if (m_dragging) + if ( m_dragging ) { - m_transform.p.x = m_basePosition.x + 0.5f * (p.x - m_startPoint.x); - m_transform.p.y = m_basePosition.y + 0.5f * (p.y - m_startPoint.y); + m_transform.p.x = m_basePosition.x + 0.5f * ( p.x - m_startPoint.x ); + m_transform.p.y = m_basePosition.y + 0.5f * ( p.y - m_startPoint.y ); } - else if (m_rotating) + else if ( m_rotating ) { float dx = p.x - m_startPoint.x; - m_angle = b2ClampFloat(m_baseAngle + 1.0f * dx, -b2_pi, b2_pi); - m_transform.q = b2MakeRot(m_angle); + m_angle = b2ClampFloat( m_baseAngle + 1.0f * dx, -b2_pi, b2_pi ); + m_transform.q = b2MakeRot( m_angle ); } } - static b2Vec2 Weight2(float a1, b2Vec2 w1, float a2, b2Vec2 w2) + static b2Vec2 Weight2( float a1, b2Vec2 w1, float a2, b2Vec2 w2 ) { - return {a1 * w1.x + a2 * w2.x, a1 * w1.y + a2 * w2.y}; + return { a1 * w1.x + a2 * w2.x, a1 * w1.y + a2 * w2.y }; } - static b2Vec2 Weight3(float a1, b2Vec2 w1, float a2, b2Vec2 w2, float a3, b2Vec2 w3) + static b2Vec2 Weight3( float a1, b2Vec2 w1, float a2, b2Vec2 w2, float a3, b2Vec2 w3 ) { - return {a1 * w1.x + a2 * w2.x + a3 * w3.x, a1 * w1.y + a2 * w2.y + a3 * w3.y}; + return { a1 * w1.x + a2 * w2.x + a3 * w3.x, a1 * w1.y + a2 * w2.y + a3 * w3.y }; } - void ComputeSimplexWitnessPoints(b2Vec2* a, b2Vec2* b, const b2Simplex* s) + void ComputeSimplexWitnessPoints( b2Vec2* a, b2Vec2* b, const b2Simplex* s ) { - switch (s->count) + switch ( s->count ) { case 0: - assert(false); + assert( false ); break; case 1: @@ -287,22 +287,22 @@ class ShapeDistance : public Sample break; case 2: - *a = Weight2(s->v1.a, s->v1.wA, s->v2.a, s->v2.wA); - *b = Weight2(s->v1.a, s->v1.wB, s->v2.a, s->v2.wB); + *a = Weight2( s->v1.a, s->v1.wA, s->v2.a, s->v2.wA ); + *b = Weight2( s->v1.a, s->v1.wB, s->v2.a, s->v2.wB ); break; case 3: - *a = Weight3(s->v1.a, s->v1.wA, s->v2.a, s->v2.wA, s->v3.a, s->v3.wA); + *a = Weight3( s->v1.a, s->v1.wA, s->v2.a, s->v2.wA, s->v3.a, s->v3.wA ); *b = *a; break; default: - assert(false); + assert( false ); break; } } - void Step(Settings&) override + void Step( Settings& ) override { b2DistanceInput input; input.proxyA = m_proxyA; @@ -311,93 +311,92 @@ class ShapeDistance : public Sample input.transformB = m_transform; input.useRadii = m_radiusA > 0.0f || m_radiusB > 0.0f; - if (m_useCache == false) + if ( m_useCache == false ) { m_cache.count = 0; } - b2DistanceOutput output = b2ShapeDistance(&m_cache, &input, m_simplexes, SIMPLEX_CAPACITY); + b2DistanceOutput output = b2ShapeDistance( &m_cache, &input, m_simplexes, SIMPLEX_CAPACITY ); m_simplexCount = output.simplexCount; - DrawShape(m_typeA, b2Transform_identity, m_radiusA, b2_colorAqua); - DrawShape(m_typeB, m_transform, m_radiusB, b2_colorBisque); + DrawShape( m_typeA, b2Transform_identity, m_radiusA, b2_colorAqua ); + DrawShape( m_typeB, m_transform, m_radiusB, b2_colorBisque ); - if (m_drawSimplex) + if ( m_drawSimplex ) { b2Simplex* simplex = m_simplexes + m_simplexIndex; - b2SimplexVertex* vertices[3] = {&simplex->v1, &simplex->v2, &simplex->v3}; + b2SimplexVertex* vertices[3] = { &simplex->v1, &simplex->v2, &simplex->v3 }; - if (m_simplexIndex > 0) + if ( m_simplexIndex > 0 ) { // The first recorded simplex does not have valid barycentric coordinates b2Vec2 pointA, pointB; - ComputeSimplexWitnessPoints(&pointA, &pointB, simplex); + ComputeSimplexWitnessPoints( &pointA, &pointB, simplex ); - g_draw.DrawSegment(pointA, pointB, b2_colorWhite); - g_draw.DrawPoint(pointA, 5.0f, b2_colorWhite); - g_draw.DrawPoint(pointB, 5.0f, b2_colorWhite); + g_draw.DrawSegment( pointA, pointB, b2_colorWhite ); + g_draw.DrawPoint( pointA, 5.0f, b2_colorWhite ); + g_draw.DrawPoint( pointB, 5.0f, b2_colorWhite ); } - b2HexColor colors[3] = {b2_colorRed, b2_colorGreen, b2_colorBlue}; + b2HexColor colors[3] = { b2_colorRed, b2_colorGreen, b2_colorBlue }; - for (int i = 0; i < simplex->count; ++i) + for ( int i = 0; i < simplex->count; ++i ) { b2SimplexVertex* vertex = vertices[i]; - g_draw.DrawPoint(vertex->wA, 5.0f, colors[i]); - g_draw.DrawPoint(vertex->wB, 5.0f, colors[i]); + g_draw.DrawPoint( vertex->wA, 5.0f, colors[i] ); + g_draw.DrawPoint( vertex->wB, 5.0f, colors[i] ); } } else { - g_draw.DrawSegment(output.pointA, output.pointB, b2_colorWhite); - g_draw.DrawPoint(output.pointA, 5.0f, b2_colorWhite); - g_draw.DrawPoint(output.pointB, 5.0f, b2_colorWhite); + g_draw.DrawSegment( output.pointA, output.pointB, b2_colorWhite ); + g_draw.DrawPoint( output.pointA, 5.0f, b2_colorWhite ); + g_draw.DrawPoint( output.pointB, 5.0f, b2_colorWhite ); } - if (m_showIndices) + if ( m_showIndices ) { - for (int i = 0; i < m_proxyA.count; ++i) + for ( int i = 0; i < m_proxyA.count; ++i ) { b2Vec2 p = m_proxyA.points[i]; - g_draw.DrawString(p, " %d", i); + g_draw.DrawString( p, " %d", i ); } - for (int i = 0; i < m_proxyB.count; ++i) + for ( int i = 0; i < m_proxyB.count; ++i ) { - b2Vec2 p = b2TransformPoint(m_transform, m_proxyB.points[i]); - g_draw.DrawString(p, " %d", i); + b2Vec2 p = b2TransformPoint( m_transform, m_proxyB.points[i] ); + g_draw.DrawString( p, " %d", i ); } } - g_draw.DrawString(5, m_textLine, "mouse button 1: drag"); + g_draw.DrawString( 5, m_textLine, "mouse button 1: drag" ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "mouse button 1 + shift: rotate"); + g_draw.DrawString( 5, m_textLine, "mouse button 1 + shift: rotate" ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "distance = %.2f, iterations = %d", output.distance, output.iterations); + g_draw.DrawString( 5, m_textLine, "distance = %.2f, iterations = %d", output.distance, output.iterations ); m_textLine += m_textIncrement; - if (m_cache.count == 1) + if ( m_cache.count == 1 ) { - g_draw.DrawString(5, m_textLine, "cache = {%d}, {%d}", m_cache.indexA[0], m_cache.indexB[0]); + g_draw.DrawString( 5, m_textLine, "cache = {%d}, {%d}", m_cache.indexA[0], m_cache.indexB[0] ); } - else if (m_cache.count == 2) + else if ( m_cache.count == 2 ) { - g_draw.DrawString(5, m_textLine, "cache = {%d, %d}, {%d, %d}", - m_cache.indexA[0], m_cache.indexA[1], m_cache.indexB[0], m_cache.indexB[1]); + g_draw.DrawString( 5, m_textLine, "cache = {%d, %d}, {%d, %d}", m_cache.indexA[0], m_cache.indexA[1], + m_cache.indexB[0], m_cache.indexB[1] ); } - else if (m_cache.count == 3) + else if ( m_cache.count == 3 ) { - g_draw.DrawString(5, m_textLine, "cache = {%d, %d, %d}, {%d, %d, %d}", - m_cache.indexA[0], m_cache.indexA[1], m_cache.indexA[2], - m_cache.indexB[0], m_cache.indexB[1], m_cache.indexB[2]); + g_draw.DrawString( 5, m_textLine, "cache = {%d, %d, %d}, {%d, %d, %d}", m_cache.indexA[0], m_cache.indexA[1], + m_cache.indexA[2], m_cache.indexB[0], m_cache.indexB[1], m_cache.indexB[2] ); } m_textLine += m_textIncrement; } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new ShapeDistance(settings); + return new ShapeDistance( settings ); } b2Polygon m_box; @@ -431,7 +430,7 @@ class ShapeDistance : public Sample bool m_drawSimplex; }; -static int sampleShapeDistance = RegisterSample("Collision", "Shape Distance", ShapeDistance::Create); +static int sampleShapeDistance = RegisterSample( "Collision", "Shape Distance", ShapeDistance::Create ); enum UpdateType { @@ -452,20 +451,20 @@ struct Proxy bool moved; }; -static bool QueryCallback(int32_t proxyId, int32_t userData, void* context); -static float RayCallback(const b2RayCastInput* input, int32_t proxyId, int32_t userData, void* context); +static bool QueryCallback( int32_t proxyId, int32_t userData, void* context ); +static float RayCallback( const b2RayCastInput* input, int32_t proxyId, int32_t userData, void* context ); // Tests the Box2D bounding volume hierarchy (BVH). The dynamic tree // can be used independently as a spatial data structure. class DynamicTree : public Sample { public: - explicit DynamicTree(Settings& settings) - : Sample(settings) + explicit DynamicTree( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {500.0f, 500.0f}; + g_camera.m_center = { 500.0f, 500.0f }; g_camera.m_zoom = 25.0f * 21.0f; } @@ -483,13 +482,13 @@ class DynamicTree : public Sample m_rowCount = g_sampleDebug ? 100 : 1000; m_columnCount = g_sampleDebug ? 100 : 1000; - memset(&m_tree, 0, sizeof(m_tree)); + memset( &m_tree, 0, sizeof( m_tree ) ); BuildTree(); m_timeStamp = 0; m_updateType = Update_Incremental; - m_startPoint = {0.0f, 0.0f}; - m_endPoint = {0.0f, 0.0f}; + m_startPoint = { 0.0f, 0.0f }; + m_endPoint = { 0.0f, 0.0f }; m_queryDrag = false; m_rayDrag = false; m_validate = true; @@ -497,22 +496,22 @@ class DynamicTree : public Sample ~DynamicTree() override { - free(m_proxies); - free(m_moveBuffer); - b2DynamicTree_Destroy(&m_tree); + free( m_proxies ); + free( m_moveBuffer ); + b2DynamicTree_Destroy( &m_tree ); } void BuildTree() { - b2DynamicTree_Destroy(&m_tree); - free(m_proxies); - free(m_moveBuffer); + b2DynamicTree_Destroy( &m_tree ); + free( m_proxies ); + free( m_moveBuffer ); m_proxyCapacity = m_rowCount * m_columnCount; - m_proxies = static_cast(malloc(m_proxyCapacity * sizeof(Proxy))); + m_proxies = static_cast( malloc( m_proxyCapacity * sizeof( Proxy ) ) ); m_proxyCount = 0; - m_moveBuffer = static_cast(malloc(m_proxyCapacity * sizeof(int))); + m_moveBuffer = static_cast( malloc( m_proxyCapacity * sizeof( int ) ) ); m_moveCount = 0; float y = -4.0f; @@ -520,24 +519,24 @@ class DynamicTree : public Sample bool isStatic = false; m_tree = b2DynamicTree_Create(); - const b2Vec2 aabbMargin = {0.1f, 0.1f}; + const b2Vec2 aabbMargin = { 0.1f, 0.1f }; - for (int i = 0; i < m_rowCount; ++i) + for ( int i = 0; i < m_rowCount; ++i ) { float x = -40.0f; - for (int j = 0; j < m_columnCount; ++j) + for ( int j = 0; j < m_columnCount; ++j ) { - float fillTest = RandomFloat(0.0f, 1.0f); - if (fillTest <= m_fill) + float fillTest = RandomFloat( 0.0f, 1.0f ); + if ( fillTest <= m_fill ) { - assert(m_proxyCount <= m_proxyCapacity); + assert( m_proxyCount <= m_proxyCapacity ); Proxy* p = m_proxies + m_proxyCount; - p->position = {x, y}; + p->position = { x, y }; - float ratio = RandomFloat(1.0f, m_ratio); - float width = RandomFloat(0.1f, 0.5f); - if (RandomFloat() > 0.0f) + float ratio = RandomFloat( 1.0f, m_ratio ); + float width = RandomFloat( 0.1f, 0.5f ); + if ( RandomFloat() > 0.0f ) { p->width.x = ratio * width; p->width.y = width; @@ -548,12 +547,12 @@ class DynamicTree : public Sample p->width.y = ratio * width; } - p->box.lowerBound = {x, y}; - p->box.upperBound = {x + p->width.x, y + p->width.y}; - p->fatBox.lowerBound = b2Sub(p->box.lowerBound, aabbMargin); - p->fatBox.upperBound = b2Add(p->box.upperBound, aabbMargin); + p->box.lowerBound = { x, y }; + p->box.upperBound = { x + p->width.x, y + p->width.y }; + p->fatBox.lowerBound = b2Sub( p->box.lowerBound, aabbMargin ); + p->fatBox.upperBound = b2Add( p->box.upperBound, aabbMargin ); - p->proxyId = b2DynamicTree_CreateProxy(&m_tree, p->fatBox, b2_defaultCategoryBits, m_proxyCount); + p->proxyId = b2DynamicTree_CreateProxy( &m_tree, p->fatBox, b2_defaultCategoryBits, m_proxyCount ); p->rayStamp = -1; p->queryStamp = -1; p->moved = false; @@ -570,60 +569,60 @@ class DynamicTree : public Sample void UpdateUI() override { float height = 320.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(200.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 200.0f, height ) ); - ImGui::Begin("Dynamic Tree", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize); + ImGui::Begin( "Dynamic Tree", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); - ImGui::PushItemWidth(100.0f); + ImGui::PushItemWidth( 100.0f ); bool changed = false; - if (ImGui::SliderInt("rows", &m_rowCount, 0, 1000, "%d")) + if ( ImGui::SliderInt( "rows", &m_rowCount, 0, 1000, "%d" ) ) { changed = true; } - if (ImGui::SliderInt("columns", &m_columnCount, 0, 1000, "%d")) + if ( ImGui::SliderInt( "columns", &m_columnCount, 0, 1000, "%d" ) ) { changed = true; } - if (ImGui::SliderFloat("fill", &m_fill, 0.0f, 1.0f, "%.2f")) + if ( ImGui::SliderFloat( "fill", &m_fill, 0.0f, 1.0f, "%.2f" ) ) { changed = true; } - if (ImGui::SliderFloat("grid", &m_grid, 0.5f, 2.0f, "%.2f")) + if ( ImGui::SliderFloat( "grid", &m_grid, 0.5f, 2.0f, "%.2f" ) ) { changed = true; } - if (ImGui::SliderFloat("ratio", &m_ratio, 1.0f, 10.0f, "%.2f")) + if ( ImGui::SliderFloat( "ratio", &m_ratio, 1.0f, 10.0f, "%.2f" ) ) { changed = true; } - if (ImGui::SliderFloat("move", &m_moveFraction, 0.0f, 1.0f, "%.2f")) + if ( ImGui::SliderFloat( "move", &m_moveFraction, 0.0f, 1.0f, "%.2f" ) ) { } - if (ImGui::SliderFloat("delta", &m_moveDelta, 0.0f, 1.0f, "%.2f")) + if ( ImGui::SliderFloat( "delta", &m_moveDelta, 0.0f, 1.0f, "%.2f" ) ) { } - if (ImGui::RadioButton("Incremental", m_updateType == Update_Incremental)) + if ( ImGui::RadioButton( "Incremental", m_updateType == Update_Incremental ) ) { m_updateType = Update_Incremental; changed = true; } - if (ImGui::RadioButton("Full Rebuild", m_updateType == Update_FullRebuild)) + if ( ImGui::RadioButton( "Full Rebuild", m_updateType == Update_FullRebuild ) ) { m_updateType = Update_FullRebuild; changed = true; } - if (ImGui::RadioButton("Partial Rebuild", m_updateType == Update_PartialRebuild)) + if ( ImGui::RadioButton( "Partial Rebuild", m_updateType == Update_PartialRebuild ) ) { m_updateType = Update_PartialRebuild; changed = true; @@ -631,29 +630,29 @@ class DynamicTree : public Sample ImGui::Separator(); - ImGui::Text("mouse button 1: ray cast"); - ImGui::Text("mouse button 1 + shift: query"); + ImGui::Text( "mouse button 1: ray cast" ); + ImGui::Text( "mouse button 1 + shift: query" ); ImGui::PopItemWidth(); ImGui::End(); - if (changed) + if ( changed ) { BuildTree(); } } - void MouseDown(b2Vec2 p, int button, int mods) override + void MouseDown( b2Vec2 p, int button, int mods ) override { - if (button == GLFW_MOUSE_BUTTON_1) + if ( button == GLFW_MOUSE_BUTTON_1 ) { - if (mods == 0 && m_queryDrag == false) + if ( mods == 0 && m_queryDrag == false ) { m_rayDrag = true; m_startPoint = p; m_endPoint = p; } - else if (mods == GLFW_MOD_SHIFT && m_rayDrag == false) + else if ( mods == GLFW_MOD_SHIFT && m_rayDrag == false ) { m_queryDrag = true; m_startPoint = p; @@ -662,63 +661,63 @@ class DynamicTree : public Sample } } - void MouseUp(b2Vec2, int button) override + void MouseUp( b2Vec2, int button ) override { - if (button == GLFW_MOUSE_BUTTON_1) + if ( button == GLFW_MOUSE_BUTTON_1 ) { m_queryDrag = false; m_rayDrag = false; } } - void MouseMove(b2Vec2 p) override + void MouseMove( b2Vec2 p ) override { m_endPoint = p; } - void Step(Settings&) override + void Step( Settings& ) override { - if (m_queryDrag) + if ( m_queryDrag ) { - b2AABB box = {b2Min(m_startPoint, m_endPoint), b2Max(m_startPoint, m_endPoint)}; - b2DynamicTree_Query(&m_tree, box, b2_defaultMaskBits, QueryCallback, this); + b2AABB box = { b2Min( m_startPoint, m_endPoint ), b2Max( m_startPoint, m_endPoint ) }; + b2DynamicTree_Query( &m_tree, box, b2_defaultMaskBits, QueryCallback, this ); - g_draw.DrawAABB(box, b2_colorWhite); + g_draw.DrawAABB( box, b2_colorWhite ); } // m_startPoint = {-1.0f, 0.5f}; // m_endPoint = {7.0f, 0.5f}; - if (m_rayDrag) + if ( m_rayDrag ) { - b2RayCastInput input = {m_startPoint, b2Sub(m_endPoint, m_startPoint), 1.0f}; - b2DynamicTree_RayCast(&m_tree, &input, b2_defaultMaskBits, RayCallback, this); + b2RayCastInput input = { m_startPoint, b2Sub( m_endPoint, m_startPoint ), 1.0f }; + b2DynamicTree_RayCast( &m_tree, &input, b2_defaultMaskBits, RayCallback, this ); - g_draw.DrawSegment(m_startPoint, m_endPoint, b2_colorWhite); - g_draw.DrawPoint(m_startPoint, 5.0f, b2_colorGreen); - g_draw.DrawPoint(m_endPoint, 5.0f, b2_colorRed); + g_draw.DrawSegment( m_startPoint, m_endPoint, b2_colorWhite ); + g_draw.DrawPoint( m_startPoint, 5.0f, b2_colorGreen ); + g_draw.DrawPoint( m_endPoint, 5.0f, b2_colorRed ); } b2HexColor c = b2_colorBlue; b2HexColor qc = b2_colorGreen; - const b2Vec2 aabbMargin = {0.1f, 0.1f}; + const b2Vec2 aabbMargin = { 0.1f, 0.1f }; - for (int i = 0; i < m_proxyCount; ++i) + for ( int i = 0; i < m_proxyCount; ++i ) { Proxy* p = m_proxies + i; - if (p->queryStamp == m_timeStamp || p->rayStamp == m_timeStamp) + if ( p->queryStamp == m_timeStamp || p->rayStamp == m_timeStamp ) { - g_draw.DrawAABB(p->box, qc); + g_draw.DrawAABB( p->box, qc ); } else { - g_draw.DrawAABB(p->box, c); + g_draw.DrawAABB( p->box, c ); } - float moveTest = RandomFloat(0.0f, 1.0f); - if (m_moveFraction > moveTest) + float moveTest = RandomFloat( 0.0f, 1.0f ); + if ( m_moveFraction > moveTest ) { float dx = m_moveDelta * RandomFloat(); float dy = m_moveDelta * RandomFloat(); @@ -731,10 +730,10 @@ class DynamicTree : public Sample p->box.upperBound.x = p->position.x + dx + p->width.x; p->box.upperBound.y = p->position.y + dy + p->width.y; - if (b2AABB_Contains(p->fatBox, p->box) == false) + if ( b2AABB_Contains( p->fatBox, p->box ) == false ) { - p->fatBox.lowerBound = b2Sub(p->box.lowerBound, aabbMargin); - p->fatBox.upperBound = b2Add(p->box.upperBound, aabbMargin); + p->fatBox.lowerBound = b2Sub( p->box.lowerBound, aabbMargin ); + p->fatBox.upperBound = b2Add( p->box.upperBound, aabbMargin ); p->moved = true; } else @@ -748,59 +747,59 @@ class DynamicTree : public Sample } } - switch (m_updateType) + switch ( m_updateType ) { case Update_Incremental: { b2Timer timer = b2CreateTimer(); - for (int i = 0; i < m_proxyCount; ++i) + for ( int i = 0; i < m_proxyCount; ++i ) { Proxy* p = m_proxies + i; - if (p->moved) + if ( p->moved ) { - b2DynamicTree_MoveProxy(&m_tree, p->proxyId, p->fatBox); + b2DynamicTree_MoveProxy( &m_tree, p->proxyId, p->fatBox ); } } - float ms = b2GetMilliseconds(&timer); - g_draw.DrawString(5, m_textLine, "incremental : %.3f ms", ms); + float ms = b2GetMilliseconds( &timer ); + g_draw.DrawString( 5, m_textLine, "incremental : %.3f ms", ms ); m_textLine += m_textIncrement; } break; case Update_FullRebuild: { - for (int i = 0; i < m_proxyCount; ++i) + for ( int i = 0; i < m_proxyCount; ++i ) { Proxy* p = m_proxies + i; - if (p->moved) + if ( p->moved ) { - b2DynamicTree_EnlargeProxy(&m_tree, p->proxyId, p->fatBox); + b2DynamicTree_EnlargeProxy( &m_tree, p->proxyId, p->fatBox ); } } b2Timer timer = b2CreateTimer(); - int boxCount = b2DynamicTree_Rebuild(&m_tree, true); - float ms = b2GetMilliseconds(&timer); - g_draw.DrawString(5, m_textLine, "full build %d : %.3f ms", boxCount, ms); + int boxCount = b2DynamicTree_Rebuild( &m_tree, true ); + float ms = b2GetMilliseconds( &timer ); + g_draw.DrawString( 5, m_textLine, "full build %d : %.3f ms", boxCount, ms ); m_textLine += m_textIncrement; } break; case Update_PartialRebuild: { - for (int i = 0; i < m_proxyCount; ++i) + for ( int i = 0; i < m_proxyCount; ++i ) { Proxy* p = m_proxies + i; - if (p->moved) + if ( p->moved ) { - b2DynamicTree_EnlargeProxy(&m_tree, p->proxyId, p->fatBox); + b2DynamicTree_EnlargeProxy( &m_tree, p->proxyId, p->fatBox ); } } b2Timer timer = b2CreateTimer(); - int boxCount = b2DynamicTree_Rebuild(&m_tree, false); - float ms = b2GetMilliseconds(&timer); - g_draw.DrawString(5, m_textLine, "partial rebuild %d : %.3f ms", boxCount, ms); + int boxCount = b2DynamicTree_Rebuild( &m_tree, false ); + float ms = b2GetMilliseconds( &timer ); + g_draw.DrawString( 5, m_textLine, "partial rebuild %d : %.3f ms", boxCount, ms ); m_textLine += m_textIncrement; } break; @@ -809,22 +808,22 @@ class DynamicTree : public Sample break; } - int height = b2DynamicTree_GetHeight(&m_tree); - float areaRatio = b2DynamicTree_GetAreaRatio(&m_tree); + int height = b2DynamicTree_GetHeight( &m_tree ); + float areaRatio = b2DynamicTree_GetAreaRatio( &m_tree ); - int hmin = (int)(ceilf(logf((float)m_proxyCount) / logf(2.0f) - 1.0f)); - g_draw.DrawString(5, m_textLine, "proxies = %d, height = %d, hmin = %d, area ratio = %.1f", m_proxyCount, height, hmin, - areaRatio); + int hmin = (int)( ceilf( logf( (float)m_proxyCount ) / logf( 2.0f ) - 1.0f ) ); + g_draw.DrawString( 5, m_textLine, "proxies = %d, height = %d, hmin = %d, area ratio = %.1f", m_proxyCount, height, hmin, + areaRatio ); m_textLine += m_textIncrement; - b2DynamicTree_Validate(&m_tree); + b2DynamicTree_Validate( &m_tree ); m_timeStamp += 1; } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new DynamicTree(settings); + return new DynamicTree( settings ); } b2DynamicTree m_tree; @@ -850,57 +849,57 @@ class DynamicTree : public Sample bool m_validate; }; -static bool QueryCallback(int proxyId, int userData, void* context) +static bool QueryCallback( int proxyId, int userData, void* context ) { - DynamicTree* sample = static_cast(context); + DynamicTree* sample = static_cast( context ); Proxy* proxy = sample->m_proxies + userData; - assert(proxy->proxyId == proxyId); + assert( proxy->proxyId == proxyId ); proxy->queryStamp = sample->m_timeStamp; return true; } -static float RayCallback(const b2RayCastInput* input, int proxyId, int userData, void* context) +static float RayCallback( const b2RayCastInput* input, int proxyId, int userData, void* context ) { - DynamicTree* sample = static_cast(context); + DynamicTree* sample = static_cast( context ); Proxy* proxy = sample->m_proxies + userData; - assert(proxy->proxyId == proxyId); + assert( proxy->proxyId == proxyId ); proxy->rayStamp = sample->m_timeStamp; return input->maxFraction; } -static int sampleDynamicTree = RegisterSample("Collision", "Dynamic Tree", DynamicTree::Create); +static int sampleDynamicTree = RegisterSample( "Collision", "Dynamic Tree", DynamicTree::Create ); class RayCast : public Sample { public: - explicit RayCast(Settings& settings) - : Sample(settings) + explicit RayCast( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 20.0f}; + g_camera.m_center = { 0.0f, 20.0f }; g_camera.m_zoom = 17.5f; } - m_circle = {{0.0f, 0.0f}, 2.0f}; - m_capsule = {{-1.0f, 1.0f}, {1.0f, -1.0f}, 1.5f}; - m_box = b2MakeBox(2.0f, 2.0f); + m_circle = { { 0.0f, 0.0f }, 2.0f }; + m_capsule = { { -1.0f, 1.0f }, { 1.0f, -1.0f }, 1.5f }; + m_box = b2MakeBox( 2.0f, 2.0f ); - b2Vec2 vertices[3] = {{-2.0f, 0.0f}, {2.0f, 0.0f}, {2.0f, 3.0f}}; - b2Hull hull = b2ComputeHull(vertices, 3); - m_triangle = b2MakePolygon(&hull, 0.0f); + b2Vec2 vertices[3] = { { -2.0f, 0.0f }, { 2.0f, 0.0f }, { 2.0f, 3.0f } }; + b2Hull hull = b2ComputeHull( vertices, 3 ); + m_triangle = b2MakePolygon( &hull, 0.0f ); - m_segment = {{-3.0f, 0.0f}, {3.0f, 0.0}}; + m_segment = { { -3.0f, 0.0f }, { 3.0f, 0.0 } }; m_transform = b2Transform_identity; m_angle = 0.0f; - m_basePosition = {0.0f, 0.0f}; + m_basePosition = { 0.0f, 0.0f }; m_baseAngle = 0.0f; - m_startPosition = {0.0f, 0.0f}; + m_startPosition = { 0.0f, 0.0f }; - m_rayStart = {0.0f, 30.0f}; - m_rayEnd = {0.0f, 0.0f}; + m_rayStart = { 0.0f, 30.0f }; + m_rayEnd = { 0.0f, 0.0f }; m_rayDrag = false; m_translating = false; @@ -912,29 +911,28 @@ class RayCast : public Sample void UpdateUI() override { float height = 230.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(200.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 200.0f, height ) ); - ImGui::Begin("Ray-cast", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize); + ImGui::Begin( "Ray-cast", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); - ImGui::PushItemWidth(100.0f); + ImGui::PushItemWidth( 100.0f ); - ImGui::SliderFloat("x offset", &m_transform.p.x, -2.0f, 2.0f, "%.2f"); - ImGui::SliderFloat("y offset", &m_transform.p.y, -2.0f, 2.0f, "%.2f"); + ImGui::SliderFloat( "x offset", &m_transform.p.x, -2.0f, 2.0f, "%.2f" ); + ImGui::SliderFloat( "y offset", &m_transform.p.y, -2.0f, 2.0f, "%.2f" ); - if (ImGui::SliderFloat("angle", &m_angle, -b2_pi, b2_pi, "%.2f")) + if ( ImGui::SliderFloat( "angle", &m_angle, -b2_pi, b2_pi, "%.2f" ) ) { - m_transform.q = b2MakeRot(m_angle); + m_transform.q = b2MakeRot( m_angle ); } // if (ImGui::SliderFloat("ray radius", &m_rayRadius, 0.0f, 1.0f, "%.1f")) //{ // } - ImGui::Checkbox("show fraction", &m_showFraction); + ImGui::Checkbox( "show fraction", &m_showFraction ); - - if (ImGui::Button("Reset")) + if ( ImGui::Button( "Reset" ) ) { m_transform = b2Transform_identity; m_angle = 0.0f; @@ -942,32 +940,32 @@ class RayCast : public Sample ImGui::Separator(); - ImGui::Text("mouse btn 1: ray cast"); - ImGui::Text("mouse btn 1 + shft: translate"); - ImGui::Text("mouse btn 1 + ctrl: rotate"); + ImGui::Text( "mouse btn 1: ray cast" ); + ImGui::Text( "mouse btn 1 + shft: translate" ); + ImGui::Text( "mouse btn 1 + ctrl: rotate" ); ImGui::PopItemWidth(); ImGui::End(); } - void MouseDown(b2Vec2 p, int button, int mods) override + void MouseDown( b2Vec2 p, int button, int mods ) override { - if (button == GLFW_MOUSE_BUTTON_1) + if ( button == GLFW_MOUSE_BUTTON_1 ) { m_startPosition = p; - if (mods == 0) + if ( mods == 0 ) { m_rayStart = p; m_rayDrag = true; } - else if (mods == GLFW_MOD_SHIFT) + else if ( mods == GLFW_MOD_SHIFT ) { m_translating = true; m_basePosition = m_transform.p; } - else if (mods == GLFW_MOD_CONTROL) + else if ( mods == GLFW_MOD_CONTROL ) { m_rotating = true; m_baseAngle = m_angle; @@ -975,9 +973,9 @@ class RayCast : public Sample } } - void MouseUp(b2Vec2, int button) override + void MouseUp( b2Vec2, int button ) override { - if (button == GLFW_MOUSE_BUTTON_1) + if ( button == GLFW_MOUSE_BUTTON_1 ) { m_rayDrag = false; m_rotating = false; @@ -985,40 +983,40 @@ class RayCast : public Sample } } - void MouseMove(b2Vec2 p) override + void MouseMove( b2Vec2 p ) override { - if (m_rayDrag) + if ( m_rayDrag ) { m_rayEnd = p; } - else if (m_translating) + else if ( m_translating ) { - m_transform.p.x = m_basePosition.x + 0.5f * (p.x - m_startPosition.x); - m_transform.p.y = m_basePosition.y + 0.5f * (p.y - m_startPosition.y); + m_transform.p.x = m_basePosition.x + 0.5f * ( p.x - m_startPosition.x ); + m_transform.p.y = m_basePosition.y + 0.5f * ( p.y - m_startPosition.y ); } - else if (m_rotating) + else if ( m_rotating ) { float dx = p.x - m_startPosition.x; - m_angle = b2ClampFloat(m_baseAngle + 0.5f * dx, -b2_pi, b2_pi); - m_transform.q = b2MakeRot(m_angle); + m_angle = b2ClampFloat( m_baseAngle + 0.5f * dx, -b2_pi, b2_pi ); + m_transform.q = b2MakeRot( m_angle ); } } - void DrawRay(const b2CastOutput* output) + void DrawRay( const b2CastOutput* output ) { b2Vec2 p1 = m_rayStart; b2Vec2 p2 = m_rayEnd; - b2Vec2 d = b2Sub(p2, p1); + b2Vec2 d = b2Sub( p2, p1 ); - if (output->hit) + if ( output->hit ) { - b2Vec2 p = b2MulAdd(p1, output->fraction, d); - g_draw.DrawSegment(p1, p, b2_colorWhite); - g_draw.DrawPoint(p1, 5.0f, b2_colorGreen); - g_draw.DrawPoint(output->point, 5.0f, b2_colorWhite); + b2Vec2 p = b2MulAdd( p1, output->fraction, d ); + g_draw.DrawSegment( p1, p, b2_colorWhite ); + g_draw.DrawPoint( p1, 5.0f, b2_colorGreen ); + g_draw.DrawPoint( output->point, 5.0f, b2_colorWhite ); - b2Vec2 n = b2MulAdd(p, 1.0f, output->normal); - g_draw.DrawSegment(p, n, b2_colorViolet); + b2Vec2 n = b2MulAdd( p, 1.0f, output->normal ); + g_draw.DrawSegment( p, n, b2_colorViolet ); // if (m_rayRadius > 0.0f) //{ @@ -1026,17 +1024,17 @@ class RayCast : public Sample // g_draw.DrawCircle(p, m_rayRadius, b2_colorRed); // } - if (m_showFraction) + if ( m_showFraction ) { - b2Vec2 ps = {p.x + 0.05f, p.y - 0.02f}; - g_draw.DrawString(ps, "%.2f", output->fraction); + b2Vec2 ps = { p.x + 0.05f, p.y - 0.02f }; + g_draw.DrawString( ps, "%.2f", output->fraction ); } } else { - g_draw.DrawSegment(p1, p2, b2_colorWhite); - g_draw.DrawPoint(p1, 5.0f, b2_colorGreen); - g_draw.DrawPoint(p2, 5.0f, b2_colorRed); + g_draw.DrawSegment( p1, p2, b2_colorWhite ); + g_draw.DrawPoint( p1, 5.0f, b2_colorGreen ); + g_draw.DrawPoint( p2, 5.0f, b2_colorRed ); // if (m_rayRadius > 0.0f) //{ @@ -1046,132 +1044,132 @@ class RayCast : public Sample } } - void Step(Settings&) override + void Step( Settings& ) override { - b2Vec2 offset = {-20.0f, 20.0f}; - b2Vec2 increment = {10.0f, 0.0f}; + b2Vec2 offset = { -20.0f, 20.0f }; + b2Vec2 increment = { 10.0f, 0.0f }; b2HexColor color1 = b2_colorYellow; - b2CastOutput output = {0}; + b2CastOutput output = { 0 }; float maxFraction = 1.0f; // circle { - b2Transform transform = {b2Add(m_transform.p, offset), m_transform.q}; - g_draw.DrawSolidCircle(transform, m_circle.center, m_circle.radius, color1); + b2Transform transform = { b2Add( m_transform.p, offset ), m_transform.q }; + g_draw.DrawSolidCircle( transform, m_circle.center, m_circle.radius, color1 ); - b2Vec2 start = b2InvTransformPoint(transform, m_rayStart); - b2Vec2 translation = b2InvRotateVector(transform.q, b2Sub(m_rayEnd, m_rayStart)); - b2RayCastInput input = {start, translation, maxFraction}; + b2Vec2 start = b2InvTransformPoint( transform, m_rayStart ); + b2Vec2 translation = b2InvRotateVector( transform.q, b2Sub( m_rayEnd, m_rayStart ) ); + b2RayCastInput input = { start, translation, maxFraction }; - b2CastOutput localOutput = b2RayCastCircle(&input, &m_circle); - if (localOutput.hit) + b2CastOutput localOutput = b2RayCastCircle( &input, &m_circle ); + if ( localOutput.hit ) { output = localOutput; - output.point = b2TransformPoint(transform, localOutput.point); - output.normal = b2RotateVector(transform.q, localOutput.normal); + output.point = b2TransformPoint( transform, localOutput.point ); + output.normal = b2RotateVector( transform.q, localOutput.normal ); maxFraction = localOutput.fraction; } - offset = b2Add(offset, increment); + offset = b2Add( offset, increment ); } // capsule { - b2Transform transform = {b2Add(m_transform.p, offset), m_transform.q}; - b2Vec2 v1 = b2TransformPoint(transform, m_capsule.center1); - b2Vec2 v2 = b2TransformPoint(transform, m_capsule.center2); - g_draw.DrawSolidCapsule(v1, v2, m_capsule.radius, color1); + b2Transform transform = { b2Add( m_transform.p, offset ), m_transform.q }; + b2Vec2 v1 = b2TransformPoint( transform, m_capsule.center1 ); + b2Vec2 v2 = b2TransformPoint( transform, m_capsule.center2 ); + g_draw.DrawSolidCapsule( v1, v2, m_capsule.radius, color1 ); - b2Vec2 start = b2InvTransformPoint(transform, m_rayStart); - b2Vec2 translation = b2InvRotateVector(transform.q, b2Sub(m_rayEnd, m_rayStart)); - b2RayCastInput input = {start, translation, maxFraction}; + b2Vec2 start = b2InvTransformPoint( transform, m_rayStart ); + b2Vec2 translation = b2InvRotateVector( transform.q, b2Sub( m_rayEnd, m_rayStart ) ); + b2RayCastInput input = { start, translation, maxFraction }; - b2CastOutput localOutput = b2RayCastCapsule(&input, &m_capsule); - if (localOutput.hit) + b2CastOutput localOutput = b2RayCastCapsule( &input, &m_capsule ); + if ( localOutput.hit ) { output = localOutput; - output.point = b2TransformPoint(transform, localOutput.point); - output.normal = b2RotateVector(transform.q, localOutput.normal); + output.point = b2TransformPoint( transform, localOutput.point ); + output.normal = b2RotateVector( transform.q, localOutput.normal ); maxFraction = localOutput.fraction; } - offset = b2Add(offset, increment); + offset = b2Add( offset, increment ); } // box { - b2Transform transform = {b2Add(m_transform.p, offset), m_transform.q}; - g_draw.DrawSolidPolygon(transform, m_box.vertices, m_box.count, 0.0f, color1); + b2Transform transform = { b2Add( m_transform.p, offset ), m_transform.q }; + g_draw.DrawSolidPolygon( transform, m_box.vertices, m_box.count, 0.0f, color1 ); - b2Vec2 start = b2InvTransformPoint(transform, m_rayStart); - b2Vec2 translation = b2InvRotateVector(transform.q, b2Sub(m_rayEnd, m_rayStart)); - b2RayCastInput input = {start, translation, maxFraction}; + b2Vec2 start = b2InvTransformPoint( transform, m_rayStart ); + b2Vec2 translation = b2InvRotateVector( transform.q, b2Sub( m_rayEnd, m_rayStart ) ); + b2RayCastInput input = { start, translation, maxFraction }; - b2CastOutput localOutput = b2RayCastPolygon(&input, &m_box); - if (localOutput.hit) + b2CastOutput localOutput = b2RayCastPolygon( &input, &m_box ); + if ( localOutput.hit ) { output = localOutput; - output.point = b2TransformPoint(transform, localOutput.point); - output.normal = b2RotateVector(transform.q, localOutput.normal); + output.point = b2TransformPoint( transform, localOutput.point ); + output.normal = b2RotateVector( transform.q, localOutput.normal ); maxFraction = localOutput.fraction; } - offset = b2Add(offset, increment); + offset = b2Add( offset, increment ); } // triangle { - b2Transform transform = {b2Add(m_transform.p, offset), m_transform.q}; - g_draw.DrawSolidPolygon(transform, m_triangle.vertices, m_triangle.count, 0.0f, color1); + b2Transform transform = { b2Add( m_transform.p, offset ), m_transform.q }; + g_draw.DrawSolidPolygon( transform, m_triangle.vertices, m_triangle.count, 0.0f, color1 ); - b2Vec2 start = b2InvTransformPoint(transform, m_rayStart); - b2Vec2 translation = b2InvRotateVector(transform.q, b2Sub(m_rayEnd, m_rayStart)); - b2RayCastInput input = {start, translation, maxFraction}; + b2Vec2 start = b2InvTransformPoint( transform, m_rayStart ); + b2Vec2 translation = b2InvRotateVector( transform.q, b2Sub( m_rayEnd, m_rayStart ) ); + b2RayCastInput input = { start, translation, maxFraction }; - b2CastOutput localOutput = b2RayCastPolygon(&input, &m_triangle); - if (localOutput.hit) + b2CastOutput localOutput = b2RayCastPolygon( &input, &m_triangle ); + if ( localOutput.hit ) { output = localOutput; - output.point = b2TransformPoint(transform, localOutput.point); - output.normal = b2RotateVector(transform.q, localOutput.normal); + output.point = b2TransformPoint( transform, localOutput.point ); + output.normal = b2RotateVector( transform.q, localOutput.normal ); maxFraction = localOutput.fraction; } - offset = b2Add(offset, increment); + offset = b2Add( offset, increment ); } // segment { - b2Transform transform = {b2Add(m_transform.p, offset), m_transform.q}; + b2Transform transform = { b2Add( m_transform.p, offset ), m_transform.q }; - b2Vec2 p1 = b2TransformPoint(transform, m_segment.point1); - b2Vec2 p2 = b2TransformPoint(transform, m_segment.point2); - g_draw.DrawSegment(p1, p2, color1); + b2Vec2 p1 = b2TransformPoint( transform, m_segment.point1 ); + b2Vec2 p2 = b2TransformPoint( transform, m_segment.point2 ); + g_draw.DrawSegment( p1, p2, color1 ); - b2Vec2 start = b2InvTransformPoint(transform, m_rayStart); - b2Vec2 translation = b2InvRotateVector(transform.q, b2Sub(m_rayEnd, m_rayStart)); - b2RayCastInput input = {start, translation, maxFraction}; + b2Vec2 start = b2InvTransformPoint( transform, m_rayStart ); + b2Vec2 translation = b2InvRotateVector( transform.q, b2Sub( m_rayEnd, m_rayStart ) ); + b2RayCastInput input = { start, translation, maxFraction }; - b2CastOutput localOutput = b2RayCastSegment(&input, &m_segment, false); - if (localOutput.hit) + b2CastOutput localOutput = b2RayCastSegment( &input, &m_segment, false ); + if ( localOutput.hit ) { output = localOutput; - output.point = b2TransformPoint(transform, localOutput.point); - output.normal = b2RotateVector(transform.q, localOutput.normal); + output.point = b2TransformPoint( transform, localOutput.point ); + output.normal = b2RotateVector( transform.q, localOutput.normal ); maxFraction = localOutput.fraction; } - offset = b2Add(offset, increment); + offset = b2Add( offset, increment ); } - DrawRay(&output); + DrawRay( &output ); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new RayCast(settings); + return new RayCast( settings ); } b2Polygon m_box; @@ -1197,7 +1195,7 @@ class RayCast : public Sample bool m_showFraction; }; -static int sampleIndex = RegisterSample("Collision", "Ray Cast", RayCast::Create); +static int sampleIndex = RegisterSample( "Collision", "Ray Cast", RayCast::Create ); // This shows how to filter a specific shape using using data. struct ShapeUserData @@ -1216,12 +1214,12 @@ struct RayCastContext }; // This callback finds the closest hit. This is the most common callback used in games. -static float RayCastClosestCallback(b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* context) +static float RayCastClosestCallback( b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* context ) { RayCastContext* rayContext = (RayCastContext*)context; - ShapeUserData* userData = (ShapeUserData*)b2Shape_GetUserData(shapeId); - if (userData != nullptr && userData->ignore) + ShapeUserData* userData = (ShapeUserData*)b2Shape_GetUserData( shapeId ); + if ( userData != nullptr && userData->ignore ) { // By returning -1, we instruct the calling code to ignore this shape and // continue the ray-cast to the next shape. @@ -1242,12 +1240,12 @@ static float RayCastClosestCallback(b2ShapeId shapeId, b2Vec2 point, b2Vec2 norm // This callback finds any hit. For this type of query we are usually just checking for obstruction, // so the hit data is not relevant. // NOTE: shape hits are not ordered, so this may not return the closest hit -static float RayCastAnyCallback(b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* context) +static float RayCastAnyCallback( b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* context ) { RayCastContext* rayContext = (RayCastContext*)context; - ShapeUserData* userData = (ShapeUserData*)b2Shape_GetUserData(shapeId); - if (userData != nullptr && userData->ignore) + ShapeUserData* userData = (ShapeUserData*)b2Shape_GetUserData( shapeId ); + if ( userData != nullptr && userData->ignore ) { // By returning -1, we instruct the calling code to ignore this shape and // continue the ray-cast to the next shape. @@ -1270,12 +1268,12 @@ static float RayCastAnyCallback(b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, // NOTE: shape hits are not ordered, so this may return hits in any order. This means that // if you limit the number of results, you may discard the closest hit. You can see this // behavior in the sample. -static float RayCastMultipleCallback(b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* context) +static float RayCastMultipleCallback( b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* context ) { RayCastContext* rayContext = (RayCastContext*)context; - ShapeUserData* userData = (ShapeUserData*)b2Shape_GetUserData(shapeId); - if (userData != nullptr && userData->ignore) + ShapeUserData* userData = (ShapeUserData*)b2Shape_GetUserData( shapeId ); + if ( userData != nullptr && userData->ignore ) { // By returning -1, we instruct the calling code to ignore this shape and // continue the ray-cast to the next shape. @@ -1283,14 +1281,14 @@ static float RayCastMultipleCallback(b2ShapeId shapeId, b2Vec2 point, b2Vec2 nor } int count = rayContext->count; - assert(count < 3); + assert( count < 3 ); rayContext->points[count] = point; rayContext->normals[count] = normal; rayContext->fractions[count] = fraction; rayContext->count = count + 1; - if (rayContext->count == 3) + if ( rayContext->count == 3 ) { // At this point the buffer is full. // By returning 0, we instruct the calling code to terminate the ray-cast. @@ -1302,12 +1300,12 @@ static float RayCastMultipleCallback(b2ShapeId shapeId, b2Vec2 point, b2Vec2 nor } // This ray cast collects multiple hits along the ray and sorts them. -static float RayCastSortedCallback(b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* context) +static float RayCastSortedCallback( b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* context ) { RayCastContext* rayContext = (RayCastContext*)context; - ShapeUserData* userData = (ShapeUserData*)b2Shape_GetUserData(shapeId); - if (userData != nullptr && userData->ignore) + ShapeUserData* userData = (ShapeUserData*)b2Shape_GetUserData( shapeId ); + if ( userData != nullptr && userData->ignore ) { // By returning -1, we instruct the calling code to ignore this shape and // continue the ray-cast to the next shape. @@ -1315,29 +1313,29 @@ static float RayCastSortedCallback(b2ShapeId shapeId, b2Vec2 point, b2Vec2 norma } int count = rayContext->count; - assert(count <= 3); + assert( count <= 3 ); int index = 3; - while (fraction < rayContext->fractions[index - 1]) + while ( fraction < rayContext->fractions[index - 1] ) { index -= 1; - if (index == 0) + if ( index == 0 ) { break; } } - if (index == 3) + if ( index == 3 ) { // not closer, continue but tell the caller not to consider fractions further than the largest fraction acquired // this only happens once the buffer is full - assert(rayContext->count == 3); - assert(rayContext->fractions[2] <= 1.0f); + assert( rayContext->count == 3 ); + assert( rayContext->fractions[2] <= 1.0f ); return rayContext->fractions[2]; } - for (int j = 2; j > index; --j) + for ( int j = 2; j > index; --j ) { rayContext->points[j] = rayContext->points[j - 1]; rayContext->normals[j] = rayContext->normals[j - 1]; @@ -1349,7 +1347,7 @@ static float RayCastSortedCallback(b2ShapeId shapeId, b2Vec2 point, b2Vec2 norma rayContext->fractions[index] = fraction; rayContext->count = count < 3 ? count + 1 : 3; - if (rayContext->count == 3) + if ( rayContext->count == 3 ) { return rayContext->fractions[2]; } @@ -1382,58 +1380,58 @@ class RayCastWorld : public Sample e_maxCount = 64 }; - explicit RayCastWorld(Settings& settings) - : Sample(settings) + explicit RayCastWorld( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {2.0f, 14.0f}; + g_camera.m_center = { 2.0f, 14.0f }; g_camera.m_zoom = 25.0f * 0.75f; } // Ground body { b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Segment segment = {{-40.0f, 0.0f}, {40.0f, 0.0f}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2Segment segment = { { -40.0f, 0.0f }, { 40.0f, 0.0f } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment ); } { - b2Vec2 vertices[3] = {{-0.5f, 0.0f}, {0.5f, 0.0f}, {0.0f, 1.5f}}; - b2Hull hull = b2ComputeHull(vertices, 3); - m_polygons[0] = b2MakePolygon(&hull, 0.0f); + b2Vec2 vertices[3] = { { -0.5f, 0.0f }, { 0.5f, 0.0f }, { 0.0f, 1.5f } }; + b2Hull hull = b2ComputeHull( vertices, 3 ); + m_polygons[0] = b2MakePolygon( &hull, 0.0f ); } { - b2Vec2 vertices[3] = {{-0.1f, 0.0f}, {0.1f, 0.0f}, {0.0f, 1.5f}}; - b2Hull hull = b2ComputeHull(vertices, 3); - m_polygons[1] = b2MakePolygon(&hull, 0.0f); + b2Vec2 vertices[3] = { { -0.1f, 0.0f }, { 0.1f, 0.0f }, { 0.0f, 1.5f } }; + b2Hull hull = b2ComputeHull( vertices, 3 ); + m_polygons[1] = b2MakePolygon( &hull, 0.0f ); m_polygons[1].radius = 0.5f; } { float w = 1.0f; - float b = w / (2.0f + sqrtf(2.0f)); - float s = sqrtf(2.0f) * b; + float b = w / ( 2.0f + sqrtf( 2.0f ) ); + float s = sqrtf( 2.0f ) * b; - b2Vec2 vertices[8] = {{0.5f * s, 0.0f}, {0.5f * w, b}, {0.5f * w, b + s}, {0.5f * s, w}, - {-0.5f * s, w}, {-0.5f * w, b + s}, {-0.5f * w, b}, {-0.5f * s, 0.0f}}; + b2Vec2 vertices[8] = { { 0.5f * s, 0.0f }, { 0.5f * w, b }, { 0.5f * w, b + s }, { 0.5f * s, w }, + { -0.5f * s, w }, { -0.5f * w, b + s }, { -0.5f * w, b }, { -0.5f * s, 0.0f } }; - b2Hull hull = b2ComputeHull(vertices, 8); - m_polygons[2] = b2MakePolygon(&hull, 0.0f); + b2Hull hull = b2ComputeHull( vertices, 8 ); + m_polygons[2] = b2MakePolygon( &hull, 0.0f ); } - m_polygons[3] = b2MakeBox(0.5f, 0.5f); - m_capsule = {{-0.5f, 0.0f}, {0.5f, 0.0f}, 0.25f}; - m_circle = {{0.0f, 0.0f}, 0.5f}; - m_segment = {{-1.0f, 0.0f}, {1.0f, 0.0f}}; + m_polygons[3] = b2MakeBox( 0.5f, 0.5f ); + m_capsule = { { -0.5f, 0.0f }, { 0.5f, 0.0f }, 0.25f }; + m_circle = { { 0.0f, 0.0f }, 0.5f }; + m_segment = { { -1.0f, 0.0f }, { 1.0f, 0.0f } }; m_bodyIndex = 0; - for (int i = 0; i < e_maxCount; ++i) + for ( int i = 0; i < e_maxCount; ++i ) { m_bodyIds[i] = b2_nullBodyId; } @@ -1444,95 +1442,95 @@ class RayCastWorld : public Sample m_castType = e_rayCast; m_castRadius = 0.5f; - m_rayStart = {-20.0f, 10.0f}; - m_rayEnd = {20.0f, 10.0f}; + m_rayStart = { -20.0f, 10.0f }; + m_rayEnd = { 20.0f, 10.0f }; m_dragging = false; m_angle = 0.0f; m_baseAngle = 0.0f; - m_angleAnchor = {0.0f, 0.0f}; + m_angleAnchor = { 0.0f, 0.0f }; m_rotating = false; m_simple = false; } - void Create(int index) + void Create( int index ) { - if (B2_IS_NON_NULL(m_bodyIds[m_bodyIndex])) + if ( B2_IS_NON_NULL( m_bodyIds[m_bodyIndex] ) ) { - b2DestroyBody(m_bodyIds[m_bodyIndex]); + b2DestroyBody( m_bodyIds[m_bodyIndex] ); m_bodyIds[m_bodyIndex] = b2_nullBodyId; } - float x = RandomFloat(-20.0f, 20.0f); - float y = RandomFloat(0.0f, 20.0f); + float x = RandomFloat( -20.0f, 20.0f ); + float y = RandomFloat( 0.0f, 20.0f ); b2BodyDef bodyDef = b2DefaultBodyDef(); - bodyDef.position = {x, y}; - bodyDef.rotation = b2MakeRot(RandomFloat(-b2_pi, b2_pi)); + bodyDef.position = { x, y }; + bodyDef.rotation = b2MakeRot( RandomFloat( -b2_pi, b2_pi ) ); - m_bodyIds[m_bodyIndex] = b2CreateBody(m_worldId, &bodyDef); + m_bodyIds[m_bodyIndex] = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.userData = m_userData + m_bodyIndex; m_userData[m_bodyIndex].ignore = false; - if (m_bodyIndex == m_ignoreIndex) + if ( m_bodyIndex == m_ignoreIndex ) { m_userData[m_bodyIndex].ignore = true; } - if (index < 4) + if ( index < 4 ) { - b2CreatePolygonShape(m_bodyIds[m_bodyIndex], &shapeDef, m_polygons + index); + b2CreatePolygonShape( m_bodyIds[m_bodyIndex], &shapeDef, m_polygons + index ); } - else if (index == 4) + else if ( index == 4 ) { - b2CreateCircleShape(m_bodyIds[m_bodyIndex], &shapeDef, &m_circle); + b2CreateCircleShape( m_bodyIds[m_bodyIndex], &shapeDef, &m_circle ); } - else if (index == 5) + else if ( index == 5 ) { - b2CreateCapsuleShape(m_bodyIds[m_bodyIndex], &shapeDef, &m_capsule); + b2CreateCapsuleShape( m_bodyIds[m_bodyIndex], &shapeDef, &m_capsule ); } else { - b2CreateSegmentShape(m_bodyIds[m_bodyIndex], &shapeDef, &m_segment); + b2CreateSegmentShape( m_bodyIds[m_bodyIndex], &shapeDef, &m_segment ); } - m_bodyIndex = (m_bodyIndex + 1) % e_maxCount; + m_bodyIndex = ( m_bodyIndex + 1 ) % e_maxCount; } - void CreateN(int index, int count) + void CreateN( int index, int count ) { - for (int i = 0; i < count; ++i) + for ( int i = 0; i < count; ++i ) { - Create(index); + Create( index ); } } void DestroyBody() { - for (int i = 0; i < e_maxCount; ++i) + for ( int i = 0; i < e_maxCount; ++i ) { - if (B2_IS_NON_NULL(m_bodyIds[i])) + if ( B2_IS_NON_NULL( m_bodyIds[i] ) ) { - b2DestroyBody(m_bodyIds[i]); + b2DestroyBody( m_bodyIds[i] ); m_bodyIds[i] = b2_nullBodyId; return; } } } - void MouseDown(b2Vec2 p, int button, int mods) override + void MouseDown( b2Vec2 p, int button, int mods ) override { - if (button == GLFW_MOUSE_BUTTON_1) + if ( button == GLFW_MOUSE_BUTTON_1 ) { - if (mods == 0 && m_rotating == false) + if ( mods == 0 && m_rotating == false ) { m_rayStart = p; m_rayEnd = p; m_dragging = true; } - else if (mods == GLFW_MOD_SHIFT && m_dragging == false) + else if ( mods == GLFW_MOD_SHIFT && m_dragging == false ) { m_rotating = true; m_angleAnchor = p; @@ -1541,22 +1539,22 @@ class RayCastWorld : public Sample } } - void MouseUp(b2Vec2, int button) override + void MouseUp( b2Vec2, int button ) override { - if (button == GLFW_MOUSE_BUTTON_1) + if ( button == GLFW_MOUSE_BUTTON_1 ) { m_dragging = false; m_rotating = false; } } - void MouseMove(b2Vec2 p) override + void MouseMove( b2Vec2 p ) override { - if (m_dragging) + if ( m_dragging ) { m_rayEnd = p; } - else if (m_rotating) + else if ( m_rotating ) { float dx = p.x - m_angleAnchor.x; m_angle = m_baseAngle + 1.0f * dx; @@ -1566,78 +1564,78 @@ class RayCastWorld : public Sample void UpdateUI() override { float height = 300.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(200.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 200.0f, height ) ); - ImGui::Begin("Ray-cast World", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize); + ImGui::Begin( "Ray-cast World", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); - ImGui::Checkbox("Simple", &m_simple); + ImGui::Checkbox( "Simple", &m_simple ); - if (m_simple == false) + if ( m_simple == false ) { - const char* castTypes[] = {"Ray", "Circle", "Capsule", "Polygon"}; - int castType = int(m_castType); - if (ImGui::Combo("Type", &castType, castTypes, IM_ARRAYSIZE(castTypes))) + const char* castTypes[] = { "Ray", "Circle", "Capsule", "Polygon" }; + int castType = int( m_castType ); + if ( ImGui::Combo( "Type", &castType, castTypes, IM_ARRAYSIZE( castTypes ) ) ) { - m_castType = CastType(castType); + m_castType = CastType( castType ); } - if (m_castType != e_rayCast) + if ( m_castType != e_rayCast ) { - ImGui::SliderFloat("Radius", &m_castRadius, 0.0f, 2.0f, "%.1f"); + ImGui::SliderFloat( "Radius", &m_castRadius, 0.0f, 2.0f, "%.1f" ); } - const char* modes[] = {"Any", "Closest", "Multiple", "Sorted"}; - int mode = int(m_mode); - if (ImGui::Combo("Mode", &mode, modes, IM_ARRAYSIZE(modes))) + const char* modes[] = { "Any", "Closest", "Multiple", "Sorted" }; + int mode = int( m_mode ); + if ( ImGui::Combo( "Mode", &mode, modes, IM_ARRAYSIZE( modes ) ) ) { - m_mode = Mode(mode); + m_mode = Mode( mode ); } } - if (ImGui::Button("Polygon 1")) - Create(0); + if ( ImGui::Button( "Polygon 1" ) ) + Create( 0 ); ImGui::SameLine(); - if (ImGui::Button("10x##Poly1")) - CreateN(0, 10); + if ( ImGui::Button( "10x##Poly1" ) ) + CreateN( 0, 10 ); - if (ImGui::Button("Polygon 2")) - Create(1); + if ( ImGui::Button( "Polygon 2" ) ) + Create( 1 ); ImGui::SameLine(); - if (ImGui::Button("10x##Poly2")) - CreateN(1, 10); + if ( ImGui::Button( "10x##Poly2" ) ) + CreateN( 1, 10 ); - if (ImGui::Button("Polygon 3")) - Create(2); + if ( ImGui::Button( "Polygon 3" ) ) + Create( 2 ); ImGui::SameLine(); - if (ImGui::Button("10x##Poly3")) - CreateN(2, 10); + if ( ImGui::Button( "10x##Poly3" ) ) + CreateN( 2, 10 ); - if (ImGui::Button("Box")) - Create(3); + if ( ImGui::Button( "Box" ) ) + Create( 3 ); ImGui::SameLine(); - if (ImGui::Button("10x##Box")) - CreateN(3, 10); + if ( ImGui::Button( "10x##Box" ) ) + CreateN( 3, 10 ); - if (ImGui::Button("Circle")) - Create(4); + if ( ImGui::Button( "Circle" ) ) + Create( 4 ); ImGui::SameLine(); - if (ImGui::Button("10x##Circle")) - CreateN(4, 10); + if ( ImGui::Button( "10x##Circle" ) ) + CreateN( 4, 10 ); - if (ImGui::Button("Capsule")) - Create(5); + if ( ImGui::Button( "Capsule" ) ) + Create( 5 ); ImGui::SameLine(); - if (ImGui::Button("10x##Capsule")) - CreateN(5, 10); + if ( ImGui::Button( "10x##Capsule" ) ) + CreateN( 5, 10 ); - if (ImGui::Button("Segment")) - Create(6); + if ( ImGui::Button( "Segment" ) ) + Create( 6 ); ImGui::SameLine(); - if (ImGui::Button("10x##Segment")) - CreateN(6, 10); + if ( ImGui::Button( "10x##Segment" ) ) + CreateN( 6, 10 ); - if (ImGui::Button("Destroy Shape")) + if ( ImGui::Button( "Destroy Shape" ) ) { DestroyBody(); } @@ -1645,13 +1643,13 @@ class RayCastWorld : public Sample ImGui::End(); } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - Sample::Step(settings); + Sample::Step( settings ); - g_draw.DrawString(5, m_textLine, "Click left mouse button and drag to modify ray cast"); + g_draw.DrawString( 5, m_textLine, "Click left mouse button and drag to modify ray cast" ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "Shape 7 is intentionally ignored by the ray"); + g_draw.DrawString( 5, m_textLine, "Shape 7 is intentionally ignored by the ray" ); m_textLine += m_textIncrement; m_textLine += m_textIncrement; @@ -1660,156 +1658,157 @@ class RayCastWorld : public Sample b2HexColor color2 = b2_colorGray8; b2HexColor color3 = b2_colorMagenta; - b2Vec2 rayTranslation = b2Sub(m_rayEnd, m_rayStart); + b2Vec2 rayTranslation = b2Sub( m_rayEnd, m_rayStart ); - if (m_simple) + if ( m_simple ) { - g_draw.DrawString(5, m_textLine, "Simple closest point ray cast"); + g_draw.DrawString( 5, m_textLine, "Simple closest point ray cast" ); m_textLine += m_textIncrement; // This version doesn't have a callback, but it doesn't skip the ignored shape - b2RayResult result = b2World_CastRayClosest(m_worldId, m_rayStart, rayTranslation, b2DefaultQueryFilter()); + b2RayResult result = b2World_CastRayClosest( m_worldId, m_rayStart, rayTranslation, b2DefaultQueryFilter() ); - if (result.hit == true) + if ( result.hit == true ) { - b2Vec2 c = b2MulAdd(m_rayStart, result.fraction, rayTranslation); - g_draw.DrawPoint(result.point, 5.0f, color1); - g_draw.DrawSegment(m_rayStart, c, color2); - b2Vec2 head = b2MulAdd(result.point, 0.5f, result.normal); - g_draw.DrawSegment(result.point, head, color3); + b2Vec2 c = b2MulAdd( m_rayStart, result.fraction, rayTranslation ); + g_draw.DrawPoint( result.point, 5.0f, color1 ); + g_draw.DrawSegment( m_rayStart, c, color2 ); + b2Vec2 head = b2MulAdd( result.point, 0.5f, result.normal ); + g_draw.DrawSegment( result.point, head, color3 ); } else { - g_draw.DrawSegment(m_rayStart, m_rayEnd, color2); + g_draw.DrawSegment( m_rayStart, m_rayEnd, color2 ); } } else { - switch (m_mode) + switch ( m_mode ) { case e_any: - g_draw.DrawString(5, m_textLine, "Cast mode: any - check for obstruction - unsorted"); + g_draw.DrawString( 5, m_textLine, "Cast mode: any - check for obstruction - unsorted" ); break; case e_closest: - g_draw.DrawString(5, m_textLine, "Cast mode: closest - find closest shape along the cast"); + g_draw.DrawString( 5, m_textLine, "Cast mode: closest - find closest shape along the cast" ); break; case e_multiple: - g_draw.DrawString(5, m_textLine, "Cast mode: multiple - gather up to 3 shapes - unsorted"); + g_draw.DrawString( 5, m_textLine, "Cast mode: multiple - gather up to 3 shapes - unsorted" ); break; case e_sorted: - g_draw.DrawString(5, m_textLine, "Cast mode: sorted - gather up to 3 shapes sorted by closeness"); + g_draw.DrawString( 5, m_textLine, "Cast mode: sorted - gather up to 3 shapes sorted by closeness" ); break; } m_textLine += m_textIncrement; - b2CastResultFcn* fcns[] = {RayCastAnyCallback, RayCastClosestCallback, RayCastMultipleCallback, - RayCastSortedCallback}; + b2CastResultFcn* fcns[] = { RayCastAnyCallback, RayCastClosestCallback, RayCastMultipleCallback, + RayCastSortedCallback }; b2CastResultFcn* modeFcn = fcns[m_mode]; - RayCastContext context = {0}; + RayCastContext context = { 0 }; // Must initialize fractions for sorting context.fractions[0] = FLT_MAX; context.fractions[1] = FLT_MAX; context.fractions[2] = FLT_MAX; - b2Circle circle = {{0.0f, 0.0f}, m_castRadius}; - b2Capsule capsule = {{-0.25f, 0.0f}, {0.25f, 0.0f}, m_castRadius}; - b2Polygon box = b2MakeRoundedBox(0.25f, 0.5f, m_castRadius); - b2Transform transform = {m_rayStart, b2MakeRot(m_angle)}; + b2Circle circle = { { 0.0f, 0.0f }, m_castRadius }; + b2Capsule capsule = { { -0.25f, 0.0f }, { 0.25f, 0.0f }, m_castRadius }; + b2Polygon box = b2MakeRoundedBox( 0.25f, 0.5f, m_castRadius ); + b2Transform transform = { m_rayStart, b2MakeRot( m_angle ) }; - switch (m_castType) + switch ( m_castType ) { case e_rayCast: - b2World_CastRay(m_worldId, m_rayStart, rayTranslation, b2DefaultQueryFilter(), modeFcn, &context); + b2World_CastRay( m_worldId, m_rayStart, rayTranslation, b2DefaultQueryFilter(), modeFcn, &context ); break; case e_circleCast: - b2World_CastCircle(m_worldId, &circle, transform, rayTranslation, b2DefaultQueryFilter(), modeFcn, &context); + b2World_CastCircle( m_worldId, &circle, transform, rayTranslation, b2DefaultQueryFilter(), modeFcn, + &context ); break; case e_capsuleCast: - b2World_CastCapsule(m_worldId, &capsule, transform, rayTranslation, b2DefaultQueryFilter(), modeFcn, - &context); + b2World_CastCapsule( m_worldId, &capsule, transform, rayTranslation, b2DefaultQueryFilter(), modeFcn, + &context ); break; case e_polygonCast: - b2World_CastPolygon(m_worldId, &box, transform, rayTranslation, b2DefaultQueryFilter(), modeFcn, &context); + b2World_CastPolygon( m_worldId, &box, transform, rayTranslation, b2DefaultQueryFilter(), modeFcn, &context ); break; } - if (context.count > 0) + if ( context.count > 0 ) { - assert(context.count <= 3); - b2HexColor colors[3] = {b2_colorRed, b2_colorGreen, b2_colorBlue}; - for (int i = 0; i < context.count; ++i) + assert( context.count <= 3 ); + b2HexColor colors[3] = { b2_colorRed, b2_colorGreen, b2_colorBlue }; + for ( int i = 0; i < context.count; ++i ) { - b2Vec2 c = b2MulAdd(m_rayStart, context.fractions[i], rayTranslation); + b2Vec2 c = b2MulAdd( m_rayStart, context.fractions[i], rayTranslation ); b2Vec2 p = context.points[i]; b2Vec2 n = context.normals[i]; - g_draw.DrawPoint(p, 5.0f, colors[i]); - g_draw.DrawSegment(m_rayStart, c, color2); - b2Vec2 head = b2MulAdd(p, 0.5f, n); - g_draw.DrawSegment(p, head, color3); + g_draw.DrawPoint( p, 5.0f, colors[i] ); + g_draw.DrawSegment( m_rayStart, c, color2 ); + b2Vec2 head = b2MulAdd( p, 0.5f, n ); + g_draw.DrawSegment( p, head, color3 ); - b2Vec2 t = b2MulSV(context.fractions[i], rayTranslation); + b2Vec2 t = b2MulSV( context.fractions[i], rayTranslation ); - if (m_castType == e_circleCast) + if ( m_castType == e_circleCast ) { - g_draw.DrawCircle(b2Add(m_rayStart, t), m_castRadius, b2_colorYellow); + g_draw.DrawCircle( b2Add( m_rayStart, t ), m_castRadius, b2_colorYellow ); } - else if (m_castType == e_capsuleCast) + else if ( m_castType == e_capsuleCast ) { - b2Vec2 p1 = b2Add(b2TransformPoint(transform, capsule.center1), t); - b2Vec2 p2 = b2Add(b2TransformPoint(transform, capsule.center2), t); - g_draw.DrawCapsule(p1, p2, m_castRadius, b2_colorYellow); + b2Vec2 p1 = b2Add( b2TransformPoint( transform, capsule.center1 ), t ); + b2Vec2 p2 = b2Add( b2TransformPoint( transform, capsule.center2 ), t ); + g_draw.DrawCapsule( p1, p2, m_castRadius, b2_colorYellow ); } - else if (m_castType == e_polygonCast) + else if ( m_castType == e_polygonCast ) { - b2Transform shiftedTransform = {b2Add(transform.p, t), transform.q}; - g_draw.DrawSolidPolygon(shiftedTransform, box.vertices, box.count, box.radius, b2_colorYellow); + b2Transform shiftedTransform = { b2Add( transform.p, t ), transform.q }; + g_draw.DrawSolidPolygon( shiftedTransform, box.vertices, box.count, box.radius, b2_colorYellow ); } } } else { - g_draw.DrawSegment(m_rayStart, m_rayEnd, color2); + g_draw.DrawSegment( m_rayStart, m_rayEnd, color2 ); - if (m_castType == e_circleCast) + if ( m_castType == e_circleCast ) { - g_draw.DrawCircle(b2Add(m_rayStart, rayTranslation), m_castRadius, b2_colorGray); + g_draw.DrawCircle( b2Add( m_rayStart, rayTranslation ), m_castRadius, b2_colorGray ); } - else if (m_castType == e_capsuleCast) + else if ( m_castType == e_capsuleCast ) { - b2Vec2 p1 = b2Add(b2TransformPoint(transform, capsule.center1), rayTranslation); - b2Vec2 p2 = b2Add(b2TransformPoint(transform, capsule.center2), rayTranslation); - g_draw.DrawCapsule(p1, p2, m_castRadius, b2_colorYellow); + b2Vec2 p1 = b2Add( b2TransformPoint( transform, capsule.center1 ), rayTranslation ); + b2Vec2 p2 = b2Add( b2TransformPoint( transform, capsule.center2 ), rayTranslation ); + g_draw.DrawCapsule( p1, p2, m_castRadius, b2_colorYellow ); } - else if (m_castType == e_polygonCast) + else if ( m_castType == e_polygonCast ) { - b2Transform shiftedTransform = {b2Add(transform.p, rayTranslation), transform.q}; - g_draw.DrawSolidPolygon(shiftedTransform, box.vertices, box.count, box.radius, b2_colorYellow); + b2Transform shiftedTransform = { b2Add( transform.p, rayTranslation ), transform.q }; + g_draw.DrawSolidPolygon( shiftedTransform, box.vertices, box.count, box.radius, b2_colorYellow ); } } } - g_draw.DrawPoint(m_rayStart, 5.0f, b2_colorGreen); + g_draw.DrawPoint( m_rayStart, 5.0f, b2_colorGreen ); - if (B2_IS_NON_NULL(m_bodyIds[m_ignoreIndex])) + if ( B2_IS_NON_NULL( m_bodyIds[m_ignoreIndex] ) ) { - b2Vec2 p = b2Body_GetPosition(m_bodyIds[m_ignoreIndex]); + b2Vec2 p = b2Body_GetPosition( m_bodyIds[m_ignoreIndex] ); p.x -= 0.2f; - g_draw.DrawString(p, "ign"); + g_draw.DrawString( p, "ign" ); } } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new RayCastWorld(settings); + return new RayCastWorld( settings ); } int m_bodyIndex; @@ -1838,7 +1837,7 @@ class RayCastWorld : public Sample bool m_dragging; }; -static int sampleRayCastWorld = RegisterSample("Collision", "Ray Cast World", RayCastWorld::Create); +static int sampleRayCastWorld = RegisterSample( "Collision", "Ray Cast World", RayCastWorld::Create ); class OverlapWorld : public Sample { @@ -1856,10 +1855,10 @@ class OverlapWorld : public Sample e_maxDoomed = 16, }; - static bool OverlapResultFcn(b2ShapeId shapeId, void* context) + static bool OverlapResultFcn( b2ShapeId shapeId, void* context ) { - ShapeUserData* userData = (ShapeUserData*)b2Shape_GetUserData(shapeId); - if (userData != nullptr && userData->ignore) + ShapeUserData* userData = (ShapeUserData*)b2Shape_GetUserData( shapeId ); + if ( userData != nullptr && userData->ignore ) { // continue the query return true; @@ -1867,7 +1866,7 @@ class OverlapWorld : public Sample OverlapWorld* sample = (OverlapWorld*)context; - if (sample->m_doomCount < e_maxDoomed) + if ( sample->m_doomCount < e_maxDoomed ) { int index = sample->m_doomCount; sample->m_doomIds[index] = shapeId; @@ -1878,47 +1877,47 @@ class OverlapWorld : public Sample return true; } - explicit OverlapWorld(Settings& settings) - : Sample(settings) + explicit OverlapWorld( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 10.0f}; + g_camera.m_center = { 0.0f, 10.0f }; g_camera.m_zoom = 25.0f * 0.7f; } { - b2Vec2 vertices[3] = {{-0.5f, 0.0f}, {0.5f, 0.0f}, {0.0f, 1.5f}}; - b2Hull hull = b2ComputeHull(vertices, 3); - m_polygons[0] = b2MakePolygon(&hull, 0.0f); + b2Vec2 vertices[3] = { { -0.5f, 0.0f }, { 0.5f, 0.0f }, { 0.0f, 1.5f } }; + b2Hull hull = b2ComputeHull( vertices, 3 ); + m_polygons[0] = b2MakePolygon( &hull, 0.0f ); } { - b2Vec2 vertices[3] = {{-0.1f, 0.0f}, {0.1f, 0.0f}, {0.0f, 1.5f}}; - b2Hull hull = b2ComputeHull(vertices, 3); - m_polygons[1] = b2MakePolygon(&hull, 0.0f); + b2Vec2 vertices[3] = { { -0.1f, 0.0f }, { 0.1f, 0.0f }, { 0.0f, 1.5f } }; + b2Hull hull = b2ComputeHull( vertices, 3 ); + m_polygons[1] = b2MakePolygon( &hull, 0.0f ); } { float w = 1.0f; - float b = w / (2.0f + sqrtf(2.0f)); - float s = sqrtf(2.0f) * b; + float b = w / ( 2.0f + sqrtf( 2.0f ) ); + float s = sqrtf( 2.0f ) * b; - b2Vec2 vertices[8] = {{0.5f * s, 0.0f}, {0.5f * w, b}, {0.5f * w, b + s}, {0.5f * s, w}, - {-0.5f * s, w}, {-0.5f * w, b + s}, {-0.5f * w, b}, {-0.5f * s, 0.0f}}; + b2Vec2 vertices[8] = { { 0.5f * s, 0.0f }, { 0.5f * w, b }, { 0.5f * w, b + s }, { 0.5f * s, w }, + { -0.5f * s, w }, { -0.5f * w, b + s }, { -0.5f * w, b }, { -0.5f * s, 0.0f } }; - b2Hull hull = b2ComputeHull(vertices, 8); - m_polygons[2] = b2MakePolygon(&hull, 0.0f); + b2Hull hull = b2ComputeHull( vertices, 8 ); + m_polygons[2] = b2MakePolygon( &hull, 0.0f ); } - m_polygons[3] = b2MakeBox(0.5f, 0.5f); - m_capsule = {{-0.5f, 0.0f}, {0.5f, 0.0f}, 0.25f}; - m_circle = {{0.0f, 0.0f}, 0.5f}; - m_segment = {{-1.0f, 0.0f}, {1.0f, 0.0f}}; + m_polygons[3] = b2MakeBox( 0.5f, 0.5f ); + m_capsule = { { -0.5f, 0.0f }, { 0.5f, 0.0f }, 0.25f }; + m_circle = { { 0.0f, 0.0f }, 0.5f }; + m_segment = { { -1.0f, 0.0f }, { 1.0f, 0.0f } }; m_bodyIndex = 0; - for (int i = 0; i < e_maxCount; ++i) + for ( int i = 0; i < e_maxCount; ++i ) { m_bodyIds[i] = b2_nullBodyId; } @@ -1927,97 +1926,97 @@ class OverlapWorld : public Sample m_shapeType = e_circleShape; - m_queryCircle = {{0.0f, 0.0f}, 1.0f}; - m_queryCapsule = {{-1.0f, 0.0f}, {1.0f, 0.0f}, 0.5f}; - m_queryBox = b2MakeBox(2.0f, 0.5f); + m_queryCircle = { { 0.0f, 0.0f }, 1.0f }; + m_queryCapsule = { { -1.0f, 0.0f }, { 1.0f, 0.0f }, 0.5f }; + m_queryBox = b2MakeBox( 2.0f, 0.5f ); - m_position = {0.0f, 10.0f}; + m_position = { 0.0f, 10.0f }; m_angle = 0.0f; m_dragging = false; m_rotating = false; m_doomCount = 0; - CreateN(0, 10); + CreateN( 0, 10 ); } - void Create(int index) + void Create( int index ) { - if (B2_IS_NON_NULL(m_bodyIds[m_bodyIndex])) + if ( B2_IS_NON_NULL( m_bodyIds[m_bodyIndex] ) ) { - b2DestroyBody(m_bodyIds[m_bodyIndex]); + b2DestroyBody( m_bodyIds[m_bodyIndex] ); m_bodyIds[m_bodyIndex] = b2_nullBodyId; } - float x = RandomFloat(-20.0f, 20.0f); - float y = RandomFloat(0.0f, 20.0f); + float x = RandomFloat( -20.0f, 20.0f ); + float y = RandomFloat( 0.0f, 20.0f ); b2BodyDef bodyDef = b2DefaultBodyDef(); - bodyDef.position = {x, y}; - bodyDef.rotation = b2MakeRot(RandomFloat(-b2_pi, b2_pi)); + bodyDef.position = { x, y }; + bodyDef.rotation = b2MakeRot( RandomFloat( -b2_pi, b2_pi ) ); - m_bodyIds[m_bodyIndex] = b2CreateBody(m_worldId, &bodyDef); + m_bodyIds[m_bodyIndex] = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.userData = m_userData + m_bodyIndex; m_userData[m_bodyIndex].index = m_bodyIndex; m_userData[m_bodyIndex].ignore = false; - if (m_bodyIndex == m_ignoreIndex) + if ( m_bodyIndex == m_ignoreIndex ) { m_userData[m_bodyIndex].ignore = true; } - if (index < 4) + if ( index < 4 ) { - b2CreatePolygonShape(m_bodyIds[m_bodyIndex], &shapeDef, m_polygons + index); + b2CreatePolygonShape( m_bodyIds[m_bodyIndex], &shapeDef, m_polygons + index ); } - else if (index == 4) + else if ( index == 4 ) { - b2CreateCircleShape(m_bodyIds[m_bodyIndex], &shapeDef, &m_circle); + b2CreateCircleShape( m_bodyIds[m_bodyIndex], &shapeDef, &m_circle ); } - else if (index == 5) + else if ( index == 5 ) { - b2CreateCapsuleShape(m_bodyIds[m_bodyIndex], &shapeDef, &m_capsule); + b2CreateCapsuleShape( m_bodyIds[m_bodyIndex], &shapeDef, &m_capsule ); } else { - b2CreateSegmentShape(m_bodyIds[m_bodyIndex], &shapeDef, &m_segment); + b2CreateSegmentShape( m_bodyIds[m_bodyIndex], &shapeDef, &m_segment ); } - m_bodyIndex = (m_bodyIndex + 1) % e_maxCount; + m_bodyIndex = ( m_bodyIndex + 1 ) % e_maxCount; } - void CreateN(int index, int count) + void CreateN( int index, int count ) { - for (int i = 0; i < count; ++i) + for ( int i = 0; i < count; ++i ) { - Create(index); + Create( index ); } } void DestroyBody() { - for (int i = 0; i < e_maxCount; ++i) + for ( int i = 0; i < e_maxCount; ++i ) { - if (B2_IS_NON_NULL(m_bodyIds[i])) + if ( B2_IS_NON_NULL( m_bodyIds[i] ) ) { - b2DestroyBody(m_bodyIds[i]); + b2DestroyBody( m_bodyIds[i] ); m_bodyIds[i] = b2_nullBodyId; return; } } } - void MouseDown(b2Vec2 p, int button, int mods) override + void MouseDown( b2Vec2 p, int button, int mods ) override { - if (button == GLFW_MOUSE_BUTTON_1) + if ( button == GLFW_MOUSE_BUTTON_1 ) { - if (mods == 0 && m_rotating == false) + if ( mods == 0 && m_rotating == false ) { m_dragging = true; m_position = p; } - else if (mods == GLFW_MOD_SHIFT && m_dragging == false) + else if ( mods == GLFW_MOD_SHIFT && m_dragging == false ) { m_rotating = true; m_startPosition = p; @@ -2026,22 +2025,22 @@ class OverlapWorld : public Sample } } - void MouseUp(b2Vec2, int button) override + void MouseUp( b2Vec2, int button ) override { - if (button == GLFW_MOUSE_BUTTON_1) + if ( button == GLFW_MOUSE_BUTTON_1 ) { m_dragging = false; m_rotating = false; } } - void MouseMove(b2Vec2 p) override + void MouseMove( b2Vec2 p ) override { - if (m_dragging) + if ( m_dragging ) { m_position = p; } - else if (m_rotating) + else if ( m_rotating ) { float dx = p.x - m_startPosition.x; m_angle = m_baseAngle + 1.0f * dx; @@ -2051,134 +2050,134 @@ class OverlapWorld : public Sample void UpdateUI() override { float height = 330.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(140.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 140.0f, height ) ); - ImGui::Begin("Overlap World", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize); + ImGui::Begin( "Overlap World", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); - if (ImGui::Button("Polygon 1")) - Create(0); + if ( ImGui::Button( "Polygon 1" ) ) + Create( 0 ); ImGui::SameLine(); - if (ImGui::Button("10x##Poly1")) - CreateN(0, 10); + if ( ImGui::Button( "10x##Poly1" ) ) + CreateN( 0, 10 ); - if (ImGui::Button("Polygon 2")) - Create(1); + if ( ImGui::Button( "Polygon 2" ) ) + Create( 1 ); ImGui::SameLine(); - if (ImGui::Button("10x##Poly2")) - CreateN(1, 10); + if ( ImGui::Button( "10x##Poly2" ) ) + CreateN( 1, 10 ); - if (ImGui::Button("Polygon 3")) - Create(2); + if ( ImGui::Button( "Polygon 3" ) ) + Create( 2 ); ImGui::SameLine(); - if (ImGui::Button("10x##Poly3")) - CreateN(2, 10); + if ( ImGui::Button( "10x##Poly3" ) ) + CreateN( 2, 10 ); - if (ImGui::Button("Box")) - Create(3); + if ( ImGui::Button( "Box" ) ) + Create( 3 ); ImGui::SameLine(); - if (ImGui::Button("10x##Box")) - CreateN(3, 10); + if ( ImGui::Button( "10x##Box" ) ) + CreateN( 3, 10 ); - if (ImGui::Button("Circle")) - Create(4); + if ( ImGui::Button( "Circle" ) ) + Create( 4 ); ImGui::SameLine(); - if (ImGui::Button("10x##Circle")) - CreateN(4, 10); + if ( ImGui::Button( "10x##Circle" ) ) + CreateN( 4, 10 ); - if (ImGui::Button("Capsule")) - Create(5); + if ( ImGui::Button( "Capsule" ) ) + Create( 5 ); ImGui::SameLine(); - if (ImGui::Button("10x##Capsule")) - CreateN(5, 10); + if ( ImGui::Button( "10x##Capsule" ) ) + CreateN( 5, 10 ); - if (ImGui::Button("Segment")) - Create(6); + if ( ImGui::Button( "Segment" ) ) + Create( 6 ); ImGui::SameLine(); - if (ImGui::Button("10x##Segment")) - CreateN(6, 10); + if ( ImGui::Button( "10x##Segment" ) ) + CreateN( 6, 10 ); - if (ImGui::Button("Destroy Shape")) + if ( ImGui::Button( "Destroy Shape" ) ) { DestroyBody(); } ImGui::Separator(); - ImGui::Text("Overlap Shape"); - ImGui::RadioButton("Circle##Overlap", &m_shapeType, e_circleShape); - ImGui::RadioButton("Capsule##Overlap", &m_shapeType, e_capsuleShape); - ImGui::RadioButton("Box##Overlap", &m_shapeType, e_boxShape); + ImGui::Text( "Overlap Shape" ); + ImGui::RadioButton( "Circle##Overlap", &m_shapeType, e_circleShape ); + ImGui::RadioButton( "Capsule##Overlap", &m_shapeType, e_capsuleShape ); + ImGui::RadioButton( "Box##Overlap", &m_shapeType, e_boxShape ); ImGui::End(); } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - Sample::Step(settings); + Sample::Step( settings ); - g_draw.DrawString(5, m_textLine, "left mouse button: drag query shape"); + g_draw.DrawString( 5, m_textLine, "left mouse button: drag query shape" ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "left mouse button + shift: rotate query shape"); + g_draw.DrawString( 5, m_textLine, "left mouse button + shift: rotate query shape" ); m_textLine += m_textIncrement; m_doomCount = 0; - b2Transform transform = {m_position, b2MakeRot(m_angle)}; + b2Transform transform = { m_position, b2MakeRot( m_angle ) }; - if (m_shapeType == e_circleShape) + if ( m_shapeType == e_circleShape ) { - b2World_OverlapCircle(m_worldId, &m_queryCircle, transform, b2DefaultQueryFilter(), OverlapWorld::OverlapResultFcn, - this); - g_draw.DrawCircle(transform.p, m_queryCircle.radius, b2_colorWhite); + b2World_OverlapCircle( m_worldId, &m_queryCircle, transform, b2DefaultQueryFilter(), OverlapWorld::OverlapResultFcn, + this ); + g_draw.DrawCircle( transform.p, m_queryCircle.radius, b2_colorWhite ); } - else if (m_shapeType == e_capsuleShape) + else if ( m_shapeType == e_capsuleShape ) { - b2World_OverlapCapsule(m_worldId, &m_queryCapsule, transform, b2DefaultQueryFilter(), OverlapWorld::OverlapResultFcn, - this); - b2Vec2 p1 = b2TransformPoint(transform, m_queryCapsule.center1); - b2Vec2 p2 = b2TransformPoint(transform, m_queryCapsule.center2); - g_draw.DrawCapsule(p1, p2, m_queryCapsule.radius, b2_colorWhite); + b2World_OverlapCapsule( m_worldId, &m_queryCapsule, transform, b2DefaultQueryFilter(), OverlapWorld::OverlapResultFcn, + this ); + b2Vec2 p1 = b2TransformPoint( transform, m_queryCapsule.center1 ); + b2Vec2 p2 = b2TransformPoint( transform, m_queryCapsule.center2 ); + g_draw.DrawCapsule( p1, p2, m_queryCapsule.radius, b2_colorWhite ); } - else if (m_shapeType == e_boxShape) + else if ( m_shapeType == e_boxShape ) { - b2World_OverlapPolygon(m_worldId, &m_queryBox, transform, b2DefaultQueryFilter(), OverlapWorld::OverlapResultFcn, - this); - b2Vec2 points[b2_maxPolygonVertices] = {0}; - for (int i = 0; i < m_queryBox.count; ++i) + b2World_OverlapPolygon( m_worldId, &m_queryBox, transform, b2DefaultQueryFilter(), OverlapWorld::OverlapResultFcn, + this ); + b2Vec2 points[b2_maxPolygonVertices] = { 0 }; + for ( int i = 0; i < m_queryBox.count; ++i ) { - points[i] = b2TransformPoint(transform, m_queryBox.vertices[i]); + points[i] = b2TransformPoint( transform, m_queryBox.vertices[i] ); } - g_draw.DrawPolygon(points, m_queryBox.count, b2_colorWhite); + g_draw.DrawPolygon( points, m_queryBox.count, b2_colorWhite ); } - if (B2_IS_NON_NULL(m_bodyIds[m_ignoreIndex])) + if ( B2_IS_NON_NULL( m_bodyIds[m_ignoreIndex] ) ) { - b2Vec2 p = b2Body_GetPosition(m_bodyIds[m_ignoreIndex]); + b2Vec2 p = b2Body_GetPosition( m_bodyIds[m_ignoreIndex] ); p.x -= 0.2f; - g_draw.DrawString(p, "skip"); + g_draw.DrawString( p, "skip" ); } - for (int i = 0; i < m_doomCount; ++i) + for ( int i = 0; i < m_doomCount; ++i ) { b2ShapeId shapeId = m_doomIds[i]; - ShapeUserData* userData = (ShapeUserData*)b2Shape_GetUserData(shapeId); - if (userData == nullptr) + ShapeUserData* userData = (ShapeUserData*)b2Shape_GetUserData( shapeId ); + if ( userData == nullptr ) { continue; } int index = userData->index; - assert(0 <= index && index < e_maxCount); - assert(B2_IS_NON_NULL(m_bodyIds[index])); + assert( 0 <= index && index < e_maxCount ); + assert( B2_IS_NON_NULL( m_bodyIds[index] ) ); - b2DestroyBody(m_bodyIds[index]); + b2DestroyBody( m_bodyIds[index] ); m_bodyIds[index] = b2_nullBodyId; } } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new OverlapWorld(settings); + return new OverlapWorld( settings ); } int m_bodyIndex; @@ -2211,19 +2210,19 @@ class OverlapWorld : public Sample bool m_rotating; }; -static int sampleOverlapWorld = RegisterSample("Collision", "Overlap World", OverlapWorld::Create); +static int sampleOverlapWorld = RegisterSample( "Collision", "Overlap World", OverlapWorld::Create ); // Tests manifolds and contact points class Manifold : public Sample { public: - explicit Manifold(Settings& settings) - : Sample(settings) + explicit Manifold( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - //g_camera.m_center = {1.8f, 15.0f}; - g_camera.m_center = {1.8f, 0.0f}; + // g_camera.m_center = {1.8f, 15.0f}; + g_camera.m_center = { 1.8f, 0.0f }; g_camera.m_zoom = 25.0f * 0.45f; } @@ -2236,8 +2235,8 @@ class Manifold : public Sample m_angle = 0.0f; m_round = 0.1f; - m_startPoint = {0.0f, 0.0f}; - m_basePosition = {0.0f, 0.0f}; + m_startPoint = { 0.0f, 0.0f }; + m_basePosition = { 0.0f, 0.0f }; m_baseAngle = 0.0f; m_dragging = false; @@ -2247,33 +2246,33 @@ class Manifold : public Sample m_showAnchors = false; m_enableCaching = true; - b2Vec2 points[3] = {{-0.1f, -0.5f}, {0.1f, -0.5f}, {0.0f, 0.5f}}; - m_wedge = b2ComputeHull(points, 3); + b2Vec2 points[3] = { { -0.1f, -0.5f }, { 0.1f, -0.5f }, { 0.0f, 0.5f } }; + m_wedge = b2ComputeHull( points, 3 ); } void UpdateUI() override { float height = 300.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(240.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); - ImGui::Begin("Manifold", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize); + ImGui::Begin( "Manifold", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); - ImGui::SliderFloat("x offset", &m_transform.p.x, -2.0f, 2.0f, "%.2f"); - ImGui::SliderFloat("y offset", &m_transform.p.y, -2.0f, 2.0f, "%.2f"); + ImGui::SliderFloat( "x offset", &m_transform.p.x, -2.0f, 2.0f, "%.2f" ); + ImGui::SliderFloat( "y offset", &m_transform.p.y, -2.0f, 2.0f, "%.2f" ); - if (ImGui::SliderFloat("angle", &m_angle, -b2_pi, b2_pi, "%.2f")) + if ( ImGui::SliderFloat( "angle", &m_angle, -b2_pi, b2_pi, "%.2f" ) ) { - m_transform.q = b2MakeRot(m_angle); + m_transform.q = b2MakeRot( m_angle ); } - ImGui::SliderFloat("round", &m_round, 0.0f, 0.4f, "%.1f"); - ImGui::Checkbox("show ids", &m_showIds); - ImGui::Checkbox("show separation", &m_showSeparation); - ImGui::Checkbox("show anchors", &m_showAnchors); - ImGui::Checkbox("enable caching", &m_enableCaching); + ImGui::SliderFloat( "round", &m_round, 0.0f, 0.4f, "%.1f" ); + ImGui::Checkbox( "show ids", &m_showIds ); + ImGui::Checkbox( "show separation", &m_showSeparation ); + ImGui::Checkbox( "show anchors", &m_showAnchors ); + ImGui::Checkbox( "enable caching", &m_enableCaching ); - if (ImGui::Button("Reset")) + if ( ImGui::Button( "Reset" ) ) { m_transform = b2Transform_identity; m_angle = 0.0f; @@ -2281,23 +2280,23 @@ class Manifold : public Sample ImGui::Separator(); - ImGui::Text("mouse button 1: drag"); - ImGui::Text("mouse button 1 + shift: rotate"); + ImGui::Text( "mouse button 1: drag" ); + ImGui::Text( "mouse button 1 + shift: rotate" ); ImGui::End(); } - void MouseDown(b2Vec2 p, int button, int mods) override + void MouseDown( b2Vec2 p, int button, int mods ) override { - if (button == GLFW_MOUSE_BUTTON_1) + if ( button == GLFW_MOUSE_BUTTON_1 ) { - if (mods == 0 && m_rotating == false) + if ( mods == 0 && m_rotating == false ) { m_dragging = true; m_startPoint = p; m_basePosition = m_transform.p; } - else if (mods == GLFW_MOD_SHIFT && m_dragging == false) + else if ( mods == GLFW_MOD_SHIFT && m_dragging == false ) { m_rotating = true; m_startPoint = p; @@ -2306,75 +2305,75 @@ class Manifold : public Sample } } - void MouseUp(b2Vec2, int button) override + void MouseUp( b2Vec2, int button ) override { - if (button == GLFW_MOUSE_BUTTON_1) + if ( button == GLFW_MOUSE_BUTTON_1 ) { m_dragging = false; m_rotating = false; } } - void MouseMove(b2Vec2 p) override + void MouseMove( b2Vec2 p ) override { - if (m_dragging) + if ( m_dragging ) { - m_transform.p.x = m_basePosition.x + 0.5f * (p.x - m_startPoint.x); - m_transform.p.y = m_basePosition.y + 0.5f * (p.y - m_startPoint.y); + m_transform.p.x = m_basePosition.x + 0.5f * ( p.x - m_startPoint.x ); + m_transform.p.y = m_basePosition.y + 0.5f * ( p.y - m_startPoint.y ); } - else if (m_rotating) + else if ( m_rotating ) { float dx = p.x - m_startPoint.x; - m_angle = b2ClampFloat(m_baseAngle + 1.0f * dx, -b2_pi, b2_pi); - m_transform.q = b2MakeRot(m_angle); + m_angle = b2ClampFloat( m_baseAngle + 1.0f * dx, -b2_pi, b2_pi ); + m_transform.q = b2MakeRot( m_angle ); } } - void DrawManifold(const b2Manifold* manifold, b2Vec2 origin1, b2Vec2 origin2) + void DrawManifold( const b2Manifold* manifold, b2Vec2 origin1, b2Vec2 origin2 ) { - for (int i = 0; i < manifold->pointCount; ++i) + for ( int i = 0; i < manifold->pointCount; ++i ) { const b2ManifoldPoint* mp = manifold->points + i; b2Vec2 p1 = mp->point; - b2Vec2 p2 = b2MulAdd(p1, 0.5f, manifold->normal); - g_draw.DrawSegment(p1, p2, b2_colorWhite); + b2Vec2 p2 = b2MulAdd( p1, 0.5f, manifold->normal ); + g_draw.DrawSegment( p1, p2, b2_colorWhite ); - if (m_showAnchors) + if ( m_showAnchors ) { - g_draw.DrawPoint(b2Add(origin1, mp->anchorA), 5.0f, b2_colorRed); - g_draw.DrawPoint(b2Add(origin2, mp->anchorB), 5.0f, b2_colorGreen); + g_draw.DrawPoint( b2Add( origin1, mp->anchorA ), 5.0f, b2_colorRed ); + g_draw.DrawPoint( b2Add( origin2, mp->anchorB ), 5.0f, b2_colorGreen ); } else { - g_draw.DrawPoint(p1, 5.0f, b2_colorBlue); + g_draw.DrawPoint( p1, 5.0f, b2_colorBlue ); } - if (m_showIds) + if ( m_showIds ) { // uint32_t indexA = mp->id >> 8; // uint32_t indexB = 0xFF & mp->id; - b2Vec2 p = {p1.x + 0.05f, p1.y - 0.02f}; - g_draw.DrawString(p, "0x%04x", mp->id); + b2Vec2 p = { p1.x + 0.05f, p1.y - 0.02f }; + g_draw.DrawString( p, "0x%04x", mp->id ); } - if (m_showSeparation) + if ( m_showSeparation ) { - b2Vec2 p = {p1.x + 0.05f, p1.y + 0.03f}; - g_draw.DrawString(p, "%.3f", mp->separation); + b2Vec2 p = { p1.x + 0.05f, p1.y + 0.03f }; + g_draw.DrawString( p, "%.3f", mp->separation ); } } } - void Step(Settings&) override + void Step( Settings& ) override { - b2Vec2 offset = {-10.0f, -5.0f}; - b2Vec2 increment = {4.0f, 0.0f}; + b2Vec2 offset = { -10.0f, -5.0f }; + b2Vec2 increment = { 4.0f, 0.0f }; b2HexColor color1 = b2_colorAquamarine; b2HexColor color2 = b2_colorMagenta; - if (m_enableCaching == false) + if ( m_enableCaching == false ) { m_smgroxCache1 = b2_emptyDistanceCache; m_smgroxCache2 = b2_emptyDistanceCache; @@ -2384,404 +2383,404 @@ class Manifold : public Sample // circle-circle { - b2Circle circle1 = {{0.0f, 0.0f}, 0.5f}; - b2Circle circle2 = {{0.0f, 0.0f}, 1.0f}; + b2Circle circle1 = { { 0.0f, 0.0f }, 0.5f }; + b2Circle circle2 = { { 0.0f, 0.0f }, 1.0f }; - b2Transform transform1 = {offset, b2Rot_identity}; - b2Transform transform2 = {b2Add(m_transform.p, offset), m_transform.q}; + b2Transform transform1 = { offset, b2Rot_identity }; + b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; - b2Manifold m = b2CollideCircles(&circle1, transform1, &circle2, transform2); + b2Manifold m = b2CollideCircles( &circle1, transform1, &circle2, transform2 ); - g_draw.DrawSolidCircle(transform1, circle1.center, circle1.radius, color1); - g_draw.DrawSolidCircle(transform2, circle2.center, circle2.radius, color2); + g_draw.DrawSolidCircle( transform1, circle1.center, circle1.radius, color1 ); + g_draw.DrawSolidCircle( transform2, circle2.center, circle2.radius, color2 ); - DrawManifold(&m, transform1.p, transform2.p); + DrawManifold( &m, transform1.p, transform2.p ); - offset = b2Add(offset, increment); + offset = b2Add( offset, increment ); } // capsule-circle { - b2Capsule capsule = {{-0.5f, 0.0f}, {0.5f, 0.0}, 0.25f}; - b2Circle circle = {{0.0f, 0.0f}, 0.5f}; + b2Capsule capsule = { { -0.5f, 0.0f }, { 0.5f, 0.0 }, 0.25f }; + b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; - b2Transform transform1 = {offset, b2Rot_identity}; - b2Transform transform2 = {b2Add(m_transform.p, offset), m_transform.q}; + b2Transform transform1 = { offset, b2Rot_identity }; + b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; - b2Manifold m = b2CollideCapsuleAndCircle(&capsule, transform1, &circle, transform2); + b2Manifold m = b2CollideCapsuleAndCircle( &capsule, transform1, &circle, transform2 ); - b2Vec2 v1 = b2TransformPoint(transform1, capsule.center1); - b2Vec2 v2 = b2TransformPoint(transform1, capsule.center2); - g_draw.DrawSolidCapsule(v1, v2, capsule.radius, color1); + b2Vec2 v1 = b2TransformPoint( transform1, capsule.center1 ); + b2Vec2 v2 = b2TransformPoint( transform1, capsule.center2 ); + g_draw.DrawSolidCapsule( v1, v2, capsule.radius, color1 ); - g_draw.DrawSolidCircle(transform2, circle.center, circle.radius, color2); + g_draw.DrawSolidCircle( transform2, circle.center, circle.radius, color2 ); - DrawManifold(&m, transform1.p, transform2.p); + DrawManifold( &m, transform1.p, transform2.p ); - offset = b2Add(offset, increment); + offset = b2Add( offset, increment ); } // segment-circle { - b2Segment segment = {{-1.0f, 0.0f}, {1.0f, 0.0}}; - b2Circle circle = {{0.0f, 0.0f}, 0.5f}; + b2Segment segment = { { -1.0f, 0.0f }, { 1.0f, 0.0 } }; + b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; - b2Transform transform1 = {offset, b2Rot_identity}; - b2Transform transform2 = {b2Add(m_transform.p, offset), m_transform.q}; + b2Transform transform1 = { offset, b2Rot_identity }; + b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; - b2Manifold m = b2CollideSegmentAndCircle(&segment, transform1, &circle, transform2); + b2Manifold m = b2CollideSegmentAndCircle( &segment, transform1, &circle, transform2 ); - b2Vec2 p1 = b2TransformPoint(transform1, segment.point1); - b2Vec2 p2 = b2TransformPoint(transform1, segment.point2); - g_draw.DrawSegment(p1, p2, color1); + b2Vec2 p1 = b2TransformPoint( transform1, segment.point1 ); + b2Vec2 p2 = b2TransformPoint( transform1, segment.point2 ); + g_draw.DrawSegment( p1, p2, color1 ); - g_draw.DrawSolidCircle(transform2, circle.center, circle.radius, color2); + g_draw.DrawSolidCircle( transform2, circle.center, circle.radius, color2 ); - DrawManifold(&m, transform1.p, transform2.p); + DrawManifold( &m, transform1.p, transform2.p ); - offset = b2Add(offset, increment); + offset = b2Add( offset, increment ); } // box-circle { - b2Circle circle = {{0.0f, 0.0f}, 0.5f}; - b2Polygon box = b2MakeSquare(0.5f); + b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; + b2Polygon box = b2MakeSquare( 0.5f ); box.radius = m_round; - b2Transform transform1 = {offset, b2Rot_identity}; - b2Transform transform2 = {b2Add(m_transform.p, offset), m_transform.q}; + b2Transform transform1 = { offset, b2Rot_identity }; + b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; - b2Manifold m = b2CollidePolygonAndCircle(&box, transform1, &circle, transform2); + b2Manifold m = b2CollidePolygonAndCircle( &box, transform1, &circle, transform2 ); - g_draw.DrawSolidPolygon(transform1, box.vertices, box.count, m_round, color1); - g_draw.DrawSolidCircle(transform2, circle.center, circle.radius, color2); + g_draw.DrawSolidPolygon( transform1, box.vertices, box.count, m_round, color1 ); + g_draw.DrawSolidCircle( transform2, circle.center, circle.radius, color2 ); - DrawManifold(&m, transform1.p, transform2.p); + DrawManifold( &m, transform1.p, transform2.p ); - offset = b2Add(offset, increment); + offset = b2Add( offset, increment ); } // capsule-capsule { - b2Capsule capsule = {{-0.5f, 0.0f}, {0.5f, 0.0}, 0.25f}; + b2Capsule capsule = { { -0.5f, 0.0f }, { 0.5f, 0.0 }, 0.25f }; - b2Transform transform1 = {offset, b2Rot_identity}; - b2Transform transform2 = {b2Add(m_transform.p, offset), m_transform.q}; + b2Transform transform1 = { offset, b2Rot_identity }; + b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; - b2Manifold m = b2CollideCapsules(&capsule, transform1, &capsule, transform2); + b2Manifold m = b2CollideCapsules( &capsule, transform1, &capsule, transform2 ); - b2Vec2 v1 = b2TransformPoint(transform1, capsule.center1); - b2Vec2 v2 = b2TransformPoint(transform1, capsule.center2); - g_draw.DrawSolidCapsule(v1, v2, capsule.radius, color1); + b2Vec2 v1 = b2TransformPoint( transform1, capsule.center1 ); + b2Vec2 v2 = b2TransformPoint( transform1, capsule.center2 ); + g_draw.DrawSolidCapsule( v1, v2, capsule.radius, color1 ); - v1 = b2TransformPoint(transform2, capsule.center1); - v2 = b2TransformPoint(transform2, capsule.center2); - g_draw.DrawSolidCapsule(v1, v2, capsule.radius, color2); + v1 = b2TransformPoint( transform2, capsule.center1 ); + v2 = b2TransformPoint( transform2, capsule.center2 ); + g_draw.DrawSolidCapsule( v1, v2, capsule.radius, color2 ); - DrawManifold(&m, transform1.p, transform2.p); + DrawManifold( &m, transform1.p, transform2.p ); - offset = b2Add(offset, increment); + offset = b2Add( offset, increment ); } // box-capsule { - b2Capsule capsule = {{-0.4f, 0.0f}, {-0.1f, 0.0f}, 0.1f}; - b2Polygon box = b2MakeOffsetBox(0.25f, 1.0f, {1.0f, -1.0f}, 0.25f * b2_pi); + b2Capsule capsule = { { -0.4f, 0.0f }, { -0.1f, 0.0f }, 0.1f }; + b2Polygon box = b2MakeOffsetBox( 0.25f, 1.0f, { 1.0f, -1.0f }, 0.25f * b2_pi ); - b2Transform transform1 = {offset, b2Rot_identity}; - b2Transform transform2 = {b2Add(m_transform.p, offset), m_transform.q}; + b2Transform transform1 = { offset, b2Rot_identity }; + b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; - b2Manifold m = b2CollidePolygonAndCapsule(&box, transform1, &capsule, transform2); + b2Manifold m = b2CollidePolygonAndCapsule( &box, transform1, &capsule, transform2 ); - g_draw.DrawSolidPolygon(transform1, box.vertices, box.count, box.radius, color1); + g_draw.DrawSolidPolygon( transform1, box.vertices, box.count, box.radius, color1 ); - b2Vec2 v1 = b2TransformPoint(transform2, capsule.center1); - b2Vec2 v2 = b2TransformPoint(transform2, capsule.center2); - g_draw.DrawSolidCapsule(v1, v2, capsule.radius, color2); + b2Vec2 v1 = b2TransformPoint( transform2, capsule.center1 ); + b2Vec2 v2 = b2TransformPoint( transform2, capsule.center2 ); + g_draw.DrawSolidCapsule( v1, v2, capsule.radius, color2 ); - DrawManifold(&m, transform1.p, transform2.p); + DrawManifold( &m, transform1.p, transform2.p ); - offset = b2Add(offset, increment); + offset = b2Add( offset, increment ); } // segment-capsule { - b2Segment segment = {{-1.0f, 0.0f}, {1.0f, 0.0}}; - b2Capsule capsule = {{-0.5f, 0.0f}, {0.5f, 0.0}, 0.25f}; + b2Segment segment = { { -1.0f, 0.0f }, { 1.0f, 0.0 } }; + b2Capsule capsule = { { -0.5f, 0.0f }, { 0.5f, 0.0 }, 0.25f }; - b2Transform transform1 = {offset, b2Rot_identity}; - b2Transform transform2 = {b2Add(m_transform.p, offset), m_transform.q}; + b2Transform transform1 = { offset, b2Rot_identity }; + b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; - b2Manifold m = b2CollideSegmentAndCapsule(&segment, transform1, &capsule, transform2); + b2Manifold m = b2CollideSegmentAndCapsule( &segment, transform1, &capsule, transform2 ); - b2Vec2 p1 = b2TransformPoint(transform1, segment.point1); - b2Vec2 p2 = b2TransformPoint(transform1, segment.point2); - g_draw.DrawSegment(p1, p2, color1); + b2Vec2 p1 = b2TransformPoint( transform1, segment.point1 ); + b2Vec2 p2 = b2TransformPoint( transform1, segment.point2 ); + g_draw.DrawSegment( p1, p2, color1 ); - p1 = b2TransformPoint(transform2, capsule.center1); - p2 = b2TransformPoint(transform2, capsule.center2); - g_draw.DrawSolidCapsule(p1, p2, capsule.radius, color2); + p1 = b2TransformPoint( transform2, capsule.center1 ); + p2 = b2TransformPoint( transform2, capsule.center2 ); + g_draw.DrawSolidCapsule( p1, p2, capsule.radius, color2 ); - DrawManifold(&m, transform1.p, transform2.p); + DrawManifold( &m, transform1.p, transform2.p ); - offset = b2Add(offset, increment); + offset = b2Add( offset, increment ); } - offset = {-10.0f, 0.0f}; + offset = { -10.0f, 0.0f }; // box-box { - b2Polygon box1 = b2MakeBox(2.0f, 0.1f); - b2Polygon box = b2MakeSquare(0.25f); + b2Polygon box1 = b2MakeBox( 2.0f, 0.1f ); + b2Polygon box = b2MakeSquare( 0.25f ); - b2Transform transform1 = {offset, b2Rot_identity}; - b2Transform transform2 = {b2Add(m_transform.p, offset), m_transform.q}; + b2Transform transform1 = { offset, b2Rot_identity }; + b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; // b2Transform transform2 = {b2Add({0.0f, -0.1f}, offset), {0.0f, 1.0f}}; - b2Manifold m = b2CollidePolygons(&box1, transform1, &box, transform2); + b2Manifold m = b2CollidePolygons( &box1, transform1, &box, transform2 ); - g_draw.DrawSolidPolygon(transform1, box1.vertices, box1.count, box1.radius, color1); - g_draw.DrawSolidPolygon(transform2, box.vertices, box.count, box.radius, color2); + g_draw.DrawSolidPolygon( transform1, box1.vertices, box1.count, box1.radius, color1 ); + g_draw.DrawSolidPolygon( transform2, box.vertices, box.count, box.radius, color2 ); - DrawManifold(&m, transform1.p, transform2.p); + DrawManifold( &m, transform1.p, transform2.p ); - offset = b2Add(offset, increment); + offset = b2Add( offset, increment ); } // box-rox { - b2Polygon box = b2MakeSquare(0.5f); + b2Polygon box = b2MakeSquare( 0.5f ); float h = 0.5f - m_round; - b2Polygon rox = b2MakeRoundedBox(h, h, m_round); + b2Polygon rox = b2MakeRoundedBox( h, h, m_round ); - b2Transform transform1 = {offset, b2Rot_identity}; - b2Transform transform2 = {b2Add(m_transform.p, offset), m_transform.q}; + b2Transform transform1 = { offset, b2Rot_identity }; + b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; // b2Transform transform2 = {b2Add({0.0f, -0.1f}, offset), {0.0f, 1.0f}}; - b2Manifold m = b2CollidePolygons(&box, transform1, &rox, transform2); + b2Manifold m = b2CollidePolygons( &box, transform1, &rox, transform2 ); - g_draw.DrawSolidPolygon(transform1, box.vertices, box.count, box.radius, color1); - g_draw.DrawSolidPolygon(transform2, rox.vertices, rox.count, rox.radius, color2); + g_draw.DrawSolidPolygon( transform1, box.vertices, box.count, box.radius, color1 ); + g_draw.DrawSolidPolygon( transform2, rox.vertices, rox.count, rox.radius, color2 ); - DrawManifold(&m, transform1.p, transform2.p); + DrawManifold( &m, transform1.p, transform2.p ); - offset = b2Add(offset, increment); + offset = b2Add( offset, increment ); } // rox-rox { float h = 0.5f - m_round; - b2Polygon rox = b2MakeRoundedBox(h, h, m_round); + b2Polygon rox = b2MakeRoundedBox( h, h, m_round ); - b2Transform transform1 = {offset, b2Rot_identity}; - b2Transform transform2 = {b2Add(m_transform.p, offset), m_transform.q}; + b2Transform transform1 = { offset, b2Rot_identity }; + b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; // b2Transform transform1 = {{6.48024225f, 2.07872653f}, {-0.938356698f, 0.345668465f}}; // b2Transform transform2 = {{5.52862263f, 2.51146317f}, {-0.859374702f, -0.511346340f}}; - b2Manifold m = b2CollidePolygons(&rox, transform1, &rox, transform2); + b2Manifold m = b2CollidePolygons( &rox, transform1, &rox, transform2 ); - g_draw.DrawSolidPolygon(transform1, rox.vertices, rox.count, rox.radius, color1); - g_draw.DrawSolidPolygon(transform2, rox.vertices, rox.count, rox.radius, color2); + g_draw.DrawSolidPolygon( transform1, rox.vertices, rox.count, rox.radius, color1 ); + g_draw.DrawSolidPolygon( transform2, rox.vertices, rox.count, rox.radius, color2 ); - DrawManifold(&m, transform1.p, transform2.p); + DrawManifold( &m, transform1.p, transform2.p ); - offset = b2Add(offset, increment); + offset = b2Add( offset, increment ); } // segment-rox { - b2Segment segment = {{-1.0f, 0.0f}, {1.0f, 0.0}}; + b2Segment segment = { { -1.0f, 0.0f }, { 1.0f, 0.0 } }; float h = 0.5f - m_round; - b2Polygon rox = b2MakeRoundedBox(h, h, m_round); + b2Polygon rox = b2MakeRoundedBox( h, h, m_round ); - b2Transform transform1 = {offset, b2Rot_identity}; - b2Transform transform2 = {b2Add(m_transform.p, offset), m_transform.q}; + b2Transform transform1 = { offset, b2Rot_identity }; + b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; // b2Transform transform2 = {b2Add({-1.44583416f, 0.397352695f}, offset), m_transform.q}; - b2Manifold m = b2CollideSegmentAndPolygon(&segment, transform1, &rox, transform2); + b2Manifold m = b2CollideSegmentAndPolygon( &segment, transform1, &rox, transform2 ); - b2Vec2 p1 = b2TransformPoint(transform1, segment.point1); - b2Vec2 p2 = b2TransformPoint(transform1, segment.point2); - g_draw.DrawSegment(p1, p2, color1); - g_draw.DrawSolidPolygon(transform2, rox.vertices, rox.count, rox.radius, color2); + b2Vec2 p1 = b2TransformPoint( transform1, segment.point1 ); + b2Vec2 p2 = b2TransformPoint( transform1, segment.point2 ); + g_draw.DrawSegment( p1, p2, color1 ); + g_draw.DrawSolidPolygon( transform2, rox.vertices, rox.count, rox.radius, color2 ); - DrawManifold(&m, transform1.p, transform2.p); + DrawManifold( &m, transform1.p, transform2.p ); - offset = b2Add(offset, increment); + offset = b2Add( offset, increment ); } // wox-wox { - b2Polygon wox = b2MakePolygon(&m_wedge, m_round); + b2Polygon wox = b2MakePolygon( &m_wedge, m_round ); - b2Transform transform1 = {offset, b2Rot_identity}; - b2Transform transform2 = {b2Add(m_transform.p, offset), m_transform.q}; + b2Transform transform1 = { offset, b2Rot_identity }; + b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; // b2Transform transform2 = {b2Add({0.0f, -0.1f}, offset), {0.0f, 1.0f}}; - b2Manifold m = b2CollidePolygons(&wox, transform1, &wox, transform2); + b2Manifold m = b2CollidePolygons( &wox, transform1, &wox, transform2 ); - g_draw.DrawSolidPolygon(transform1, wox.vertices, wox.count, wox.radius, color1); - g_draw.DrawSolidPolygon(transform1, wox.vertices, wox.count, 0.0f, color1); - g_draw.DrawSolidPolygon(transform2, wox.vertices, wox.count, wox.radius, color2); - g_draw.DrawSolidPolygon(transform2, wox.vertices, wox.count, 0.0f, color2); + g_draw.DrawSolidPolygon( transform1, wox.vertices, wox.count, wox.radius, color1 ); + g_draw.DrawSolidPolygon( transform1, wox.vertices, wox.count, 0.0f, color1 ); + g_draw.DrawSolidPolygon( transform2, wox.vertices, wox.count, wox.radius, color2 ); + g_draw.DrawSolidPolygon( transform2, wox.vertices, wox.count, 0.0f, color2 ); - DrawManifold(&m, transform1.p, transform2.p); + DrawManifold( &m, transform1.p, transform2.p ); - offset = b2Add(offset, increment); + offset = b2Add( offset, increment ); } // wox-wox { - b2Vec2 p1s[3] = {{0.175740838, 0.224936664}, {-0.301293969, 0.194021404}, { -0.105151534, -0.432157338 }}; - b2Vec2 p2s[3] = {{-0.427884758, -0.225028217}, {0.0566576123, -0.128772855}, { 0.176625848, 0.338923335 }}; + b2Vec2 p1s[3] = { { 0.175740838, 0.224936664 }, { -0.301293969, 0.194021404 }, { -0.105151534, -0.432157338 } }; + b2Vec2 p2s[3] = { { -0.427884758, -0.225028217 }, { 0.0566576123, -0.128772855 }, { 0.176625848, 0.338923335 } }; - b2Hull h1 = b2ComputeHull(p1s, 3); - b2Hull h2 = b2ComputeHull(p2s, 3); - b2Polygon w1 = b2MakePolygon(&h1, 0.158798501); - b2Polygon w2 = b2MakePolygon(&h2, 0.205900759); + b2Hull h1 = b2ComputeHull( p1s, 3 ); + b2Hull h2 = b2ComputeHull( p2s, 3 ); + b2Polygon w1 = b2MakePolygon( &h1, 0.158798501 ); + b2Polygon w2 = b2MakePolygon( &h2, 0.205900759 ); - b2Transform transform1 = {offset, b2Rot_identity}; - b2Transform transform2 = {b2Add(m_transform.p, offset), m_transform.q}; + b2Transform transform1 = { offset, b2Rot_identity }; + b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; // b2Transform transform2 = {b2Add({0.0f, -0.1f}, offset), {0.0f, 1.0f}}; - b2Manifold m = b2CollidePolygons(&w1, transform1, &w2, transform2); + b2Manifold m = b2CollidePolygons( &w1, transform1, &w2, transform2 ); - g_draw.DrawSolidPolygon(transform1, w1.vertices, w1.count, w1.radius, color1); - g_draw.DrawSolidPolygon(transform1, w1.vertices, w1.count, 0.0f, color1); - g_draw.DrawSolidPolygon(transform2, w2.vertices, w2.count, w2.radius, color2); - g_draw.DrawSolidPolygon(transform2, w2.vertices, w2.count, 0.0f, color2); + g_draw.DrawSolidPolygon( transform1, w1.vertices, w1.count, w1.radius, color1 ); + g_draw.DrawSolidPolygon( transform1, w1.vertices, w1.count, 0.0f, color1 ); + g_draw.DrawSolidPolygon( transform2, w2.vertices, w2.count, w2.radius, color2 ); + g_draw.DrawSolidPolygon( transform2, w2.vertices, w2.count, 0.0f, color2 ); - DrawManifold(&m, transform1.p, transform2.p); + DrawManifold( &m, transform1.p, transform2.p ); - offset = b2Add(offset, increment); + offset = b2Add( offset, increment ); } - offset = {-10.0f, 5.0f}; + offset = { -10.0f, 5.0f }; // smooth-segment vs circle { - b2SmoothSegment segment = {{2.0f, 1.0f}, {{1.0f, 1.0f}, {-1.0f, 0.0f}}, {-2.0f, 0.0f}, -1}; - b2Circle circle = {{0.0f, 0.0f}, 0.5f}; + b2SmoothSegment segment = { { 2.0f, 1.0f }, { { 1.0f, 1.0f }, { -1.0f, 0.0f } }, { -2.0f, 0.0f }, -1 }; + b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; - b2Transform transform1 = {offset, b2Rot_identity}; - b2Transform transform2 = {b2Add(m_transform.p, offset), m_transform.q}; + b2Transform transform1 = { offset, b2Rot_identity }; + b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; - b2Manifold m = b2CollideSmoothSegmentAndCircle(&segment, transform1, &circle, transform2); + b2Manifold m = b2CollideSmoothSegmentAndCircle( &segment, transform1, &circle, transform2 ); - b2Vec2 g1 = b2TransformPoint(transform1, segment.ghost1); - b2Vec2 g2 = b2TransformPoint(transform1, segment.ghost2); - b2Vec2 p1 = b2TransformPoint(transform1, segment.segment.point1); - b2Vec2 p2 = b2TransformPoint(transform1, segment.segment.point2); - g_draw.DrawSegment(g1, p1, b2_colorLightGray); - g_draw.DrawSegment(p1, p2, color1); - g_draw.DrawSegment(p2, g2, b2_colorLightGray); - g_draw.DrawSolidCircle(transform2, circle.center, circle.radius, color2); + b2Vec2 g1 = b2TransformPoint( transform1, segment.ghost1 ); + b2Vec2 g2 = b2TransformPoint( transform1, segment.ghost2 ); + b2Vec2 p1 = b2TransformPoint( transform1, segment.segment.point1 ); + b2Vec2 p2 = b2TransformPoint( transform1, segment.segment.point2 ); + g_draw.DrawSegment( g1, p1, b2_colorLightGray ); + g_draw.DrawSegment( p1, p2, color1 ); + g_draw.DrawSegment( p2, g2, b2_colorLightGray ); + g_draw.DrawSolidCircle( transform2, circle.center, circle.radius, color2 ); - DrawManifold(&m, transform1.p, transform2.p); + DrawManifold( &m, transform1.p, transform2.p ); offset.x += 2.0f * increment.x; } // smooth-segment vs rounded polygon { - b2SmoothSegment segment1 = {{2.0f, 1.0f}, {{1.0f, 1.0f}, {-1.0f, 0.0f}}, {-2.0f, 0.0f}, -1}; - b2SmoothSegment segment2 = {{3.0f, 1.0f}, {{2.0f, 1.0f}, {1.0f, 1.0f}}, {-1.0f, 0.0f}, -1}; + b2SmoothSegment segment1 = { { 2.0f, 1.0f }, { { 1.0f, 1.0f }, { -1.0f, 0.0f } }, { -2.0f, 0.0f }, -1 }; + b2SmoothSegment segment2 = { { 3.0f, 1.0f }, { { 2.0f, 1.0f }, { 1.0f, 1.0f } }, { -1.0f, 0.0f }, -1 }; // b2SmoothSegment segment1 = {{2.0f, 0.0f}, {{1.0f, 0.0f}, {-1.0f, 0.0f}}, {-2.0f, 0.0f}, -1}; // b2SmoothSegment segment2 = {{3.0f, 0.0f}, {{2.0f, 0.0f}, {1.0f, 0.0f}}, {-1.0f, 0.0f}, -1}; // b2SmoothSegment segment1 = {{0.5f, 1.0f}, {{0.0f, 2.0f}, {-0.5f, 1.0f}}, {-1.0f, 0.0f}, -1}; // b2SmoothSegment segment2 = {{1.0f, 0.0f}, {{0.5f, 1.0f}, {0.0f, 2.0f}}, {-0.5f, 1.0f}, -1}; float h = 0.5f - m_round; - b2Polygon rox = b2MakeRoundedBox(h, h, m_round); + b2Polygon rox = b2MakeRoundedBox( h, h, m_round ); - b2Transform transform1 = {offset, b2Rot_identity}; - b2Transform transform2 = {b2Add(m_transform.p, offset), m_transform.q}; + b2Transform transform1 = { offset, b2Rot_identity }; + b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; - b2Manifold m1 = b2CollideSmoothSegmentAndPolygon(&segment1, transform1, &rox, transform2, &m_smgroxCache1); - b2Manifold m2 = b2CollideSmoothSegmentAndPolygon(&segment2, transform1, &rox, transform2, &m_smgroxCache2); + b2Manifold m1 = b2CollideSmoothSegmentAndPolygon( &segment1, transform1, &rox, transform2, &m_smgroxCache1 ); + b2Manifold m2 = b2CollideSmoothSegmentAndPolygon( &segment2, transform1, &rox, transform2, &m_smgroxCache2 ); { - b2Vec2 g1 = b2TransformPoint(transform1, segment1.ghost1); - b2Vec2 g2 = b2TransformPoint(transform1, segment1.ghost2); - b2Vec2 p1 = b2TransformPoint(transform1, segment1.segment.point1); - b2Vec2 p2 = b2TransformPoint(transform1, segment1.segment.point2); - g_draw.DrawSegment(p1, p2, color1); - g_draw.DrawPoint(p1, 4.0f, color1); - g_draw.DrawPoint(p2, 4.0f, color1); - g_draw.DrawSegment(p2, g2, b2_colorLightGray); + b2Vec2 g1 = b2TransformPoint( transform1, segment1.ghost1 ); + b2Vec2 g2 = b2TransformPoint( transform1, segment1.ghost2 ); + b2Vec2 p1 = b2TransformPoint( transform1, segment1.segment.point1 ); + b2Vec2 p2 = b2TransformPoint( transform1, segment1.segment.point2 ); + g_draw.DrawSegment( p1, p2, color1 ); + g_draw.DrawPoint( p1, 4.0f, color1 ); + g_draw.DrawPoint( p2, 4.0f, color1 ); + g_draw.DrawSegment( p2, g2, b2_colorLightGray ); } { - b2Vec2 g1 = b2TransformPoint(transform1, segment2.ghost1); - b2Vec2 g2 = b2TransformPoint(transform1, segment2.ghost2); - b2Vec2 p1 = b2TransformPoint(transform1, segment2.segment.point1); - b2Vec2 p2 = b2TransformPoint(transform1, segment2.segment.point2); - g_draw.DrawSegment(g1, p1, b2_colorLightGray); - g_draw.DrawSegment(p1, p2, color1); - g_draw.DrawPoint(p1, 4.0f, color1); - g_draw.DrawPoint(p2, 4.0f, color1); + b2Vec2 g1 = b2TransformPoint( transform1, segment2.ghost1 ); + b2Vec2 g2 = b2TransformPoint( transform1, segment2.ghost2 ); + b2Vec2 p1 = b2TransformPoint( transform1, segment2.segment.point1 ); + b2Vec2 p2 = b2TransformPoint( transform1, segment2.segment.point2 ); + g_draw.DrawSegment( g1, p1, b2_colorLightGray ); + g_draw.DrawSegment( p1, p2, color1 ); + g_draw.DrawPoint( p1, 4.0f, color1 ); + g_draw.DrawPoint( p2, 4.0f, color1 ); } - g_draw.DrawSolidPolygon(transform2, rox.vertices, rox.count, rox.radius, color2); - g_draw.DrawPoint(b2TransformPoint(transform2, rox.centroid), 5.0f, b2_colorGainsboro); + g_draw.DrawSolidPolygon( transform2, rox.vertices, rox.count, rox.radius, color2 ); + g_draw.DrawPoint( b2TransformPoint( transform2, rox.centroid ), 5.0f, b2_colorGainsboro ); - DrawManifold(&m1, transform1.p, transform2.p); - DrawManifold(&m2, transform1.p, transform2.p); + DrawManifold( &m1, transform1.p, transform2.p ); + DrawManifold( &m2, transform1.p, transform2.p ); offset.x += 2.0f * increment.x; } // smooth-segment vs capsule { - b2SmoothSegment segment1 = {{2.0f, 1.0f}, {{1.0f, 1.0f}, {-1.0f, 0.0f}}, {-2.0f, 0.0f}, -1}; - b2SmoothSegment segment2 = {{3.0f, 1.0f}, {{2.0f, 1.0f}, {1.0f, 1.0f}}, {-1.0f, 0.0f}, -1}; - b2Capsule capsule = {{-0.5f, 0.0f}, {0.5f, 0.0}, 0.25f}; + b2SmoothSegment segment1 = { { 2.0f, 1.0f }, { { 1.0f, 1.0f }, { -1.0f, 0.0f } }, { -2.0f, 0.0f }, -1 }; + b2SmoothSegment segment2 = { { 3.0f, 1.0f }, { { 2.0f, 1.0f }, { 1.0f, 1.0f } }, { -1.0f, 0.0f }, -1 }; + b2Capsule capsule = { { -0.5f, 0.0f }, { 0.5f, 0.0 }, 0.25f }; - b2Transform transform1 = {offset, b2Rot_identity}; - b2Transform transform2 = {b2Add(m_transform.p, offset), m_transform.q}; + b2Transform transform1 = { offset, b2Rot_identity }; + b2Transform transform2 = { b2Add( m_transform.p, offset ), m_transform.q }; - b2Manifold m1 = b2CollideSmoothSegmentAndCapsule(&segment1, transform1, &capsule, transform2, &m_smgcapCache1); - b2Manifold m2 = b2CollideSmoothSegmentAndCapsule(&segment2, transform1, &capsule, transform2, &m_smgcapCache2); + b2Manifold m1 = b2CollideSmoothSegmentAndCapsule( &segment1, transform1, &capsule, transform2, &m_smgcapCache1 ); + b2Manifold m2 = b2CollideSmoothSegmentAndCapsule( &segment2, transform1, &capsule, transform2, &m_smgcapCache2 ); { - b2Vec2 g1 = b2TransformPoint(transform1, segment1.ghost1); - b2Vec2 g2 = b2TransformPoint(transform1, segment1.ghost2); - b2Vec2 p1 = b2TransformPoint(transform1, segment1.segment.point1); - b2Vec2 p2 = b2TransformPoint(transform1, segment1.segment.point2); + b2Vec2 g1 = b2TransformPoint( transform1, segment1.ghost1 ); + b2Vec2 g2 = b2TransformPoint( transform1, segment1.ghost2 ); + b2Vec2 p1 = b2TransformPoint( transform1, segment1.segment.point1 ); + b2Vec2 p2 = b2TransformPoint( transform1, segment1.segment.point2 ); // g_draw.DrawSegment(g1, p1, b2_colorLightGray); - g_draw.DrawSegment(p1, p2, color1); - g_draw.DrawPoint(p1, 4.0f, color1); - g_draw.DrawPoint(p2, 4.0f, color1); - g_draw.DrawSegment(p2, g2, b2_colorLightGray); + g_draw.DrawSegment( p1, p2, color1 ); + g_draw.DrawPoint( p1, 4.0f, color1 ); + g_draw.DrawPoint( p2, 4.0f, color1 ); + g_draw.DrawSegment( p2, g2, b2_colorLightGray ); } { - b2Vec2 g1 = b2TransformPoint(transform1, segment2.ghost1); - b2Vec2 g2 = b2TransformPoint(transform1, segment2.ghost2); - b2Vec2 p1 = b2TransformPoint(transform1, segment2.segment.point1); - b2Vec2 p2 = b2TransformPoint(transform1, segment2.segment.point2); - g_draw.DrawSegment(g1, p1, b2_colorLightGray); - g_draw.DrawSegment(p1, p2, color1); - g_draw.DrawPoint(p1, 4.0f, color1); - g_draw.DrawPoint(p2, 4.0f, color1); + b2Vec2 g1 = b2TransformPoint( transform1, segment2.ghost1 ); + b2Vec2 g2 = b2TransformPoint( transform1, segment2.ghost2 ); + b2Vec2 p1 = b2TransformPoint( transform1, segment2.segment.point1 ); + b2Vec2 p2 = b2TransformPoint( transform1, segment2.segment.point2 ); + g_draw.DrawSegment( g1, p1, b2_colorLightGray ); + g_draw.DrawSegment( p1, p2, color1 ); + g_draw.DrawPoint( p1, 4.0f, color1 ); + g_draw.DrawPoint( p2, 4.0f, color1 ); // g_draw.DrawSegment(p2, g2, b2_colorLightGray); } - b2Vec2 p1 = b2TransformPoint(transform2, capsule.center1); - b2Vec2 p2 = b2TransformPoint(transform2, capsule.center2); - g_draw.DrawSolidCapsule(p1, p2, capsule.radius, color2); + b2Vec2 p1 = b2TransformPoint( transform2, capsule.center1 ); + b2Vec2 p2 = b2TransformPoint( transform2, capsule.center2 ); + g_draw.DrawSolidCapsule( p1, p2, capsule.radius, color2 ); - g_draw.DrawPoint(b2Lerp(p1, p2, 0.5f), 5.0f, b2_colorGainsboro); + g_draw.DrawPoint( b2Lerp( p1, p2, 0.5f ), 5.0f, b2_colorGainsboro ); - DrawManifold(&m1, transform1.p, transform2.p); - DrawManifold(&m2, transform1.p, transform2.p); + DrawManifold( &m1, transform1.p, transform2.p ); + DrawManifold( &m2, transform1.p, transform2.p ); offset.x += 2.0f * increment.x; } } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new Manifold(settings); + return new Manifold( settings ); } b2DistanceCache m_smgroxCache1; @@ -2807,7 +2806,7 @@ class Manifold : public Sample bool m_enableCaching; }; -static int sampleManifoldIndex = RegisterSample("Collision", "Manifold", Manifold::Create); +static int sampleManifoldIndex = RegisterSample( "Collision", "Manifold", Manifold::Create ); class SmoothManifold : public Sample { @@ -2818,22 +2817,22 @@ class SmoothManifold : public Sample e_boxShape }; - explicit SmoothManifold(Settings& settings) - : Sample(settings) + explicit SmoothManifold( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {2.0f, 20.0f}; + g_camera.m_center = { 2.0f, 20.0f }; g_camera.m_zoom = 21.0f; } m_shapeType = e_boxShape; - m_transform = {{0.0f, 20.0f}, b2Rot_identity}; + m_transform = { { 0.0f, 20.0f }, b2Rot_identity }; m_angle = 0.0f; m_round = 0.0f; - m_startPoint = {0.0f, 00.0f}; - m_basePosition = {0.0f, 0.0f}; + m_startPoint = { 0.0f, 00.0f }; + m_basePosition = { 0.0f, 0.0f }; m_baseAngle = 0.0f; m_dragging = false; @@ -2846,46 +2845,46 @@ class SmoothManifold : public Sample m_count = 36; b2Vec2 points[36]; - points[0] = {-20.58325, 14.54175}; - points[1] = {-21.90625, 15.8645}; - points[2] = {-24.552, 17.1875}; - points[3] = {-27.198, 11.89575}; - points[4] = {-29.84375, 15.8645}; - points[5] = {-29.84375, 21.15625}; - points[6] = {-25.875, 23.802}; - points[7] = {-20.58325, 25.125}; - points[8] = {-25.875, 29.09375}; - points[9] = {-20.58325, 31.7395}; - points[10] = {-11.0089998, 23.2290001}; - points[11] = {-8.67700005, 21.15625}; - points[12] = {-6.03125, 21.15625}; - points[13] = {-7.35424995, 29.09375}; - points[14] = {-3.38549995, 29.09375}; - points[15] = {1.90625, 30.41675}; - points[16] = {5.875, 17.1875}; - points[17] = {11.16675, 25.125}; - points[18] = {9.84375, 29.09375}; - points[19] = {13.8125, 31.7395}; - points[20] = {21.75, 30.41675}; - points[21] = {28.3644981, 26.448}; - points[22] = {25.71875, 18.5105}; - points[23] = {24.3957481, 13.21875}; - points[24] = {17.78125, 11.89575}; - points[25] = {15.1355, 7.92700005}; - points[26] = {5.875, 9.25}; - points[27] = {1.90625, 11.89575}; - points[28] = {-3.25, 11.89575}; - points[29] = {-3.25, 9.9375}; - points[30] = {-4.70825005, 9.25}; - points[31] = {-8.67700005, 9.25}; - points[32] = {-11.323, 11.89575}; - points[33] = {-13.96875, 11.89575}; - points[34] = {-15.29175, 14.54175}; - points[35] = {-19.2605, 14.54175}; - - m_segments = (b2SmoothSegment*)malloc(m_count * sizeof(b2SmoothSegment)); - - for (int i = 0; i < m_count; ++i) + points[0] = { -20.58325, 14.54175 }; + points[1] = { -21.90625, 15.8645 }; + points[2] = { -24.552, 17.1875 }; + points[3] = { -27.198, 11.89575 }; + points[4] = { -29.84375, 15.8645 }; + points[5] = { -29.84375, 21.15625 }; + points[6] = { -25.875, 23.802 }; + points[7] = { -20.58325, 25.125 }; + points[8] = { -25.875, 29.09375 }; + points[9] = { -20.58325, 31.7395 }; + points[10] = { -11.0089998, 23.2290001 }; + points[11] = { -8.67700005, 21.15625 }; + points[12] = { -6.03125, 21.15625 }; + points[13] = { -7.35424995, 29.09375 }; + points[14] = { -3.38549995, 29.09375 }; + points[15] = { 1.90625, 30.41675 }; + points[16] = { 5.875, 17.1875 }; + points[17] = { 11.16675, 25.125 }; + points[18] = { 9.84375, 29.09375 }; + points[19] = { 13.8125, 31.7395 }; + points[20] = { 21.75, 30.41675 }; + points[21] = { 28.3644981, 26.448 }; + points[22] = { 25.71875, 18.5105 }; + points[23] = { 24.3957481, 13.21875 }; + points[24] = { 17.78125, 11.89575 }; + points[25] = { 15.1355, 7.92700005 }; + points[26] = { 5.875, 9.25 }; + points[27] = { 1.90625, 11.89575 }; + points[28] = { -3.25, 11.89575 }; + points[29] = { -3.25, 9.9375 }; + points[30] = { -4.70825005, 9.25 }; + points[31] = { -8.67700005, 9.25 }; + points[32] = { -11.323, 11.89575 }; + points[33] = { -13.96875, 11.89575 }; + points[34] = { -15.29175, 14.54175 }; + points[35] = { -19.2605, 14.54175 }; + + m_segments = (b2SmoothSegment*)malloc( m_count * sizeof( b2SmoothSegment ) ); + + for ( int i = 0; i < m_count; ++i ) { int i0 = i > 0 ? i - 1 : m_count - 1; int i1 = i; @@ -2897,45 +2896,45 @@ class SmoothManifold : public Sample b2Vec2 p2 = points[i2]; b2Vec2 g2 = points[i3]; - m_segments[i] = {g1, {p1, p2}, g2, -1}; + m_segments[i] = { g1, { p1, p2 }, g2, -1 }; } } virtual ~SmoothManifold() override { - free(m_segments); + free( m_segments ); } void UpdateUI() override { float height = 290.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(180.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 180.0f, height ) ); - ImGui::Begin("Smooth Manifold", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize); - ImGui::PushItemWidth(100.0f); + ImGui::Begin( "Smooth Manifold", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); + ImGui::PushItemWidth( 100.0f ); { - const char* shapeTypes[] = {"Circle", "Box"}; - int shapeType = int(m_shapeType); - ImGui::Combo("Shape", &shapeType, shapeTypes, IM_ARRAYSIZE(shapeTypes)); - m_shapeType = ShapeType(shapeType); + const char* shapeTypes[] = { "Circle", "Box" }; + int shapeType = int( m_shapeType ); + ImGui::Combo( "Shape", &shapeType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ); + m_shapeType = ShapeType( shapeType ); } - ImGui::SliderFloat("x Offset", &m_transform.p.x, -2.0f, 2.0f, "%.2f"); - ImGui::SliderFloat("y Offset", &m_transform.p.y, -2.0f, 2.0f, "%.2f"); + ImGui::SliderFloat( "x Offset", &m_transform.p.x, -2.0f, 2.0f, "%.2f" ); + ImGui::SliderFloat( "y Offset", &m_transform.p.y, -2.0f, 2.0f, "%.2f" ); - if (ImGui::SliderFloat("Angle", &m_angle, -b2_pi, b2_pi, "%.2f")) + if ( ImGui::SliderFloat( "Angle", &m_angle, -b2_pi, b2_pi, "%.2f" ) ) { - m_transform.q = b2MakeRot(m_angle); + m_transform.q = b2MakeRot( m_angle ); } - ImGui::SliderFloat("Round", &m_round, 0.0f, 0.4f, "%.1f"); - ImGui::Checkbox("Show Ids", &m_showIds); - ImGui::Checkbox("Show Separation", &m_showSeparation); - ImGui::Checkbox("Show Anchors", &m_showAnchors); + ImGui::SliderFloat( "Round", &m_round, 0.0f, 0.4f, "%.1f" ); + ImGui::Checkbox( "Show Ids", &m_showIds ); + ImGui::Checkbox( "Show Separation", &m_showSeparation ); + ImGui::Checkbox( "Show Anchors", &m_showAnchors ); - if (ImGui::Button("Reset")) + if ( ImGui::Button( "Reset" ) ) { m_transform = b2Transform_identity; m_angle = 0.0f; @@ -2943,24 +2942,24 @@ class SmoothManifold : public Sample ImGui::Separator(); - ImGui::Text("mouse button 1: drag"); - ImGui::Text("mouse button 1 + shift: rotate"); + ImGui::Text( "mouse button 1: drag" ); + ImGui::Text( "mouse button 1 + shift: rotate" ); ImGui::PopItemWidth(); ImGui::End(); } - void MouseDown(b2Vec2 p, int button, int mods) override + void MouseDown( b2Vec2 p, int button, int mods ) override { - if (button == GLFW_MOUSE_BUTTON_1) + if ( button == GLFW_MOUSE_BUTTON_1 ) { - if (mods == 0 && m_rotating == false) + if ( mods == 0 && m_rotating == false ) { m_dragging = true; m_startPoint = p; m_basePosition = m_transform.p; } - else if (mods == GLFW_MOD_SHIFT && m_dragging == false) + else if ( mods == GLFW_MOD_SHIFT && m_dragging == false ) { m_rotating = true; m_startPoint = p; @@ -2969,66 +2968,66 @@ class SmoothManifold : public Sample } } - void MouseUp(b2Vec2, int button) override + void MouseUp( b2Vec2, int button ) override { - if (button == GLFW_MOUSE_BUTTON_1) + if ( button == GLFW_MOUSE_BUTTON_1 ) { m_dragging = false; m_rotating = false; } } - void MouseMove(b2Vec2 p) override + void MouseMove( b2Vec2 p ) override { - if (m_dragging) + if ( m_dragging ) { - m_transform.p.x = m_basePosition.x + (p.x - m_startPoint.x); - m_transform.p.y = m_basePosition.y + (p.y - m_startPoint.y); + m_transform.p.x = m_basePosition.x + ( p.x - m_startPoint.x ); + m_transform.p.y = m_basePosition.y + ( p.y - m_startPoint.y ); } - else if (m_rotating) + else if ( m_rotating ) { float dx = p.x - m_startPoint.x; - m_angle = b2ClampFloat(m_baseAngle + 1.0f * dx, -b2_pi, b2_pi); - m_transform.q = b2MakeRot(m_angle); + m_angle = b2ClampFloat( m_baseAngle + 1.0f * dx, -b2_pi, b2_pi ); + m_transform.q = b2MakeRot( m_angle ); } } - void DrawManifold(const b2Manifold* manifold) + void DrawManifold( const b2Manifold* manifold ) { - for (int i = 0; i < manifold->pointCount; ++i) + for ( int i = 0; i < manifold->pointCount; ++i ) { const b2ManifoldPoint* mp = manifold->points + i; b2Vec2 p1 = mp->point; - b2Vec2 p2 = b2MulAdd(p1, 0.5f, manifold->normal); - g_draw.DrawSegment(p1, p2, b2_colorWhite); + b2Vec2 p2 = b2MulAdd( p1, 0.5f, manifold->normal ); + g_draw.DrawSegment( p1, p2, b2_colorWhite ); - if (m_showAnchors) + if ( m_showAnchors ) { - g_draw.DrawPoint(p1, 5.0f, b2_colorGreen); + g_draw.DrawPoint( p1, 5.0f, b2_colorGreen ); } else { - g_draw.DrawPoint(p1, 5.0f, b2_colorGreen); + g_draw.DrawPoint( p1, 5.0f, b2_colorGreen ); } - if (m_showIds) + if ( m_showIds ) { // uint32_t indexA = mp->id >> 8; // uint32_t indexB = 0xFF & mp->id; - b2Vec2 p = {p1.x + 0.05f, p1.y - 0.02f}; - g_draw.DrawString(p, "0x%04x", mp->id); + b2Vec2 p = { p1.x + 0.05f, p1.y - 0.02f }; + g_draw.DrawString( p, "0x%04x", mp->id ); } - if (m_showSeparation) + if ( m_showSeparation ) { - b2Vec2 p = {p1.x + 0.05f, p1.y + 0.03f}; - g_draw.DrawString(p, "%.3f", mp->separation); + b2Vec2 p = { p1.x + 0.05f, p1.y + 0.03f }; + g_draw.DrawString( p, "%.3f", mp->separation ); } } } - void Step(Settings&) override + void Step( Settings& ) override { b2HexColor color1 = b2_colorYellow; b2HexColor color2 = b2_colorMagenta; @@ -3036,47 +3035,47 @@ class SmoothManifold : public Sample b2Transform transform1 = b2Transform_identity; b2Transform transform2 = m_transform; - for (int i = 0; i < m_count; ++i) + for ( int i = 0; i < m_count; ++i ) { const b2SmoothSegment* segment = m_segments + i; - b2Vec2 p1 = b2TransformPoint(transform1, segment->segment.point1); - b2Vec2 p2 = b2TransformPoint(transform1, segment->segment.point2); - g_draw.DrawSegment(p1, p2, color1); - g_draw.DrawPoint(p1, 4.0f, color1); + b2Vec2 p1 = b2TransformPoint( transform1, segment->segment.point1 ); + b2Vec2 p2 = b2TransformPoint( transform1, segment->segment.point2 ); + g_draw.DrawSegment( p1, p2, color1 ); + g_draw.DrawPoint( p1, 4.0f, color1 ); } // smooth-segment vs circle - if (m_shapeType == e_circleShape) + if ( m_shapeType == e_circleShape ) { - b2Circle circle = {{0.0f, 0.0f}, 0.5f}; - g_draw.DrawSolidCircle(transform2, circle.center, circle.radius, color2); + b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; + g_draw.DrawSolidCircle( transform2, circle.center, circle.radius, color2 ); - for (int i = 0; i < m_count; ++i) + for ( int i = 0; i < m_count; ++i ) { const b2SmoothSegment* segment = m_segments + i; - b2Manifold m = b2CollideSmoothSegmentAndCircle(segment, transform1, &circle, transform2); - DrawManifold(&m); + b2Manifold m = b2CollideSmoothSegmentAndCircle( segment, transform1, &circle, transform2 ); + DrawManifold( &m ); } } - else if (m_shapeType == e_boxShape) + else if ( m_shapeType == e_boxShape ) { float h = 0.5f - m_round; - b2Polygon rox = b2MakeRoundedBox(h, h, m_round); - g_draw.DrawSolidPolygon(transform2, rox.vertices, rox.count, rox.radius, color2); + b2Polygon rox = b2MakeRoundedBox( h, h, m_round ); + g_draw.DrawSolidPolygon( transform2, rox.vertices, rox.count, rox.radius, color2 ); - for (int i = 0; i < m_count; ++i) + for ( int i = 0; i < m_count; ++i ) { const b2SmoothSegment* segment = m_segments + i; b2DistanceCache cache = {}; - b2Manifold m = b2CollideSmoothSegmentAndPolygon(segment, transform1, &rox, transform2, &cache); - DrawManifold(&m); + b2Manifold m = b2CollideSmoothSegmentAndPolygon( segment, transform1, &rox, transform2, &cache ); + DrawManifold( &m ); } } } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new SmoothManifold(settings); + return new SmoothManifold( settings ); } ShapeType m_shapeType; @@ -3099,7 +3098,7 @@ class SmoothManifold : public Sample bool m_showSeparation; }; -static int sampleSmoothManifoldIndex = RegisterSample("Collision", "Smooth Manifold", SmoothManifold::Create); +static int sampleSmoothManifoldIndex = RegisterSample( "Collision", "Smooth Manifold", SmoothManifold::Create ); class ShapeCast : public Sample { @@ -3109,12 +3108,12 @@ class ShapeCast : public Sample e_vertexCount = 8 }; - explicit ShapeCast(Settings& settings) - : Sample(settings) + explicit ShapeCast( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {-1.5f, 1.0f}; + g_camera.m_center = { -1.5f, 1.0f }; g_camera.m_zoom = 25.0f * 0.2f; } @@ -3140,212 +3139,212 @@ class ShapeCast : public Sample m_translationB = {8.0f, 0.0f}; #elif 1 // box swept against a segment - m_vAs[0] = {-2.0f, 0.0f}; - m_vAs[1] = {2.0f, 0.0f}; + m_vAs[0] = { -2.0f, 0.0f }; + m_vAs[1] = { 2.0f, 0.0f }; m_countA = 2; m_radiusA = 0.0f; - m_vBs[0] = {-0.25f, -0.25f}; - m_vBs[1] = {0.25f, -0.25f}; - m_vBs[2] = {0.25f, 0.25f}; - m_vBs[3] = {-0.25f, 0.25f}; + m_vBs[0] = { -0.25f, -0.25f }; + m_vBs[1] = { 0.25f, -0.25f }; + m_vBs[2] = { 0.25f, 0.25f }; + m_vBs[3] = { -0.25f, 0.25f }; m_countB = 4; m_radiusB = 0.25f; - m_transformA.p = {0.0f, 0.0}; - m_transformA.q = b2MakeRot(0.25f * b2_pi); - m_transformB.p = {-8.0f, 0.0f}; + m_transformA.p = { 0.0f, 0.0 }; + m_transformA.q = b2MakeRot( 0.25f * b2_pi ); + m_transformB.p = { -8.0f, 0.0f }; m_transformB.q = b2Rot_identity; - m_translationB = {8.0f, 0.0f}; + m_translationB = { 8.0f, 0.0f }; #elif 0 // A point swept against a box - m_vAs[0] = {-0.5f, -0.5f}; - m_vAs[1] = {0.5f, -0.5f}; - m_vAs[2] = {0.5f, 0.5f}; - m_vAs[3] = {-0.5f, 0.5f}; + m_vAs[0] = { -0.5f, -0.5f }; + m_vAs[1] = { 0.5f, -0.5f }; + m_vAs[2] = { 0.5f, 0.5f }; + m_vAs[3] = { -0.5f, 0.5f }; m_countA = 4; m_radiusA = 0.0f; - m_vBs[0] = {0.0f, 0.0f}; + m_vBs[0] = { 0.0f, 0.0f }; m_countB = 1; m_radiusB = 0.0f; - m_transformA.p = {0.0f, 0.0f}; + m_transformA.p = { 0.0f, 0.0f }; m_transformA.q = b2Rot_identity; - m_transformB.p = {-1.0f, 0.0f}; + m_transformB.p = { -1.0f, 0.0f }; m_transformB.q = b2Rot_identity; - m_translationB = {1.0f, 0.0f}; + m_translationB = { 1.0f, 0.0f }; #elif 0 - m_vAs[0] = {0.0f, 0.0f}; + m_vAs[0] = { 0.0f, 0.0f }; m_countA = 1; m_radiusA = 0.5f; - m_vBs[0] = {0.0f, 0.0f}; + m_vBs[0] = { 0.0f, 0.0f }; m_countB = 1; m_radiusB = 0.5f; - m_transformA.p = {0.0f, 0.25f}; + m_transformA.p = { 0.0f, 0.25f }; m_transformA.q = b2Rot_identity; - m_transformB.p = {-4.0f, 0.0f}; + m_transformB.p = { -4.0f, 0.0f }; m_transformB.q = b2Rot_identity; - m_translationB = {8.0f, 0.0f}; + m_translationB = { 8.0f, 0.0f }; #else - m_vAs[0] = {0.0f, 0.0f}; - m_vAs[1] = {2.0f, 0.0f}; + m_vAs[0] = { 0.0f, 0.0f }; + m_vAs[1] = { 2.0f, 0.0f }; m_countA = 2; m_radiusA = 0.0f; - m_vBs[0] = {0.0f, 0.0f}; + m_vBs[0] = { 0.0f, 0.0f }; m_countB = 1; m_radiusB = 0.25f; // Initial overlap m_transformA.p = b2Vec2_zero; m_transformA.q = b2Rot_identity; - m_transformB.p = {-0.244360745f, 0.05999358f}; + m_transformB.p = { -0.244360745f, 0.05999358f }; m_transformB.q = b2Rot_identity; - m_translationB = {0.0f, 0.0399999991f}; + m_translationB = { 0.0f, 0.0399999991f }; #endif m_rayDrag = false; } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new ShapeCast(settings); + return new ShapeCast( settings ); } - void MouseDown(b2Vec2 p, int button, int mods) override + void MouseDown( b2Vec2 p, int button, int mods ) override { - if (button == GLFW_MOUSE_BUTTON_1) + if ( button == GLFW_MOUSE_BUTTON_1 ) { m_transformB.p = p; m_rayDrag = true; } } - void MouseUp(b2Vec2, int button) override + void MouseUp( b2Vec2, int button ) override { - if (button == GLFW_MOUSE_BUTTON_1) + if ( button == GLFW_MOUSE_BUTTON_1 ) { m_rayDrag = false; } } - void MouseMove(b2Vec2 p) override + void MouseMove( b2Vec2 p ) override { - if (m_rayDrag) + if ( m_rayDrag ) { - m_translationB = b2Sub(p, m_transformB.p); + m_translationB = b2Sub( p, m_transformB.p ); } } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - Sample::Step(settings); + Sample::Step( settings ); - b2ShapeCastPairInput input = {0}; - input.proxyA = b2MakeProxy(m_vAs, m_countA, m_radiusA); - input.proxyB = b2MakeProxy(m_vBs, m_countB, m_radiusB); + b2ShapeCastPairInput input = { 0 }; + input.proxyA = b2MakeProxy( m_vAs, m_countA, m_radiusA ); + input.proxyB = b2MakeProxy( m_vBs, m_countB, m_radiusB ); input.transformA = m_transformA; input.transformB = m_transformB; input.translationB = m_translationB; input.maxFraction = 1.0f; - b2CastOutput output = b2ShapeCast(&input); + b2CastOutput output = b2ShapeCast( &input ); b2Transform transformB2; transformB2.q = m_transformB.q; - transformB2.p = b2MulAdd(m_transformB.p, output.fraction, input.translationB); + transformB2.p = b2MulAdd( m_transformB.p, output.fraction, input.translationB ); b2DistanceInput distanceInput; - distanceInput.proxyA = b2MakeProxy(m_vAs, m_countA, m_radiusA); - distanceInput.proxyB = b2MakeProxy(m_vBs, m_countB, m_radiusB); + distanceInput.proxyA = b2MakeProxy( m_vAs, m_countA, m_radiusA ); + distanceInput.proxyB = b2MakeProxy( m_vBs, m_countB, m_radiusB ); distanceInput.transformA = m_transformA; distanceInput.transformB = transformB2; distanceInput.useRadii = false; b2DistanceCache distanceCache; distanceCache.count = 0; - b2DistanceOutput distanceOutput = b2ShapeDistance(&distanceCache, &distanceInput, nullptr, 0); + b2DistanceOutput distanceOutput = b2ShapeDistance( &distanceCache, &distanceInput, nullptr, 0 ); - g_draw.DrawString(5, m_textLine, "hit = %s, iters = %d, lambda = %g, distance = %g", output.hit ? "true" : "false", - output.iterations, output.fraction, distanceOutput.distance); + g_draw.DrawString( 5, m_textLine, "hit = %s, iters = %d, lambda = %g, distance = %g", output.hit ? "true" : "false", + output.iterations, output.fraction, distanceOutput.distance ); m_textLine += m_textIncrement; b2Vec2 vertices[b2_maxPolygonVertices]; - for (int i = 0; i < m_countA; ++i) + for ( int i = 0; i < m_countA; ++i ) { - vertices[i] = b2TransformPoint(m_transformA, m_vAs[i]); + vertices[i] = b2TransformPoint( m_transformA, m_vAs[i] ); } - if (m_countA == 1) + if ( m_countA == 1 ) { - if (m_radiusA > 0.0f) + if ( m_radiusA > 0.0f ) { - g_draw.DrawCircle(vertices[0], m_radiusA, b2_colorGray9); + g_draw.DrawCircle( vertices[0], m_radiusA, b2_colorGray9 ); } else { - g_draw.DrawPoint(vertices[0], 5.0f, b2_colorGray9); + g_draw.DrawPoint( vertices[0], 5.0f, b2_colorGray9 ); } } else { - g_draw.DrawSolidPolygon(b2Transform_identity, vertices, m_countA, m_radiusA, b2_colorGray9); + g_draw.DrawSolidPolygon( b2Transform_identity, vertices, m_countA, m_radiusA, b2_colorGray9 ); } - for (int i = 0; i < m_countB; ++i) + for ( int i = 0; i < m_countB; ++i ) { - vertices[i] = b2TransformPoint(m_transformB, m_vBs[i]); + vertices[i] = b2TransformPoint( m_transformB, m_vBs[i] ); } - if (m_countB == 1) + if ( m_countB == 1 ) { - if (m_radiusB > 0.0f) + if ( m_radiusB > 0.0f ) { - g_draw.DrawCircle(vertices[0], m_radiusB, b2_colorGreen); + g_draw.DrawCircle( vertices[0], m_radiusB, b2_colorGreen ); } else { - g_draw.DrawPoint(vertices[0], 5.0f, b2_colorGreen); + g_draw.DrawPoint( vertices[0], 5.0f, b2_colorGreen ); } } else { - g_draw.DrawSolidPolygon(b2Transform_identity, vertices, m_countB, m_radiusB, b2_colorGreen); + g_draw.DrawSolidPolygon( b2Transform_identity, vertices, m_countB, m_radiusB, b2_colorGreen ); } - for (int i = 0; i < m_countB; ++i) + for ( int i = 0; i < m_countB; ++i ) { - vertices[i] = b2TransformPoint(transformB2, m_vBs[i]); + vertices[i] = b2TransformPoint( transformB2, m_vBs[i] ); } - if (m_countB == 1) + if ( m_countB == 1 ) { - if (m_radiusB > 0.0f) + if ( m_radiusB > 0.0f ) { - g_draw.DrawCircle(vertices[0], m_radiusB, b2_colorOrange); + g_draw.DrawCircle( vertices[0], m_radiusB, b2_colorOrange ); } else { - g_draw.DrawPoint(vertices[0], 5.0f, b2_colorOrange); + g_draw.DrawPoint( vertices[0], 5.0f, b2_colorOrange ); } } else { - g_draw.DrawSolidPolygon(b2Transform_identity, vertices, m_countB, m_radiusB, b2_colorOrange); + g_draw.DrawSolidPolygon( b2Transform_identity, vertices, m_countB, m_radiusB, b2_colorOrange ); } - if (output.hit) + if ( output.hit ) { b2Vec2 p1 = output.point; - g_draw.DrawPoint(p1, 10.0f, b2_colorRed); - b2Vec2 p2 = b2MulAdd(p1, 1.0f, output.normal); - g_draw.DrawSegment(p1, p2, b2_colorRed); + g_draw.DrawPoint( p1, 10.0f, b2_colorRed ); + b2Vec2 p2 = b2MulAdd( p1, 1.0f, output.normal ); + g_draw.DrawSegment( p1, p2, b2_colorRed ); } - g_draw.DrawSegment(m_transformB.p, b2Add(m_transformB.p, m_translationB), b2_colorGray); + g_draw.DrawSegment( m_transformB.p, b2Add( m_transformB.p, m_translationB ), b2_colorGray ); } b2Vec2 m_vAs[b2_maxPolygonVertices]; @@ -3362,43 +3361,43 @@ class ShapeCast : public Sample bool m_rayDrag; }; -static int sampleShapeCast = RegisterSample("Collision", "Shape Cast", ShapeCast::Create); +static int sampleShapeCast = RegisterSample( "Collision", "Shape Cast", ShapeCast::Create ); class TimeOfImpact : public Sample { public: - explicit TimeOfImpact(Settings& settings) - : Sample(settings) + explicit TimeOfImpact( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.6f, 2.0f}; + g_camera.m_center = { 0.6f, 2.0f }; g_camera.m_zoom = 25.0f * 0.18f; } } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new TimeOfImpact(settings); + return new TimeOfImpact( settings ); } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - Sample::Step(settings); + Sample::Step( settings ); - b2Sweep sweepA = {b2Vec2_zero, {0.0f, 0.0f}, {0.0f, 0.0f}, b2Rot_identity, b2Rot_identity}; - b2Sweep sweepB = {b2Vec2_zero, {2.0f, 4.0f}, {2.0f, 4.0f}, b2Rot_identity, b2MakeRot(-0.25f * b2_pi)}; + b2Sweep sweepA = { b2Vec2_zero, { 0.0f, 0.0f }, { 0.0f, 0.0f }, b2Rot_identity, b2Rot_identity }; + b2Sweep sweepB = { b2Vec2_zero, { 2.0f, 4.0f }, { 2.0f, 4.0f }, b2Rot_identity, b2MakeRot( -0.25f * b2_pi ) }; b2TOIInput input; - input.proxyA = b2MakeProxy(m_verticesA, m_countA, 0.0f); - input.proxyB = b2MakeProxy(m_verticesB, m_countB, 0.0f); + input.proxyA = b2MakeProxy( m_verticesA, m_countA, 0.0f ); + input.proxyB = b2MakeProxy( m_verticesB, m_countB, 0.0f ); input.sweepA = sweepA; input.sweepB = sweepB; input.tMax = 1.0f; - b2TOIOutput output = b2TimeOfImpact(&input); + b2TOIOutput output = b2TimeOfImpact( &input ); - g_draw.DrawString(5, m_textLine, "toi = %g", output.t); + g_draw.DrawString( 5, m_textLine, "toi = %g", output.t ); m_textLine += m_textIncrement; // g_draw.DrawString(5, m_textLine, "max toi iters = %d, max root iters = %d", b2_toiMaxIters, @@ -3408,48 +3407,48 @@ class TimeOfImpact : public Sample b2Vec2 vertices[b2_maxPolygonVertices]; // Draw A - b2Transform transformA = b2GetSweepTransform(&sweepA, 0.0f); - for (int i = 0; i < m_countA; ++i) + b2Transform transformA = b2GetSweepTransform( &sweepA, 0.0f ); + for ( int i = 0; i < m_countA; ++i ) { - vertices[i] = b2TransformPoint(transformA, m_verticesA[i]); + vertices[i] = b2TransformPoint( transformA, m_verticesA[i] ); } - g_draw.DrawPolygon(vertices, m_countA, b2_colorGray); + g_draw.DrawPolygon( vertices, m_countA, b2_colorGray ); // Draw B at t = 0 - b2Transform transformB = b2GetSweepTransform(&sweepB, 0.0f); - for (int i = 0; i < m_countB; ++i) + b2Transform transformB = b2GetSweepTransform( &sweepB, 0.0f ); + for ( int i = 0; i < m_countB; ++i ) { - vertices[i] = b2TransformPoint(transformB, m_verticesB[i]); + vertices[i] = b2TransformPoint( transformB, m_verticesB[i] ); } - g_draw.DrawPolygon(vertices, m_countB, b2_colorGreen); + g_draw.DrawPolygon( vertices, m_countB, b2_colorGreen ); // Draw B at t = hit_time - transformB = b2GetSweepTransform(&sweepB, output.t); - for (int i = 0; i < m_countB; ++i) + transformB = b2GetSweepTransform( &sweepB, output.t ); + for ( int i = 0; i < m_countB; ++i ) { - vertices[i] = b2TransformPoint(transformB, m_verticesB[i]); + vertices[i] = b2TransformPoint( transformB, m_verticesB[i] ); } - g_draw.DrawPolygon(vertices, m_countB, b2_colorOrange); + g_draw.DrawPolygon( vertices, m_countB, b2_colorOrange ); // Draw B at t = 1 - transformB = b2GetSweepTransform(&sweepB, 1.0f); - for (int i = 0; i < m_countB; ++i) + transformB = b2GetSweepTransform( &sweepB, 1.0f ); + for ( int i = 0; i < m_countB; ++i ) { - vertices[i] = b2TransformPoint(transformB, m_verticesB[i]); + vertices[i] = b2TransformPoint( transformB, m_verticesB[i] ); } - g_draw.DrawPolygon(vertices, m_countB, b2_colorRed); + g_draw.DrawPolygon( vertices, m_countB, b2_colorRed ); - if (output.state == b2_toiStateHit) + if ( output.state == b2_toiStateHit ) { b2DistanceInput dinput; dinput.proxyA = input.proxyA; dinput.proxyB = input.proxyB; - dinput.transformA = b2GetSweepTransform(&sweepA, output.t); - dinput.transformB = b2GetSweepTransform(&sweepB, output.t); + dinput.transformA = b2GetSweepTransform( &sweepA, output.t ); + dinput.transformB = b2GetSweepTransform( &sweepB, output.t ); dinput.useRadii = false; - b2DistanceCache cache = {0}; - b2DistanceOutput doutput = b2ShapeDistance(&cache, &dinput, nullptr, 0); - g_draw.DrawString(5, m_textLine, "distance = %g", doutput.distance); + b2DistanceCache cache = { 0 }; + b2DistanceOutput doutput = b2ShapeDistance( &cache, &dinput, nullptr, 0 ); + g_draw.DrawString( 5, m_textLine, "distance = %g", doutput.distance ); m_textLine += m_textIncrement; } @@ -3466,10 +3465,10 @@ class TimeOfImpact : public Sample #endif } - b2Vec2 m_verticesA[4] = {{-1.0f, -1.0f}, {1.0f, -1.0f}, {1.0f, 5.0f}, {-1.0f, 5.0f}}; - b2Vec2 m_verticesB[4] = {{-0.5f, -4.0f}, {0.0f, -4.0f}, {0.0f, 0.0f}, {-0.5f, 0.0f}}; - int m_countA = ARRAY_COUNT(m_verticesA); - int m_countB = ARRAY_COUNT(m_verticesB); + b2Vec2 m_verticesA[4] = { { -1.0f, -1.0f }, { 1.0f, -1.0f }, { 1.0f, 5.0f }, { -1.0f, 5.0f } }; + b2Vec2 m_verticesB[4] = { { -0.5f, -4.0f }, { 0.0f, -4.0f }, { 0.0f, 0.0f }, { -0.5f, 0.0f } }; + int m_countA = ARRAY_COUNT( m_verticesA ); + int m_countB = ARRAY_COUNT( m_verticesB ); }; -static int sampleTimeOfImpact = RegisterSample("Collision", "Time of Impact", TimeOfImpact::Create); +static int sampleTimeOfImpact = RegisterSample( "Collision", "Time of Impact", TimeOfImpact::Create ); diff --git a/samples/sample_continuous.cpp b/samples/sample_continuous.cpp index 06b6dac7..14835441 100644 --- a/samples/sample_continuous.cpp +++ b/samples/sample_continuous.cpp @@ -30,37 +30,37 @@ class BounceHouse : public Sample e_boxShape }; - explicit BounceHouse(Settings& settings) - : Sample(settings) + explicit BounceHouse( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 0.0f}; + g_camera.m_center = { 0.0f, 0.0f }; g_camera.m_zoom = 25.0f * 0.45f; } b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); { - b2Segment segment = {{-10.0f, -10.0f}, {10.0f, -10.0f}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2Segment segment = { { -10.0f, -10.0f }, { 10.0f, -10.0f } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment ); } { - b2Segment segment = {{10.0f, -10.0f}, {10.0f, 10.0f}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2Segment segment = { { 10.0f, -10.0f }, { 10.0f, 10.0f } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment ); } { - b2Segment segment = {{10.0f, 10.0f}, {-10.0f, 10.0f}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2Segment segment = { { 10.0f, 10.0f }, { -10.0f, 10.0f } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment ); } { - b2Segment segment = {{-10.0f, 10.0f}, {-10.0f, -10.0f}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2Segment segment = { { -10.0f, 10.0f }, { -10.0f, -10.0f } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment ); } m_shapeType = e_circleShape; @@ -72,17 +72,17 @@ class BounceHouse : public Sample void Launch() { - if (B2_IS_NON_NULL(m_bodyId)) + if ( B2_IS_NON_NULL( m_bodyId ) ) { - b2DestroyBody(m_bodyId); + b2DestroyBody( m_bodyId ); } b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.linearVelocity = {10.0f, 20.0f}; - bodyDef.position = {0.0f, 0.0f}; + bodyDef.linearVelocity = { 10.0f, 20.0f }; + bodyDef.position = { 0.0f, 0.0f }; bodyDef.gravityScale = 0.0f; - m_bodyId = b2CreateBody(m_worldId, &bodyDef); + m_bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; @@ -90,61 +90,61 @@ class BounceHouse : public Sample shapeDef.friction = 0.3f; shapeDef.enableHitEvents = m_enableHitEvents; - if (m_shapeType == e_circleShape) + if ( m_shapeType == e_circleShape ) { - b2Circle circle = {{0.0f, 0.0f}, 0.5f}; - b2CreateCircleShape(m_bodyId, &shapeDef, &circle); + b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; + b2CreateCircleShape( m_bodyId, &shapeDef, &circle ); } - else if (m_shapeType == e_capsuleShape) + else if ( m_shapeType == e_capsuleShape ) { - b2Capsule capsule = {{-0.5f, 0.0f}, {0.5f, 0.0}, 0.25f}; - b2CreateCapsuleShape(m_bodyId, &shapeDef, &capsule); + b2Capsule capsule = { { -0.5f, 0.0f }, { 0.5f, 0.0 }, 0.25f }; + b2CreateCapsuleShape( m_bodyId, &shapeDef, &capsule ); } else { float h = 0.1f; - b2Polygon box = b2MakeBox(20.0f * h, h); - b2CreatePolygonShape(m_bodyId, &shapeDef, &box); + b2Polygon box = b2MakeBox( 20.0f * h, h ); + b2CreatePolygonShape( m_bodyId, &shapeDef, &box ); } } void UpdateUI() override { float height = 100.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(240.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); - ImGui::Begin("Bounce House", nullptr, ImGuiWindowFlags_NoResize); + ImGui::Begin( "Bounce House", nullptr, ImGuiWindowFlags_NoResize ); - const char* shapeTypes[] = {"Circle", "Capsule", "Box"}; - int shapeType = int(m_shapeType); - if (ImGui::Combo("Shape", &shapeType, shapeTypes, IM_ARRAYSIZE(shapeTypes))) + const char* shapeTypes[] = { "Circle", "Capsule", "Box" }; + int shapeType = int( m_shapeType ); + if ( ImGui::Combo( "Shape", &shapeType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ) ) { - m_shapeType = ShapeType(shapeType); + m_shapeType = ShapeType( shapeType ); Launch(); } - if (ImGui::Checkbox("hit events", &m_enableHitEvents)) + if ( ImGui::Checkbox( "hit events", &m_enableHitEvents ) ) { - b2Body_EnableHitEvents(m_bodyId, m_enableHitEvents); + b2Body_EnableHitEvents( m_bodyId, m_enableHitEvents ); } ImGui::End(); } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - Sample::Step(settings); + Sample::Step( settings ); - b2ContactEvents events = b2World_GetContactEvents(m_worldId); - for (int i = 0; i < events.hitCount; ++i) + b2ContactEvents events = b2World_GetContactEvents( m_worldId ); + for ( int i = 0; i < events.hitCount; ++i ) { b2ContactHitEvent* event = events.hitEvents + i; HitEvent* e = m_hitEvents + 0; - for (int j = 1; j < 4; ++j) + for ( int j = 1; j < 4; ++j ) { - if (m_hitEvents[j].stepIndex < e->stepIndex) + if ( m_hitEvents[j].stepIndex < e->stepIndex ) { e = m_hitEvents + j; } @@ -155,20 +155,20 @@ class BounceHouse : public Sample e->stepIndex = m_stepCount; } - for (int i = 0; i < 4; ++i) + for ( int i = 0; i < 4; ++i ) { HitEvent* e = m_hitEvents + i; - if (e->stepIndex > 0 && m_stepCount <= e->stepIndex + 30) + if ( e->stepIndex > 0 && m_stepCount <= e->stepIndex + 30 ) { - g_draw.DrawCircle(e->point, 0.1f, b2_colorOrangeRed); - g_draw.DrawString(e->point, "%.1f", e->speed); + g_draw.DrawCircle( e->point, 0.1f, b2_colorOrangeRed ); + g_draw.DrawString( e->point, "%.1f", e->speed ); } } } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new BounceHouse(settings); + return new BounceHouse( settings ); } HitEvent m_hitEvents[4]; @@ -177,32 +177,32 @@ class BounceHouse : public Sample bool m_enableHitEvents; }; -static int sampleBounceHouse = RegisterSample("Continuous", "Bounce House", BounceHouse::Create); +static int sampleBounceHouse = RegisterSample( "Continuous", "Bounce House", BounceHouse::Create ); class FastChain : public Sample { public: - explicit FastChain(Settings& settings) - : Sample(settings) + explicit FastChain( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 0.0f}; + g_camera.m_center = { 0.0f, 0.0f }; g_camera.m_zoom = 25.0f * 0.35f; } b2BodyDef bodyDef = b2DefaultBodyDef(); - bodyDef.position = {0.0f, -6.0f}; - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { 0.0f, -6.0f }; + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); - b2Vec2 points[4] = {{-10.0f, -2.0f}, {10.0f, -2.0f}, {10.0f, 1.0f}, {-10.0f, 1.0f}}; + b2Vec2 points[4] = { { -10.0f, -2.0f }, { 10.0f, -2.0f }, { 10.0f, 1.0f }, { -10.0f, 1.0f } }; b2ChainDef chainDef = b2DefaultChainDef(); chainDef.points = points; chainDef.count = 4; chainDef.isLoop = true; - b2CreateChain(groundId, &chainDef); + b2CreateChain( groundId, &chainDef ); m_bodyId = b2_nullBodyId; @@ -211,32 +211,32 @@ class FastChain : public Sample void Launch() { - if (B2_IS_NON_NULL(m_bodyId)) + if ( B2_IS_NON_NULL( m_bodyId ) ) { - b2DestroyBody(m_bodyId); + b2DestroyBody( m_bodyId ); } b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.linearVelocity = {0.0f, -200.0f}; - bodyDef.position = {0.0f, 10.0f}; + bodyDef.linearVelocity = { 0.0f, -200.0f }; + bodyDef.position = { 0.0f, 10.0f }; bodyDef.gravityScale = 1.0f; - m_bodyId = b2CreateBody(m_worldId, &bodyDef); + m_bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Circle circle = {{0.0f, 0.0f}, 0.5f}; - b2CreateCircleShape(m_bodyId, &shapeDef, &circle); + b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; + b2CreateCircleShape( m_bodyId, &shapeDef, &circle ); } void UpdateUI() override { float height = 70.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(240.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); - ImGui::Begin("Fast Chain", nullptr, ImGuiWindowFlags_NoResize); + ImGui::Begin( "Fast Chain", nullptr, ImGuiWindowFlags_NoResize ); - if (ImGui::Button("Launch")) + if ( ImGui::Button( "Launch" ) ) { Launch(); } @@ -244,39 +244,39 @@ class FastChain : public Sample ImGui::End(); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new FastChain(settings); + return new FastChain( settings ); } b2BodyId m_bodyId; }; -static int sampleFastChainHouse = RegisterSample("Continuous", "Fast Chain", FastChain::Create); +static int sampleFastChainHouse = RegisterSample( "Continuous", "Fast Chain", FastChain::Create ); class SkinnyBox : public Sample { public: - explicit SkinnyBox(Settings& settings) - : Sample(settings) + explicit SkinnyBox( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {1.0f, 5.0f}; + g_camera.m_center = { 1.0f, 5.0f }; g_camera.m_zoom = 25.0f * 0.25f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); - b2Segment segment = {{-10.0f, 0.0f}, {10.0f, 0.0f}}; + b2Segment segment = { { -10.0f, 0.0f }, { 10.0f, 0.0f } }; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.friction = 0.9f; - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2CreateSegmentShape( groundId, &shapeDef, &segment ); - b2Polygon box = b2MakeOffsetBox(0.1f, 1.0f, {0.0f, 1.0f}, 0.0f); - b2CreatePolygonShape(groundId, &shapeDef, &box); + b2Polygon box = b2MakeOffsetBox( 0.1f, 1.0f, { 0.0f, 1.0f }, 0.0f ); + b2CreatePolygonShape( groundId, &shapeDef, &box ); } m_autoTest = false; @@ -291,86 +291,86 @@ class SkinnyBox : public Sample void Launch() { - if (B2_IS_NON_NULL(m_bodyId)) + if ( B2_IS_NON_NULL( m_bodyId ) ) { - b2DestroyBody(m_bodyId); + b2DestroyBody( m_bodyId ); } - if (B2_IS_NON_NULL(m_bulletId)) + if ( B2_IS_NON_NULL( m_bulletId ) ) { - b2DestroyBody(m_bulletId); + b2DestroyBody( m_bulletId ); } - m_angularVelocity = RandomFloat(-50.0f, 50.0f); + m_angularVelocity = RandomFloat( -50.0f, 50.0f ); // m_angularVelocity = -30.6695766f; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {0.0f, 8.0f}; + bodyDef.position = { 0.0f, 8.0f }; bodyDef.angularVelocity = m_angularVelocity; - bodyDef.linearVelocity = {0.0f, -100.0f}; + bodyDef.linearVelocity = { 0.0f, -100.0f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; shapeDef.friction = 0.9f; - m_bodyId = b2CreateBody(m_worldId, &bodyDef); + m_bodyId = b2CreateBody( m_worldId, &bodyDef ); - if (m_capsule) + if ( m_capsule ) { - b2Capsule capsule = {{0.0f, -1.0f}, {0.0f, 1.0f}, 0.1f}; - b2CreateCapsuleShape(m_bodyId, &shapeDef, &capsule); + b2Capsule capsule = { { 0.0f, -1.0f }, { 0.0f, 1.0f }, 0.1f }; + b2CreateCapsuleShape( m_bodyId, &shapeDef, &capsule ); } else { - b2Polygon polygon = b2MakeBox(2.0f, 0.05f); - b2CreatePolygonShape(m_bodyId, &shapeDef, &polygon); + b2Polygon polygon = b2MakeBox( 2.0f, 0.05f ); + b2CreatePolygonShape( m_bodyId, &shapeDef, &polygon ); } - if (m_bullet) + if ( m_bullet ) { - b2Polygon polygon = b2MakeBox(0.25f, 0.25f); - m_x = RandomFloat(-1.0f, 1.0f); - bodyDef.position = {m_x, 10.0f}; - bodyDef.linearVelocity = {0.0f, -50.0f}; - m_bulletId = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(m_bulletId, &shapeDef, &polygon); + b2Polygon polygon = b2MakeBox( 0.25f, 0.25f ); + m_x = RandomFloat( -1.0f, 1.0f ); + bodyDef.position = { m_x, 10.0f }; + bodyDef.linearVelocity = { 0.0f, -50.0f }; + m_bulletId = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( m_bulletId, &shapeDef, &polygon ); } } void UpdateUI() override { float height = 110.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(140.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 140.0f, height ) ); - ImGui::Begin("Skinny Box", nullptr, ImGuiWindowFlags_NoResize); + ImGui::Begin( "Skinny Box", nullptr, ImGuiWindowFlags_NoResize ); - ImGui::Checkbox("Capsule", &m_capsule); + ImGui::Checkbox( "Capsule", &m_capsule ); - if (ImGui::Button("Launch")) + if ( ImGui::Button( "Launch" ) ) { Launch(); } - ImGui::Checkbox("Auto Test", &m_autoTest); + ImGui::Checkbox( "Auto Test", &m_autoTest ); ImGui::End(); } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - Sample::Step(settings); + Sample::Step( settings ); - if (m_autoTest && m_stepCount % 60 == 0) + if ( m_autoTest && m_stepCount % 60 == 0 ) { Launch(); } } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new SkinnyBox(settings); + return new SkinnyBox( settings ); } b2BodyId m_bodyId, m_bulletId; @@ -381,7 +381,7 @@ class SkinnyBox : public Sample bool m_bullet; }; -static int sampleSkinnyBox = RegisterSample("Continuous", "Skinny Box", SkinnyBox::Create); +static int sampleSkinnyBox = RegisterSample( "Continuous", "Skinny Box", SkinnyBox::Create ); // This sample shows ghost collisions class GhostCollision : public Sample @@ -394,12 +394,12 @@ class GhostCollision : public Sample e_boxShape }; - explicit GhostCollision(Settings& settings) - : Sample(settings) + explicit GhostCollision( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {1.5f, 16.0f}; + g_camera.m_center = { 1.5f, 16.0f }; g_camera.m_zoom = 25.0f * 0.8f; } @@ -418,43 +418,45 @@ class GhostCollision : public Sample void CreateScene() { - if (B2_IS_NON_NULL(m_groundId)) + if ( B2_IS_NON_NULL( m_groundId ) ) { - b2DestroyBody(m_groundId); + b2DestroyBody( m_groundId ); } m_shapeId = b2_nullShapeId; b2BodyDef bodyDef = b2DefaultBodyDef(); - m_groundId = b2CreateBody(m_worldId, &bodyDef); + m_groundId = b2CreateBody( m_worldId, &bodyDef ); - float m = 1.0f / sqrt(2.0f); - float mm = 2.0f * (sqrt(2.0f) - 1.0f); + float m = 1.0f / sqrt( 2.0f ); + float mm = 2.0f * ( sqrt( 2.0f ) - 1.0f ); float hx = 4.0f, hy = 0.25f; - if (m_useChain) + if ( m_useChain ) { b2Vec2 points[20]; - points[0] = {-3.0f * hx, hy}; - points[1] = b2Add(points[0], {-2.0f * hx * m, 2.0f * hx * m}); - points[2] = b2Add(points[1], {-2.0f * hx * m, 2.0f * hx * m}); - points[3] = b2Add(points[2], {-2.0f * hx * m, 2.0f * hx * m}); - points[4] = b2Add(points[3], {-2.0f * hy * m, -2.0f * hy * m}); - points[5] = b2Add(points[4], {2.0f * hx * m, -2.0f * hx * m}); - points[6] = b2Add(points[5], {2.0f * hx * m, -2.0f * hx * m}); - points[7] = b2Add(points[6], {2.0f * hx * m + 2.0f * hy * (1.0f - m), -2.0f * hx * m - 2.0f * hy * (1.0f - m)}); - points[8] = b2Add(points[7], {2.0f * hx + hy * mm, 0.0f}); - points[9] = b2Add(points[8], {2.0f * hx, 0.0f}); - points[10] = b2Add(points[9], {2.0f * hx + hy * mm, 0.0f}); - points[11] = b2Add(points[10], {2.0f * hx * m + 2.0f * hy * (1.0f - m), 2.0f * hx * m + 2.0f * hy * (1.0f - m)}); - points[12] = b2Add(points[11], {2.0f * hx * m, 2.0f * hx * m}); - points[13] = b2Add(points[12], {2.0f * hx * m, 2.0f * hx * m}); - points[14] = b2Add(points[13], {-2.0f * hy * m, 2.0f * hy * m}); - points[15] = b2Add(points[14], {-2.0f * hx * m, -2.0f * hx * m}); - points[16] = b2Add(points[15], {-2.0f * hx * m, -2.0f * hx * m}); - points[17] = b2Add(points[16], {-2.0f * hx * m, -2.0f * hx * m}); - points[18] = b2Add(points[17], {-2.0f * hx, 0.0f}); - points[19] = b2Add(points[18], {-2.0f * hx, 0.0f}); + points[0] = { -3.0f * hx, hy }; + points[1] = b2Add( points[0], { -2.0f * hx * m, 2.0f * hx * m } ); + points[2] = b2Add( points[1], { -2.0f * hx * m, 2.0f * hx * m } ); + points[3] = b2Add( points[2], { -2.0f * hx * m, 2.0f * hx * m } ); + points[4] = b2Add( points[3], { -2.0f * hy * m, -2.0f * hy * m } ); + points[5] = b2Add( points[4], { 2.0f * hx * m, -2.0f * hx * m } ); + points[6] = b2Add( points[5], { 2.0f * hx * m, -2.0f * hx * m } ); + points[7] = + b2Add( points[6], { 2.0f * hx * m + 2.0f * hy * ( 1.0f - m ), -2.0f * hx * m - 2.0f * hy * ( 1.0f - m ) } ); + points[8] = b2Add( points[7], { 2.0f * hx + hy * mm, 0.0f } ); + points[9] = b2Add( points[8], { 2.0f * hx, 0.0f } ); + points[10] = b2Add( points[9], { 2.0f * hx + hy * mm, 0.0f } ); + points[11] = + b2Add( points[10], { 2.0f * hx * m + 2.0f * hy * ( 1.0f - m ), 2.0f * hx * m + 2.0f * hy * ( 1.0f - m ) } ); + points[12] = b2Add( points[11], { 2.0f * hx * m, 2.0f * hx * m } ); + points[13] = b2Add( points[12], { 2.0f * hx * m, 2.0f * hx * m } ); + points[14] = b2Add( points[13], { -2.0f * hy * m, 2.0f * hy * m } ); + points[15] = b2Add( points[14], { -2.0f * hx * m, -2.0f * hx * m } ); + points[16] = b2Add( points[15], { -2.0f * hx * m, -2.0f * hx * m } ); + points[17] = b2Add( points[16], { -2.0f * hx * m, -2.0f * hx * m } ); + points[18] = b2Add( points[17], { -2.0f * hx, 0.0f } ); + points[19] = b2Add( points[18], { -2.0f * hx, 0.0f } ); b2ChainDef chainDef = b2DefaultChainDef(); chainDef.points = points; @@ -462,26 +464,26 @@ class GhostCollision : public Sample chainDef.isLoop = true; chainDef.friction = m_friction; - b2CreateChain(m_groundId, &chainDef); + b2CreateChain( m_groundId, &chainDef ); } else { b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.friction = m_friction; - b2Hull hull = {0}; + b2Hull hull = { 0 }; - if (m_bevel > 0.0f) + if ( m_bevel > 0.0f ) { float hb = m_bevel; - b2Vec2 vs[8] = {{hx + hb, hy - 0.05f}, {hx, hy}, {-hx, hy}, {-hx - hb, hy - 0.05f}, - {-hx - hb, -hy + 0.05f}, {-hx, -hy}, {hx, -hy}, {hx + hb, -hy + 0.05f}}; - hull = b2ComputeHull(vs, 8); + b2Vec2 vs[8] = { { hx + hb, hy - 0.05f }, { hx, hy }, { -hx, hy }, { -hx - hb, hy - 0.05f }, + { -hx - hb, -hy + 0.05f }, { -hx, -hy }, { hx, -hy }, { hx + hb, -hy + 0.05f } }; + hull = b2ComputeHull( vs, 8 ); } else { - b2Vec2 vs[4] = {{hx, hy}, {-hx, hy}, {-hx, -hy}, {hx, -hy}}; - hull = b2ComputeHull(vs, 4); + b2Vec2 vs[4] = { { hx, hy }, { -hx, hy }, { -hx, -hy }, { hx, -hy } }; + hull = b2ComputeHull( vs, 4 ); } b2Transform transform; @@ -490,75 +492,75 @@ class GhostCollision : public Sample // Left slope x = -3.0f * hx - m * hx - m * hy; y = hy + m * hx - m * hy; - transform.q = b2MakeRot(-0.25f * b2_pi); + transform.q = b2MakeRot( -0.25f * b2_pi ); { - transform.p = {x, y}; - b2Polygon polygon = b2MakeOffsetPolygon(&hull, 0.0f, transform); - b2CreatePolygonShape(m_groundId, &shapeDef, &polygon); + transform.p = { x, y }; + b2Polygon polygon = b2MakeOffsetPolygon( &hull, 0.0f, transform ); + b2CreatePolygonShape( m_groundId, &shapeDef, &polygon ); x -= 2.0f * m * hx; y += 2.0f * m * hx; } { - transform.p = {x, y}; - b2Polygon polygon = b2MakeOffsetPolygon(&hull, 0.0f, transform); - b2CreatePolygonShape(m_groundId, &shapeDef, &polygon); + transform.p = { x, y }; + b2Polygon polygon = b2MakeOffsetPolygon( &hull, 0.0f, transform ); + b2CreatePolygonShape( m_groundId, &shapeDef, &polygon ); x -= 2.0f * m * hx; y += 2.0f * m * hx; } { - transform.p = {x, y}; - b2Polygon polygon = b2MakeOffsetPolygon(&hull, 0.0f, transform); - b2CreatePolygonShape(m_groundId, &shapeDef, &polygon); + transform.p = { x, y }; + b2Polygon polygon = b2MakeOffsetPolygon( &hull, 0.0f, transform ); + b2CreatePolygonShape( m_groundId, &shapeDef, &polygon ); x -= 2.0f * m * hx; y += 2.0f * m * hx; } x = -2.0f * hx; y = 0.0f; - transform.q = b2MakeRot(0.0f); + transform.q = b2MakeRot( 0.0f ); { - transform.p = {x, y}; - b2Polygon polygon = b2MakeOffsetPolygon(&hull, 0.0f, transform); - b2CreatePolygonShape(m_groundId, &shapeDef, &polygon); + transform.p = { x, y }; + b2Polygon polygon = b2MakeOffsetPolygon( &hull, 0.0f, transform ); + b2CreatePolygonShape( m_groundId, &shapeDef, &polygon ); x += 2.0f * hx; } { - transform.p = {x, y}; - b2Polygon polygon = b2MakeOffsetPolygon(&hull, 0.0f, transform); - b2CreatePolygonShape(m_groundId, &shapeDef, &polygon); + transform.p = { x, y }; + b2Polygon polygon = b2MakeOffsetPolygon( &hull, 0.0f, transform ); + b2CreatePolygonShape( m_groundId, &shapeDef, &polygon ); x += 2.0f * hx; } { - transform.p = {x, y}; - b2Polygon polygon = b2MakeOffsetPolygon(&hull, 0.0f, transform); - b2CreatePolygonShape(m_groundId, &shapeDef, &polygon); + transform.p = { x, y }; + b2Polygon polygon = b2MakeOffsetPolygon( &hull, 0.0f, transform ); + b2CreatePolygonShape( m_groundId, &shapeDef, &polygon ); x += 2.0f * hx; } x = 3.0f * hx + m * hx + m * hy; y = hy + m * hx - m * hy; - transform.q = b2MakeRot(0.25f * b2_pi); + transform.q = b2MakeRot( 0.25f * b2_pi ); { - transform.p = {x, y}; - b2Polygon polygon = b2MakeOffsetPolygon(&hull, 0.0f, transform); - b2CreatePolygonShape(m_groundId, &shapeDef, &polygon); + transform.p = { x, y }; + b2Polygon polygon = b2MakeOffsetPolygon( &hull, 0.0f, transform ); + b2CreatePolygonShape( m_groundId, &shapeDef, &polygon ); x += 2.0f * m * hx; y += 2.0f * m * hx; } { - transform.p = {x, y}; - b2Polygon polygon = b2MakeOffsetPolygon(&hull, 0.0f, transform); - b2CreatePolygonShape(m_groundId, &shapeDef, &polygon); + transform.p = { x, y }; + b2Polygon polygon = b2MakeOffsetPolygon( &hull, 0.0f, transform ); + b2CreatePolygonShape( m_groundId, &shapeDef, &polygon ); x += 2.0f * m * hx; y += 2.0f * m * hx; } { - transform.p = {x, y}; - b2Polygon polygon = b2MakeOffsetPolygon(&hull, 0.0f, transform); - b2CreatePolygonShape(m_groundId, &shapeDef, &polygon); + transform.p = { x, y }; + b2Polygon polygon = b2MakeOffsetPolygon( &hull, 0.0f, transform ); + b2CreatePolygonShape( m_groundId, &shapeDef, &polygon ); x += 2.0f * m * hx; y += 2.0f * m * hx; } @@ -567,85 +569,85 @@ class GhostCollision : public Sample void Launch() { - if (B2_IS_NON_NULL(m_bodyId)) + if ( B2_IS_NON_NULL( m_bodyId ) ) { - b2DestroyBody(m_bodyId); + b2DestroyBody( m_bodyId ); m_shapeId = b2_nullShapeId; } b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {-28.0f, 18.0f}; - bodyDef.linearVelocity = {0.0f, 0.0f}; - m_bodyId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { -28.0f, 18.0f }; + bodyDef.linearVelocity = { 0.0f, 0.0f }; + m_bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; shapeDef.friction = m_friction; - if (m_shapeType == e_circleShape) + if ( m_shapeType == e_circleShape ) { - b2Circle circle = {{0.0f, 0.0f}, 0.5f}; - m_shapeId = b2CreateCircleShape(m_bodyId, &shapeDef, &circle); + b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; + m_shapeId = b2CreateCircleShape( m_bodyId, &shapeDef, &circle ); } - else if (m_shapeType == e_capsuleShape) + else if ( m_shapeType == e_capsuleShape ) { - b2Capsule capsule = {{-0.5f, 0.0f}, {0.5f, 0.0}, 0.25f}; - m_shapeId = b2CreateCapsuleShape(m_bodyId, &shapeDef, &capsule); + b2Capsule capsule = { { -0.5f, 0.0f }, { 0.5f, 0.0 }, 0.25f }; + m_shapeId = b2CreateCapsuleShape( m_bodyId, &shapeDef, &capsule ); } else { float h = 0.5f - m_round; - b2Polygon box = b2MakeRoundedBox(h, 2.0f * h, m_round); - m_shapeId = b2CreatePolygonShape(m_bodyId, &shapeDef, &box); + b2Polygon box = b2MakeRoundedBox( h, 2.0f * h, m_round ); + m_shapeId = b2CreatePolygonShape( m_bodyId, &shapeDef, &box ); } } void UpdateUI() override { float height = 140.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(180.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 180.0f, height ) ); - ImGui::Begin("Ghost Collision", nullptr, ImGuiWindowFlags_NoResize); - ImGui::PushItemWidth(100.0f); + ImGui::Begin( "Ghost Collision", nullptr, ImGuiWindowFlags_NoResize ); + ImGui::PushItemWidth( 100.0f ); - if (ImGui::Checkbox("Chain", &m_useChain)) + if ( ImGui::Checkbox( "Chain", &m_useChain ) ) { CreateScene(); } - if (m_useChain == false) + if ( m_useChain == false ) { - if (ImGui::SliderFloat("Bevel", &m_bevel, 0.0f, 1.0f, "%.2f")) + if ( ImGui::SliderFloat( "Bevel", &m_bevel, 0.0f, 1.0f, "%.2f" ) ) { CreateScene(); } } { - const char* shapeTypes[] = {"Circle", "Capsule", "Box"}; - int shapeType = int(m_shapeType); - ImGui::Combo("Shape", &shapeType, shapeTypes, IM_ARRAYSIZE(shapeTypes)); - m_shapeType = ShapeType(shapeType); + const char* shapeTypes[] = { "Circle", "Capsule", "Box" }; + int shapeType = int( m_shapeType ); + ImGui::Combo( "Shape", &shapeType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ); + m_shapeType = ShapeType( shapeType ); } - if (m_shapeType == e_boxShape) + if ( m_shapeType == e_boxShape ) { - ImGui::SliderFloat("Round", &m_round, 0.0f, 0.4f, "%.1f"); + ImGui::SliderFloat( "Round", &m_round, 0.0f, 0.4f, "%.1f" ); } - if (ImGui::SliderFloat("Friction", &m_friction, 0.0f, 1.0f, "%.1f")) + if ( ImGui::SliderFloat( "Friction", &m_friction, 0.0f, 1.0f, "%.1f" ) ) { - if (B2_IS_NON_NULL(m_shapeId)) + if ( B2_IS_NON_NULL( m_shapeId ) ) { - b2Shape_SetFriction(m_shapeId, m_friction); + b2Shape_SetFriction( m_shapeId, m_friction ); } CreateScene(); } - if (ImGui::Button("Launch")) + if ( ImGui::Button( "Launch" ) ) { Launch(); } @@ -654,9 +656,9 @@ class GhostCollision : public Sample ImGui::End(); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new GhostCollision(settings); + return new GhostCollision( settings ); } b2BodyId m_groundId; @@ -669,34 +671,34 @@ class GhostCollision : public Sample bool m_useChain; }; -static int sampleGhostCollision = RegisterSample("Continuous", "Ghost Collision", GhostCollision::Create); +static int sampleGhostCollision = RegisterSample( "Continuous", "Ghost Collision", GhostCollision::Create ); // Speculative collision failure case suggested by Dirk Gregorius. This uses // a simple fallback scheme to prevent tunneling. class SpeculativeFallback : public Sample { public: - explicit SpeculativeFallback(Settings& settings) - : Sample(settings) + explicit SpeculativeFallback( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {1.0f, 5.0f}; + g_camera.m_center = { 1.0f, 5.0f }; g_camera.m_zoom = 25.0f * 0.25f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Segment segment = {{-10.0f, 0.0f}, {10.0f, 0.0f}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2Segment segment = { { -10.0f, 0.0f }, { 10.0f, 0.0f } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment ); - b2Vec2 points[5] = {{-2.0f, 4.0f}, {2.0f, 4.0f}, {2.0f, 4.1f}, {-0.5f, 4.2f}, {-2.0f, 4.2f}}; - b2Hull hull = b2ComputeHull(points, 5); - b2Polygon poly = b2MakePolygon(&hull, 0.0f); - b2CreatePolygonShape(groundId, &shapeDef, &poly); + b2Vec2 points[5] = { { -2.0f, 4.0f }, { 2.0f, 4.0f }, { 2.0f, 4.1f }, { -0.5f, 4.2f }, { -2.0f, 4.2f } }; + b2Hull hull = b2ComputeHull( points, 5 ); + b2Polygon poly = b2MakePolygon( &hull, 0.0f ); + b2CreatePolygonShape( groundId, &shapeDef, &poly ); } // Fast moving skinny box. Also testing a large shape offset. @@ -704,35 +706,35 @@ class SpeculativeFallback : public Sample float offset = 8.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {offset, 12.0f}; - bodyDef.linearVelocity = {0.0f, -100.0f}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { offset, 12.0f }; + bodyDef.linearVelocity = { 0.0f, -100.0f }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Polygon box = b2MakeOffsetBox(2.0f, 0.05f, {-offset, 0.0f}, b2_pi); - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2Polygon box = b2MakeOffsetBox( 2.0f, 0.05f, { -offset, 0.0f }, b2_pi ); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); } } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new SpeculativeFallback(settings); + return new SpeculativeFallback( settings ); } }; -static int sampleSpeculativeFallback = RegisterSample("Continuous", "Speculative Fallback", SpeculativeFallback::Create); +static int sampleSpeculativeFallback = RegisterSample( "Continuous", "Speculative Fallback", SpeculativeFallback::Create ); // This shows a fast moving body that uses continuous collision versus static and dynamic bodies. // This is achieved by setting the ball body as a *bullet*. class Pinball : public Sample { public: - explicit Pinball(Settings& settings) - : Sample(settings) + explicit Pinball( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 9.0f}; + g_camera.m_center = { 0.0f, 9.0f }; g_camera.m_zoom = 25.0f * 0.5f; } @@ -742,37 +744,37 @@ class Pinball : public Sample b2BodyId groundId = {}; { b2BodyDef bodyDef = b2DefaultBodyDef(); - groundId = b2CreateBody(m_worldId, &bodyDef); + groundId = b2CreateBody( m_worldId, &bodyDef ); - b2Vec2 vs[5] = {{-8.0f, 6.0f}, {-8.0f, 20.0f}, {8.0f, 20.0f}, {8.0f, 6.0f}, {0.0f, -2.0f}}; + b2Vec2 vs[5] = { { -8.0f, 6.0f }, { -8.0f, 20.0f }, { 8.0f, 20.0f }, { 8.0f, 6.0f }, { 0.0f, -2.0f } }; b2ChainDef chainDef = b2DefaultChainDef(); chainDef.points = vs; chainDef.count = 5; chainDef.isLoop = true; - b2CreateChain(groundId, &chainDef); + b2CreateChain( groundId, &chainDef ); } // Flippers { - b2Vec2 p1 = {-2.0f, 0.0f}, p2 = {2.0f, 0.0f}; + b2Vec2 p1 = { -2.0f, 0.0f }, p2 = { 2.0f, 0.0f }; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.enableSleep = false; bodyDef.position = p1; - b2BodyId leftFlipperId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId leftFlipperId = b2CreateBody( m_worldId, &bodyDef ); bodyDef.position = p2; - b2BodyId rightFlipperId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId rightFlipperId = b2CreateBody( m_worldId, &bodyDef ); - b2Polygon box = b2MakeBox(1.75f, 0.2f); + b2Polygon box = b2MakeBox( 1.75f, 0.2f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreatePolygonShape(leftFlipperId, &shapeDef, &box); - b2CreatePolygonShape(rightFlipperId, &shapeDef, &box); + b2CreatePolygonShape( leftFlipperId, &shapeDef, &box ); + b2CreatePolygonShape( rightFlipperId, &shapeDef, &box ); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.bodyIdA = groundId; @@ -786,30 +788,30 @@ class Pinball : public Sample jointDef.bodyIdB = leftFlipperId; jointDef.lowerAngle = -30.0f * b2_pi / 180.0f; jointDef.upperAngle = 5.0f * b2_pi / 180.0f; - m_leftJointId = b2CreateRevoluteJoint(m_worldId, &jointDef); + m_leftJointId = b2CreateRevoluteJoint( m_worldId, &jointDef ); jointDef.motorSpeed = 0.0f; jointDef.localAnchorA = p2; jointDef.bodyIdB = rightFlipperId; jointDef.lowerAngle = -5.0f * b2_pi / 180.0f; jointDef.upperAngle = 30.0f * b2_pi / 180.0f; - m_rightJointId = b2CreateRevoluteJoint(m_worldId, &jointDef); + m_rightJointId = b2CreateRevoluteJoint( m_worldId, &jointDef ); } // Spinners { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {-4.0f, 17.0f}; + bodyDef.position = { -4.0f, 17.0f }; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Polygon box1 = b2MakeBox(1.5f, 0.125f); - b2Polygon box2 = b2MakeBox(0.125f, 1.5f); + b2Polygon box1 = b2MakeBox( 1.5f, 0.125f ); + b2Polygon box2 = b2MakeBox( 0.125f, 1.5f ); - b2CreatePolygonShape(bodyId, &shapeDef, &box1); - b2CreatePolygonShape(bodyId, &shapeDef, &box2); + b2CreatePolygonShape( bodyId, &shapeDef, &box1 ); + b2CreatePolygonShape( bodyId, &shapeDef, &box2 ); b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.bodyIdA = groundId; @@ -818,69 +820,69 @@ class Pinball : public Sample jointDef.localAnchorB = b2Vec2_zero; jointDef.enableMotor = true; jointDef.maxMotorTorque = 0.1f; - b2CreateRevoluteJoint(m_worldId, &jointDef); + b2CreateRevoluteJoint( m_worldId, &jointDef ); - bodyDef.position = {4.0f, 8.0f}; - bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &box1); - b2CreatePolygonShape(bodyId, &shapeDef, &box2); + bodyDef.position = { 4.0f, 8.0f }; + bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &box1 ); + b2CreatePolygonShape( bodyId, &shapeDef, &box2 ); jointDef.localAnchorA = bodyDef.position; jointDef.bodyIdB = bodyId; - b2CreateRevoluteJoint(m_worldId, &jointDef); + b2CreateRevoluteJoint( m_worldId, &jointDef ); } // Bumpers { b2BodyDef bodyDef = b2DefaultBodyDef(); - bodyDef.position = {-4.0f, 8.0f}; + bodyDef.position = { -4.0f, 8.0f }; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.restitution = 1.5f; - b2Circle circle = {{0.0f, 0.0f}, 1.0f}; - b2CreateCircleShape(bodyId, &shapeDef, &circle); + b2Circle circle = { { 0.0f, 0.0f }, 1.0f }; + b2CreateCircleShape( bodyId, &shapeDef, &circle ); - bodyDef.position = {4.0f, 17.0f}; - bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreateCircleShape(bodyId, &shapeDef, &circle); + bodyDef.position = { 4.0f, 17.0f }; + bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreateCircleShape( bodyId, &shapeDef, &circle ); } // Ball { b2BodyDef bodyDef = b2DefaultBodyDef(); - bodyDef.position = {1.0f, 15.0f}; + bodyDef.position = { 1.0f, 15.0f }; bodyDef.type = b2_dynamicBody; bodyDef.isBullet = true; - m_ballId = b2CreateBody(m_worldId, &bodyDef); + m_ballId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Circle circle = {{0.0f, 0.0f}, 0.2f}; - b2CreateCircleShape(m_ballId, &shapeDef, &circle); + b2Circle circle = { { 0.0f, 0.0f }, 0.2f }; + b2CreateCircleShape( m_ballId, &shapeDef, &circle ); } } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - Sample::Step(settings); + Sample::Step( settings ); - if (glfwGetKey(g_mainWindow, GLFW_KEY_SPACE) == GLFW_PRESS) + if ( glfwGetKey( g_mainWindow, GLFW_KEY_SPACE ) == GLFW_PRESS ) { - b2RevoluteJoint_SetMotorSpeed(m_leftJointId, 20.0f); - b2RevoluteJoint_SetMotorSpeed(m_rightJointId, -20.0f); + b2RevoluteJoint_SetMotorSpeed( m_leftJointId, 20.0f ); + b2RevoluteJoint_SetMotorSpeed( m_rightJointId, -20.0f ); } else { - b2RevoluteJoint_SetMotorSpeed(m_leftJointId, -10.0f); - b2RevoluteJoint_SetMotorSpeed(m_rightJointId, 10.0f); + b2RevoluteJoint_SetMotorSpeed( m_leftJointId, -10.0f ); + b2RevoluteJoint_SetMotorSpeed( m_rightJointId, 10.0f ); } } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new Pinball(settings); + return new Pinball( settings ); } b2JointId m_leftJointId; @@ -888,4 +890,4 @@ class Pinball : public Sample b2BodyId m_ballId; }; -static int samplePinball = RegisterSample("Continuous", "Pinball", Pinball::Create); +static int samplePinball = RegisterSample( "Continuous", "Pinball", Pinball::Create ); diff --git a/samples/sample_events.cpp b/samples/sample_events.cpp index e05f8534..8d2fa303 100644 --- a/samples/sample_events.cpp +++ b/samples/sample_events.cpp @@ -23,20 +23,20 @@ class SensorEvent : public Sample e_count = 32 }; - explicit SensorEvent(Settings& settings) - : Sample(settings) + explicit SensorEvent( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 0.0f}; + g_camera.m_center = { 0.0f, 0.0f }; g_camera.m_zoom = 25.0f * 1.333f; } - + settings.drawJoints = false; { b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); // b2Vec2 points[] = { //{42.333, 44.979}, {177.271, 44.979}, {177.271, 100.542}, {142.875, 121.708}, {177.271, 121.708}, @@ -46,14 +46,16 @@ class SensorEvent : public Sample //}; b2Vec2 points[] = { - {-16.8672504, 31.088623}, {16.8672485, 31.088623}, {16.8672485, 17.1978741}, {8.26824951, 11.906374}, - {16.8672485, 11.906374}, {16.8672485, -0.661376953}, {8.26824951, -5.953125}, {16.8672485, -5.953125}, - {16.8672485, -13.229126}, {3.63799858, -23.151123}, {3.63799858, -31.088623}, {-3.63800049, -31.088623}, - {-3.63800049, -23.151123}, {-16.8672504, -13.229126}, {-16.8672504, -5.953125}, {-8.26825142, -5.953125}, - {-16.8672504, -0.661376953}, {-16.8672504, 11.906374}, {-8.26825142, 11.906374}, {-16.8672504, 17.1978741}, + { -16.8672504, 31.088623 }, { 16.8672485, 31.088623 }, { 16.8672485, 17.1978741 }, + { 8.26824951, 11.906374 }, { 16.8672485, 11.906374 }, { 16.8672485, -0.661376953 }, + { 8.26824951, -5.953125 }, { 16.8672485, -5.953125 }, { 16.8672485, -13.229126 }, + { 3.63799858, -23.151123 }, { 3.63799858, -31.088623 }, { -3.63800049, -31.088623 }, + { -3.63800049, -23.151123 }, { -16.8672504, -13.229126 }, { -16.8672504, -5.953125 }, + { -8.26825142, -5.953125 }, { -16.8672504, -0.661376953 }, { -16.8672504, 11.906374 }, + { -8.26825142, 11.906374 }, { -16.8672504, 17.1978741 }, }; - int count = sizeof(points) / sizeof(points[0]); + int count = sizeof( points ) / sizeof( points[0] ); // float scale = 0.25f; // b2Vec2 lower = {FLT_MAX, FLT_MAX}; @@ -92,25 +94,25 @@ class SensorEvent : public Sample chainDef.count = count; chainDef.isLoop = true; chainDef.friction = 0.2f; - b2CreateChain(groundId, &chainDef); + b2CreateChain( groundId, &chainDef ); float sign = 1.0f; float y = 14.0f; - for (int i = 0; i < 3; ++i) + for ( int i = 0; i < 3; ++i ) { b2BodyDef bodyDef = b2DefaultBodyDef(); - bodyDef.position = {0.0f, y}; + bodyDef.position = { 0.0f, y }; bodyDef.type = b2_dynamicBody; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); - b2Polygon box = b2MakeBox(6.0f, 0.5f); + b2Polygon box = b2MakeBox( 6.0f, 0.5f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.friction = 0.1f; shapeDef.restitution = 1.0f; shapeDef.density = 1.0f; - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); b2RevoluteJointDef revoluteDef = b2DefaultRevoluteJointDef(); revoluteDef.bodyIdA = groundId; @@ -121,17 +123,17 @@ class SensorEvent : public Sample revoluteDef.motorSpeed = 2.0f * sign; revoluteDef.enableMotor = true; - b2CreateRevoluteJoint(m_worldId, &revoluteDef); + b2CreateRevoluteJoint( m_worldId, &revoluteDef ); y -= 14.0f; sign = -sign; } { - b2Polygon box = b2MakeOffsetBox(4.0f, 1.0f, {0.0f, -30.5f}, 0.0f); + b2Polygon box = b2MakeOffsetBox( 4.0f, 1.0f, { 0.0f, -30.5f }, 0.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.isSensor = true; - b2CreatePolygonShape(groundId, &shapeDef, &box); + b2CreatePolygonShape( groundId, &shapeDef, &box ); } } @@ -139,7 +141,7 @@ class SensorEvent : public Sample m_side = -15.0f; m_type = e_human; - for (int i = 0; i < e_count; ++i) + for ( int i = 0; i < e_count; ++i ) { m_isSpawned[i] = false; } @@ -150,41 +152,41 @@ class SensorEvent : public Sample void CreateElement() { int index = -1; - for (int i = 0; i < e_count; ++i) + for ( int i = 0; i < e_count; ++i ) { - if (m_isSpawned[i] == false) + if ( m_isSpawned[i] == false ) { index = i; break; } } - if (index == -1) + if ( index == -1 ) { return; } - b2Vec2 center = {m_side, 29.5f}; + b2Vec2 center = { m_side, 29.5f }; - if (m_type == e_donut) + if ( m_type == e_donut ) { Donut* donut = m_donuts + index; - //donut->Spawn(m_worldId, center, index + 1, donut); - donut->Spawn(m_worldId, center, 1.0f, 0, donut); + // donut->Spawn(m_worldId, center, index + 1, donut); + donut->Spawn( m_worldId, center, 1.0f, 0, donut ); } else { Human* human = m_humans + index; - human->Spawn(m_worldId, center, 2.0f, index + 1, human); + human->Spawn( m_worldId, center, 2.0f, 0.05f, 0.0f, 0.0f, index + 1, human, false ); } m_isSpawned[index] = true; m_side = -m_side; } - void DestroyElement(int index) + void DestroyElement( int index ) { - if (m_type == e_donut) + if ( m_type == e_donut ) { Donut* donut = m_donuts + index; donut->Despawn(); @@ -200,11 +202,11 @@ class SensorEvent : public Sample void Clear() { - for (int i = 0; i < e_count; ++i) + for ( int i = 0; i < e_count; ++i ) { - if (m_isSpawned[i] == true) + if ( m_isSpawned[i] == true ) { - if (m_type == e_donut) + if ( m_type == e_donut ) { m_donuts[i].Despawn(); } @@ -216,24 +218,23 @@ class SensorEvent : public Sample m_isSpawned[i] = false; } } - } void UpdateUI() override { float height = 90.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(140.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 140.0f, height ) ); - ImGui::Begin("Sensor Event", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize); + ImGui::Begin( "Sensor Event", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); - if (ImGui::RadioButton("donut", m_type == e_donut)) + if ( ImGui::RadioButton( "donut", m_type == e_donut ) ) { Clear(); m_type = e_donut; } - if (ImGui::RadioButton("human", m_type == e_human)) + if ( ImGui::RadioButton( "human", m_type == e_human ) ) { Clear(); m_type = e_human; @@ -242,31 +243,31 @@ class SensorEvent : public Sample ImGui::End(); } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - if (m_stepCount == 832) + if ( m_stepCount == 832 ) { m_stepCount += 0; } - Sample::Step(settings); + Sample::Step( settings ); // Discover rings that touch the bottom sensor bool deferredDestructions[e_count] = {}; - b2SensorEvents sensorEvents = b2World_GetSensorEvents(m_worldId); - for (int i = 0; i < sensorEvents.beginCount; ++i) + b2SensorEvents sensorEvents = b2World_GetSensorEvents( m_worldId ); + for ( int i = 0; i < sensorEvents.beginCount; ++i ) { b2SensorBeginTouchEvent event = sensorEvents.beginEvents[i]; b2ShapeId visitorId = event.visitorShapeId; - b2BodyId bodyId = b2Shape_GetBody(visitorId); + b2BodyId bodyId = b2Shape_GetBody( visitorId ); - if (m_type == e_donut) + if ( m_type == e_donut ) { - Donut* donut = (Donut*)b2Body_GetUserData(bodyId); - if (donut != nullptr) + Donut* donut = (Donut*)b2Body_GetUserData( bodyId ); + if ( donut != nullptr ) { - int index = (int)(donut - m_donuts); - assert(0 <= index && index < e_count); + int index = (int)( donut - m_donuts ); + assert( 0 <= index && index < e_count ); // Defer destruction to avoid double destruction and event invalidation (orphaned shape ids) deferredDestructions[index] = true; @@ -274,11 +275,11 @@ class SensorEvent : public Sample } else { - Human* human = (Human*)b2Body_GetUserData(bodyId); - if (human != nullptr) + Human* human = (Human*)b2Body_GetUserData( bodyId ); + if ( human != nullptr ) { - int index = (int)(human - m_humans); - assert(0 <= index && index < e_count); + int index = (int)( human - m_humans ); + assert( 0 <= index && index < e_count ); // Defer destruction to avoid double destruction and event invalidation (orphaned shape ids) deferredDestructions[index] = true; @@ -289,18 +290,18 @@ class SensorEvent : public Sample // todo destroy mouse joint if necessary // Safely destroy rings that hit the bottom sensor - for (int i = 0; i < e_count; ++i) + for ( int i = 0; i < e_count; ++i ) { - if (deferredDestructions[i]) + if ( deferredDestructions[i] ) { - DestroyElement(i); + DestroyElement( i ); } } - if (settings.hertz > 0.0f && settings.pause == false) + if ( settings.hertz > 0.0f && settings.pause == false ) { m_wait -= 1.0f / settings.hertz; - if (m_wait < 0.0f) + if ( m_wait < 0.0f ) { CreateElement(); m_wait += 0.5f; @@ -308,9 +309,9 @@ class SensorEvent : public Sample } } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new SensorEvent(settings); + return new SensorEvent( settings ); } Human m_humans[e_count]; @@ -321,7 +322,7 @@ class SensorEvent : public Sample float m_side; }; -static int sampleSensorEvent = RegisterSample("Events", "Sensor", SensorEvent::Create); +static int sampleSensorEvent = RegisterSample( "Events", "Sensor", SensorEvent::Create ); struct BodyUserData { @@ -336,27 +337,27 @@ class ContactEvent : public Sample e_count = 20 }; - explicit ContactEvent(Settings& settings) - : Sample(settings) + explicit ContactEvent( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 0.0f}; + g_camera.m_center = { 0.0f, 0.0f }; g_camera.m_zoom = 25.0f * 1.75f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); - b2Vec2 points[] = {{40.0f, -40.0f}, {-40.0f, -40.0f}, {-40.0f, 40.0f}, {40.0f, 40.0f}}; + b2Vec2 points[] = { { 40.0f, -40.0f }, { -40.0f, -40.0f }, { -40.0f, 40.0f }, { 40.0f, 40.0f } }; b2ChainDef chainDef = b2DefaultChainDef(); chainDef.count = 4; chainDef.points = points; chainDef.isLoop = true; - b2CreateChain(groundId, &chainDef); + b2CreateChain( groundId, &chainDef ); } // Player @@ -367,18 +368,18 @@ class ContactEvent : public Sample bodyDef.linearDamping = 0.5f; bodyDef.angularDamping = 0.5f; bodyDef.isBullet = true; - m_playerId = b2CreateBody(m_worldId, &bodyDef); + m_playerId = b2CreateBody( m_worldId, &bodyDef ); - b2Circle circle = {{0.0f, 0.0f}, 1.0f}; + b2Circle circle = { { 0.0f, 0.0f }, 1.0f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); // Enable contact events for the player shape shapeDef.enableContactEvents = true; - m_coreShapeId = b2CreateCircleShape(m_playerId, &shapeDef, &circle); + m_coreShapeId = b2CreateCircleShape( m_playerId, &shapeDef, &circle ); } - for (int i = 0; i < e_count; ++i) + for ( int i = 0; i < e_count; ++i ) { m_debrisIds[i] = b2_nullBodyId; m_bodyUserData[i].index = i; @@ -391,16 +392,16 @@ class ContactEvent : public Sample void SpawnDebris() { int index = -1; - for (int i = 0; i < e_count; ++i) + for ( int i = 0; i < e_count; ++i ) { - if (B2_IS_NULL(m_debrisIds[i])) + if ( B2_IS_NULL( m_debrisIds[i] ) ) { index = i; break; } } - if (index == -1) + if ( index == -1 ) { return; } @@ -408,13 +409,13 @@ class ContactEvent : public Sample // Debris b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {RandomFloat(-38.0f, 38.0f), RandomFloat(-38.0f, 38.0f)}; - bodyDef.rotation = b2MakeRot(RandomFloat(-b2_pi, b2_pi)); - bodyDef.linearVelocity = {RandomFloat(-5.0f, 5.0f), RandomFloat(-5.0f, 5.0f)}; - bodyDef.angularVelocity = RandomFloat(-1.0f, 1.0f); + bodyDef.position = { RandomFloat( -38.0f, 38.0f ), RandomFloat( -38.0f, 38.0f ) }; + bodyDef.rotation = b2MakeRot( RandomFloat( -b2_pi, b2_pi ) ); + bodyDef.linearVelocity = { RandomFloat( -5.0f, 5.0f ), RandomFloat( -5.0f, 5.0f ) }; + bodyDef.angularVelocity = RandomFloat( -1.0f, 1.0f ); bodyDef.gravityScale = 0.0f; bodyDef.userData = m_bodyUserData + index; - m_debrisIds[index] = b2CreateBody(m_worldId, &bodyDef); + m_debrisIds[index] = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.restitution = 0.8f; @@ -422,91 +423,91 @@ class ContactEvent : public Sample // No events when debris hits debris shapeDef.enableContactEvents = false; - if ((index + 1) % 3 == 0) + if ( ( index + 1 ) % 3 == 0 ) { - b2Circle circle = {{0.0f, 0.0f}, 0.5f}; - b2CreateCircleShape(m_debrisIds[index], &shapeDef, &circle); + b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; + b2CreateCircleShape( m_debrisIds[index], &shapeDef, &circle ); } - else if ((index + 1) % 2 == 0) + else if ( ( index + 1 ) % 2 == 0 ) { - b2Capsule capsule = {{0.0f, -0.25f}, {0.0f, 0.25f}, 0.25f}; - b2CreateCapsuleShape(m_debrisIds[index], &shapeDef, &capsule); + b2Capsule capsule = { { 0.0f, -0.25f }, { 0.0f, 0.25f }, 0.25f }; + b2CreateCapsuleShape( m_debrisIds[index], &shapeDef, &capsule ); } else { - b2Polygon box = b2MakeBox(0.4f, 0.6f); - b2CreatePolygonShape(m_debrisIds[index], &shapeDef, &box); + b2Polygon box = b2MakeBox( 0.4f, 0.6f ); + b2CreatePolygonShape( m_debrisIds[index], &shapeDef, &box ); } } void UpdateUI() override { float height = 60.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(240.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); - ImGui::Begin("Contact Event", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize); + ImGui::Begin( "Contact Event", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); - ImGui::SliderFloat("force", &m_force, 100.0f, 500.0f, "%.1f"); + ImGui::SliderFloat( "force", &m_force, 100.0f, 500.0f, "%.1f" ); ImGui::End(); } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - g_draw.DrawString(5, m_textLine, "move using WASD"); + g_draw.DrawString( 5, m_textLine, "move using WASD" ); m_textLine += m_textIncrement; - b2Vec2 position = b2Body_GetPosition(m_playerId); + b2Vec2 position = b2Body_GetPosition( m_playerId ); - if (glfwGetKey(g_mainWindow, GLFW_KEY_A) == GLFW_PRESS) + if ( glfwGetKey( g_mainWindow, GLFW_KEY_A ) == GLFW_PRESS ) { - b2Body_ApplyForce(m_playerId, {-m_force, 0.0f}, position, true); + b2Body_ApplyForce( m_playerId, { -m_force, 0.0f }, position, true ); } - if (glfwGetKey(g_mainWindow, GLFW_KEY_D) == GLFW_PRESS) + if ( glfwGetKey( g_mainWindow, GLFW_KEY_D ) == GLFW_PRESS ) { - b2Body_ApplyForce(m_playerId, {m_force, 0.0f}, position, true); + b2Body_ApplyForce( m_playerId, { m_force, 0.0f }, position, true ); } - if (glfwGetKey(g_mainWindow, GLFW_KEY_W) == GLFW_PRESS) + if ( glfwGetKey( g_mainWindow, GLFW_KEY_W ) == GLFW_PRESS ) { - b2Body_ApplyForce(m_playerId, {0.0f, m_force}, position, true); + b2Body_ApplyForce( m_playerId, { 0.0f, m_force }, position, true ); } - if (glfwGetKey(g_mainWindow, GLFW_KEY_S) == GLFW_PRESS) + if ( glfwGetKey( g_mainWindow, GLFW_KEY_S ) == GLFW_PRESS ) { - b2Body_ApplyForce(m_playerId, {0.0f, -m_force}, position, true); + b2Body_ApplyForce( m_playerId, { 0.0f, -m_force }, position, true ); } - Sample::Step(settings); + Sample::Step( settings ); // Discover rings that touch the bottom sensor int debrisToAttach[e_count] = {}; - b2ShapeId shapesToDestroy[e_count] = {b2_nullShapeId}; + b2ShapeId shapesToDestroy[e_count] = { b2_nullShapeId }; int attachCount = 0; int destroyCount = 0; - b2ContactEvents contactEvents = b2World_GetContactEvents(m_worldId); - for (int i = 0; i < contactEvents.beginCount; ++i) + b2ContactEvents contactEvents = b2World_GetContactEvents( m_worldId ); + for ( int i = 0; i < contactEvents.beginCount; ++i ) { b2ContactBeginTouchEvent event = contactEvents.beginEvents[i]; - b2BodyId bodyIdA = b2Shape_GetBody(event.shapeIdA); - b2BodyId bodyIdB = b2Shape_GetBody(event.shapeIdB); + b2BodyId bodyIdA = b2Shape_GetBody( event.shapeIdA ); + b2BodyId bodyIdB = b2Shape_GetBody( event.shapeIdB ); - if (B2_ID_EQUALS(bodyIdA, m_playerId)) + if ( B2_ID_EQUALS( bodyIdA, m_playerId ) ) { - BodyUserData* userDataB = static_cast(b2Body_GetUserData(bodyIdB)); - if (userDataB == nullptr) + BodyUserData* userDataB = static_cast( b2Body_GetUserData( bodyIdB ) ); + if ( userDataB == nullptr ) { - if (B2_ID_EQUALS(event.shapeIdA, m_coreShapeId) == false && destroyCount < e_count) + if ( B2_ID_EQUALS( event.shapeIdA, m_coreShapeId ) == false && destroyCount < e_count ) { // player non-core shape hit the wall bool found = false; - for (int j = 0; j < destroyCount; ++j) + for ( int j = 0; j < destroyCount; ++j ) { - if (B2_ID_EQUALS(event.shapeIdA, shapesToDestroy[j])) + if ( B2_ID_EQUALS( event.shapeIdA, shapesToDestroy[j] ) ) { found = true; break; @@ -514,14 +515,14 @@ class ContactEvent : public Sample } // avoid double deletion - if (found == false) + if ( found == false ) { shapesToDestroy[destroyCount] = event.shapeIdA; destroyCount += 1; } } } - else if (attachCount < e_count) + else if ( attachCount < e_count ) { debrisToAttach[attachCount] = userDataB->index; attachCount += 1; @@ -530,18 +531,18 @@ class ContactEvent : public Sample else { // Only expect events for the player - assert(B2_ID_EQUALS(bodyIdB, m_playerId)); - BodyUserData* userDataA = static_cast(b2Body_GetUserData(bodyIdA)); - if (userDataA == nullptr) + assert( B2_ID_EQUALS( bodyIdB, m_playerId ) ); + BodyUserData* userDataA = static_cast( b2Body_GetUserData( bodyIdA ) ); + if ( userDataA == nullptr ) { - if (B2_ID_EQUALS(event.shapeIdB, m_coreShapeId) == false && destroyCount < e_count) + if ( B2_ID_EQUALS( event.shapeIdB, m_coreShapeId ) == false && destroyCount < e_count ) { // player non-core shape hit the wall bool found = false; - for (int j = 0; j < destroyCount; ++j) + for ( int j = 0; j < destroyCount; ++j ) { - if (B2_ID_EQUALS(event.shapeIdB, shapesToDestroy[j])) + if ( B2_ID_EQUALS( event.shapeIdB, shapesToDestroy[j] ) ) { found = true; break; @@ -549,14 +550,14 @@ class ContactEvent : public Sample } // avoid double deletion - if (found == false) + if ( found == false ) { shapesToDestroy[destroyCount] = event.shapeIdB; destroyCount += 1; } } } - else if (attachCount < e_count) + else if ( attachCount < e_count ) { debrisToAttach[attachCount] = userDataA->index; attachCount += 1; @@ -566,80 +567,80 @@ class ContactEvent : public Sample // Attach debris to player body b2ShapeId shapeBuffer[4]; - for (int i = 0; i < attachCount; ++i) + for ( int i = 0; i < attachCount; ++i ) { int index = debrisToAttach[i]; b2BodyId debrisId = m_debrisIds[index]; - if (B2_IS_NULL(debrisId)) + if ( B2_IS_NULL( debrisId ) ) { continue; } - b2Transform playerTransform = b2Body_GetTransform(m_playerId); - b2Transform debrisTransform = b2Body_GetTransform(debrisId); - b2Transform relativeTransform = b2InvMulTransforms(playerTransform, debrisTransform); + b2Transform playerTransform = b2Body_GetTransform( m_playerId ); + b2Transform debrisTransform = b2Body_GetTransform( debrisId ); + b2Transform relativeTransform = b2InvMulTransforms( playerTransform, debrisTransform ); - int shapeCount = b2Body_GetShapeCount(debrisId); - if (shapeCount == 0) + int shapeCount = b2Body_GetShapeCount( debrisId ); + if ( shapeCount == 0 ) { continue; } b2ShapeId shapeId; - b2Body_GetShapes(debrisId, &shapeId, 1); + b2Body_GetShapes( debrisId, &shapeId, 1 ); - b2ShapeType type = b2Shape_GetType(shapeId); + b2ShapeType type = b2Shape_GetType( shapeId ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.enableContactEvents = true; - switch (type) + switch ( type ) { case b2_circleShape: { - b2Circle circle = b2Shape_GetCircle(shapeId); - circle.center = b2TransformPoint(relativeTransform, circle.center); + b2Circle circle = b2Shape_GetCircle( shapeId ); + circle.center = b2TransformPoint( relativeTransform, circle.center ); - b2CreateCircleShape(m_playerId, &shapeDef, &circle); + b2CreateCircleShape( m_playerId, &shapeDef, &circle ); } break; case b2_capsuleShape: { - b2Capsule capsule = b2Shape_GetCapsule(shapeId); - capsule.center1 = b2TransformPoint(relativeTransform, capsule.center1); - capsule.center2 = b2TransformPoint(relativeTransform, capsule.center2); + b2Capsule capsule = b2Shape_GetCapsule( shapeId ); + capsule.center1 = b2TransformPoint( relativeTransform, capsule.center1 ); + capsule.center2 = b2TransformPoint( relativeTransform, capsule.center2 ); - b2CreateCapsuleShape(m_playerId, &shapeDef, &capsule); + b2CreateCapsuleShape( m_playerId, &shapeDef, &capsule ); } break; case b2_polygonShape: { - b2Polygon originalPolygon = b2Shape_GetPolygon(shapeId); - b2Polygon polygon = b2TransformPolygon(relativeTransform, &originalPolygon); + b2Polygon originalPolygon = b2Shape_GetPolygon( shapeId ); + b2Polygon polygon = b2TransformPolygon( relativeTransform, &originalPolygon ); - b2CreatePolygonShape(m_playerId, &shapeDef, &polygon); + b2CreatePolygonShape( m_playerId, &shapeDef, &polygon ); } break; default: - assert(false); + assert( false ); } - b2DestroyBody(debrisId); + b2DestroyBody( debrisId ); m_debrisIds[index] = b2_nullBodyId; } - for (int i = 0; i < destroyCount; ++i) + for ( int i = 0; i < destroyCount; ++i ) { - b2DestroyShape(shapesToDestroy[i]); + b2DestroyShape( shapesToDestroy[i] ); } - if (settings.hertz > 0.0f && settings.pause == false) + if ( settings.hertz > 0.0f && settings.pause == false ) { m_wait -= 1.0f / settings.hertz; - if (m_wait < 0.0f) + if ( m_wait < 0.0f ) { SpawnDebris(); m_wait += 0.5f; @@ -647,9 +648,9 @@ class ContactEvent : public Sample } } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new ContactEvent(settings); + return new ContactEvent( settings ); } b2BodyId m_playerId; @@ -660,43 +661,43 @@ class ContactEvent : public Sample float m_wait; }; -static int sampleWeeble = RegisterSample("Events", "Contact", ContactEvent::Create); +static int sampleWeeble = RegisterSample( "Events", "Contact", ContactEvent::Create ); // Shows how to make a rigid body character mover and use the pre-solve callback. class Platformer : public Sample { public: - explicit Platformer(Settings& settings) - : Sample(settings) + explicit Platformer( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.5f, 7.5f}; + g_camera.m_center = { 0.5f, 7.5f }; g_camera.m_zoom = 25.0f * 0.4f; } - b2World_SetPreSolveCallback(m_worldId, PreSolveStatic, this); + b2World_SetPreSolveCallback( m_worldId, PreSolveStatic, this ); // Ground { b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Segment segment = {{-20.0f, 0.0f}, {20.0f, 0.0f}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2Segment segment = { { -20.0f, 0.0f }, { 20.0f, 0.0f } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment ); } // Platform { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_kinematicBody; - bodyDef.position = {0.0f, 6.0f}; - bodyDef.linearVelocity = {2.0f, 0.0f}; - m_platformId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { 0.0f, 6.0f }; + bodyDef.linearVelocity = { 2.0f, 0.0f }; + m_platformId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Polygon box = b2MakeBox(3.0f, 0.5f); - m_platformShapeId = b2CreatePolygonShape(m_platformId, &shapeDef, &box); + b2Polygon box = b2MakeBox( 3.0f, 0.5f ); + m_platformShapeId = b2CreatePolygonShape( m_platformId, &shapeDef, &box ); } // Actor @@ -705,18 +706,18 @@ class Platformer : public Sample bodyDef.type = b2_dynamicBody; bodyDef.fixedRotation = true; bodyDef.linearDamping = 0.5f; - bodyDef.position = {0.0f, 1.0f}; - m_characterId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { 0.0f, 1.0f }; + m_characterId = b2CreateBody( m_worldId, &bodyDef ); m_radius = 0.5f; - b2Capsule capsule = {{0.0f, 0.0f}, {0.0f, 1.0f}, m_radius}; + b2Capsule capsule = { { 0.0f, 0.0f }, { 0.0f, 1.0f }, m_radius }; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.friction = 0.1f; // Need to turn this on to get the callback shapeDef.enablePreSolveEvents = true; - b2CreateCapsuleShape(m_characterId, &shapeDef, &capsule); + b2CreateCapsuleShape( m_characterId, &shapeDef, &capsule ); } m_force = 25.0f; @@ -725,28 +726,28 @@ class Platformer : public Sample m_jumping = false; } - static bool PreSolveStatic(b2ShapeId shapeIdA, b2ShapeId shapeIdB, b2Manifold* manifold, void* context) + static bool PreSolveStatic( b2ShapeId shapeIdA, b2ShapeId shapeIdB, b2Manifold* manifold, void* context ) { - Platformer* platformer = static_cast(context); - return platformer->PreSolve(shapeIdA, shapeIdB, manifold); + Platformer* platformer = static_cast( context ); + return platformer->PreSolve( shapeIdA, shapeIdB, manifold ); } // This callback must be thread-safe. It may be called multiple times simultaneously. // Notice how this method is constant and doesn't change any data. It also // does not try to access any values in the world that may be changing, such as contact data. - bool PreSolve(b2ShapeId shapeIdA, b2ShapeId shapeIdB, b2Manifold* manifold) const + bool PreSolve( b2ShapeId shapeIdA, b2ShapeId shapeIdB, b2Manifold* manifold ) const { - assert(b2Shape_IsValid(shapeIdA)); - assert(b2Shape_IsValid(shapeIdB)); + assert( b2Shape_IsValid( shapeIdA ) ); + assert( b2Shape_IsValid( shapeIdB ) ); b2ShapeId actorShapeId = b2_nullShapeId; float sign = 0.0f; - if (B2_ID_EQUALS(shapeIdA, m_platformShapeId)) + if ( B2_ID_EQUALS( shapeIdA, m_platformShapeId ) ) { sign = 1.0f; actorShapeId = shapeIdB; } - else if (B2_ID_EQUALS(shapeIdB, m_platformShapeId)) + else if ( B2_ID_EQUALS( shapeIdB, m_platformShapeId ) ) { sign = -1.0f; actorShapeId = shapeIdA; @@ -757,27 +758,27 @@ class Platformer : public Sample return true; } - b2BodyId bodyId = b2Shape_GetBody(actorShapeId); - if (B2_ID_EQUALS(bodyId, m_characterId) == false) + b2BodyId bodyId = b2Shape_GetBody( actorShapeId ); + if ( B2_ID_EQUALS( bodyId, m_characterId ) == false ) { // not the character, enable contact return true; } b2Vec2 normal = manifold->normal; - if (sign * normal.y > 0.95f) + if ( sign * normal.y > 0.95f ) { return true; } float separation = 0.0f; - for (int i = 0; i < manifold->pointCount; ++i) + for ( int i = 0; i < manifold->pointCount; ++i ) { float s = manifold->points[i].separation; separation = separation < s ? separation : s; } - if (separation > 0.1f * m_radius) + if ( separation > 0.1f * m_radius ) { // shallow overlap return true; @@ -790,32 +791,32 @@ class Platformer : public Sample void UpdateUI() override { float height = 100.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(240.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); - ImGui::Begin("Platformer", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize); + ImGui::Begin( "Platformer", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); - ImGui::SliderFloat("force", &m_force, 0.0f, 50.0f, "%.1f"); - ImGui::SliderFloat("impulse", &m_impulse, 0.0f, 50.0f, "%.1f"); + ImGui::SliderFloat( "force", &m_force, 0.0f, 50.0f, "%.1f" ); + ImGui::SliderFloat( "impulse", &m_impulse, 0.0f, 50.0f, "%.1f" ); ImGui::End(); } - void Step(Settings& settings) override + void Step( Settings& settings ) override { bool canJump = false; - b2Vec2 velocity = b2Body_GetLinearVelocity(m_characterId); - if (m_jumpDelay == 0.0f && m_jumping == false && velocity.y < 0.01f) + b2Vec2 velocity = b2Body_GetLinearVelocity( m_characterId ); + if ( m_jumpDelay == 0.0f && m_jumping == false && velocity.y < 0.01f ) { - int capacity = b2Body_GetContactCapacity(m_characterId); - capacity = b2MinInt(capacity, 4); + int capacity = b2Body_GetContactCapacity( m_characterId ); + capacity = b2MinInt( capacity, 4 ); b2ContactData contactData[4]; - int count = b2Body_GetContactData(m_characterId, contactData, capacity); - for (int i = 0; i < count; ++i) + int count = b2Body_GetContactData( m_characterId, contactData, capacity ); + for ( int i = 0; i < count; ++i ) { - b2BodyId bodyIdA = b2Shape_GetBody(contactData[i].shapeIdA); + b2BodyId bodyIdA = b2Shape_GetBody( contactData[i].shapeIdA ); float sign = 0.0f; - if (B2_ID_EQUALS(bodyIdA, m_characterId)) + if ( B2_ID_EQUALS( bodyIdA, m_characterId ) ) { // normal points from A to B sign = -1.0f; @@ -825,7 +826,7 @@ class Platformer : public Sample sign = 1.0f; } - if (sign * contactData[i].manifold.normal.y > 0.9f) + if ( sign * contactData[i].manifold.normal.y > 0.9f ) { canJump = true; break; @@ -835,32 +836,32 @@ class Platformer : public Sample // A kinematic body is moved by setting its velocity. This // ensure friction works correctly. - b2Vec2 platformPosition = b2Body_GetPosition(m_platformId); - if (platformPosition.x < -15.0f) + b2Vec2 platformPosition = b2Body_GetPosition( m_platformId ); + if ( platformPosition.x < -15.0f ) { - b2Body_SetLinearVelocity(m_platformId, {2.0f, 0.0f}); + b2Body_SetLinearVelocity( m_platformId, { 2.0f, 0.0f } ); } - else if (platformPosition.x > 15.0f) + else if ( platformPosition.x > 15.0f ) { - b2Body_SetLinearVelocity(m_platformId, {-2.0f, 0.0f}); + b2Body_SetLinearVelocity( m_platformId, { -2.0f, 0.0f } ); } - if (glfwGetKey(g_mainWindow, GLFW_KEY_A) == GLFW_PRESS) + if ( glfwGetKey( g_mainWindow, GLFW_KEY_A ) == GLFW_PRESS ) { - b2Body_ApplyForceToCenter(m_characterId, {-m_force, 0.0f}, true); + b2Body_ApplyForceToCenter( m_characterId, { -m_force, 0.0f }, true ); } - if (glfwGetKey(g_mainWindow, GLFW_KEY_D) == GLFW_PRESS) + if ( glfwGetKey( g_mainWindow, GLFW_KEY_D ) == GLFW_PRESS ) { - b2Body_ApplyForceToCenter(m_characterId, {m_force, 0.0f}, true); + b2Body_ApplyForceToCenter( m_characterId, { m_force, 0.0f }, true ); } - int keyState = glfwGetKey(g_mainWindow, GLFW_KEY_SPACE); - if (keyState == GLFW_PRESS) + int keyState = glfwGetKey( g_mainWindow, GLFW_KEY_SPACE ); + if ( keyState == GLFW_PRESS ) { - if (canJump) + if ( canJump ) { - b2Body_ApplyLinearImpulseToCenter(m_characterId, {0.0f, m_impulse}, true); + b2Body_ApplyLinearImpulseToCenter( m_characterId, { 0.0f, m_impulse }, true ); m_jumpDelay = 0.5f; m_jumping = true; } @@ -870,23 +871,23 @@ class Platformer : public Sample m_jumping = false; } - Sample::Step(settings); + Sample::Step( settings ); - g_draw.DrawString(5, m_textLine, "Movement: A/D/Space"); + g_draw.DrawString( 5, m_textLine, "Movement: A/D/Space" ); m_textLine += m_textIncrement; - g_draw.DrawString(5, m_textLine, "Can jump = %s", canJump ? "true" : "false"); + g_draw.DrawString( 5, m_textLine, "Can jump = %s", canJump ? "true" : "false" ); m_textLine += m_textIncrement; - if (settings.hertz > 0.0f) + if ( settings.hertz > 0.0f ) { - m_jumpDelay = b2MaxFloat(0.0f, m_jumpDelay - 1.0f / settings.hertz); + m_jumpDelay = b2MaxFloat( 0.0f, m_jumpDelay - 1.0f / settings.hertz ); } } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new Platformer(settings); + return new Platformer( settings ); } bool m_jumping; @@ -899,7 +900,7 @@ class Platformer : public Sample b2ShapeId m_platformShapeId; }; -static int samplePlatformer = RegisterSample("Events", "Platformer", Platformer::Create); +static int samplePlatformer = RegisterSample( "Events", "Platformer", Platformer::Create ); // This shows how to process body events. class BodyMove : public Sample @@ -910,84 +911,84 @@ class BodyMove : public Sample e_count = 50 }; - explicit BodyMove(Settings& settings) - : Sample(settings) + explicit BodyMove( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {2.0f, 8.0f}; + g_camera.m_center = { 2.0f, 8.0f }; g_camera.m_zoom = 25.0f * 0.55f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.friction = 0.1f; - b2Polygon box = b2MakeOffsetBox(12.0f, 0.1f, {-10.0f, -0.1f}, -0.15f * b2_pi); - b2CreatePolygonShape(groundId, &shapeDef, &box); - - box = b2MakeOffsetBox(12.0f, 0.1f, {10.0f, -0.1f}, 0.15f * b2_pi); - b2CreatePolygonShape(groundId, &shapeDef, &box); + b2Polygon box = b2MakeOffsetBox( 12.0f, 0.1f, { -10.0f, -0.1f }, -0.15f * b2_pi ); + b2CreatePolygonShape( groundId, &shapeDef, &box ); + + box = b2MakeOffsetBox( 12.0f, 0.1f, { 10.0f, -0.1f }, 0.15f * b2_pi ); + b2CreatePolygonShape( groundId, &shapeDef, &box ); shapeDef.restitution = 0.8f; - box = b2MakeOffsetBox(0.1f, 10.0f, {19.9f, 10.0f}, 0.0f); - b2CreatePolygonShape(groundId, &shapeDef, &box); + box = b2MakeOffsetBox( 0.1f, 10.0f, { 19.9f, 10.0f }, 0.0f ); + b2CreatePolygonShape( groundId, &shapeDef, &box ); - box = b2MakeOffsetBox(0.1f, 10.0f, {-19.9f, 10.0f}, 0.0f); - b2CreatePolygonShape(groundId, &shapeDef, &box); + box = b2MakeOffsetBox( 0.1f, 10.0f, { -19.9f, 10.0f }, 0.0f ); + b2CreatePolygonShape( groundId, &shapeDef, &box ); - box = b2MakeOffsetBox(20.0f, 0.1f, {0.0f, 20.1f}, 0.0f); - b2CreatePolygonShape(groundId, &shapeDef, &box); + box = b2MakeOffsetBox( 20.0f, 0.1f, { 0.0f, 20.1f }, 0.0f ); + b2CreatePolygonShape( groundId, &shapeDef, &box ); } m_sleepCount = 0; m_count = 0; - m_explosionPosition = {0.0f, -5.0f}; + m_explosionPosition = { 0.0f, -5.0f }; m_explosionRadius = 10.0f; m_explosionMagnitude = 6.0f; } void CreateBodies() { - b2Capsule capsule = {{-0.25f, 0.0f}, {0.25f, 0.0f}, 0.25f}; - b2Circle circle = {{0.0f, 0.0f}, 0.35f}; - b2Polygon square = b2MakeSquare(0.35f); + b2Capsule capsule = { { -0.25f, 0.0f }, { 0.25f, 0.0f }, 0.25f }; + b2Circle circle = { { 0.0f, 0.0f }, 0.35f }; + b2Polygon square = b2MakeSquare( 0.35f ); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; b2ShapeDef shapeDef = b2DefaultShapeDef(); float x = -5.0f, y = 10.0f; - for (int32_t i = 0; i < 10 && m_count < e_count; ++i) + for ( int32_t i = 0; i < 10 && m_count < e_count; ++i ) { - bodyDef.position = {x, y}; + bodyDef.position = { x, y }; bodyDef.userData = m_bodyIds + m_count; - m_bodyIds[m_count] = b2CreateBody(m_worldId, &bodyDef); + m_bodyIds[m_count] = b2CreateBody( m_worldId, &bodyDef ); m_sleeping[m_count] = false; int remainder = m_count % 4; - if (remainder == 0) + if ( remainder == 0 ) { - b2CreateCapsuleShape(m_bodyIds[m_count], &shapeDef, &capsule); + b2CreateCapsuleShape( m_bodyIds[m_count], &shapeDef, &capsule ); } - else if (remainder == 1) + else if ( remainder == 1 ) { - b2CreateCircleShape(m_bodyIds[m_count], &shapeDef, &circle); + b2CreateCircleShape( m_bodyIds[m_count], &shapeDef, &circle ); } - else if (remainder == 2) + else if ( remainder == 2 ) { - b2CreatePolygonShape(m_bodyIds[m_count], &shapeDef, &square); + b2CreatePolygonShape( m_bodyIds[m_count], &shapeDef, &square ); } else { - b2Polygon poly = RandomPolygon(0.75f); + b2Polygon poly = RandomPolygon( 0.75f ); poly.radius = 0.1f; - b2CreatePolygonShape(m_bodyIds[m_count], &shapeDef, &poly); + b2CreatePolygonShape( m_bodyIds[m_count], &shapeDef, &poly ); } m_count += 1; @@ -998,51 +999,51 @@ class BodyMove : public Sample void UpdateUI() override { float height = 100.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(240.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); - ImGui::Begin("Body Move", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize); + ImGui::Begin( "Body Move", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize ); - if (ImGui::Button("Explode")) + if ( ImGui::Button( "Explode" ) ) { - b2World_Explode(m_worldId, m_explosionPosition, m_explosionRadius, m_explosionMagnitude); + b2World_Explode( m_worldId, m_explosionPosition, m_explosionRadius, m_explosionMagnitude ); } - ImGui::SliderFloat("Magnitude", &m_explosionMagnitude, -8.0f, 8.0f, "%.1f"); + ImGui::SliderFloat( "Magnitude", &m_explosionMagnitude, -8.0f, 8.0f, "%.1f" ); ImGui::End(); } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - if (settings.pause == false && (m_stepCount & 15) == 15 && m_count < e_count) + if ( settings.pause == false && ( m_stepCount & 15 ) == 15 && m_count < e_count ) { CreateBodies(); } - Sample::Step(settings); + Sample::Step( settings ); // Process body events - b2BodyEvents events = b2World_GetBodyEvents(m_worldId); - for (int i = 0; i < events.moveCount; ++i) + b2BodyEvents events = b2World_GetBodyEvents( m_worldId ); + for ( int i = 0; i < events.moveCount; ++i ) { // draw the transform of every body that moved (not sleeping) const b2BodyMoveEvent* event = events.moveEvents + i; - g_draw.DrawTransform(event->transform); + g_draw.DrawTransform( event->transform ); // this shows a somewhat contrived way to track body sleeping - b2BodyId* bodyId = static_cast(event->userData); + b2BodyId* bodyId = static_cast( event->userData ); ptrdiff_t diff = bodyId - m_bodyIds; bool* sleeping = m_sleeping + diff; - if (event->fellAsleep) + if ( event->fellAsleep ) { *sleeping = true; m_sleepCount += 1; } else { - if (*sleeping) + if ( *sleeping ) { *sleeping = false; m_sleepCount -= 1; @@ -1050,15 +1051,15 @@ class BodyMove : public Sample } } - g_draw.DrawCircle(m_explosionPosition, m_explosionRadius, b2_colorAzure); + g_draw.DrawCircle( m_explosionPosition, m_explosionRadius, b2_colorAzure ); - g_draw.DrawString(5, m_textLine, "sleep count: %d", m_sleepCount); + g_draw.DrawString( 5, m_textLine, "sleep count: %d", m_sleepCount ); m_textLine += m_textIncrement; } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new BodyMove(settings); + return new BodyMove( settings ); } b2BodyId m_bodyIds[e_count]; @@ -1070,4 +1071,4 @@ class BodyMove : public Sample float m_explosionMagnitude; }; -static int sampleBodyMove = RegisterSample("Events", "Body Move", BodyMove::Create); +static int sampleBodyMove = RegisterSample( "Events", "Body Move", BodyMove::Create ); diff --git a/samples/sample_geometry.cpp b/samples/sample_geometry.cpp index 0c352604..7ed1a8dc 100644 --- a/samples/sample_geometry.cpp +++ b/samples/sample_geometry.cpp @@ -17,12 +17,12 @@ class ConvexHull : public Sample e_count = b2_maxPolygonVertices }; - explicit ConvexHull(Settings& settings) - : Sample(settings) + explicit ConvexHull( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.5f, 0.0f}; + g_camera.m_center = { 0.5f, 0.0f }; g_camera.m_zoom = 25.0f * 0.3f; } @@ -46,40 +46,40 @@ class ConvexHull : public Sample m_count = e_count; #elif 0 - m_points[0] = {-0.328125, 0.179688}; - m_points[1] = {-0.203125, 0.304688}; - m_points[2] = {0.171875, 0.304688}; - m_points[3] = {0.359375, 0.117188}; - m_points[4] = {0.359375, -0.195313}; - m_points[5] = {0.234375, -0.320313}; - m_points[6] = {-0.265625, -0.257813}; - m_points[7] = {-0.328125, -0.132813}; - - b2Hull hull = b2ComputeHull(m_points, 8); - bool valid = b2ValidateHull(&hull); - if (valid == false) + m_points[0] = { -0.328125, 0.179688 }; + m_points[1] = { -0.203125, 0.304688 }; + m_points[2] = { 0.171875, 0.304688 }; + m_points[3] = { 0.359375, 0.117188 }; + m_points[4] = { 0.359375, -0.195313 }; + m_points[5] = { 0.234375, -0.320313 }; + m_points[6] = { -0.265625, -0.257813 }; + m_points[7] = { -0.328125, -0.132813 }; + + b2Hull hull = b2ComputeHull( m_points, 8 ); + bool valid = b2ValidateHull( &hull ); + if ( valid == false ) { - assert(valid); + assert( valid ); } m_count = e_count; #else float angle = b2_pi * RandomFloat(); - b2Rot r = b2MakeRot(angle); + b2Rot r = b2MakeRot( angle ); - b2Vec2 lowerBound = {-4.0f, -4.0f}; - b2Vec2 upperBound = {4.0f, 4.0f}; + b2Vec2 lowerBound = { -4.0f, -4.0f }; + b2Vec2 upperBound = { 4.0f, 4.0f }; - for (int i = 0; i < e_count; ++i) + for ( int i = 0; i < e_count; ++i ) { float x = 10.0f * RandomFloat(); float y = 10.0f * RandomFloat(); // Clamp onto a square to help create collinearities. // This will stress the convex hull algorithm. - b2Vec2 v = b2Clamp({x, y}, lowerBound, upperBound); - m_points[i] = b2RotateVector(r, v); + b2Vec2 v = b2Clamp( { x, y }, lowerBound, upperBound ); + m_points[i] = b2RotateVector( r, v ); } m_count = e_count; @@ -88,55 +88,55 @@ class ConvexHull : public Sample m_generation += 1; } - void Keyboard(int key) override + void Keyboard( int key ) override { - switch (key) + switch ( key ) { - case GLFW_KEY_A: - m_auto = !m_auto; - break; + case GLFW_KEY_A: + m_auto = !m_auto; + break; - case GLFW_KEY_B: - m_bulk = !m_bulk; - break; + case GLFW_KEY_B: + m_bulk = !m_bulk; + break; - case GLFW_KEY_G: - Generate(); - break; - - default: - break; + case GLFW_KEY_G: + Generate(); + break; + + default: + break; } } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - Sample::Step(settings); + Sample::Step( settings ); - g_draw.DrawString(5, m_textLine, "Options: generate(g), auto(a), bulk(b)"); + g_draw.DrawString( 5, m_textLine, "Options: generate(g), auto(a), bulk(b)" ); m_textLine += m_textIncrement; - + b2Hull hull; bool valid = false; float milliseconds = 0.0f; - if (m_bulk) + if ( m_bulk ) { #if 1 // defect hunting - for (int i = 0; i < 10000; ++i) + for ( int i = 0; i < 10000; ++i ) { Generate(); - hull = b2ComputeHull(m_points, m_count); - if (hull.count == 0) + hull = b2ComputeHull( m_points, m_count ); + if ( hull.count == 0 ) { - //m_bulk = false; - //break; + // m_bulk = false; + // break; continue; } - valid = b2ValidateHull(&hull); - if (valid == false || m_bulk == false) + valid = b2ValidateHull( &hull ); + if ( valid == false || m_bulk == false ) { m_bulk = false; break; @@ -146,9 +146,9 @@ class ConvexHull : public Sample // performance Generate(); b2Timer timer; - for (int i = 0; i < 1000000; ++i) + for ( int i = 0; i < 1000000; ++i ) { - hull = b2ComputeHull(m_points, m_count); + hull = b2ComputeHull( m_points, m_count ); } valid = hull.count > 0; milliseconds = timer.GetMilliseconds(); @@ -156,58 +156,58 @@ class ConvexHull : public Sample } else { - if (m_auto) + if ( m_auto ) { Generate(); } - hull = b2ComputeHull(m_points, m_count); - if (hull.count > 0) + hull = b2ComputeHull( m_points, m_count ); + if ( hull.count > 0 ) { - valid = b2ValidateHull(&hull); - if (valid == false) + valid = b2ValidateHull( &hull ); + if ( valid == false ) { m_auto = false; } } } - if (valid == false) + if ( valid == false ) { - g_draw.DrawString(5, m_textLine, "generation = %d, FAILED", m_generation); + g_draw.DrawString( 5, m_textLine, "generation = %d, FAILED", m_generation ); m_textLine += m_textIncrement; } else { - g_draw.DrawString(5, m_textLine, "generation = %d, count = %d", m_generation, hull.count); + g_draw.DrawString( 5, m_textLine, "generation = %d, count = %d", m_generation, hull.count ); m_textLine += m_textIncrement; } - if (milliseconds > 0.0f) + if ( milliseconds > 0.0f ) { - g_draw.DrawString(5, m_textLine, "milliseconds = %g", milliseconds); + g_draw.DrawString( 5, m_textLine, "milliseconds = %g", milliseconds ); m_textLine += m_textIncrement; } m_textLine += m_textIncrement; - g_draw.DrawPolygon(hull.points, hull.count, b2_colorGray); + g_draw.DrawPolygon( hull.points, hull.count, b2_colorGray ); - for (int32_t i = 0; i < m_count; ++i) + for ( int32_t i = 0; i < m_count; ++i ) { - g_draw.DrawPoint(m_points[i], 5.0f, b2_colorBlue); - g_draw.DrawString(b2Add(m_points[i], {0.1f, 0.1f}), "%d", i); + g_draw.DrawPoint( m_points[i], 5.0f, b2_colorBlue ); + g_draw.DrawString( b2Add( m_points[i], { 0.1f, 0.1f } ), "%d", i ); } - for (int32_t i = 0; i < hull.count; ++i) + for ( int32_t i = 0; i < hull.count; ++i ) { - g_draw.DrawPoint(hull.points[i], 6.0f, b2_colorGreen); + g_draw.DrawPoint( hull.points[i], 6.0f, b2_colorGreen ); } } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new ConvexHull(settings); + return new ConvexHull( settings ); } b2Vec2 m_points[b2_maxPolygonVertices]; @@ -217,4 +217,4 @@ class ConvexHull : public Sample bool m_bulk; }; -static int sampleIndex = RegisterSample("Geometry", "Convex Hull", ConvexHull::Create); +static int sampleIndex = RegisterSample( "Geometry", "Convex Hull", ConvexHull::Create ); diff --git a/samples/sample_joints.cpp b/samples/sample_joints.cpp index 9d96a713..1c226367 100644 --- a/samples/sample_joints.cpp +++ b/samples/sample_joints.cpp @@ -24,18 +24,18 @@ class DistanceJoint : public Sample e_maxCount = 10 }; - explicit DistanceJoint(Settings& settings) - : Sample(settings) + explicit DistanceJoint( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 12.0f}; + g_camera.m_center = { 0.0f, 12.0f }; g_camera.m_zoom = 25.0f * 0.35f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); - m_groundId = b2CreateBody(m_worldId, &bodyDef); + m_groundId = b2CreateBody( m_worldId, &bodyDef ); } m_count = 0; @@ -47,34 +47,34 @@ class DistanceJoint : public Sample m_enableSpring = false; m_enableLimit = false; - for (int i = 0; i < e_maxCount; ++i) + for ( int i = 0; i < e_maxCount; ++i ) { m_bodyIds[i] = b2_nullBodyId; m_jointIds[i] = b2_nullJointId; } - CreateScene(1); + CreateScene( 1 ); } - void CreateScene(int newCount) + void CreateScene( int newCount ) { // Must destroy joints before bodies - for (int i = 0; i < m_count; ++i) + for ( int i = 0; i < m_count; ++i ) { - b2DestroyJoint(m_jointIds[i]); + b2DestroyJoint( m_jointIds[i] ); m_jointIds[i] = b2_nullJointId; } - for (int i = 0; i < m_count; ++i) + for ( int i = 0; i < m_count; ++i ) { - b2DestroyBody(m_bodyIds[i]); + b2DestroyBody( m_bodyIds[i] ); m_bodyIds[i] = b2_nullBodyId; } m_count = newCount; float radius = 0.25f; - b2Circle circle = {{0.0f, 0.0f}, radius}; + b2Circle circle = { { 0.0f, 0.0f }, radius }; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 20.0f; @@ -91,21 +91,21 @@ class DistanceJoint : public Sample jointDef.enableLimit = m_enableLimit; b2BodyId prevBodyId = m_groundId; - for (int i = 0; i < m_count; ++i) + for ( int i = 0; i < m_count; ++i ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {m_length * (i + 1.0f), yOffset}; - m_bodyIds[i] = b2CreateBody(m_worldId, &bodyDef); - b2CreateCircleShape(m_bodyIds[i], &shapeDef, &circle); + bodyDef.position = { m_length * ( i + 1.0f ), yOffset }; + m_bodyIds[i] = b2CreateBody( m_worldId, &bodyDef ); + b2CreateCircleShape( m_bodyIds[i], &shapeDef, &circle ); - b2Vec2 pivotA = {m_length * i, yOffset}; - b2Vec2 pivotB = {m_length * (i + 1.0f), yOffset}; + b2Vec2 pivotA = { m_length * i, yOffset }; + b2Vec2 pivotB = { m_length * ( i + 1.0f ), yOffset }; jointDef.bodyIdA = prevBodyId; jointDef.bodyIdB = m_bodyIds[i]; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivotA); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivotB); - m_jointIds[i] = b2CreateDistanceJoint(m_worldId, &jointDef); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivotA ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivotB ); + m_jointIds[i] = b2CreateDistanceJoint( m_worldId, &jointDef ); prevBodyId = m_bodyIds[i]; } @@ -114,94 +114,94 @@ class DistanceJoint : public Sample void UpdateUI() override { float height = 140.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(180.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 180.0f, height ) ); - ImGui::Begin("Distance Joint", nullptr, ImGuiWindowFlags_NoResize); - ImGui::PushItemWidth(100.0f); + ImGui::Begin( "Distance Joint", nullptr, ImGuiWindowFlags_NoResize ); + ImGui::PushItemWidth( 100.0f ); - if (ImGui::SliderFloat("Length", &m_length, 0.1f, 4.0f, "%3.1f")) + if ( ImGui::SliderFloat( "Length", &m_length, 0.1f, 4.0f, "%3.1f" ) ) { - for (int i = 0; i < m_count; ++i) + for ( int i = 0; i < m_count; ++i ) { - b2DistanceJoint_SetLength(m_jointIds[i], m_length); - b2Joint_WakeBodies(m_jointIds[i]); + b2DistanceJoint_SetLength( m_jointIds[i], m_length ); + b2Joint_WakeBodies( m_jointIds[i] ); } } - if (ImGui::Checkbox("Spring", &m_enableSpring)) + if ( ImGui::Checkbox( "Spring", &m_enableSpring ) ) { - for (int i = 0; i < m_count; ++i) + for ( int i = 0; i < m_count; ++i ) { - b2DistanceJoint_EnableSpring(m_jointIds[i], m_enableSpring); - b2Joint_WakeBodies(m_jointIds[i]); + b2DistanceJoint_EnableSpring( m_jointIds[i], m_enableSpring ); + b2Joint_WakeBodies( m_jointIds[i] ); } } - if (m_enableSpring) + if ( m_enableSpring ) { - if (ImGui::SliderFloat("Hertz", &m_hertz, 0.0f, 15.0f, "%3.1f")) + if ( ImGui::SliderFloat( "Hertz", &m_hertz, 0.0f, 15.0f, "%3.1f" ) ) { - for (int i = 0; i < m_count; ++i) + for ( int i = 0; i < m_count; ++i ) { - b2DistanceJoint_SetSpringHertz(m_jointIds[i], m_hertz); - b2Joint_WakeBodies(m_jointIds[i]); + b2DistanceJoint_SetSpringHertz( m_jointIds[i], m_hertz ); + b2Joint_WakeBodies( m_jointIds[i] ); } } - if (ImGui::SliderFloat("Damping", &m_dampingRatio, 0.0f, 4.0f, "%3.1f")) + if ( ImGui::SliderFloat( "Damping", &m_dampingRatio, 0.0f, 4.0f, "%3.1f" ) ) { - for (int i = 0; i < m_count; ++i) + for ( int i = 0; i < m_count; ++i ) { - b2DistanceJoint_SetSpringDampingRatio(m_jointIds[i], m_dampingRatio); - b2Joint_WakeBodies(m_jointIds[i]); + b2DistanceJoint_SetSpringDampingRatio( m_jointIds[i], m_dampingRatio ); + b2Joint_WakeBodies( m_jointIds[i] ); } } } - if (ImGui::Checkbox("Limit", &m_enableLimit)) + if ( ImGui::Checkbox( "Limit", &m_enableLimit ) ) { - for (int i = 0; i < m_count; ++i) + for ( int i = 0; i < m_count; ++i ) { - b2DistanceJoint_EnableLimit(m_jointIds[i], m_enableLimit); - b2Joint_WakeBodies(m_jointIds[i]); + b2DistanceJoint_EnableLimit( m_jointIds[i], m_enableLimit ); + b2Joint_WakeBodies( m_jointIds[i] ); } } - if (m_enableLimit) + if ( m_enableLimit ) { - if (ImGui::SliderFloat("Min Length", &m_minLength, 0.1f, 4.0f, "%3.1f")) + if ( ImGui::SliderFloat( "Min Length", &m_minLength, 0.1f, 4.0f, "%3.1f" ) ) { - for (int i = 0; i < m_count; ++i) + for ( int i = 0; i < m_count; ++i ) { - b2DistanceJoint_SetLengthRange(m_jointIds[i], m_minLength, m_maxLength); - b2Joint_WakeBodies(m_jointIds[i]); + b2DistanceJoint_SetLengthRange( m_jointIds[i], m_minLength, m_maxLength ); + b2Joint_WakeBodies( m_jointIds[i] ); } } - if (ImGui::SliderFloat("Max Length", &m_maxLength, 0.1f, 4.0f, "%3.1f")) + if ( ImGui::SliderFloat( "Max Length", &m_maxLength, 0.1f, 4.0f, "%3.1f" ) ) { - for (int i = 0; i < m_count; ++i) + for ( int i = 0; i < m_count; ++i ) { - b2DistanceJoint_SetLengthRange(m_jointIds[i], m_minLength, m_maxLength); - b2Joint_WakeBodies(m_jointIds[i]); + b2DistanceJoint_SetLengthRange( m_jointIds[i], m_minLength, m_maxLength ); + b2Joint_WakeBodies( m_jointIds[i] ); } } } int count = m_count; - if (ImGui::SliderInt("Count", &count, 1, e_maxCount)) + if ( ImGui::SliderInt( "Count", &count, 1, e_maxCount ) ) { - CreateScene(count); + CreateScene( count ); } ImGui::PopItemWidth(); ImGui::End(); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new DistanceJoint(settings); + return new DistanceJoint( settings ); } b2BodyId m_groundId; @@ -217,7 +217,7 @@ class DistanceJoint : public Sample bool m_enableLimit; }; -static int sampleDistanceJoint = RegisterSample("Joints", "Distance Joint", DistanceJoint::Create); +static int sampleDistanceJoint = RegisterSample( "Joints", "Distance Joint", DistanceJoint::Create ); /// This test shows how to use a motor joint. A motor joint /// can be used to animate a dynamic body. With finite motor forces @@ -227,35 +227,35 @@ static int sampleDistanceJoint = RegisterSample("Joints", "Distance Joint", Dist class MotorJoint : public Sample { public: - explicit MotorJoint(Settings& settings) - : Sample(settings) + explicit MotorJoint( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 7.0f}; + g_camera.m_center = { 0.0f, 7.0f }; g_camera.m_zoom = 25.0f * 0.4f; } b2BodyId groundId; { b2BodyDef bodyDef = b2DefaultBodyDef(); - groundId = b2CreateBody(m_worldId, &bodyDef); + groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Segment segment = {{-20.0f, 0.0f}, {20.0f, 0.0f}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2Segment segment = { { -20.0f, 0.0f }, { 20.0f, 0.0f } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment ); } // Define motorized body { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {0.0f, 8.0f}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { 0.0f, 8.0f }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); - b2Polygon box = b2MakeBox(2.0f, 0.5f); + b2Polygon box = b2MakeBox( 2.0f, 0.5f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); m_maxForce = 500.0f; m_maxTorque = 500.0f; @@ -268,7 +268,7 @@ class MotorJoint : public Sample jointDef.maxTorque = m_maxTorque; jointDef.correctionFactor = m_correctionFactor; - m_jointId = b2CreateMotorJoint(m_worldId, &jointDef); + m_jointId = b2CreateMotorJoint( m_worldId, &jointDef ); } m_go = true; @@ -278,64 +278,64 @@ class MotorJoint : public Sample void UpdateUI() override { float height = 140.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(240.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); - ImGui::Begin("Motor Joint", nullptr, ImGuiWindowFlags_NoResize); + ImGui::Begin( "Motor Joint", nullptr, ImGuiWindowFlags_NoResize ); - if (ImGui::Checkbox("Go", &m_go)) + if ( ImGui::Checkbox( "Go", &m_go ) ) { } - if (ImGui::SliderFloat("Max Force", &m_maxForce, 0.0f, 1000.0f, "%.0f")) + if ( ImGui::SliderFloat( "Max Force", &m_maxForce, 0.0f, 1000.0f, "%.0f" ) ) { - b2MotorJoint_SetMaxForce(m_jointId, m_maxForce); + b2MotorJoint_SetMaxForce( m_jointId, m_maxForce ); } - if (ImGui::SliderFloat("Max Torque", &m_maxTorque, 0.0f, 1000.0f, "%.0f")) + if ( ImGui::SliderFloat( "Max Torque", &m_maxTorque, 0.0f, 1000.0f, "%.0f" ) ) { - b2MotorJoint_SetMaxTorque(m_jointId, m_maxTorque); + b2MotorJoint_SetMaxTorque( m_jointId, m_maxTorque ); } - if (ImGui::SliderFloat("Correction", &m_correctionFactor, 0.0f, 1.0f, "%.1f")) + if ( ImGui::SliderFloat( "Correction", &m_correctionFactor, 0.0f, 1.0f, "%.1f" ) ) { - b2MotorJoint_SetCorrectionFactor(m_jointId, m_correctionFactor); + b2MotorJoint_SetCorrectionFactor( m_jointId, m_correctionFactor ); } ImGui::End(); } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - if (m_go && settings.hertz > 0.0f) + if ( m_go && settings.hertz > 0.0f ) { m_time += 1.0f / settings.hertz; } b2Vec2 linearOffset; - linearOffset.x = 6.0f * sinf(2.0f * m_time); - linearOffset.y = 8.0f + 4.0f * sinf(1.0f * m_time); + linearOffset.x = 6.0f * sinf( 2.0f * m_time ); + linearOffset.y = 8.0f + 4.0f * sinf( 1.0f * m_time ); - float angularOffset = b2_pi * sinf(-0.5f * m_time); + float angularOffset = b2_pi * sinf( -0.5f * m_time ); - b2MotorJoint_SetLinearOffset(m_jointId, linearOffset); - b2MotorJoint_SetAngularOffset(m_jointId, angularOffset); + b2MotorJoint_SetLinearOffset( m_jointId, linearOffset ); + b2MotorJoint_SetAngularOffset( m_jointId, angularOffset ); - b2Transform transform = {linearOffset, b2MakeRot(angularOffset)}; - g_draw.DrawTransform(transform); + b2Transform transform = { linearOffset, b2MakeRot( angularOffset ) }; + g_draw.DrawTransform( transform ); - Sample::Step(settings); + Sample::Step( settings ); - b2Vec2 force = b2Joint_GetConstraintForce(m_jointId); - float torque = b2Joint_GetConstraintTorque(m_jointId); + b2Vec2 force = b2Joint_GetConstraintForce( m_jointId ); + float torque = b2Joint_GetConstraintTorque( m_jointId ); - g_draw.DrawString(5, m_textLine, "force = {%3.f, %3.f}, torque = %3.f", force.x, force.y, torque); + g_draw.DrawString( 5, m_textLine, "force = {%3.f, %3.f}, torque = %3.f", force.x, force.y, torque ); m_textLine += 15; } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new MotorJoint(settings); + return new MotorJoint( settings ); } b2JointId m_jointId; @@ -346,30 +346,30 @@ class MotorJoint : public Sample bool m_go; }; -static int sampleMotorJoint = RegisterSample("Joints", "Motor Joint", MotorJoint::Create); +static int sampleMotorJoint = RegisterSample( "Joints", "Motor Joint", MotorJoint::Create ); class RevoluteJoint : public Sample { public: - explicit RevoluteJoint(Settings& settings) - : Sample(settings) + explicit RevoluteJoint( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 15.5f}; + g_camera.m_center = { 0.0f, 15.5f }; g_camera.m_zoom = 25.0f * 0.7f; } b2BodyId groundId = b2_nullBodyId; { b2BodyDef bodyDef = b2DefaultBodyDef(); - bodyDef.position = {0.0f, -1.0f}; - groundId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { 0.0f, -1.0f }; + groundId = b2CreateBody( m_worldId, &bodyDef ); - b2Polygon box = b2MakeBox(40.0f, 1.0f); + b2Polygon box = b2MakeBox( 40.0f, 1.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreatePolygonShape(groundId, &shapeDef, &box); + b2CreatePolygonShape( groundId, &shapeDef, &box ); } m_enableSpring = false; @@ -383,21 +383,21 @@ class RevoluteJoint : public Sample { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {-10.0f, 20.0f}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { -10.0f, 20.0f }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; - - b2Capsule capsule = {{0.0f, -1.0f}, {0.0f, 6.0f}, 0.5f}; - b2CreateCapsuleShape(bodyId, &shapeDef, &capsule); - b2Vec2 pivot = {-10.0f, 20.5f}; + b2Capsule capsule = { { 0.0f, -1.0f }, { 0.0f, 6.0f }, 0.5f }; + b2CreateCapsuleShape( bodyId, &shapeDef, &capsule ); + + b2Vec2 pivot = { -10.0f, 20.5f }; b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.bodyIdA = groundId; jointDef.bodyIdB = bodyId; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); jointDef.enableSpring = m_enableSpring; jointDef.hertz = m_hertz; jointDef.dampingRatio = m_dampingRatio; @@ -409,41 +409,41 @@ class RevoluteJoint : public Sample jointDef.upperAngle = 0.75f * b2_pi; jointDef.enableLimit = m_enableLimit; - m_jointId1 = b2CreateRevoluteJoint(m_worldId, &jointDef); + m_jointId1 = b2CreateRevoluteJoint( m_worldId, &jointDef ); } { - b2Circle circle = {0}; + b2Circle circle = { 0 }; circle.radius = 2.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {5.0f, 30.0f}; - m_ball = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { 5.0f, 30.0f }; + m_ball = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; - b2CreateCircleShape(m_ball, &shapeDef, &circle); + b2CreateCircleShape( m_ball, &shapeDef, &circle ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); - bodyDef.position = {20.0f, 10.0f}; + bodyDef.position = { 20.0f, 10.0f }; bodyDef.type = b2_dynamicBody; - b2BodyId body = b2CreateBody(m_worldId, &bodyDef); + b2BodyId body = b2CreateBody( m_worldId, &bodyDef ); - b2Polygon box = b2MakeOffsetBox(10.0f, 0.5f, {-10.0f, 0.0f}, 0.0f); + b2Polygon box = b2MakeOffsetBox( 10.0f, 0.5f, { -10.0f, 0.0f }, 0.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; - b2CreatePolygonShape(body, &shapeDef, &box); + b2CreatePolygonShape( body, &shapeDef, &box ); - b2Vec2 pivot = {19.0f, 10.0f}; + b2Vec2 pivot = { 19.0f, 10.0f }; b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.bodyIdA = groundId; jointDef.bodyIdB = body; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); jointDef.lowerAngle = -0.25f * b2_pi; jointDef.upperAngle = 0.0f * b2_pi; jointDef.enableLimit = true; @@ -451,89 +451,89 @@ class RevoluteJoint : public Sample jointDef.motorSpeed = 0.0f; jointDef.maxMotorTorque = m_motorTorque; - m_jointId2 = b2CreateRevoluteJoint(m_worldId, &jointDef); + m_jointId2 = b2CreateRevoluteJoint( m_worldId, &jointDef ); } } void UpdateUI() override { float height = 220.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(240.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); - ImGui::Begin("Revolute Joint", nullptr, ImGuiWindowFlags_NoResize); + ImGui::Begin( "Revolute Joint", nullptr, ImGuiWindowFlags_NoResize ); - if (ImGui::Checkbox("Limit", &m_enableLimit)) + if ( ImGui::Checkbox( "Limit", &m_enableLimit ) ) { - b2RevoluteJoint_EnableLimit(m_jointId1, m_enableLimit); - b2Joint_WakeBodies(m_jointId1); + b2RevoluteJoint_EnableLimit( m_jointId1, m_enableLimit ); + b2Joint_WakeBodies( m_jointId1 ); } - if (ImGui::Checkbox("Motor", &m_enableMotor)) + if ( ImGui::Checkbox( "Motor", &m_enableMotor ) ) { - b2RevoluteJoint_EnableMotor(m_jointId1, m_enableMotor); - b2Joint_WakeBodies(m_jointId1); + b2RevoluteJoint_EnableMotor( m_jointId1, m_enableMotor ); + b2Joint_WakeBodies( m_jointId1 ); } - if (m_enableMotor) + if ( m_enableMotor ) { - if (ImGui::SliderFloat("Max Torque", &m_motorTorque, 0.0f, 5000.0f, "%.0f")) + if ( ImGui::SliderFloat( "Max Torque", &m_motorTorque, 0.0f, 5000.0f, "%.0f" ) ) { - b2RevoluteJoint_SetMaxMotorTorque(m_jointId1, m_motorTorque); - b2Joint_WakeBodies(m_jointId1); + b2RevoluteJoint_SetMaxMotorTorque( m_jointId1, m_motorTorque ); + b2Joint_WakeBodies( m_jointId1 ); } - - if (ImGui::SliderFloat("Speed", &m_motorSpeed, -20.0f, 20.0f, "%.0f")) + + if ( ImGui::SliderFloat( "Speed", &m_motorSpeed, -20.0f, 20.0f, "%.0f" ) ) { - b2RevoluteJoint_SetMotorSpeed(m_jointId1, m_motorSpeed); - b2Joint_WakeBodies(m_jointId1); + b2RevoluteJoint_SetMotorSpeed( m_jointId1, m_motorSpeed ); + b2Joint_WakeBodies( m_jointId1 ); } } - if (ImGui::Checkbox("Spring", &m_enableSpring)) + if ( ImGui::Checkbox( "Spring", &m_enableSpring ) ) { - b2RevoluteJoint_EnableSpring(m_jointId1, m_enableSpring); - b2Joint_WakeBodies(m_jointId1); + b2RevoluteJoint_EnableSpring( m_jointId1, m_enableSpring ); + b2Joint_WakeBodies( m_jointId1 ); } - if (m_enableSpring) + if ( m_enableSpring ) { - if (ImGui::SliderFloat("Hertz", &m_hertz, 0.0f, 10.0f, "%.1f")) + if ( ImGui::SliderFloat( "Hertz", &m_hertz, 0.0f, 10.0f, "%.1f" ) ) { - b2RevoluteJoint_SetSpringHertz(m_jointId1, m_hertz); - b2Joint_WakeBodies(m_jointId1); + b2RevoluteJoint_SetSpringHertz( m_jointId1, m_hertz ); + b2Joint_WakeBodies( m_jointId1 ); } - if (ImGui::SliderFloat("Damping", &m_dampingRatio, 0.0f, 2.0f, "%.1f")) + if ( ImGui::SliderFloat( "Damping", &m_dampingRatio, 0.0f, 2.0f, "%.1f" ) ) { - b2RevoluteJoint_SetSpringDampingRatio(m_jointId1, m_dampingRatio); - b2Joint_WakeBodies(m_jointId1); + b2RevoluteJoint_SetSpringDampingRatio( m_jointId1, m_dampingRatio ); + b2Joint_WakeBodies( m_jointId1 ); } } - + ImGui::End(); } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - Sample::Step(settings); + Sample::Step( settings ); - float angle1 = b2RevoluteJoint_GetAngle(m_jointId1); - g_draw.DrawString(5, m_textLine, "Angle (Deg) 1 = %2.1f", angle1); + float angle1 = b2RevoluteJoint_GetAngle( m_jointId1 ); + g_draw.DrawString( 5, m_textLine, "Angle (Deg) 1 = %2.1f", angle1 ); m_textLine += m_textIncrement; - float torque1 = b2RevoluteJoint_GetMotorTorque(m_jointId1); - g_draw.DrawString(5, m_textLine, "Motor Torque 1 = %4.1f", torque1); + float torque1 = b2RevoluteJoint_GetMotorTorque( m_jointId1 ); + g_draw.DrawString( 5, m_textLine, "Motor Torque 1 = %4.1f", torque1 ); m_textLine += m_textIncrement; - float torque2 = b2RevoluteJoint_GetMotorTorque(m_jointId2); - g_draw.DrawString(5, m_textLine, "Motor Torque 2 = %4.1f", torque2); + float torque2 = b2RevoluteJoint_GetMotorTorque( m_jointId2 ); + g_draw.DrawString( 5, m_textLine, "Motor Torque 2 = %4.1f", torque2 ); m_textLine += m_textIncrement; } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new RevoluteJoint(settings); + return new RevoluteJoint( settings ); } b2BodyId m_ball; @@ -548,24 +548,24 @@ class RevoluteJoint : public Sample bool m_enableLimit; }; -static int sampleRevolute = RegisterSample("Joints", "Revolute", RevoluteJoint::Create); +static int sampleRevolute = RegisterSample( "Joints", "Revolute", RevoluteJoint::Create ); class PrismaticJoint : public Sample { public: - explicit PrismaticJoint(Settings& settings) - : Sample(settings) + explicit PrismaticJoint( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 8.0f}; + g_camera.m_center = { 0.0f, 8.0f }; g_camera.m_zoom = 25.0f * 0.5f; } b2BodyId groundId; { b2BodyDef bodyDef = b2DefaultBodyDef(); - groundId = b2CreateBody(m_worldId, &bodyDef); + groundId = b2CreateBody( m_worldId, &bodyDef ); } m_enableSpring = false; @@ -578,23 +578,23 @@ class PrismaticJoint : public Sample { b2BodyDef bodyDef = b2DefaultBodyDef(); - bodyDef.position = {0.0f, 10.0f}; + bodyDef.position = { 0.0f, 10.0f }; bodyDef.type = b2_dynamicBody; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Polygon box = b2MakeBox(0.5f, 2.0f); - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2Polygon box = b2MakeBox( 0.5f, 2.0f ); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); - b2Vec2 pivot = {0.0f, 9.0f}; + b2Vec2 pivot = { 0.0f, 9.0f }; // b2Vec2 axis = b2Normalize({1.0f, 0.0f}); - b2Vec2 axis = b2Normalize({1.0f, 1.0f}); + b2Vec2 axis = b2Normalize( { 1.0f, 1.0f } ); b2PrismaticJointDef jointDef = b2DefaultPrismaticJointDef(); jointDef.bodyIdA = groundId; jointDef.bodyIdB = bodyId; - jointDef.localAxisA = b2Body_GetLocalVector(jointDef.bodyIdA, axis); - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); + jointDef.localAxisA = b2Body_GetLocalVector( jointDef.bodyIdA, axis ); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); jointDef.motorSpeed = m_motorSpeed; jointDef.maxMotorForce = m_motorForce; jointDef.enableMotor = m_enableMotor; @@ -605,81 +605,81 @@ class PrismaticJoint : public Sample jointDef.hertz = m_hertz; jointDef.dampingRatio = m_dampingRatio; - m_jointId = b2CreatePrismaticJoint(m_worldId, &jointDef); + m_jointId = b2CreatePrismaticJoint( m_worldId, &jointDef ); } } void UpdateUI() override { float height = 220.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(240.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); - ImGui::Begin("Prismatic Joint", nullptr, ImGuiWindowFlags_NoResize); + ImGui::Begin( "Prismatic Joint", nullptr, ImGuiWindowFlags_NoResize ); - if (ImGui::Checkbox("Limit", &m_enableLimit)) + if ( ImGui::Checkbox( "Limit", &m_enableLimit ) ) { - b2PrismaticJoint_EnableLimit(m_jointId, m_enableLimit); - b2Joint_WakeBodies(m_jointId); + b2PrismaticJoint_EnableLimit( m_jointId, m_enableLimit ); + b2Joint_WakeBodies( m_jointId ); } - if (ImGui::Checkbox("Motor", &m_enableMotor)) + if ( ImGui::Checkbox( "Motor", &m_enableMotor ) ) { - b2PrismaticJoint_EnableMotor(m_jointId, m_enableMotor); - b2Joint_WakeBodies(m_jointId); + b2PrismaticJoint_EnableMotor( m_jointId, m_enableMotor ); + b2Joint_WakeBodies( m_jointId ); } - if (m_enableMotor) + if ( m_enableMotor ) { - if (ImGui::SliderFloat("Max Force", &m_motorForce, 0.0f, 200.0f, "%.0f")) + if ( ImGui::SliderFloat( "Max Force", &m_motorForce, 0.0f, 200.0f, "%.0f" ) ) { - b2PrismaticJoint_SetMaxMotorForce(m_jointId, m_motorForce); - b2Joint_WakeBodies(m_jointId); + b2PrismaticJoint_SetMaxMotorForce( m_jointId, m_motorForce ); + b2Joint_WakeBodies( m_jointId ); } - if (ImGui::SliderFloat("Speed", &m_motorSpeed, -40.0f, 40.0f, "%.0f")) + if ( ImGui::SliderFloat( "Speed", &m_motorSpeed, -40.0f, 40.0f, "%.0f" ) ) { - b2PrismaticJoint_SetMotorSpeed(m_jointId, m_motorSpeed); - b2Joint_WakeBodies(m_jointId); + b2PrismaticJoint_SetMotorSpeed( m_jointId, m_motorSpeed ); + b2Joint_WakeBodies( m_jointId ); } } - if (ImGui::Checkbox("Spring", &m_enableSpring)) + if ( ImGui::Checkbox( "Spring", &m_enableSpring ) ) { - b2PrismaticJoint_EnableSpring(m_jointId, m_enableSpring); - b2Joint_WakeBodies(m_jointId); + b2PrismaticJoint_EnableSpring( m_jointId, m_enableSpring ); + b2Joint_WakeBodies( m_jointId ); } - if (m_enableSpring) + if ( m_enableSpring ) { - if (ImGui::SliderFloat("Hertz", &m_hertz, 0.0f, 10.0f, "%.1f")) + if ( ImGui::SliderFloat( "Hertz", &m_hertz, 0.0f, 10.0f, "%.1f" ) ) { - b2PrismaticJoint_SetSpringHertz(m_jointId, m_hertz); - b2Joint_WakeBodies(m_jointId); + b2PrismaticJoint_SetSpringHertz( m_jointId, m_hertz ); + b2Joint_WakeBodies( m_jointId ); } - if (ImGui::SliderFloat("Damping", &m_dampingRatio, 0.0f, 2.0f, "%.1f")) + if ( ImGui::SliderFloat( "Damping", &m_dampingRatio, 0.0f, 2.0f, "%.1f" ) ) { - b2PrismaticJoint_SetSpringDampingRatio(m_jointId, m_dampingRatio); - b2Joint_WakeBodies(m_jointId); + b2PrismaticJoint_SetSpringDampingRatio( m_jointId, m_dampingRatio ); + b2Joint_WakeBodies( m_jointId ); } } - + ImGui::End(); } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - Sample::Step(settings); + Sample::Step( settings ); - float force = b2PrismaticJoint_GetMotorForce(m_jointId); - g_draw.DrawString(5, m_textLine, "Motor Force = %4.1f", force); + float force = b2PrismaticJoint_GetMotorForce( m_jointId ); + g_draw.DrawString( 5, m_textLine, "Motor Force = %4.1f", force ); m_textLine += m_textIncrement; } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new PrismaticJoint(settings); + return new PrismaticJoint( settings ); } b2JointId m_jointId; @@ -692,17 +692,17 @@ class PrismaticJoint : public Sample bool m_enableLimit; }; -static int samplePrismatic = RegisterSample("Joints", "Prismatic", PrismaticJoint::Create); +static int samplePrismatic = RegisterSample( "Joints", "Prismatic", PrismaticJoint::Create ); class WheelJoint : public Sample { public: - explicit WheelJoint(Settings& settings) - : Sample(settings) + explicit WheelJoint( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 10.0f}; + g_camera.m_center = { 0.0f, 10.0f }; g_camera.m_zoom = 25.0f * 0.15f; } @@ -710,7 +710,7 @@ class WheelJoint : public Sample { b2BodyDef bodyDef = b2DefaultBodyDef(); - groundId = b2CreateBody(m_worldId, &bodyDef); + groundId = b2CreateBody( m_worldId, &bodyDef ); } m_enableSpring = true; @@ -723,22 +723,22 @@ class WheelJoint : public Sample { b2BodyDef bodyDef = b2DefaultBodyDef(); - bodyDef.position = {0.0f, 10.25f}; + bodyDef.position = { 0.0f, 10.25f }; bodyDef.type = b2_dynamicBody; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Capsule capsule = {{0.0f, -0.5f}, {0.0f, 0.5f}, 0.5f}; - b2CreateCapsuleShape(bodyId, &shapeDef, &capsule); + b2Capsule capsule = { { 0.0f, -0.5f }, { 0.0f, 0.5f }, 0.5f }; + b2CreateCapsuleShape( bodyId, &shapeDef, &capsule ); - b2Vec2 pivot = {0.0f, 10.0f}; - b2Vec2 axis = b2Normalize({1.0f, 1.0f}); + b2Vec2 pivot = { 0.0f, 10.0f }; + b2Vec2 axis = b2Normalize( { 1.0f, 1.0f } ); b2WheelJointDef jointDef = b2DefaultWheelJointDef(); jointDef.bodyIdA = groundId; jointDef.bodyIdB = bodyId; - jointDef.localAxisA = b2Body_GetLocalVector(jointDef.bodyIdA, axis); - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); + jointDef.localAxisA = b2Body_GetLocalVector( jointDef.bodyIdA, axis ); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); jointDef.motorSpeed = m_motorSpeed; jointDef.maxMotorTorque = m_motorTorque; jointDef.enableMotor = m_enableMotor; @@ -748,74 +748,74 @@ class WheelJoint : public Sample jointDef.hertz = m_hertz; jointDef.dampingRatio = m_dampingRatio; - m_jointId = b2CreateWheelJoint(m_worldId, &jointDef); + m_jointId = b2CreateWheelJoint( m_worldId, &jointDef ); } } void UpdateUI() override { float height = 220.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(240.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); - ImGui::Begin("Wheel Joint", nullptr, ImGuiWindowFlags_NoResize); + ImGui::Begin( "Wheel Joint", nullptr, ImGuiWindowFlags_NoResize ); - if (ImGui::Checkbox("Limit", &m_enableLimit)) + if ( ImGui::Checkbox( "Limit", &m_enableLimit ) ) { - b2WheelJoint_EnableLimit(m_jointId, m_enableLimit); + b2WheelJoint_EnableLimit( m_jointId, m_enableLimit ); } - if (ImGui::Checkbox("Motor", &m_enableMotor)) + if ( ImGui::Checkbox( "Motor", &m_enableMotor ) ) { - b2WheelJoint_EnableMotor(m_jointId, m_enableMotor); + b2WheelJoint_EnableMotor( m_jointId, m_enableMotor ); } - if (m_enableMotor) + if ( m_enableMotor ) { - if (ImGui::SliderFloat("Torque", &m_motorTorque, 0.0f, 20.0f, "%.0f")) + if ( ImGui::SliderFloat( "Torque", &m_motorTorque, 0.0f, 20.0f, "%.0f" ) ) { - b2WheelJoint_SetMaxMotorTorque(m_jointId, m_motorTorque); + b2WheelJoint_SetMaxMotorTorque( m_jointId, m_motorTorque ); } - - if (ImGui::SliderFloat("Speed", &m_motorSpeed, -20.0f, 20.0f, "%.0f")) + + if ( ImGui::SliderFloat( "Speed", &m_motorSpeed, -20.0f, 20.0f, "%.0f" ) ) { - b2WheelJoint_SetMotorSpeed(m_jointId, m_motorSpeed); + b2WheelJoint_SetMotorSpeed( m_jointId, m_motorSpeed ); } } - - if (ImGui::Checkbox("Spring", &m_enableSpring)) + + if ( ImGui::Checkbox( "Spring", &m_enableSpring ) ) { - b2WheelJoint_EnableSpring(m_jointId, m_enableSpring); + b2WheelJoint_EnableSpring( m_jointId, m_enableSpring ); } - if (m_enableSpring) + if ( m_enableSpring ) { - if (ImGui::SliderFloat("Hertz", &m_hertz, 0.0f, 10.0f, "%.1f")) + if ( ImGui::SliderFloat( "Hertz", &m_hertz, 0.0f, 10.0f, "%.1f" ) ) { - b2WheelJoint_SetSpringHertz(m_jointId, m_hertz); + b2WheelJoint_SetSpringHertz( m_jointId, m_hertz ); } - if (ImGui::SliderFloat("Damping", &m_dampingRatio, 0.0f, 2.0f, "%.1f")) + if ( ImGui::SliderFloat( "Damping", &m_dampingRatio, 0.0f, 2.0f, "%.1f" ) ) { - b2WheelJoint_SetSpringDampingRatio(m_jointId, m_dampingRatio); + b2WheelJoint_SetSpringDampingRatio( m_jointId, m_dampingRatio ); } } - + ImGui::End(); } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - Sample::Step(settings); + Sample::Step( settings ); - float torque = b2WheelJoint_GetMotorTorque(m_jointId); - g_draw.DrawString(5, m_textLine, "Motor Torque = %4.1f", torque); + float torque = b2WheelJoint_GetMotorTorque( m_jointId ); + g_draw.DrawString( 5, m_textLine, "Motor Torque = %4.1f", torque ); m_textLine += m_textIncrement; } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new WheelJoint(settings); + return new WheelJoint( settings ); } b2JointId m_jointId; @@ -828,7 +828,7 @@ class WheelJoint : public Sample bool m_enableLimit; }; -static int sampleWheel = RegisterSample("Joints", "Wheel", WheelJoint::Create); +static int sampleWheel = RegisterSample( "Joints", "Wheel", WheelJoint::Create ); // A suspension bridge class Bridge : public Sample @@ -839,10 +839,10 @@ class Bridge : public Sample e_count = 160 }; - explicit Bridge(Settings& settings) - : Sample(settings) + explicit Bridge( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { g_camera.m_zoom = 25.0f * 2.5f; } @@ -850,11 +850,11 @@ class Bridge : public Sample b2BodyId groundId = b2_nullBodyId; { b2BodyDef bodyDef = b2DefaultBodyDef(); - groundId = b2CreateBody(m_worldId, &bodyDef); + groundId = b2CreateBody( m_worldId, &bodyDef ); } { - b2Polygon box = b2MakeBox(0.5f, 0.125f); + b2Polygon box = b2MakeBox( 0.5f, 0.125f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 20.0f; @@ -867,105 +867,105 @@ class Bridge : public Sample float xbase = -80.0f; b2BodyId prevBodyId = groundId; - for (int i = 0; i < e_count; ++i) + for ( int i = 0; i < e_count; ++i ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {xbase + 0.5f + 1.0f * i, 20.0f}; + bodyDef.position = { xbase + 0.5f + 1.0f * i, 20.0f }; bodyDef.linearDamping = 0.1f; bodyDef.angularDamping = 0.1f; - m_bodyIds[i] = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(m_bodyIds[i], &shapeDef, &box); + m_bodyIds[i] = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( m_bodyIds[i], &shapeDef, &box ); - b2Vec2 pivot = {xbase + 1.0f * i, 20.0f}; + b2Vec2 pivot = { xbase + 1.0f * i, 20.0f }; jointDef.bodyIdA = prevBodyId; jointDef.bodyIdB = m_bodyIds[i]; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); jointDef.enableMotor = true; jointDef.maxMotorTorque = m_frictionTorque; - m_jointIds[jointIndex++] = b2CreateRevoluteJoint(m_worldId, &jointDef); + m_jointIds[jointIndex++] = b2CreateRevoluteJoint( m_worldId, &jointDef ); prevBodyId = m_bodyIds[i]; } - b2Vec2 pivot = {xbase + 1.0f * e_count, 20.0f}; + b2Vec2 pivot = { xbase + 1.0f * e_count, 20.0f }; jointDef.bodyIdA = prevBodyId; jointDef.bodyIdB = groundId; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); jointDef.enableMotor = true; jointDef.maxMotorTorque = m_frictionTorque; - m_jointIds[jointIndex++] = b2CreateRevoluteJoint(m_worldId, &jointDef); + m_jointIds[jointIndex++] = b2CreateRevoluteJoint( m_worldId, &jointDef ); - assert(jointIndex == e_count + 1); + assert( jointIndex == e_count + 1 ); } - for (int i = 0; i < 2; ++i) + for ( int i = 0; i < 2; ++i ) { - b2Vec2 vertices[3] = {{-0.5f, 0.0f}, {0.5f, 0.0f}, {0.0f, 1.5f}}; + b2Vec2 vertices[3] = { { -0.5f, 0.0f }, { 0.5f, 0.0f }, { 0.0f, 1.5f } }; - b2Hull hull = b2ComputeHull(vertices, 3); - b2Polygon triangle = b2MakePolygon(&hull, 0.0f); + b2Hull hull = b2ComputeHull( vertices, 3 ); + b2Polygon triangle = b2MakePolygon( &hull, 0.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 20.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {-8.0f + 8.0f * i, 22.0f}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &triangle); + bodyDef.position = { -8.0f + 8.0f * i, 22.0f }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &triangle ); } - for (int i = 0; i < 3; ++i) + for ( int i = 0; i < 3; ++i ) { - b2Circle circle = {{0.0f, 0.0f}, 0.5f}; + b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 20.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {-6.0f + 6.0f * i, 25.0f}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreateCircleShape(bodyId, &shapeDef, &circle); + bodyDef.position = { -6.0f + 6.0f * i, 25.0f }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreateCircleShape( bodyId, &shapeDef, &circle ); } } void UpdateUI() override { float height = 80.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(240.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); - ImGui::Begin("Bridge", nullptr, ImGuiWindowFlags_NoResize); + ImGui::Begin( "Bridge", nullptr, ImGuiWindowFlags_NoResize ); // Slider takes half the window - ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f); - bool updateFriction = ImGui::SliderFloat("Joint Friction", &m_frictionTorque, 0.0f, 1000.0f, "%2.f"); - if (updateFriction) + ImGui::PushItemWidth( ImGui::GetWindowWidth() * 0.5f ); + bool updateFriction = ImGui::SliderFloat( "Joint Friction", &m_frictionTorque, 0.0f, 1000.0f, "%2.f" ); + if ( updateFriction ) { - for (int i = 0; i <= e_count; ++i) + for ( int i = 0; i <= e_count; ++i ) { - b2RevoluteJoint_SetMaxMotorTorque(m_jointIds[i], m_frictionTorque); + b2RevoluteJoint_SetMaxMotorTorque( m_jointIds[i], m_frictionTorque ); } } - if (ImGui::SliderFloat("Gravity scale", &m_gravityScale, -1.0f, 1.0f, "%.1f")) + if ( ImGui::SliderFloat( "Gravity scale", &m_gravityScale, -1.0f, 1.0f, "%.1f" ) ) { - for (int i = 0; i < e_count; ++i) + for ( int i = 0; i < e_count; ++i ) { - b2Body_SetGravityScale(m_bodyIds[i], m_gravityScale); + b2Body_SetGravityScale( m_bodyIds[i], m_gravityScale ); } } ImGui::End(); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new Bridge(settings); + return new Bridge( settings ); } b2BodyId m_bodyIds[e_count]; @@ -974,7 +974,7 @@ class Bridge : public Sample float m_gravityScale; }; -static int sampleBridgeIndex = RegisterSample("Joints", "Bridge", Bridge::Create); +static int sampleBridgeIndex = RegisterSample( "Joints", "Bridge", Bridge::Create ); class BallAndChain : public Sample { @@ -984,26 +984,26 @@ class BallAndChain : public Sample e_count = 30 }; - explicit BallAndChain(Settings& settings) - : Sample(settings) + explicit BallAndChain( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, -8.0f}; + g_camera.m_center = { 0.0f, -8.0f }; g_camera.m_zoom = 27.5f; } b2BodyId groundId = b2_nullBodyId; { b2BodyDef bodyDef = b2DefaultBodyDef(); - groundId = b2CreateBody(m_worldId, &bodyDef); + groundId = b2CreateBody( m_worldId, &bodyDef ); } m_frictionTorque = 100.0f; { float hx = 0.5f; - b2Capsule capsule = {{-hx, 0.0f}, {hx, 0.0f}, 0.125f}; + b2Capsule capsule = { { -hx, 0.0f }, { hx, 0.0f }, 0.125f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 20.0f; @@ -1013,77 +1013,77 @@ class BallAndChain : public Sample int jointIndex = 0; b2BodyId prevBodyId = groundId; - for (int i = 0; i < e_count; ++i) + for ( int i = 0; i < e_count; ++i ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {(1.0f + 2.0f * i) * hx, e_count * hx}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreateCapsuleShape(bodyId, &shapeDef, &capsule); + bodyDef.position = { ( 1.0f + 2.0f * i ) * hx, e_count * hx }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreateCapsuleShape( bodyId, &shapeDef, &capsule ); - b2Vec2 pivot = {(2.0f * i) * hx, e_count * hx}; + b2Vec2 pivot = { ( 2.0f * i ) * hx, e_count * hx }; jointDef.bodyIdA = prevBodyId; jointDef.bodyIdB = bodyId; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); // jointDef.enableMotor = true; jointDef.maxMotorTorque = m_frictionTorque; - m_jointIds[jointIndex++] = b2CreateRevoluteJoint(m_worldId, &jointDef); + m_jointIds[jointIndex++] = b2CreateRevoluteJoint( m_worldId, &jointDef ); prevBodyId = bodyId; } - b2Circle circle = {{0.0f, 0.0f}, 4.0f}; + b2Circle circle = { { 0.0f, 0.0f }, 4.0f }; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {(1.0f + 2.0f * e_count) * hx + circle.radius - hx, e_count * hx}; + bodyDef.position = { ( 1.0f + 2.0f * e_count ) * hx + circle.radius - hx, e_count * hx }; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreateCircleShape(bodyId, &shapeDef, &circle); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreateCircleShape( bodyId, &shapeDef, &circle ); - b2Vec2 pivot = {(2.0f * e_count) * hx, e_count * hx}; + b2Vec2 pivot = { ( 2.0f * e_count ) * hx, e_count * hx }; jointDef.bodyIdA = prevBodyId; jointDef.bodyIdB = bodyId; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); jointDef.enableMotor = true; jointDef.maxMotorTorque = m_frictionTorque; - m_jointIds[jointIndex++] = b2CreateRevoluteJoint(m_worldId, &jointDef); - assert(jointIndex == e_count + 1); + m_jointIds[jointIndex++] = b2CreateRevoluteJoint( m_worldId, &jointDef ); + assert( jointIndex == e_count + 1 ); } } void UpdateUI() override { float height = 60.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(240.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); - ImGui::Begin("Ball and Chain", nullptr, ImGuiWindowFlags_NoResize); + ImGui::Begin( "Ball and Chain", nullptr, ImGuiWindowFlags_NoResize ); - bool updateFriction = ImGui::SliderFloat("Joint Friction", &m_frictionTorque, 0.0f, 1000.0f, "%2.f"); - if (updateFriction) + bool updateFriction = ImGui::SliderFloat( "Joint Friction", &m_frictionTorque, 0.0f, 1000.0f, "%2.f" ); + if ( updateFriction ) { - for (int i = 0; i <= e_count; ++i) + for ( int i = 0; i <= e_count; ++i ) { - b2RevoluteJoint_SetMaxMotorTorque(m_jointIds[i], m_frictionTorque); + b2RevoluteJoint_SetMaxMotorTorque( m_jointIds[i], m_frictionTorque ); } } ImGui::End(); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new BallAndChain(settings); + return new BallAndChain( settings ); } b2JointId m_jointIds[e_count + 1]; float m_frictionTorque; }; -static int sampleBallAndChainIndex = RegisterSample("Joints", "Ball & Chain", BallAndChain::Create); +static int sampleBallAndChainIndex = RegisterSample( "Joints", "Ball & Chain", BallAndChain::Create ); // This sample shows the limitations of an iterative solver. The cantilever sags even though the weld // joint is stiff as possible. @@ -1095,19 +1095,19 @@ class Cantilever : public Sample e_count = 8 }; - explicit Cantilever(Settings& settings) - : Sample(settings) + explicit Cantilever( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 0.0f}; + g_camera.m_center = { 0.0f, 0.0f }; g_camera.m_zoom = 25.0f * 0.35f; } b2BodyId groundId = b2_nullBodyId; { b2BodyDef bodyDef = b2DefaultBodyDef(); - groundId = b2CreateBody(m_worldId, &bodyDef); + groundId = b2CreateBody( m_worldId, &bodyDef ); } { @@ -1119,7 +1119,7 @@ class Cantilever : public Sample m_collideConnected = false; float hx = 0.5f; - b2Capsule capsule = {{-hx, 0.0f}, {hx, 0.0f}, 0.125f}; + b2Capsule capsule = { { -hx, 0.0f }, { hx, 0.0f }, 0.125f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 20.0f; @@ -1130,23 +1130,23 @@ class Cantilever : public Sample bodyDef.isAwake = false; b2BodyId prevBodyId = groundId; - for (int i = 0; i < e_count; ++i) + for ( int i = 0; i < e_count; ++i ) { - bodyDef.position = {(1.0f + 2.0f * i) * hx, 0.0f}; - m_bodyIds[i] = b2CreateBody(m_worldId, &bodyDef); - b2CreateCapsuleShape(m_bodyIds[i], &shapeDef, &capsule); + bodyDef.position = { ( 1.0f + 2.0f * i ) * hx, 0.0f }; + m_bodyIds[i] = b2CreateBody( m_worldId, &bodyDef ); + b2CreateCapsuleShape( m_bodyIds[i], &shapeDef, &capsule ); - b2Vec2 pivot = {(2.0f * i) * hx, 0.0f}; + b2Vec2 pivot = { ( 2.0f * i ) * hx, 0.0f }; jointDef.bodyIdA = prevBodyId; jointDef.bodyIdB = m_bodyIds[i]; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); jointDef.linearHertz = m_linearHertz; jointDef.linearDampingRatio = m_linearDampingRatio; jointDef.angularHertz = m_angularHertz; jointDef.angularDampingRatio = m_angularDampingRatio; jointDef.collideConnected = m_collideConnected; - m_jointIds[i] = b2CreateWeldJoint(m_worldId, &jointDef); + m_jointIds[i] = b2CreateWeldJoint( m_worldId, &jointDef ); prevBodyId = m_bodyIds[i]; } @@ -1158,57 +1158,57 @@ class Cantilever : public Sample void UpdateUI() override { float height = 180.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(240.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); - ImGui::Begin("Cantilever", nullptr, ImGuiWindowFlags_NoResize); - ImGui::PushItemWidth(100.0f); + ImGui::Begin( "Cantilever", nullptr, ImGuiWindowFlags_NoResize ); + ImGui::PushItemWidth( 100.0f ); - if (ImGui::SliderFloat("Linear Hertz", &m_linearHertz, 0.0f, 20.0f, "%.0f")) + if ( ImGui::SliderFloat( "Linear Hertz", &m_linearHertz, 0.0f, 20.0f, "%.0f" ) ) { - for (int i = 0; i < e_count; ++i) + for ( int i = 0; i < e_count; ++i ) { - b2WeldJoint_SetLinearHertz(m_jointIds[i], m_linearHertz); + b2WeldJoint_SetLinearHertz( m_jointIds[i], m_linearHertz ); } } - if (ImGui::SliderFloat("Linear Damping Ratio", &m_linearDampingRatio, 0.0f, 10.0f, "%.1f")) + if ( ImGui::SliderFloat( "Linear Damping Ratio", &m_linearDampingRatio, 0.0f, 10.0f, "%.1f" ) ) { - for (int i = 0; i < e_count; ++i) + for ( int i = 0; i < e_count; ++i ) { - b2WeldJoint_SetLinearDampingRatio(m_jointIds[i], m_linearDampingRatio); + b2WeldJoint_SetLinearDampingRatio( m_jointIds[i], m_linearDampingRatio ); } } - if (ImGui::SliderFloat("Angular Hertz", &m_angularHertz, 0.0f, 20.0f, "%.0f")) + if ( ImGui::SliderFloat( "Angular Hertz", &m_angularHertz, 0.0f, 20.0f, "%.0f" ) ) { - for (int i = 0; i < e_count; ++i) + for ( int i = 0; i < e_count; ++i ) { - b2WeldJoint_SetAngularHertz(m_jointIds[i], m_angularHertz); + b2WeldJoint_SetAngularHertz( m_jointIds[i], m_angularHertz ); } } - if (ImGui::SliderFloat("Angular Damping Ratio", &m_angularDampingRatio, 0.0f, 10.0f, "%.1f")) + if ( ImGui::SliderFloat( "Angular Damping Ratio", &m_angularDampingRatio, 0.0f, 10.0f, "%.1f" ) ) { - for (int i = 0; i < e_count; ++i) + for ( int i = 0; i < e_count; ++i ) { - b2WeldJoint_SetAngularDampingRatio(m_jointIds[i], m_angularDampingRatio); + b2WeldJoint_SetAngularDampingRatio( m_jointIds[i], m_angularDampingRatio ); } } - if (ImGui::Checkbox("Collide Connected", &m_collideConnected)) + if ( ImGui::Checkbox( "Collide Connected", &m_collideConnected ) ) { - for (int i = 0; i < e_count; ++i) + for ( int i = 0; i < e_count; ++i ) { - b2Joint_SetCollideConnected(m_jointIds[i], m_collideConnected); + b2Joint_SetCollideConnected( m_jointIds[i], m_collideConnected ); } } - if (ImGui::SliderFloat("Gravity Scale", &m_gravityScale, -1.0f, 1.0f, "%.1f")) + if ( ImGui::SliderFloat( "Gravity Scale", &m_gravityScale, -1.0f, 1.0f, "%.1f" ) ) { - for (int i = 0; i < e_count; ++i) + for ( int i = 0; i < e_count; ++i ) { - b2Body_SetGravityScale(m_bodyIds[i], m_gravityScale); + b2Body_SetGravityScale( m_bodyIds[i], m_gravityScale ); } } @@ -1216,18 +1216,18 @@ class Cantilever : public Sample ImGui::End(); } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - Sample::Step(settings); + Sample::Step( settings ); - b2Vec2 tipPosition = b2Body_GetPosition(m_tipId); - g_draw.DrawString(5, m_textLine, "tip-y = %.2f", tipPosition.y); + b2Vec2 tipPosition = b2Body_GetPosition( m_tipId ); + g_draw.DrawString( 5, m_textLine, "tip-y = %.2f", tipPosition.y ); m_textLine += m_textIncrement; } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new Cantilever(settings); + return new Cantilever( settings ); } float m_linearHertz; @@ -1241,7 +1241,7 @@ class Cantilever : public Sample bool m_collideConnected; }; -static int sampleCantileverIndex = RegisterSample("Joints", "Cantilever", Cantilever::Create); +static int sampleCantileverIndex = RegisterSample( "Joints", "Cantilever", Cantilever::Create ); // This test ensures joints work correctly with bodies that have fixed rotation class FixedRotation : public Sample @@ -1252,20 +1252,20 @@ class FixedRotation : public Sample e_count = 6 }; - explicit FixedRotation(Settings& settings) - : Sample(settings) + explicit FixedRotation( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 8.0f}; + g_camera.m_center = { 0.0f, 8.0f }; g_camera.m_zoom = 25.0f * 0.7f; } b2BodyDef bodyDef = b2DefaultBodyDef(); - m_groundId = b2CreateBody(m_worldId, &bodyDef); + m_groundId = b2CreateBody( m_worldId, &bodyDef ); m_fixedRotation = true; - for (int i = 0; i < e_count; ++i) + for ( int i = 0; i < e_count; ++i ) { m_bodyIds[i] = b2_nullBodyId; m_jointIds[i] = b2_nullJointId; @@ -1276,49 +1276,49 @@ class FixedRotation : public Sample void CreateScene() { - for (int i = 0; i < e_count; ++i) + for ( int i = 0; i < e_count; ++i ) { - if (B2_IS_NON_NULL(m_jointIds[i])) + if ( B2_IS_NON_NULL( m_jointIds[i] ) ) { - b2DestroyJoint(m_jointIds[i]); + b2DestroyJoint( m_jointIds[i] ); m_jointIds[i] = b2_nullJointId; } - if (B2_IS_NON_NULL(m_bodyIds[i])) + if ( B2_IS_NON_NULL( m_bodyIds[i] ) ) { - b2DestroyBody(m_bodyIds[i]); + b2DestroyBody( m_bodyIds[i] ); m_bodyIds[i] = b2_nullBodyId; } } - b2Vec2 position = {-12.5f, 10.0f}; + b2Vec2 position = { -12.5f, 10.0f }; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; bodyDef.fixedRotation = m_fixedRotation; - b2Polygon box = b2MakeBox(1.0f, 1.0f); + b2Polygon box = b2MakeBox( 1.0f, 1.0f ); int index = 0; // distance joint { - assert(index < e_count); + assert( index < e_count ); bodyDef.position = position; - m_bodyIds[index] = b2CreateBody(m_worldId, &bodyDef); + m_bodyIds[index] = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreatePolygonShape(m_bodyIds[index], &shapeDef, &box); + b2CreatePolygonShape( m_bodyIds[index], &shapeDef, &box ); float length = 2.0f; - b2Vec2 pivot1 = {position.x, position.y + 1.0f + length}; - b2Vec2 pivot2 = {position.x, position.y + 1.0f}; + b2Vec2 pivot1 = { position.x, position.y + 1.0f + length }; + b2Vec2 pivot2 = { position.x, position.y + 1.0f }; b2DistanceJointDef jointDef = b2DefaultDistanceJointDef(); jointDef.bodyIdA = m_groundId; jointDef.bodyIdB = m_bodyIds[index]; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot1); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot2); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot1 ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot2 ); jointDef.length = length; - m_jointIds[index] = b2CreateDistanceJoint(m_worldId, &jointDef); + m_jointIds[index] = b2CreateDistanceJoint( m_worldId, &jointDef ); } position.x += 5.0f; @@ -1326,12 +1326,12 @@ class FixedRotation : public Sample // motor joint { - assert(index < e_count); + assert( index < e_count ); bodyDef.position = position; - m_bodyIds[index] = b2CreateBody(m_worldId, &bodyDef); + m_bodyIds[index] = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreatePolygonShape(m_bodyIds[index], &shapeDef, &box); + b2CreatePolygonShape( m_bodyIds[index], &shapeDef, &box ); b2MotorJointDef jointDef = b2DefaultMotorJointDef(); jointDef.bodyIdA = m_groundId; @@ -1339,7 +1339,7 @@ class FixedRotation : public Sample jointDef.linearOffset = position; jointDef.maxForce = 200.0f; jointDef.maxTorque = 20.0f; - m_jointIds[index] = b2CreateMotorJoint(m_worldId, &jointDef); + m_jointIds[index] = b2CreateMotorJoint( m_worldId, &jointDef ); } position.x += 5.0f; @@ -1347,21 +1347,21 @@ class FixedRotation : public Sample // prismatic joint { - assert(index < e_count); + assert( index < e_count ); bodyDef.position = position; - m_bodyIds[index] = b2CreateBody(m_worldId, &bodyDef); + m_bodyIds[index] = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreatePolygonShape(m_bodyIds[index], &shapeDef, &box); + b2CreatePolygonShape( m_bodyIds[index], &shapeDef, &box ); - b2Vec2 pivot = {position.x - 1.0f, position.y}; + b2Vec2 pivot = { position.x - 1.0f, position.y }; b2PrismaticJointDef jointDef = b2DefaultPrismaticJointDef(); jointDef.bodyIdA = m_groundId; jointDef.bodyIdB = m_bodyIds[index]; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); - jointDef.localAxisA = b2Body_GetLocalVector(jointDef.bodyIdA, {1.0f, 0.0f}); - m_jointIds[index] = b2CreatePrismaticJoint(m_worldId, &jointDef); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); + jointDef.localAxisA = b2Body_GetLocalVector( jointDef.bodyIdA, { 1.0f, 0.0f } ); + m_jointIds[index] = b2CreatePrismaticJoint( m_worldId, &jointDef ); } position.x += 5.0f; @@ -1369,20 +1369,20 @@ class FixedRotation : public Sample // revolute joint { - assert(index < e_count); + assert( index < e_count ); bodyDef.position = position; - m_bodyIds[index] = b2CreateBody(m_worldId, &bodyDef); + m_bodyIds[index] = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreatePolygonShape(m_bodyIds[index], &shapeDef, &box); + b2CreatePolygonShape( m_bodyIds[index], &shapeDef, &box ); - b2Vec2 pivot = {position.x - 1.0f, position.y}; + b2Vec2 pivot = { position.x - 1.0f, position.y }; b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.bodyIdA = m_groundId; jointDef.bodyIdB = m_bodyIds[index]; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); - m_jointIds[index] = b2CreateRevoluteJoint(m_worldId, &jointDef); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); + m_jointIds[index] = b2CreateRevoluteJoint( m_worldId, &jointDef ); } position.x += 5.0f; @@ -1390,24 +1390,24 @@ class FixedRotation : public Sample // weld joint { - assert(index < e_count); + assert( index < e_count ); bodyDef.position = position; - m_bodyIds[index] = b2CreateBody(m_worldId, &bodyDef); + m_bodyIds[index] = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreatePolygonShape(m_bodyIds[index], &shapeDef, &box); + b2CreatePolygonShape( m_bodyIds[index], &shapeDef, &box ); - b2Vec2 pivot = {position.x - 1.0f, position.y}; + b2Vec2 pivot = { position.x - 1.0f, position.y }; b2WeldJointDef jointDef = b2DefaultWeldJointDef(); jointDef.bodyIdA = m_groundId; jointDef.bodyIdB = m_bodyIds[index]; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); jointDef.angularHertz = 1.0f; jointDef.angularDampingRatio = 0.5f; jointDef.linearHertz = 1.0f; jointDef.linearDampingRatio = 0.5f; - m_jointIds[index] = b2CreateWeldJoint(m_worldId, &jointDef); + m_jointIds[index] = b2CreateWeldJoint( m_worldId, &jointDef ); } position.x += 5.0f; @@ -1415,20 +1415,20 @@ class FixedRotation : public Sample // wheel joint { - assert(index < e_count); + assert( index < e_count ); bodyDef.position = position; - m_bodyIds[index] = b2CreateBody(m_worldId, &bodyDef); + m_bodyIds[index] = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreatePolygonShape(m_bodyIds[index], &shapeDef, &box); + b2CreatePolygonShape( m_bodyIds[index], &shapeDef, &box ); - b2Vec2 pivot = {position.x - 1.0f, position.y}; + b2Vec2 pivot = { position.x - 1.0f, position.y }; b2WheelJointDef jointDef = b2DefaultWheelJointDef(); jointDef.bodyIdA = m_groundId; jointDef.bodyIdB = m_bodyIds[index]; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); - jointDef.localAxisA = b2Body_GetLocalVector(jointDef.bodyIdA, {1.0f, 0.0f}); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); + jointDef.localAxisA = b2Body_GetLocalVector( jointDef.bodyIdA, { 1.0f, 0.0f } ); jointDef.hertz = 1.0f; jointDef.dampingRatio = 0.7f; jointDef.lowerTranslation = -1.0f; @@ -1437,7 +1437,7 @@ class FixedRotation : public Sample jointDef.enableMotor = true; jointDef.maxMotorTorque = 10.0f; jointDef.motorSpeed = 1.0f; - m_jointIds[index] = b2CreateWheelJoint(m_worldId, &jointDef); + m_jointIds[index] = b2CreateWheelJoint( m_worldId, &jointDef ); } position.x += 5.0f; @@ -1447,25 +1447,25 @@ class FixedRotation : public Sample void UpdateUI() override { float height = 60.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(180.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 180.0f, height ) ); - ImGui::Begin("Fixed Rotation", nullptr, ImGuiWindowFlags_NoResize); + ImGui::Begin( "Fixed Rotation", nullptr, ImGuiWindowFlags_NoResize ); - if (ImGui::Checkbox("Fixed Rotation", &m_fixedRotation)) + if ( ImGui::Checkbox( "Fixed Rotation", &m_fixedRotation ) ) { - for (int i = 0; i < e_count; ++i) + for ( int i = 0; i < e_count; ++i ) { - b2Body_SetFixedRotation(m_bodyIds[i], m_fixedRotation); + b2Body_SetFixedRotation( m_bodyIds[i], m_fixedRotation ); } } ImGui::End(); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new FixedRotation(settings); + return new FixedRotation( settings ); } b2BodyId m_groundId; @@ -1474,7 +1474,7 @@ class FixedRotation : public Sample bool m_fixedRotation; }; -static int sampleFixedRotation = RegisterSample("Joints", "Fixed Rotation", FixedRotation::Create); +static int sampleFixedRotation = RegisterSample( "Joints", "Fixed Rotation", FixedRotation::Create ); // This sample shows how to break joints when the internal reaction force becomes large. class BreakableJoint : public Sample @@ -1485,54 +1485,54 @@ class BreakableJoint : public Sample e_count = 6 }; - explicit BreakableJoint(Settings& settings) - : Sample(settings) + explicit BreakableJoint( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 8.0f}; + g_camera.m_center = { 0.0f, 8.0f }; g_camera.m_zoom = 25.0f * 0.7f; } b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Segment segment = {{-40.0f, 0.0f}, {40.0f, 0.0f}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2Segment segment = { { -40.0f, 0.0f }, { 40.0f, 0.0f } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment ); - for (int i = 0; i < e_count; ++i) + for ( int i = 0; i < e_count; ++i ) { m_jointIds[i] = b2_nullJointId; } - b2Vec2 position = {-12.5f, 10.0f}; + b2Vec2 position = { -12.5f, 10.0f }; bodyDef.type = b2_dynamicBody; bodyDef.enableSleep = false; - b2Polygon box = b2MakeBox(1.0f, 1.0f); + b2Polygon box = b2MakeBox( 1.0f, 1.0f ); int index = 0; // distance joint { - assert(index < e_count); + assert( index < e_count ); bodyDef.position = position; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); float length = 2.0f; - b2Vec2 pivot1 = {position.x, position.y + 1.0f + length}; - b2Vec2 pivot2 = {position.x, position.y + 1.0f}; + b2Vec2 pivot1 = { position.x, position.y + 1.0f + length }; + b2Vec2 pivot2 = { position.x, position.y + 1.0f }; b2DistanceJointDef jointDef = b2DefaultDistanceJointDef(); jointDef.bodyIdA = groundId; jointDef.bodyIdB = bodyId; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot1); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot2); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot1 ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot2 ); jointDef.length = length; jointDef.collideConnected = true; - m_jointIds[index] = b2CreateDistanceJoint(m_worldId, &jointDef); + m_jointIds[index] = b2CreateDistanceJoint( m_worldId, &jointDef ); } position.x += 5.0f; @@ -1540,11 +1540,11 @@ class BreakableJoint : public Sample // motor joint { - assert(index < e_count); + assert( index < e_count ); bodyDef.position = position; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); b2MotorJointDef jointDef = b2DefaultMotorJointDef(); jointDef.bodyIdA = groundId; @@ -1553,7 +1553,7 @@ class BreakableJoint : public Sample jointDef.maxForce = 1000.0f; jointDef.maxTorque = 20.0f; jointDef.collideConnected = true; - m_jointIds[index] = b2CreateMotorJoint(m_worldId, &jointDef); + m_jointIds[index] = b2CreateMotorJoint( m_worldId, &jointDef ); } position.x += 5.0f; @@ -1561,21 +1561,21 @@ class BreakableJoint : public Sample // prismatic joint { - assert(index < e_count); + assert( index < e_count ); bodyDef.position = position; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); - b2Vec2 pivot = {position.x - 1.0f, position.y}; + b2Vec2 pivot = { position.x - 1.0f, position.y }; b2PrismaticJointDef jointDef = b2DefaultPrismaticJointDef(); jointDef.bodyIdA = groundId; jointDef.bodyIdB = bodyId; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); - jointDef.localAxisA = b2Body_GetLocalVector(jointDef.bodyIdA, {1.0f, 0.0f}); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); + jointDef.localAxisA = b2Body_GetLocalVector( jointDef.bodyIdA, { 1.0f, 0.0f } ); jointDef.collideConnected = true; - m_jointIds[index] = b2CreatePrismaticJoint(m_worldId, &jointDef); + m_jointIds[index] = b2CreatePrismaticJoint( m_worldId, &jointDef ); } position.x += 5.0f; @@ -1583,20 +1583,20 @@ class BreakableJoint : public Sample // revolute joint { - assert(index < e_count); + assert( index < e_count ); bodyDef.position = position; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); - b2Vec2 pivot = {position.x - 1.0f, position.y}; + b2Vec2 pivot = { position.x - 1.0f, position.y }; b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.bodyIdA = groundId; jointDef.bodyIdB = bodyId; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); jointDef.collideConnected = true; - m_jointIds[index] = b2CreateRevoluteJoint(m_worldId, &jointDef); + m_jointIds[index] = b2CreateRevoluteJoint( m_worldId, &jointDef ); } position.x += 5.0f; @@ -1604,24 +1604,24 @@ class BreakableJoint : public Sample // weld joint { - assert(index < e_count); + assert( index < e_count ); bodyDef.position = position; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); - b2Vec2 pivot = {position.x - 1.0f, position.y}; + b2Vec2 pivot = { position.x - 1.0f, position.y }; b2WeldJointDef jointDef = b2DefaultWeldJointDef(); jointDef.bodyIdA = groundId; jointDef.bodyIdB = bodyId; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); jointDef.angularHertz = 2.0f; jointDef.angularDampingRatio = 0.5f; jointDef.linearHertz = 2.0f; jointDef.linearDampingRatio = 0.5f; jointDef.collideConnected = true; - m_jointIds[index] = b2CreateWeldJoint(m_worldId, &jointDef); + m_jointIds[index] = b2CreateWeldJoint( m_worldId, &jointDef ); } position.x += 5.0f; @@ -1629,19 +1629,19 @@ class BreakableJoint : public Sample // wheel joint { - assert(index < e_count); + assert( index < e_count ); bodyDef.position = position; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); - b2Vec2 pivot = {position.x - 1.0f, position.y}; + b2Vec2 pivot = { position.x - 1.0f, position.y }; b2WheelJointDef jointDef = b2DefaultWheelJointDef(); jointDef.bodyIdA = groundId; jointDef.bodyIdB = bodyId; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); - jointDef.localAxisA = b2Body_GetLocalVector(jointDef.bodyIdA, {1.0f, 0.0f}); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); + jointDef.localAxisA = b2Body_GetLocalVector( jointDef.bodyIdA, { 1.0f, 0.0f } ); jointDef.hertz = 1.0f; jointDef.dampingRatio = 0.7f; jointDef.lowerTranslation = -1.0f; @@ -1651,7 +1651,7 @@ class BreakableJoint : public Sample jointDef.maxMotorTorque = 10.0f; jointDef.motorSpeed = 1.0f; jointDef.collideConnected = true; - m_jointIds[index] = b2CreateWheelJoint(m_worldId, &jointDef); + m_jointIds[index] = b2CreateWheelJoint( m_worldId, &jointDef ); } position.x += 5.0f; @@ -1663,73 +1663,72 @@ class BreakableJoint : public Sample void UpdateUI() override { float height = 100.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(240.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); - ImGui::Begin("Breakable Joint", nullptr, ImGuiWindowFlags_NoResize); + ImGui::Begin( "Breakable Joint", nullptr, ImGuiWindowFlags_NoResize ); - ImGui::SliderFloat("break force", &m_breakForce, 0.0f, 10000.0f, "%.1f"); + ImGui::SliderFloat( "break force", &m_breakForce, 0.0f, 10000.0f, "%.1f" ); - b2Vec2 gravity = b2World_GetGravity(m_worldId); - if (ImGui::SliderFloat("gravity", &gravity.y, -50.0f, 50.0f, "%.1f")) + b2Vec2 gravity = b2World_GetGravity( m_worldId ); + if ( ImGui::SliderFloat( "gravity", &gravity.y, -50.0f, 50.0f, "%.1f" ) ) { - b2World_SetGravity(m_worldId, gravity); + b2World_SetGravity( m_worldId, gravity ); } ImGui::End(); } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - for (int i = 0; i < e_count; ++i) + for ( int i = 0; i < e_count; ++i ) { - if (B2_IS_NULL(m_jointIds[i])) + if ( B2_IS_NULL( m_jointIds[i] ) ) { continue; } - b2Vec2 force = b2Joint_GetConstraintForce(m_jointIds[i]); - if (b2LengthSquared(force) > m_breakForce * m_breakForce) + b2Vec2 force = b2Joint_GetConstraintForce( m_jointIds[i] ); + if ( b2LengthSquared( force ) > m_breakForce * m_breakForce ) { - b2DestroyJoint(m_jointIds[i]); + b2DestroyJoint( m_jointIds[i] ); m_jointIds[i] = b2_nullJointId; } else { - b2Vec2 point = b2Joint_GetLocalAnchorA(m_jointIds[i]); - g_draw.DrawString(point, "(%.1f, %.1f)", force.x, force.y); + b2Vec2 point = b2Joint_GetLocalAnchorA( m_jointIds[i] ); + g_draw.DrawString( point, "(%.1f, %.1f)", force.x, force.y ); } } - Sample::Step(settings); + Sample::Step( settings ); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new BreakableJoint(settings); + return new BreakableJoint( settings ); } - b2JointId m_jointIds[e_count]; float m_breakForce; }; -static int sampleBreakableJoint = RegisterSample("Joints", "Breakable", BreakableJoint::Create); +static int sampleBreakableJoint = RegisterSample( "Joints", "Breakable", BreakableJoint::Create ); // This shows how you can implement a constraint outside of Box2D class UserConstraint : public Sample { public: - explicit UserConstraint(Settings& settings) - : Sample(settings) + explicit UserConstraint( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {3.0f, -1.0f}; + g_camera.m_center = { 3.0f, -1.0f }; g_camera.m_zoom = 25.0f * 0.15f; } - b2Polygon box = b2MakeBox(1.0f, 0.5f); + b2Polygon box = b2MakeBox( 1.0f, 0.5f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 20.0f; @@ -1739,27 +1738,27 @@ class UserConstraint : public Sample bodyDef.gravityScale = 1.0f; bodyDef.angularDamping = 0.5f; bodyDef.linearDamping = 0.2f; - m_bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(m_bodyId, &shapeDef, &box); + m_bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( m_bodyId, &shapeDef, &box ); m_impulses[0] = 0.0f; m_impulses[1] = 0.0f; } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - Sample::Step(settings); + Sample::Step( settings ); b2Transform axes = b2Transform_identity; - g_draw.DrawTransform(axes); + g_draw.DrawTransform( axes ); - if (settings.pause) + if ( settings.pause ) { return; } float timeStep = settings.hertz > 0.0f ? 1.0f / settings.hertz : 0.0f; - if (timeStep == 0.0f) + if ( timeStep == 0.0f ) { return; } @@ -1772,81 +1771,81 @@ class UserConstraint : public Sample float omega = 2.0f * b2_pi * hertz; float sigma = 2.0f * zeta + timeStep * omega; float s = timeStep * omega * sigma; - float impulseCoefficient = 1.0f / (1.0f + s); + float impulseCoefficient = 1.0f / ( 1.0f + s ); float massCoefficient = s * impulseCoefficient; float biasCoefficient = omega / sigma; - b2Vec2 localAnchors[2] = {{1.0f, -0.5f}, {1.0f, 0.5f}}; - float mass = b2Body_GetMass(m_bodyId); + b2Vec2 localAnchors[2] = { { 1.0f, -0.5f }, { 1.0f, 0.5f } }; + float mass = b2Body_GetMass( m_bodyId ); float invMass = mass < 0.0001f ? 0.0f : 1.0f / mass; - float inertiaTensor = b2Body_GetInertiaTensor(m_bodyId); + float inertiaTensor = b2Body_GetInertiaTensor( m_bodyId ); float invI = inertiaTensor < 0.0001f ? 0.0f : 1.0f / inertiaTensor; - b2Vec2 vB = b2Body_GetLinearVelocity(m_bodyId); - float omegaB = b2Body_GetAngularVelocity(m_bodyId); - b2Vec2 pB = b2Body_GetWorldCenterOfMass(m_bodyId); + b2Vec2 vB = b2Body_GetLinearVelocity( m_bodyId ); + float omegaB = b2Body_GetAngularVelocity( m_bodyId ); + b2Vec2 pB = b2Body_GetWorldCenterOfMass( m_bodyId ); - for (int i = 0; i < 2; ++i) + for ( int i = 0; i < 2; ++i ) { - b2Vec2 anchorA = {3.0f, 0.0f}; - b2Vec2 anchorB = b2Body_GetWorldPoint(m_bodyId, localAnchors[i]); + b2Vec2 anchorA = { 3.0f, 0.0f }; + b2Vec2 anchorB = b2Body_GetWorldPoint( m_bodyId, localAnchors[i] ); - b2Vec2 deltaAnchor = b2Sub(anchorB, anchorA); + b2Vec2 deltaAnchor = b2Sub( anchorB, anchorA ); float slackLength = 1.0f; - float length = b2Length(deltaAnchor); + float length = b2Length( deltaAnchor ); float C = length - slackLength; - if (C < 0.0f || length < 0.001f) + if ( C < 0.0f || length < 0.001f ) { - g_draw.DrawSegment(anchorA, anchorB, b2_colorLightCyan); + g_draw.DrawSegment( anchorA, anchorB, b2_colorLightCyan ); m_impulses[i] = 0.0f; continue; } - g_draw.DrawSegment(anchorA, anchorB, b2_colorViolet); - b2Vec2 axis = b2Normalize(deltaAnchor); + g_draw.DrawSegment( anchorA, anchorB, b2_colorViolet ); + b2Vec2 axis = b2Normalize( deltaAnchor ); - b2Vec2 rB = b2Sub(anchorB, pB); - float Jb = b2Cross(rB, axis); + b2Vec2 rB = b2Sub( anchorB, pB ); + float Jb = b2Cross( rB, axis ); float K = invMass + Jb * invI * Jb; float invK = K < 0.0001f ? 0.0f : 1.0f / K; - float Cdot = b2Dot(vB, axis) + Jb * omegaB; - float impulse = -massCoefficient * invK * (Cdot + biasCoefficient * C); - float appliedImpulse = b2ClampFloat(impulse, -maxForce * timeStep, 0.0f); + float Cdot = b2Dot( vB, axis ) + Jb * omegaB; + float impulse = -massCoefficient * invK * ( Cdot + biasCoefficient * C ); + float appliedImpulse = b2ClampFloat( impulse, -maxForce * timeStep, 0.0f ); - vB = b2MulAdd(vB, invMass * appliedImpulse, axis); + vB = b2MulAdd( vB, invMass * appliedImpulse, axis ); omegaB += appliedImpulse * invI * Jb; m_impulses[i] = appliedImpulse; } - b2Body_SetLinearVelocity(m_bodyId, vB); - b2Body_SetAngularVelocity(m_bodyId, omegaB); + b2Body_SetLinearVelocity( m_bodyId, vB ); + b2Body_SetAngularVelocity( m_bodyId, omegaB ); - g_draw.DrawString(5, m_textLine, "forces = %g, %g", m_impulses[0] * invTimeStep, m_impulses[1] * invTimeStep); + g_draw.DrawString( 5, m_textLine, "forces = %g, %g", m_impulses[0] * invTimeStep, m_impulses[1] * invTimeStep ); m_textLine += m_textIncrement; } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new UserConstraint(settings); + return new UserConstraint( settings ); } b2BodyId m_bodyId; float m_impulses[2]; }; -static int sampleUserConstraintIndex = RegisterSample("Joints", "User Constraint", UserConstraint::Create); +static int sampleUserConstraintIndex = RegisterSample( "Joints", "User Constraint", UserConstraint::Create ); // This is a fun demo that shows off the wheel joint class Driving : public Sample { public: - explicit Driving(Settings& settings) - : Sample(settings) + explicit Driving( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { g_camera.m_center.y = 5.0f; g_camera.m_zoom = 25.0f * 0.4f; @@ -1856,127 +1855,127 @@ class Driving : public Sample b2BodyId groundId; { b2BodyDef bodyDef = b2DefaultBodyDef(); - groundId = b2CreateBody(m_worldId, &bodyDef); + groundId = b2CreateBody( m_worldId, &bodyDef ); b2Vec2 points[25]; int count = 24; // fill in reverse to match line list convention - points[count--] = {-20.0f, -20.0f}; - points[count--] = {-20.0f, 0.0f}; - points[count--] = {20.0f, 0.0f}; + points[count--] = { -20.0f, -20.0f }; + points[count--] = { -20.0f, 0.0f }; + points[count--] = { 20.0f, 0.0f }; - float hs[10] = {0.25f, 1.0f, 4.0f, 0.0f, 0.0f, -1.0f, -2.0f, -2.0f, -1.25f, 0.0f}; + float hs[10] = { 0.25f, 1.0f, 4.0f, 0.0f, 0.0f, -1.0f, -2.0f, -2.0f, -1.25f, 0.0f }; float x = 20.0f, y1 = 0.0f, dx = 5.0f; - for (int j = 0; j < 2; ++j) + for ( int j = 0; j < 2; ++j ) { - for (int i = 0; i < 10; ++i) + for ( int i = 0; i < 10; ++i ) { float y2 = hs[i]; - points[count--] = {x + dx, y2}; + points[count--] = { x + dx, y2 }; y1 = y2; x += dx; } } // flat before bridge - points[count--] = {x + 40.0f, 0.0f}; - points[count--] = {x + 40.0f, -20.0f}; + points[count--] = { x + 40.0f, 0.0f }; + points[count--] = { x + 40.0f, -20.0f }; - assert(count == -1); + assert( count == -1 ); b2ChainDef chainDef = b2DefaultChainDef(); chainDef.points = points; chainDef.count = 25; chainDef.isLoop = true; - b2CreateChain(groundId, &chainDef); + b2CreateChain( groundId, &chainDef ); // flat after bridge x += 80.0f; b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Segment segment = {{x, 0.0f}, {x + 40.0f, 0.0f}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2Segment segment = { { x, 0.0f }, { x + 40.0f, 0.0f } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment ); // jump ramp x += 40.0f; - segment = {{x, 0.0f}, {x + 10.0f, 5.0f}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment); + segment = { { x, 0.0f }, { x + 10.0f, 5.0f } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment ); // final corner x += 20.0f; - segment = {{x, 0.0f}, {x + 40.0f, 0.0f}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment); + segment = { { x, 0.0f }, { x + 40.0f, 0.0f } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment ); x += 40.0f; - segment = {{x, 0.0f}, {x, 20.0f}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment); + segment = { { x, 0.0f }, { x, 20.0f } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment ); } // Teeter { b2BodyDef bodyDef = b2DefaultBodyDef(); - bodyDef.position = {140.0f, 1.0f}; + bodyDef.position = { 140.0f, 1.0f }; bodyDef.angularVelocity = 1.0f; bodyDef.type = b2_dynamicBody; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Polygon box = b2MakeBox(10.0f, 0.25f); - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2Polygon box = b2MakeBox( 10.0f, 0.25f ); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); b2Vec2 pivot = bodyDef.position; b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); jointDef.bodyIdA = groundId; jointDef.bodyIdB = bodyId; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); jointDef.lowerAngle = -8.0f * b2_pi / 180.0f; jointDef.upperAngle = 8.0f * b2_pi / 180.0f; jointDef.enableLimit = true; - b2CreateRevoluteJoint(m_worldId, &jointDef); + b2CreateRevoluteJoint( m_worldId, &jointDef ); } // Bridge { int N = 20; b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Capsule capsule = {{-1.0f, 0.0f}, {1.0f, 0.0f}, 0.125f}; + b2Capsule capsule = { { -1.0f, 0.0f }, { 1.0f, 0.0f }, 0.125f }; b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef(); b2BodyId prevBodyId = groundId; - for (int i = 0; i < N; ++i) + for ( int i = 0; i < N; ++i ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {161.0f + 2.0f * i, -0.125f}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreateCapsuleShape(bodyId, &shapeDef, &capsule); + bodyDef.position = { 161.0f + 2.0f * i, -0.125f }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreateCapsuleShape( bodyId, &shapeDef, &capsule ); - b2Vec2 pivot = {160.0f + 2.0f * i, -0.125f}; + b2Vec2 pivot = { 160.0f + 2.0f * i, -0.125f }; jointDef.bodyIdA = prevBodyId; jointDef.bodyIdB = bodyId; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); - b2CreateRevoluteJoint(m_worldId, &jointDef); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); + b2CreateRevoluteJoint( m_worldId, &jointDef ); prevBodyId = bodyId; } - b2Vec2 pivot = {160.0f + 2.0f * N, -0.125f}; + b2Vec2 pivot = { 160.0f + 2.0f * N, -0.125f }; jointDef.bodyIdA = prevBodyId; jointDef.bodyIdB = groundId; - jointDef.localAnchorA = b2Body_GetLocalPoint(jointDef.bodyIdA, pivot); - jointDef.localAnchorB = b2Body_GetLocalPoint(jointDef.bodyIdB, pivot); + jointDef.localAnchorA = b2Body_GetLocalPoint( jointDef.bodyIdA, pivot ); + jointDef.localAnchorB = b2Body_GetLocalPoint( jointDef.bodyIdB, pivot ); jointDef.enableMotor = true; jointDef.maxMotorTorque = 50.0f; - b2CreateRevoluteJoint(m_worldId, &jointDef); + b2CreateRevoluteJoint( m_worldId, &jointDef ); } // Boxes { - b2Polygon box = b2MakeBox(0.5f, 0.5f); + b2Polygon box = b2MakeBox( 0.5f, 0.5f ); b2BodyId bodyId; b2BodyDef bodyDef = b2DefaultBodyDef(); @@ -1987,25 +1986,25 @@ class Driving : public Sample shapeDef.restitution = 0.25f; shapeDef.density = 0.25f; - bodyDef.position = {230.0f, 0.5f}; - bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &box); + bodyDef.position = { 230.0f, 0.5f }; + bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); - bodyDef.position = {230.0f, 1.5f}; - bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &box); + bodyDef.position = { 230.0f, 1.5f }; + bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); - bodyDef.position = {230.0f, 2.5f}; - bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &box); + bodyDef.position = { 230.0f, 2.5f }; + bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); - bodyDef.position = {230.0f, 3.5f}; - bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &box); + bodyDef.position = { 230.0f, 3.5f }; + bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); - bodyDef.position = {230.0f, 4.5f}; - bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &box); + bodyDef.position = { 230.0f, 4.5f }; + bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); } // Car @@ -2016,79 +2015,79 @@ class Driving : public Sample m_hertz = 5.0f; m_dampingRatio = 0.7f; - m_car.Spawn(m_worldId, {0.0f, 0.0f}, 1.0f, m_hertz, m_dampingRatio, m_torque, NULL); + m_car.Spawn( m_worldId, { 0.0f, 0.0f }, 1.0f, m_hertz, m_dampingRatio, m_torque, NULL ); } void UpdateUI() override { float height = 140.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(200.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 200.0f, height ) ); - ImGui::Begin("Driving", nullptr, ImGuiWindowFlags_NoResize); + ImGui::Begin( "Driving", nullptr, ImGuiWindowFlags_NoResize ); - ImGui::PushItemWidth(100.0f); - if (ImGui::SliderFloat("Spring Hertz", &m_hertz, 0.0f, 20.0f, "%.0f")) + ImGui::PushItemWidth( 100.0f ); + if ( ImGui::SliderFloat( "Spring Hertz", &m_hertz, 0.0f, 20.0f, "%.0f" ) ) { - m_car.SetHertz(m_hertz); + m_car.SetHertz( m_hertz ); } - if (ImGui::SliderFloat("Damping Ratio", &m_dampingRatio, 0.0f, 10.0f, "%.1f")) + if ( ImGui::SliderFloat( "Damping Ratio", &m_dampingRatio, 0.0f, 10.0f, "%.1f" ) ) { - m_car.SetDampingRadio(m_dampingRatio); + m_car.SetDampingRadio( m_dampingRatio ); } - if (ImGui::SliderFloat("Speed", &m_speed, 0.0f, 50.0f, "%.0f")) + if ( ImGui::SliderFloat( "Speed", &m_speed, 0.0f, 50.0f, "%.0f" ) ) { - m_car.SetSpeed(m_throttle * m_speed); + m_car.SetSpeed( m_throttle * m_speed ); } - if (ImGui::SliderFloat("Torque", &m_torque, 0.0f, 5.0f, "%.1f")) + if ( ImGui::SliderFloat( "Torque", &m_torque, 0.0f, 5.0f, "%.1f" ) ) { - m_car.SetTorque(m_torque); + m_car.SetTorque( m_torque ); } ImGui::PopItemWidth(); ImGui::End(); } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - if (glfwGetKey(g_mainWindow, GLFW_KEY_A) == GLFW_PRESS) + if ( glfwGetKey( g_mainWindow, GLFW_KEY_A ) == GLFW_PRESS ) { m_throttle = 1.0f; - m_car.SetSpeed(m_speed); + m_car.SetSpeed( m_speed ); } - if (glfwGetKey(g_mainWindow, GLFW_KEY_S) == GLFW_PRESS) + if ( glfwGetKey( g_mainWindow, GLFW_KEY_S ) == GLFW_PRESS ) { m_throttle = 0.0f; - m_car.SetSpeed(0.0f); + m_car.SetSpeed( 0.0f ); } - if (glfwGetKey(g_mainWindow, GLFW_KEY_D) == GLFW_PRESS) + if ( glfwGetKey( g_mainWindow, GLFW_KEY_D ) == GLFW_PRESS ) { m_throttle = -1.0f; - m_car.SetSpeed(-m_speed); + m_car.SetSpeed( -m_speed ); } - g_draw.DrawString(5, m_textLine, "Keys: left = a, brake = s, right = d"); + g_draw.DrawString( 5, m_textLine, "Keys: left = a, brake = s, right = d" ); m_textLine += m_textIncrement; - b2Vec2 linearVelocity = b2Body_GetLinearVelocity(m_car.m_chassisId); + b2Vec2 linearVelocity = b2Body_GetLinearVelocity( m_car.m_chassisId ); float kph = linearVelocity.x * 3.6f; - g_draw.DrawString(5, m_textLine, "speed in kph: %.2g", kph); + g_draw.DrawString( 5, m_textLine, "speed in kph: %.2g", kph ); m_textLine += m_textIncrement; - b2Vec2 carPosition = b2Body_GetPosition(m_car.m_chassisId); + b2Vec2 carPosition = b2Body_GetPosition( m_car.m_chassisId ); g_camera.m_center.x = carPosition.x; - Sample::Step(settings); + Sample::Step( settings ); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new Driving(settings); + return new Driving( settings ); } Car m_car; @@ -2100,130 +2099,166 @@ class Driving : public Sample float m_speed; }; -static int sampleDriving = RegisterSample("Joints", "Driving", Driving::Create); +static int sampleDriving = RegisterSample( "Joints", "Driving", Driving::Create ); class Ragdoll : public Sample { public: - explicit Ragdoll(Settings& settings) - : Sample(settings) + explicit Ragdoll( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 3.0f}; + g_camera.m_center = { 0.0f, 3.0f }; g_camera.m_zoom = 25.0f * 0.15f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Segment segment = {{-20.0f, 0.0f}, {20.0f, 0.0f}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2Segment segment = { { -20.0f, 0.0f }, { 20.0f, 0.0f } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment ); + } + + m_jointFrictionTorque = 0.05f; + m_jointHertz = 0.0f; + m_jointDampingRatio = 0.5f; + + m_human.Spawn( m_worldId, { 0.0f, 5.0f }, 1.0f, m_jointFrictionTorque, m_jointHertz, m_jointDampingRatio, 1, nullptr, + true ); + m_human.ApplyRandomAngularImpulse( 10.0f ); + } + + void UpdateUI() override + { + float height = 140.0f; + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 180.0f, height ) ); + + ImGui::Begin( "Ragdoll", nullptr, ImGuiWindowFlags_NoResize ); + ImGui::PushItemWidth( 100.0f ); + + if ( ImGui::SliderFloat( "Friction", &m_jointFrictionTorque, 0.0f, 1.0f, "%3.2f" ) ) + { + m_human.SetJointFrictionTorque( m_jointFrictionTorque ); + } + + if ( ImGui::SliderFloat( "Hertz", &m_jointHertz, 0.0f, 10.0f, "%3.1f" ) ) + { + m_human.SetJointSpringHertz( m_jointHertz ); + } + + if ( ImGui::SliderFloat( "Damping", &m_jointDampingRatio, 0.0f, 4.0f, "%3.1f" ) ) + { + m_human.SetJointDampingRatio( m_jointDampingRatio ); } - m_human.Spawn(m_worldId, {0.0f, 5.0f}, 1.0f, 1, nullptr); + ImGui::PopItemWidth(); + ImGui::End(); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new Ragdoll(settings); + return new Ragdoll( settings ); } Human m_human; + float m_jointFrictionTorque; + float m_jointHertz; + float m_jointDampingRatio; }; -static int sampleRagdoll = RegisterSample("Joints", "Ragdoll", Ragdoll::Create); +static int sampleRagdoll = RegisterSample( "Joints", "Ragdoll", Ragdoll::Create ); class SoftBody : public Sample { public: - explicit SoftBody(Settings& settings) - : Sample(settings) + explicit SoftBody( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 5.0f}; + g_camera.m_center = { 0.0f, 5.0f }; g_camera.m_zoom = 25.0f * 0.25f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Segment segment = {{-20.0f, 0.0f}, {20.0f, 0.0f}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2Segment segment = { { -20.0f, 0.0f }, { 20.0f, 0.0f } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment ); } - m_donut.Spawn(m_worldId, {0.0f, 10.0f}, 2.0f, 0, nullptr); + m_donut.Spawn( m_worldId, { 0.0f, 10.0f }, 2.0f, 0, nullptr ); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new SoftBody(settings); + return new SoftBody( settings ); } Donut m_donut; }; -static int sampleDonut = RegisterSample("Joints", "Soft Body", SoftBody::Create); +static int sampleDonut = RegisterSample( "Joints", "Soft Body", SoftBody::Create ); class DoohickeyFarm : public Sample { public: - explicit DoohickeyFarm(Settings& settings) - : Sample(settings) + explicit DoohickeyFarm( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 5.0f}; + g_camera.m_center = { 0.0f, 5.0f }; g_camera.m_zoom = 25.0f * 0.35f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Segment segment = {{-20.0f, 0.0f}, {20.0f, 0.0f}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2Segment segment = { { -20.0f, 0.0f }, { 20.0f, 0.0f } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment ); - b2Polygon box = b2MakeOffsetBox(1.0f, 1.0f, {0.0f, 1.0f}, 0.0f); - b2CreatePolygonShape(groundId, &shapeDef, &box); + b2Polygon box = b2MakeOffsetBox( 1.0f, 1.0f, { 0.0f, 1.0f }, 0.0f ); + b2CreatePolygonShape( groundId, &shapeDef, &box ); } float y = 4.0f; - for (int i = 0; i < 4; ++i) + for ( int i = 0; i < 4; ++i ) { Doohickey doohickey; - doohickey.Spawn(m_worldId, {0.0f, y}, 0.5f); + doohickey.Spawn( m_worldId, { 0.0f, y }, 0.5f ); y += 2.0f; } } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - Sample::Step(settings); + Sample::Step( settings ); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new DoohickeyFarm(settings); + return new DoohickeyFarm( settings ); } }; -static int sampleDoohickey = RegisterSample("Joints", "Doohickey", DoohickeyFarm::Create); - +static int sampleDoohickey = RegisterSample( "Joints", "Doohickey", DoohickeyFarm::Create ); class ScissorLift : public Sample { public: - explicit ScissorLift(Settings& settings) - : Sample(settings) + explicit ScissorLift( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 9.0f}; + g_camera.m_center = { 0.0f, 9.0f }; g_camera.m_zoom = 25.0f * 0.4f; } @@ -2233,11 +2268,11 @@ class ScissorLift : public Sample b2BodyId groundId; { b2BodyDef bodyDef = b2DefaultBodyDef(); - groundId = b2CreateBody(m_worldId, &bodyDef); + groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Segment segment = {{-20.0f, 0.0f}, {20.0f, 0.0f}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2Segment segment = { { -20.0f, 0.0f }, { 20.0f, 0.0f } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment ); } b2BodyDef bodyDef = b2DefaultBodyDef(); @@ -2245,31 +2280,31 @@ class ScissorLift : public Sample bodyDef.sleepThreshold = 0.01f; b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Capsule capsule = {{-2.5f, 0.0f}, {2.5f, 0.0f}, 0.15f}; + b2Capsule capsule = { { -2.5f, 0.0f }, { 2.5f, 0.0f }, 0.15f }; b2BodyId baseId1 = groundId; b2BodyId baseId2 = groundId; - b2Vec2 baseAnchor1 = {-2.5f, 0.2f}; - b2Vec2 baseAnchor2 = {2.5f, 0.2f}; + b2Vec2 baseAnchor1 = { -2.5f, 0.2f }; + b2Vec2 baseAnchor2 = { 2.5f, 0.2f }; float y = 0.5f; b2BodyId linkId1; int N = 3; - for (int i = 0; i < N; ++i) + for ( int i = 0; i < N; ++i ) { - bodyDef.position = {0.0f, y}; - bodyDef.rotation = b2MakeRot(0.15f); - b2BodyId bodyId1 = b2CreateBody(m_worldId, &bodyDef); - b2CreateCapsuleShape(bodyId1, &shapeDef, &capsule); + bodyDef.position = { 0.0f, y }; + bodyDef.rotation = b2MakeRot( 0.15f ); + b2BodyId bodyId1 = b2CreateBody( m_worldId, &bodyDef ); + b2CreateCapsuleShape( bodyId1, &shapeDef, &capsule ); - bodyDef.position = {0.0f, y}; - bodyDef.rotation = b2MakeRot(-0.15f); + bodyDef.position = { 0.0f, y }; + bodyDef.rotation = b2MakeRot( -0.15f ); - b2BodyId bodyId2 = b2CreateBody(m_worldId, &bodyDef); - b2CreateCapsuleShape(bodyId2, &shapeDef, &capsule); + b2BodyId bodyId2 = b2CreateBody( m_worldId, &bodyDef ); + b2CreateCapsuleShape( bodyId2, &shapeDef, &capsule ); - if (i == 1) + if ( i == 1 ) { linkId1 = bodyId2; } @@ -2280,86 +2315,86 @@ class ScissorLift : public Sample revoluteDef.bodyIdA = baseId1; revoluteDef.bodyIdB = bodyId1; revoluteDef.localAnchorA = baseAnchor1; - revoluteDef.localAnchorB = {-2.5f, 0.0f}; + revoluteDef.localAnchorB = { -2.5f, 0.0f }; revoluteDef.enableMotor = false; revoluteDef.maxMotorTorque = 1.0f; - revoluteDef.collideConnected = (i == 0) ? true : false; + revoluteDef.collideConnected = ( i == 0 ) ? true : false; - b2CreateRevoluteJoint(m_worldId, &revoluteDef); + b2CreateRevoluteJoint( m_worldId, &revoluteDef ); // right pin - if (i == 0) + if ( i == 0 ) { b2WheelJointDef wheelDef = b2DefaultWheelJointDef(); wheelDef.bodyIdA = baseId2; wheelDef.bodyIdB = bodyId2; - wheelDef.localAxisA = {1.0f, 0.0f}; + wheelDef.localAxisA = { 1.0f, 0.0f }; wheelDef.localAnchorA = baseAnchor2; - wheelDef.localAnchorB = {2.5f, 0.0f}; + wheelDef.localAnchorB = { 2.5f, 0.0f }; wheelDef.enableSpring = false; wheelDef.collideConnected = true; - b2CreateWheelJoint(m_worldId, &wheelDef); + b2CreateWheelJoint( m_worldId, &wheelDef ); } else { revoluteDef.bodyIdA = baseId2; revoluteDef.bodyIdB = bodyId2; revoluteDef.localAnchorA = baseAnchor2; - revoluteDef.localAnchorB = {2.5f, 0.0f}; + revoluteDef.localAnchorB = { 2.5f, 0.0f }; revoluteDef.enableMotor = false; revoluteDef.maxMotorTorque = 1.0f; revoluteDef.collideConnected = false; - b2CreateRevoluteJoint(m_worldId, &revoluteDef); + b2CreateRevoluteJoint( m_worldId, &revoluteDef ); } // middle pin revoluteDef.bodyIdA = bodyId1; revoluteDef.bodyIdB = bodyId2; - revoluteDef.localAnchorA = {0.0f, 0.0f}; - revoluteDef.localAnchorB = {0.0f, 0.0f}; + revoluteDef.localAnchorA = { 0.0f, 0.0f }; + revoluteDef.localAnchorB = { 0.0f, 0.0f }; revoluteDef.enableMotor = false; revoluteDef.maxMotorTorque = 1.0f; revoluteDef.collideConnected = false; - b2CreateRevoluteJoint(m_worldId, &revoluteDef); + b2CreateRevoluteJoint( m_worldId, &revoluteDef ); baseId1 = bodyId2; baseId2 = bodyId1; - baseAnchor1 = {-2.5f, 0.0f}; - baseAnchor2 = {2.5f, 0.0f}; + baseAnchor1 = { -2.5f, 0.0f }; + baseAnchor2 = { 2.5f, 0.0f }; y += 1.0f; } - bodyDef.position = {0.0f, y}; + bodyDef.position = { 0.0f, y }; bodyDef.rotation = b2Rot_identity; - b2BodyId platformId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId platformId = b2CreateBody( m_worldId, &bodyDef ); - b2Polygon box = b2MakeBox(3.0f, 0.2f); - b2CreatePolygonShape(platformId, &shapeDef, &box); + b2Polygon box = b2MakeBox( 3.0f, 0.2f ); + b2CreatePolygonShape( platformId, &shapeDef, &box ); // left pin b2RevoluteJointDef revoluteDef = b2DefaultRevoluteJointDef(); revoluteDef.bodyIdA = platformId; revoluteDef.bodyIdB = baseId1; - revoluteDef.localAnchorA = {-2.5f, -0.4f}; + revoluteDef.localAnchorA = { -2.5f, -0.4f }; revoluteDef.localAnchorB = baseAnchor1; revoluteDef.enableMotor = false; revoluteDef.maxMotorTorque = 1.0f; revoluteDef.collideConnected = true; - b2CreateRevoluteJoint(m_worldId, &revoluteDef); + b2CreateRevoluteJoint( m_worldId, &revoluteDef ); // right pin b2WheelJointDef wheelDef = b2DefaultWheelJointDef(); wheelDef.bodyIdA = platformId; wheelDef.bodyIdB = baseId2; - wheelDef.localAxisA = {1.0f, 0.0f}; - wheelDef.localAnchorA = {2.5f, -0.4f}; + wheelDef.localAxisA = { 1.0f, 0.0f }; + wheelDef.localAnchorA = { 2.5f, -0.4f }; wheelDef.localAnchorB = baseAnchor2; wheelDef.enableSpring = false; wheelDef.collideConnected = true; - b2CreateWheelJoint(m_worldId, &wheelDef); + b2CreateWheelJoint( m_worldId, &wheelDef ); m_enableMotor = false; m_motorSpeed = 0.25f; @@ -2368,8 +2403,8 @@ class ScissorLift : public Sample b2DistanceJointDef distanceDef = b2DefaultDistanceJointDef(); distanceDef.bodyIdA = groundId; distanceDef.bodyIdB = linkId1; - distanceDef.localAnchorA = {-2.5f, 0.2f}; - distanceDef.localAnchorB = {0.5f, 0.0f}; + distanceDef.localAnchorA = { -2.5f, 0.2f }; + distanceDef.localAnchorB = { 0.5f, 0.0f }; distanceDef.enableSpring = true; distanceDef.minLength = 0.2f; distanceDef.maxLength = 5.5f; @@ -2377,49 +2412,49 @@ class ScissorLift : public Sample distanceDef.enableMotor = m_enableMotor; distanceDef.motorSpeed = m_motorSpeed; distanceDef.maxMotorForce = m_motorForce; - m_liftJointId = b2CreateDistanceJoint(m_worldId, &distanceDef); + m_liftJointId = b2CreateDistanceJoint( m_worldId, &distanceDef ); Car car; - car.Spawn(m_worldId, {0.0f, y + 2.0f}, 1.0f, 3.0f, 0.7f, 0.0f, NULL); + car.Spawn( m_worldId, { 0.0f, y + 2.0f }, 1.0f, 3.0f, 0.7f, 0.0f, NULL ); } void UpdateUI() override { float height = 140.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(240.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); - ImGui::Begin("Scissor Lift", nullptr, ImGuiWindowFlags_NoResize); + ImGui::Begin( "Scissor Lift", nullptr, ImGuiWindowFlags_NoResize ); - if (ImGui::Checkbox("Motor", &m_enableMotor)) + if ( ImGui::Checkbox( "Motor", &m_enableMotor ) ) { - b2DistanceJoint_EnableMotor(m_liftJointId, m_enableMotor); - b2Joint_WakeBodies(m_liftJointId); + b2DistanceJoint_EnableMotor( m_liftJointId, m_enableMotor ); + b2Joint_WakeBodies( m_liftJointId ); } - if (ImGui::SliderFloat("Max Force", &m_motorForce, 0.0f, 3000.0f, "%.0f")) + if ( ImGui::SliderFloat( "Max Force", &m_motorForce, 0.0f, 3000.0f, "%.0f" ) ) { - b2DistanceJoint_SetMaxMotorForce(m_liftJointId, m_motorForce); - b2Joint_WakeBodies(m_liftJointId); + b2DistanceJoint_SetMaxMotorForce( m_liftJointId, m_motorForce ); + b2Joint_WakeBodies( m_liftJointId ); } - if (ImGui::SliderFloat("Speed", &m_motorSpeed, -0.3f, 0.3f, "%.2f")) + if ( ImGui::SliderFloat( "Speed", &m_motorSpeed, -0.3f, 0.3f, "%.2f" ) ) { - b2DistanceJoint_SetMotorSpeed(m_liftJointId, m_motorSpeed); - b2Joint_WakeBodies(m_liftJointId); + b2DistanceJoint_SetMotorSpeed( m_liftJointId, m_motorSpeed ); + b2Joint_WakeBodies( m_liftJointId ); } ImGui::End(); } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - Sample::Step(settings); + Sample::Step( settings ); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new ScissorLift(settings); + return new ScissorLift( settings ); } b2JointId m_liftJointId; @@ -2428,4 +2463,4 @@ class ScissorLift : public Sample bool m_enableMotor; }; -static int sampleScissorLift = RegisterSample("Joints", "Scissor Lift", ScissorLift::Create); +static int sampleScissorLift = RegisterSample( "Joints", "Scissor Lift", ScissorLift::Create ); diff --git a/samples/sample_robustness.cpp b/samples/sample_robustness.cpp index b008dfc7..60130383 100644 --- a/samples/sample_robustness.cpp +++ b/samples/sample_robustness.cpp @@ -13,13 +13,13 @@ // Pyramid with heavy box on top class HighMassRatio1 : public Sample { - public: - explicit HighMassRatio1(Settings& settings) - : Sample(settings) +public: + explicit HighMassRatio1( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {3.0f, 14.0f}; + g_camera.m_center = { 3.0f, 14.0f }; g_camera.m_zoom = 25.0f; } @@ -27,72 +27,71 @@ class HighMassRatio1 : public Sample { b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Polygon box = b2MakeOffsetBox(50.0f, 1.0f, {0.0f, -1.0f}, 0.0f); - b2CreatePolygonShape(groundId, &shapeDef, &box); + b2Polygon box = b2MakeOffsetBox( 50.0f, 1.0f, { 0.0f, -1.0f }, 0.0f ); + b2CreatePolygonShape( groundId, &shapeDef, &box ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - b2Polygon box = b2MakeBox(extent, extent); + b2Polygon box = b2MakeBox( extent, extent ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - for (int j = 0; j < 3; ++j) + for ( int j = 0; j < 3; ++j ) { int count = 10; - float offset = -20.0f * extent + 2.0f * (count + 1.0f) * extent * j; + float offset = -20.0f * extent + 2.0f * ( count + 1.0f ) * extent * j; float y = extent; - while (count > 0) + while ( count > 0 ) { - for (int i = 0; i < count; ++i) + for ( int i = 0; i < count; ++i ) { float coeff = i - 0.5f * count; float yy = count == 1 ? y + 2.0f : y; - bodyDef.position = {2.0f * coeff * extent + offset, yy}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { 2.0f * coeff * extent + offset, yy }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); - shapeDef.density = count == 1 ? (j + 1.0f) * 100.0f : 1.0f; - b2CreatePolygonShape(bodyId, &shapeDef, &box); + shapeDef.density = count == 1 ? ( j + 1.0f ) * 100.0f : 1.0f; + b2CreatePolygonShape( bodyId, &shapeDef, &box ); } --count; y += 2.0f * extent; } } - } } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new HighMassRatio1(settings); + return new HighMassRatio1( settings ); } }; -static int sampleIndex1 = RegisterSample("Robustness", "HighMassRatio1", HighMassRatio1::Create); +static int sampleIndex1 = RegisterSample( "Robustness", "HighMassRatio1", HighMassRatio1::Create ); // Big box on small boxes class HighMassRatio2 : public Sample { - public: - explicit HighMassRatio2(Settings& settings) - : Sample(settings) +public: + explicit HighMassRatio2( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 16.5f}; + g_camera.m_center = { 0.0f, 16.5f }; g_camera.m_zoom = 25.0f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Polygon box = b2MakeOffsetBox(50.0f, 1.0f, {0.0f, -1.0f}, 0.0f); - b2CreatePolygonShape(groundId, &shapeDef, &box); + b2Polygon box = b2MakeOffsetBox( 50.0f, 1.0f, { 0.0f, -1.0f }, 0.0f ); + b2CreatePolygonShape( groundId, &shapeDef, &box ); } { @@ -101,49 +100,49 @@ class HighMassRatio2 : public Sample b2ShapeDef shapeDef = b2DefaultShapeDef(); float extent = 1.0f; - b2Vec2 points[3] = {{-0.5f * extent, 0.0f}, {0.5f * extent, 0.0f}, {0.0f, 1.0f * extent}}; - b2Hull hull = b2ComputeHull(points, 3); - b2Polygon smallTriangle = b2MakePolygon(&hull, 0.0f); - b2Polygon smallBox = b2MakeBox(0.5f * extent, 0.5f * extent); - b2Polygon bigBox = b2MakeBox(10.0f * extent, 10.0f * extent); + b2Vec2 points[3] = { { -0.5f * extent, 0.0f }, { 0.5f * extent, 0.0f }, { 0.0f, 1.0f * extent } }; + b2Hull hull = b2ComputeHull( points, 3 ); + b2Polygon smallTriangle = b2MakePolygon( &hull, 0.0f ); + b2Polygon smallBox = b2MakeBox( 0.5f * extent, 0.5f * extent ); + b2Polygon bigBox = b2MakeBox( 10.0f * extent, 10.0f * extent ); { - bodyDef.position = {-9.0f * extent, 0.5f * extent}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &smallBox); + bodyDef.position = { -9.0f * extent, 0.5f * extent }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &smallBox ); } { - bodyDef.position = {9.0f * extent, 0.5f * extent}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &smallBox); + bodyDef.position = { 9.0f * extent, 0.5f * extent }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &smallBox ); } { - bodyDef.position = {0.0f, (10.0f + 16.0f) * extent}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &bigBox); + bodyDef.position = { 0.0f, ( 10.0f + 16.0f ) * extent }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &bigBox ); } } } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new HighMassRatio2(settings); + return new HighMassRatio2( settings ); } }; -static int sampleIndex2 = RegisterSample("Robustness", "HighMassRatio2", HighMassRatio2::Create); +static int sampleIndex2 = RegisterSample( "Robustness", "HighMassRatio2", HighMassRatio2::Create ); class OverlapRecovery : public Sample { - public: - explicit OverlapRecovery(Settings& settings) - : Sample(settings) +public: + explicit OverlapRecovery( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 2.5f}; + g_camera.m_center = { 0.0f, 2.5f }; g_camera.m_zoom = 25.0f * 0.15f; } @@ -157,55 +156,55 @@ class OverlapRecovery : public Sample m_dampingRatio = 10.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); float groundWidth = 40.0f; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; - b2Segment segment = {{-groundWidth, 0.0f}, {groundWidth, 0.0f}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2Segment segment = { { -groundWidth, 0.0f }, { groundWidth, 0.0f } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment ); CreateScene(); } ~OverlapRecovery() override { - free(m_bodyIds); + free( m_bodyIds ); } void CreateScene() { - for (int32_t i = 0; i < m_bodyCount; ++i) + for ( int32_t i = 0; i < m_bodyCount; ++i ) { - b2DestroyBody(m_bodyIds[i]); + b2DestroyBody( m_bodyIds[i] ); } - b2World_SetContactTuning(m_worldId, m_hertz, m_dampingRatio, m_pushout); + b2World_SetContactTuning( m_worldId, m_hertz, m_dampingRatio, m_pushout ); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - b2Polygon box = b2MakeBox(m_extent, m_extent); + b2Polygon box = b2MakeBox( m_extent, m_extent ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; - - m_bodyCount = m_baseCount * (m_baseCount + 1) / 2; - m_bodyIds = (b2BodyId*)realloc(m_bodyIds, m_bodyCount * sizeof(b2BodyId)); + + m_bodyCount = m_baseCount * ( m_baseCount + 1 ) / 2; + m_bodyIds = (b2BodyId*)realloc( m_bodyIds, m_bodyCount * sizeof( b2BodyId ) ); int32_t bodyIndex = 0; float fraction = 1.0f - m_overlap; float y = m_extent; - for (int32_t i = 0; i < m_baseCount; ++i) + for ( int32_t i = 0; i < m_baseCount; ++i ) { - float x = fraction * m_extent * (i - m_baseCount); - for (int32_t j = i; j < m_baseCount; ++j) + float x = fraction * m_extent * ( i - m_baseCount ); + for ( int32_t j = i; j < m_baseCount; ++j ) { - bodyDef.position = {x, y}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { x, y }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + + b2CreatePolygonShape( bodyId, &shapeDef, &box ); - b2CreatePolygonShape(bodyId, &shapeDef, &box); - m_bodyIds[bodyIndex++] = bodyId; x += 2.0f * fraction * m_extent; @@ -214,28 +213,28 @@ class OverlapRecovery : public Sample y += 2.0f * fraction * m_extent; } - assert(bodyIndex == m_bodyCount); + assert( bodyIndex == m_bodyCount ); } void UpdateUI() override { float height = 210.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(220.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 220.0f, height ) ); - ImGui::Begin("Overlap Recovery", nullptr, ImGuiWindowFlags_NoResize); - ImGui::PushItemWidth(100.0f); + ImGui::Begin( "Overlap Recovery", nullptr, ImGuiWindowFlags_NoResize ); + ImGui::PushItemWidth( 100.0f ); bool changed = false; - changed = changed || ImGui::SliderFloat("Extent", &m_extent, 0.1f, 1.0f, "%.1f"); - changed = changed || ImGui::SliderInt("Base Count", &m_baseCount, 1, 10); - changed = changed || ImGui::SliderFloat("Overlap", &m_overlap, 0.0f, 1.0f, "%.2f"); - changed = changed || ImGui::SliderFloat("Pushout", &m_pushout, 0.0f, 10.0f, "%.1f"); - changed = changed || ImGui::SliderFloat("Hertz", &m_hertz, 0.0f, 120.0f, "%.f"); - changed = changed || ImGui::SliderFloat("Damping Ratio", &m_dampingRatio, 0.0f, 20.0f, "%.1f"); - changed = changed || ImGui::Button("Reset Scene"); - - if (changed) + changed = changed || ImGui::SliderFloat( "Extent", &m_extent, 0.1f, 1.0f, "%.1f" ); + changed = changed || ImGui::SliderInt( "Base Count", &m_baseCount, 1, 10 ); + changed = changed || ImGui::SliderFloat( "Overlap", &m_overlap, 0.0f, 1.0f, "%.2f" ); + changed = changed || ImGui::SliderFloat( "Pushout", &m_pushout, 0.0f, 10.0f, "%.1f" ); + changed = changed || ImGui::SliderFloat( "Hertz", &m_hertz, 0.0f, 120.0f, "%.f" ); + changed = changed || ImGui::SliderFloat( "Damping Ratio", &m_dampingRatio, 0.0f, 20.0f, "%.1f" ); + changed = changed || ImGui::Button( "Reset Scene" ); + + if ( changed ) { CreateScene(); } @@ -244,9 +243,9 @@ class OverlapRecovery : public Sample ImGui::End(); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new OverlapRecovery(settings); + return new OverlapRecovery( settings ); } b2BodyId* m_bodyIds; @@ -259,4 +258,4 @@ class OverlapRecovery : public Sample float m_dampingRatio; }; -static int sampleIndex4 = RegisterSample("Robustness", "Overlap Recovery", OverlapRecovery::Create); +static int sampleIndex4 = RegisterSample( "Robustness", "Overlap Recovery", OverlapRecovery::Create ); diff --git a/samples/sample_shapes.cpp b/samples/sample_shapes.cpp index 48c52b24..e610e130 100644 --- a/samples/sample_shapes.cpp +++ b/samples/sample_shapes.cpp @@ -21,12 +21,12 @@ class ChainShape : public Sample e_boxShape }; - explicit ChainShape(Settings& settings) - : Sample(settings) + explicit ChainShape( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 0.0f}; + g_camera.m_center = { 0.0f, 0.0f }; g_camera.m_zoom = 25.0f * 1.75f; } @@ -43,9 +43,9 @@ class ChainShape : public Sample void CreateScene() { - if (B2_IS_NON_NULL(m_groundId)) + if ( B2_IS_NON_NULL( m_groundId ) ) { - b2DestroyBody(m_groundId); + b2DestroyBody( m_groundId ); } // https://betravis.github.io/shape-tools/path-to-polygon/ @@ -63,14 +63,14 @@ class ChainShape : public Sample // {-13.96875, 11.89575}, {-15.29175, 14.54175}, {-19.2605, 14.54175}}; b2Vec2 points[] = { - {-56.885498, 12.8985004}, {-56.885498, 16.2057495}, {56.885498, 16.2057495}, {56.885498, -16.2057514}, - {51.5935059, -16.2057514}, {43.6559982, -10.9139996}, {35.7184982, -10.9139996}, {27.7809982, -10.9139996}, - {21.1664963, -14.2212505}, {11.9059982, -16.2057514}, {0, -16.2057514}, {-10.5835037, -14.8827496}, - {-17.1980019, -13.5597477}, {-21.1665001, -12.2370014}, {-25.1355019, -9.5909977}, {-31.75, -3.63799858}, - {-38.3644981, 6.2840004}, {-42.3334999, 9.59125137}, {-47.625, 11.5755005}, {-56.885498, 12.8985004}, + { -56.885498, 12.8985004 }, { -56.885498, 16.2057495 }, { 56.885498, 16.2057495 }, { 56.885498, -16.2057514 }, + { 51.5935059, -16.2057514 }, { 43.6559982, -10.9139996 }, { 35.7184982, -10.9139996 }, { 27.7809982, -10.9139996 }, + { 21.1664963, -14.2212505 }, { 11.9059982, -16.2057514 }, { 0, -16.2057514 }, { -10.5835037, -14.8827496 }, + { -17.1980019, -13.5597477 }, { -21.1665001, -12.2370014 }, { -25.1355019, -9.5909977 }, { -31.75, -3.63799858 }, + { -38.3644981, 6.2840004 }, { -42.3334999, 9.59125137 }, { -47.625, 11.5755005 }, { -56.885498, 12.8985004 }, }; - int count = sizeof(points) / sizeof(points[0]); + int count = sizeof( points ) / sizeof( points[0] ); // float scale = 0.25f; // b2Vec2 lower = {FLT_MAX, FLT_MAX}; @@ -111,74 +111,74 @@ class ChainShape : public Sample chainDef.friction = 0.2f; b2BodyDef bodyDef = b2DefaultBodyDef(); - m_groundId = b2CreateBody(m_worldId, &bodyDef); + m_groundId = b2CreateBody( m_worldId, &bodyDef ); - m_chainId = b2CreateChain(m_groundId, &chainDef); - } + m_chainId = b2CreateChain( m_groundId, &chainDef ); + } void Launch() { - if (B2_IS_NON_NULL(m_bodyId)) + if ( B2_IS_NON_NULL( m_bodyId ) ) { - b2DestroyBody(m_bodyId); + b2DestroyBody( m_bodyId ); } b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {-55.0f, 13.5f}; - m_bodyId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { -55.0f, 13.5f }; + m_bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; shapeDef.friction = m_friction; shapeDef.restitution = m_restitution; - - if (m_shapeType == e_circleShape) + + if ( m_shapeType == e_circleShape ) { - b2Circle circle = {{0.0f, 0.0f}, 0.5f}; - m_shapeId = b2CreateCircleShape(m_bodyId, &shapeDef, &circle); + b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; + m_shapeId = b2CreateCircleShape( m_bodyId, &shapeDef, &circle ); } - else if (m_shapeType == e_capsuleShape) + else if ( m_shapeType == e_capsuleShape ) { - b2Capsule capsule = {{-0.5f, 0.0f}, {0.5f, 0.0}, 0.25f}; - m_shapeId = b2CreateCapsuleShape(m_bodyId, &shapeDef, &capsule); + b2Capsule capsule = { { -0.5f, 0.0f }, { 0.5f, 0.0 }, 0.25f }; + m_shapeId = b2CreateCapsuleShape( m_bodyId, &shapeDef, &capsule ); } else { float h = 0.5f; - b2Polygon box = b2MakeBox(h, h); - m_shapeId = b2CreatePolygonShape(m_bodyId, &shapeDef, &box); + b2Polygon box = b2MakeBox( h, h ); + m_shapeId = b2CreatePolygonShape( m_bodyId, &shapeDef, &box ); } } void UpdateUI() override { float height = 135.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(240.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); - ImGui::Begin("Chain Shape", nullptr, ImGuiWindowFlags_NoResize); + ImGui::Begin( "Chain Shape", nullptr, ImGuiWindowFlags_NoResize ); - const char* shapeTypes[] = {"Circle", "Capsule", "Box"}; - int shapeType = int(m_shapeType); - if (ImGui::Combo("Shape", &shapeType, shapeTypes, IM_ARRAYSIZE(shapeTypes))) + const char* shapeTypes[] = { "Circle", "Capsule", "Box" }; + int shapeType = int( m_shapeType ); + if ( ImGui::Combo( "Shape", &shapeType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ) ) { - m_shapeType = ShapeType(shapeType); + m_shapeType = ShapeType( shapeType ); Launch(); } - if (ImGui::SliderFloat("Friction", &m_friction, 0.0f, 1.0f, "%.2f")) + if ( ImGui::SliderFloat( "Friction", &m_friction, 0.0f, 1.0f, "%.2f" ) ) { - b2Shape_SetFriction(m_shapeId, m_friction); - b2Chain_SetFriction(m_chainId, m_friction); + b2Shape_SetFriction( m_shapeId, m_friction ); + b2Chain_SetFriction( m_chainId, m_friction ); } - if (ImGui::SliderFloat("Restitution", &m_restitution, 0.0f, 2.0f, "%.1f")) + if ( ImGui::SliderFloat( "Restitution", &m_restitution, 0.0f, 2.0f, "%.1f" ) ) { - b2Shape_SetRestitution(m_shapeId, m_restitution); + b2Shape_SetRestitution( m_shapeId, m_restitution ); } - if (ImGui::Button("Launch")) + if ( ImGui::Button( "Launch" ) ) { Launch(); } @@ -186,17 +186,17 @@ class ChainShape : public Sample ImGui::End(); } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - Sample::Step(settings); + Sample::Step( settings ); - g_draw.DrawSegment(b2Vec2_zero, {0.5f, 0.0f}, b2_colorRed); - g_draw.DrawSegment(b2Vec2_zero, {0.0f, 0.5f}, b2_colorGreen); + g_draw.DrawSegment( b2Vec2_zero, { 0.5f, 0.0f }, b2_colorRed ); + g_draw.DrawSegment( b2Vec2_zero, { 0.0f, 0.5f }, b2_colorGreen ); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new ChainShape(settings); + return new ChainShape( settings ); } b2BodyId m_groundId; @@ -208,7 +208,7 @@ class ChainShape : public Sample float m_friction; }; -static int sampleChainShape = RegisterSample("Shapes", "Chain Shape", ChainShape::Create); +static int sampleChainShape = RegisterSample( "Shapes", "Chain Shape", ChainShape::Create ); // This sample shows how careful creation of compound shapes leads to better simulation and avoids // objects getting stuck. @@ -216,107 +216,107 @@ static int sampleChainShape = RegisterSample("Shapes", "Chain Shape", ChainShape class CompoundShapes : public Sample { public: - explicit CompoundShapes(Settings& settings) - : Sample(settings) + explicit CompoundShapes( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 6.0f}; + g_camera.m_center = { 0.0f, 6.0f }; g_camera.m_zoom = 25.0f * 0.5f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Segment segment = {{50.0f, 0.0f}, {-50.0f, 0.0f}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2Segment segment = { { 50.0f, 0.0f }, { -50.0f, 0.0f } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment ); } // Table 1 { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {-15.0f, 1.0f}; - m_table1Id = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { -15.0f, 1.0f }; + m_table1Id = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Polygon top = b2MakeOffsetBox(3.0f, 0.5f, {0.0f, 3.5f}, 0.0f); - b2Polygon leftLeg = b2MakeOffsetBox(0.5f, 1.5f, {-2.5f, 1.5f}, 0.0f); - b2Polygon rightLeg = b2MakeOffsetBox(0.5f, 1.5f, {2.5f, 1.5f}, 0.0f); + b2Polygon top = b2MakeOffsetBox( 3.0f, 0.5f, { 0.0f, 3.5f }, 0.0f ); + b2Polygon leftLeg = b2MakeOffsetBox( 0.5f, 1.5f, { -2.5f, 1.5f }, 0.0f ); + b2Polygon rightLeg = b2MakeOffsetBox( 0.5f, 1.5f, { 2.5f, 1.5f }, 0.0f ); - b2CreatePolygonShape(m_table1Id, &shapeDef, &top); - b2CreatePolygonShape(m_table1Id, &shapeDef, &leftLeg); - b2CreatePolygonShape(m_table1Id, &shapeDef, &rightLeg); + b2CreatePolygonShape( m_table1Id, &shapeDef, &top ); + b2CreatePolygonShape( m_table1Id, &shapeDef, &leftLeg ); + b2CreatePolygonShape( m_table1Id, &shapeDef, &rightLeg ); } // Table 2 { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {-5.0f, 1.0f}; - m_table2Id = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { -5.0f, 1.0f }; + m_table2Id = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Polygon top = b2MakeOffsetBox(3.0f, 0.5f, {0.0f, 3.5f}, 0.0f); - b2Polygon leftLeg = b2MakeOffsetBox(0.5f, 2.0f, {-2.5f, 2.0f}, 0.0f); - b2Polygon rightLeg = b2MakeOffsetBox(0.5f, 2.0f, {2.5f, 2.0f}, 0.0f); + b2Polygon top = b2MakeOffsetBox( 3.0f, 0.5f, { 0.0f, 3.5f }, 0.0f ); + b2Polygon leftLeg = b2MakeOffsetBox( 0.5f, 2.0f, { -2.5f, 2.0f }, 0.0f ); + b2Polygon rightLeg = b2MakeOffsetBox( 0.5f, 2.0f, { 2.5f, 2.0f }, 0.0f ); - b2CreatePolygonShape(m_table2Id, &shapeDef, &top); - b2CreatePolygonShape(m_table2Id, &shapeDef, &leftLeg); - b2CreatePolygonShape(m_table2Id, &shapeDef, &rightLeg); + b2CreatePolygonShape( m_table2Id, &shapeDef, &top ); + b2CreatePolygonShape( m_table2Id, &shapeDef, &leftLeg ); + b2CreatePolygonShape( m_table2Id, &shapeDef, &rightLeg ); } // Spaceship 1 { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {5.0f, 1.0f}; - m_ship1Id = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { 5.0f, 1.0f }; + m_ship1Id = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Vec2 vertices[3]; - vertices[0] = {-2.0f, 0.0f}; - vertices[1] = {0.0f, 4.0f / 3.0f}; - vertices[2] = {0.0f, 4.0f}; - b2Hull hull = b2ComputeHull(vertices, 3); - b2Polygon left = b2MakePolygon(&hull, 0.0f); + vertices[0] = { -2.0f, 0.0f }; + vertices[1] = { 0.0f, 4.0f / 3.0f }; + vertices[2] = { 0.0f, 4.0f }; + b2Hull hull = b2ComputeHull( vertices, 3 ); + b2Polygon left = b2MakePolygon( &hull, 0.0f ); - vertices[0] = {2.0f, 0.0f}; - vertices[1] = {0.0f, 4.0f / 3.0f}; - vertices[2] = {0.0f, 4.0f}; - hull = b2ComputeHull(vertices, 3); - b2Polygon right = b2MakePolygon(&hull, 0.0f); + vertices[0] = { 2.0f, 0.0f }; + vertices[1] = { 0.0f, 4.0f / 3.0f }; + vertices[2] = { 0.0f, 4.0f }; + hull = b2ComputeHull( vertices, 3 ); + b2Polygon right = b2MakePolygon( &hull, 0.0f ); - b2CreatePolygonShape(m_ship1Id, &shapeDef, &left); - b2CreatePolygonShape(m_ship1Id, &shapeDef, &right); + b2CreatePolygonShape( m_ship1Id, &shapeDef, &left ); + b2CreatePolygonShape( m_ship1Id, &shapeDef, &right ); } // Spaceship 2 { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {15.0f, 1.0f}; - m_ship2Id = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { 15.0f, 1.0f }; + m_ship2Id = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Vec2 vertices[3]; - vertices[0] = {-2.0f, 0.0f}; - vertices[1] = {1.0f, 2.0f}; - vertices[2] = {0.0f, 4.0f}; - b2Hull hull = b2ComputeHull(vertices, 3); - b2Polygon left = b2MakePolygon(&hull, 0.0f); + vertices[0] = { -2.0f, 0.0f }; + vertices[1] = { 1.0f, 2.0f }; + vertices[2] = { 0.0f, 4.0f }; + b2Hull hull = b2ComputeHull( vertices, 3 ); + b2Polygon left = b2MakePolygon( &hull, 0.0f ); - vertices[0] = {2.0f, 0.0f}; - vertices[1] = {-1.0f, 2.0f}; - vertices[2] = {0.0f, 4.0f}; - hull = b2ComputeHull(vertices, 3); - b2Polygon right = b2MakePolygon(&hull, 0.0f); + vertices[0] = { 2.0f, 0.0f }; + vertices[1] = { -1.0f, 2.0f }; + vertices[2] = { 0.0f, 4.0f }; + hull = b2ComputeHull( vertices, 3 ); + b2Polygon right = b2MakePolygon( &hull, 0.0f ); - b2CreatePolygonShape(m_ship2Id, &shapeDef, &left); - b2CreatePolygonShape(m_ship2Id, &shapeDef, &right); + b2CreatePolygonShape( m_ship2Id, &shapeDef, &left ); + b2CreatePolygonShape( m_ship2Id, &shapeDef, &right ); } m_drawBodyAABBs = false; @@ -328,98 +328,98 @@ class CompoundShapes : public Sample { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = b2Body_GetPosition(m_table1Id); - bodyDef.rotation = b2Body_GetRotation(m_table1Id); - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = b2Body_GetPosition( m_table1Id ); + bodyDef.rotation = b2Body_GetRotation( m_table1Id ); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Polygon box = b2MakeOffsetBox(4.0f, 0.1f, {0.0f, 3.0f}, 0.0f); - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2Polygon box = b2MakeOffsetBox( 4.0f, 0.1f, { 0.0f, 3.0f }, 0.0f ); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); } // Table 2 obstruction { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = b2Body_GetPosition(m_table2Id); - bodyDef.rotation = b2Body_GetRotation(m_table2Id); - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = b2Body_GetPosition( m_table2Id ); + bodyDef.rotation = b2Body_GetRotation( m_table2Id ); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Polygon box = b2MakeOffsetBox(4.0f, 0.1f, {0.0f, 3.0f}, 0.0f); - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2Polygon box = b2MakeOffsetBox( 4.0f, 0.1f, { 0.0f, 3.0f }, 0.0f ); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); } // Ship 1 obstruction { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = b2Body_GetPosition(m_ship1Id); - bodyDef.rotation = b2Body_GetRotation(m_ship1Id); + bodyDef.position = b2Body_GetPosition( m_ship1Id ); + bodyDef.rotation = b2Body_GetRotation( m_ship1Id ); // bodyDef.gravityScale = 0.0f; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Circle circle = {{0.0f, 2.0f}, 0.5f}; - b2CreateCircleShape(bodyId, &shapeDef, &circle); + b2Circle circle = { { 0.0f, 2.0f }, 0.5f }; + b2CreateCircleShape( bodyId, &shapeDef, &circle ); } // Ship 2 obstruction { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = b2Body_GetPosition(m_ship2Id); - bodyDef.rotation = b2Body_GetRotation(m_ship2Id); + bodyDef.position = b2Body_GetPosition( m_ship2Id ); + bodyDef.rotation = b2Body_GetRotation( m_ship2Id ); // bodyDef.gravityScale = 0.0f; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Circle circle = {{0.0f, 2.0f}, 0.5f}; - b2CreateCircleShape(bodyId, &shapeDef, &circle); + b2Circle circle = { { 0.0f, 2.0f }, 0.5f }; + b2CreateCircleShape( bodyId, &shapeDef, &circle ); } } void UpdateUI() override { float height = 100.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(180.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 180.0f, height ) ); - ImGui::Begin("Compound Shapes", nullptr, ImGuiWindowFlags_NoResize); + ImGui::Begin( "Compound Shapes", nullptr, ImGuiWindowFlags_NoResize ); - if (ImGui::Button("Intrude")) + if ( ImGui::Button( "Intrude" ) ) { Spawn(); } - ImGui::Checkbox("Body AABBs", &m_drawBodyAABBs); + ImGui::Checkbox( "Body AABBs", &m_drawBodyAABBs ); ImGui::End(); } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - Sample::Step(settings); + Sample::Step( settings ); - if (m_drawBodyAABBs) + if ( m_drawBodyAABBs ) { - b2AABB aabb = b2Body_ComputeAABB(m_table1Id); - g_draw.DrawAABB(aabb, b2_colorYellow); + b2AABB aabb = b2Body_ComputeAABB( m_table1Id ); + g_draw.DrawAABB( aabb, b2_colorYellow ); - aabb = b2Body_ComputeAABB(m_table2Id); - g_draw.DrawAABB(aabb, b2_colorYellow); + aabb = b2Body_ComputeAABB( m_table2Id ); + g_draw.DrawAABB( aabb, b2_colorYellow ); - aabb = b2Body_ComputeAABB(m_ship1Id); - g_draw.DrawAABB(aabb, b2_colorYellow); + aabb = b2Body_ComputeAABB( m_ship1Id ); + g_draw.DrawAABB( aabb, b2_colorYellow ); - aabb = b2Body_ComputeAABB(m_ship2Id); - g_draw.DrawAABB(aabb, b2_colorYellow); + aabb = b2Body_ComputeAABB( m_ship2Id ); + g_draw.DrawAABB( aabb, b2_colorYellow ); } } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new CompoundShapes(settings); + return new CompoundShapes( settings ); } b2BodyId m_table1Id; @@ -429,7 +429,7 @@ class CompoundShapes : public Sample bool m_drawBodyAABBs; }; -static int sampleCompoundShape = RegisterSample("Shapes", "Compound Shapes", CompoundShapes::Create); +static int sampleCompoundShape = RegisterSample( "Shapes", "Compound Shapes", CompoundShapes::Create ); class ShapeFilter : public Sample { @@ -441,76 +441,76 @@ class ShapeFilter : public Sample TEAM2 = 0x00000004, TEAM3 = 0x00000008, - ALL_BITS = (~0u) + ALL_BITS = ( ~0u ) }; - explicit ShapeFilter(Settings& settings) - : Sample(settings) + explicit ShapeFilter( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { g_camera.m_zoom = 25.0f * 0.5f; - g_camera.m_center = {0.0f, 5.0f}; + g_camera.m_center = { 0.0f, 5.0f }; } { b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); - b2Segment segment = {{-20.0f, 0.0f}, {20.0f, 0.0f}}; + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); + b2Segment segment = { { -20.0f, 0.0f }, { 20.0f, 0.0f } }; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.filter.categoryBits = GROUND; shapeDef.filter.maskBits = ALL_BITS; - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2CreateSegmentShape( groundId, &shapeDef, &segment ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {0.0f, 2.0f}; - m_player1Id = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { 0.0f, 2.0f }; + m_player1Id = b2CreateBody( m_worldId, &bodyDef ); - bodyDef.position = {0.0f, 5.0f}; - m_player2Id = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { 0.0f, 5.0f }; + m_player2Id = b2CreateBody( m_worldId, &bodyDef ); - bodyDef.position = {0.0f, 8.0f}; - m_player3Id = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { 0.0f, 8.0f }; + m_player3Id = b2CreateBody( m_worldId, &bodyDef ); - b2Polygon box = b2MakeBox(2.0f, 1.0f); + b2Polygon box = b2MakeBox( 2.0f, 1.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.filter.categoryBits = TEAM1; shapeDef.filter.maskBits = GROUND | TEAM2 | TEAM3; - m_shape1Id = b2CreatePolygonShape(m_player1Id, &shapeDef, &box); + m_shape1Id = b2CreatePolygonShape( m_player1Id, &shapeDef, &box ); shapeDef.filter.categoryBits = TEAM2; shapeDef.filter.maskBits = GROUND | TEAM1 | TEAM3; - m_shape2Id = b2CreatePolygonShape(m_player2Id, &shapeDef, &box); + m_shape2Id = b2CreatePolygonShape( m_player2Id, &shapeDef, &box ); shapeDef.filter.categoryBits = TEAM3; shapeDef.filter.maskBits = GROUND | TEAM1 | TEAM2; - m_shape3Id = b2CreatePolygonShape(m_player3Id, &shapeDef, &box); + m_shape3Id = b2CreatePolygonShape( m_player3Id, &shapeDef, &box ); } } void UpdateUI() override { float height = 240.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(240.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); - ImGui::Begin("Shape Filter", nullptr, ImGuiWindowFlags_NoResize); + ImGui::Begin( "Shape Filter", nullptr, ImGuiWindowFlags_NoResize ); - ImGui::Text("Player 1 Collides With"); + ImGui::Text( "Player 1 Collides With" ); { - b2Filter filter1 = b2Shape_GetFilter(m_shape1Id); - bool team2 = (filter1.maskBits & TEAM2) == TEAM2; - if (ImGui::Checkbox("Team 2##1", &team2)) + b2Filter filter1 = b2Shape_GetFilter( m_shape1Id ); + bool team2 = ( filter1.maskBits & TEAM2 ) == TEAM2; + if ( ImGui::Checkbox( "Team 2##1", &team2 ) ) { - if (team2) + if ( team2 ) { filter1.maskBits |= TEAM2; } @@ -519,13 +519,13 @@ class ShapeFilter : public Sample filter1.maskBits &= ~TEAM2; } - b2Shape_SetFilter(m_shape1Id, filter1); + b2Shape_SetFilter( m_shape1Id, filter1 ); } - bool team3 = (filter1.maskBits & TEAM3) == TEAM3; - if (ImGui::Checkbox("Team 3##1", &team3)) + bool team3 = ( filter1.maskBits & TEAM3 ) == TEAM3; + if ( ImGui::Checkbox( "Team 3##1", &team3 ) ) { - if (team3) + if ( team3 ) { filter1.maskBits |= TEAM3; } @@ -534,19 +534,19 @@ class ShapeFilter : public Sample filter1.maskBits &= ~TEAM3; } - b2Shape_SetFilter(m_shape1Id, filter1); + b2Shape_SetFilter( m_shape1Id, filter1 ); } } ImGui::Separator(); - ImGui::Text("Player 2 Collides With"); + ImGui::Text( "Player 2 Collides With" ); { - b2Filter filter2 = b2Shape_GetFilter(m_shape2Id); - bool team1 = (filter2.maskBits & TEAM1) == TEAM1; - if (ImGui::Checkbox("Team 1##2", &team1)) + b2Filter filter2 = b2Shape_GetFilter( m_shape2Id ); + bool team1 = ( filter2.maskBits & TEAM1 ) == TEAM1; + if ( ImGui::Checkbox( "Team 1##2", &team1 ) ) { - if (team1) + if ( team1 ) { filter2.maskBits |= TEAM1; } @@ -555,13 +555,13 @@ class ShapeFilter : public Sample filter2.maskBits &= ~TEAM1; } - b2Shape_SetFilter(m_shape2Id, filter2); + b2Shape_SetFilter( m_shape2Id, filter2 ); } - bool team3 = (filter2.maskBits & TEAM3) == TEAM3; - if (ImGui::Checkbox("Team 3##2", &team3)) + bool team3 = ( filter2.maskBits & TEAM3 ) == TEAM3; + if ( ImGui::Checkbox( "Team 3##2", &team3 ) ) { - if (team3) + if ( team3 ) { filter2.maskBits |= TEAM3; } @@ -570,19 +570,19 @@ class ShapeFilter : public Sample filter2.maskBits &= ~TEAM3; } - b2Shape_SetFilter(m_shape2Id, filter2); + b2Shape_SetFilter( m_shape2Id, filter2 ); } } ImGui::Separator(); - ImGui::Text("Player 3 Collides With"); + ImGui::Text( "Player 3 Collides With" ); { - b2Filter filter3 = b2Shape_GetFilter(m_shape3Id); - bool team1 = (filter3.maskBits & TEAM1) == TEAM1; - if (ImGui::Checkbox("Team 1##3", &team1)) + b2Filter filter3 = b2Shape_GetFilter( m_shape3Id ); + bool team1 = ( filter3.maskBits & TEAM1 ) == TEAM1; + if ( ImGui::Checkbox( "Team 1##3", &team1 ) ) { - if (team1) + if ( team1 ) { filter3.maskBits |= TEAM1; } @@ -591,13 +591,13 @@ class ShapeFilter : public Sample filter3.maskBits &= ~TEAM1; } - b2Shape_SetFilter(m_shape3Id, filter3); + b2Shape_SetFilter( m_shape3Id, filter3 ); } - bool team2 = (filter3.maskBits & TEAM2) == TEAM2; - if (ImGui::Checkbox("Team 2##3", &team2)) + bool team2 = ( filter3.maskBits & TEAM2 ) == TEAM2; + if ( ImGui::Checkbox( "Team 2##3", &team2 ) ) { - if (team2) + if ( team2 ) { filter3.maskBits |= TEAM2; } @@ -606,30 +606,30 @@ class ShapeFilter : public Sample filter3.maskBits &= ~TEAM2; } - b2Shape_SetFilter(m_shape3Id, filter3); + b2Shape_SetFilter( m_shape3Id, filter3 ); } } ImGui::End(); } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - Sample::Step(settings); + Sample::Step( settings ); - b2Vec2 p1 = b2Body_GetPosition(m_player1Id); - g_draw.DrawString({p1.x - 0.5f, p1.y}, "player 1"); + b2Vec2 p1 = b2Body_GetPosition( m_player1Id ); + g_draw.DrawString( { p1.x - 0.5f, p1.y }, "player 1" ); - b2Vec2 p2 = b2Body_GetPosition(m_player2Id); - g_draw.DrawString({p2.x - 0.5f, p2.y}, "player 2"); + b2Vec2 p2 = b2Body_GetPosition( m_player2Id ); + g_draw.DrawString( { p2.x - 0.5f, p2.y }, "player 2" ); - b2Vec2 p3 = b2Body_GetPosition(m_player3Id); - g_draw.DrawString({p3.x - 0.5f, p3.y}, "player 3"); + b2Vec2 p3 = b2Body_GetPosition( m_player3Id ); + g_draw.DrawString( { p3.x - 0.5f, p3.y }, "player 3" ); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new ShapeFilter(settings); + return new ShapeFilter( settings ); } b2BodyId m_player1Id; @@ -641,7 +641,7 @@ class ShapeFilter : public Sample b2ShapeId m_shape3Id; }; -static int sampleShapeFilter = RegisterSample("Shapes", "Filter", ShapeFilter::Create); +static int sampleShapeFilter = RegisterSample( "Shapes", "Filter", ShapeFilter::Create ); // This shows how to use custom filtering class CustomFilter : public Sample @@ -652,91 +652,91 @@ class CustomFilter : public Sample e_count = 10 }; - explicit CustomFilter(Settings& settings) - : Sample(settings) + explicit CustomFilter( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 5.0f}; + g_camera.m_center = { 0.0f, 5.0f }; g_camera.m_zoom = 10.0f; } // Register custom filter - b2World_SetCustomFilterCallback(m_worldId, CustomFilterStatic, this); + b2World_SetCustomFilterCallback( m_worldId, CustomFilterStatic, this ); { b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); - b2Segment segment = {{-40.0f, 0.0f}, {40.0f, 0.0f}}; + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); + b2Segment segment = { { -40.0f, 0.0f }, { 40.0f, 0.0f } }; b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2CreateSegmentShape( groundId, &shapeDef, &segment ); } b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Polygon box = b2MakeSquare(1.0f); + b2Polygon box = b2MakeSquare( 1.0f ); float x = -e_count; - for (int i = 0; i < e_count; ++i) + for ( int i = 0; i < e_count; ++i ) { - bodyDef.position = {x, 5.0f}; - m_bodyIds[i] = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { x, 5.0f }; + m_bodyIds[i] = b2CreateBody( m_worldId, &bodyDef ); - shapeDef.userData = reinterpret_cast(intptr_t(i + 1)); - m_shapeIds[i] = b2CreatePolygonShape(m_bodyIds[i], &shapeDef, &box); + shapeDef.userData = reinterpret_cast( intptr_t( i + 1 ) ); + m_shapeIds[i] = b2CreatePolygonShape( m_bodyIds[i], &shapeDef, &box ); x += 2.0f; } } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - g_draw.DrawString(5, m_textLine, "Custom filter disables collision between odd and even shapes"); + g_draw.DrawString( 5, m_textLine, "Custom filter disables collision between odd and even shapes" ); m_textLine += m_textIncrement; - Sample::Step(settings); + Sample::Step( settings ); - for (int i = 0; i < e_count; ++i) + for ( int i = 0; i < e_count; ++i ) { - b2Vec2 p = b2Body_GetPosition(m_bodyIds[i]); - g_draw.DrawString({p.x, p.y}, "%d", i); + b2Vec2 p = b2Body_GetPosition( m_bodyIds[i] ); + g_draw.DrawString( { p.x, p.y }, "%d", i ); } } - bool ShouldCollide(b2ShapeId shapeIdA, b2ShapeId shapeIdB) + bool ShouldCollide( b2ShapeId shapeIdA, b2ShapeId shapeIdB ) { - void* userDataA = b2Shape_GetUserData(shapeIdA); - void* userDataB = b2Shape_GetUserData(shapeIdB); + void* userDataA = b2Shape_GetUserData( shapeIdA ); + void* userDataB = b2Shape_GetUserData( shapeIdB ); - if (userDataA == NULL || userDataB == NULL) + if ( userDataA == NULL || userDataB == NULL ) { return true; } - int indexA = static_cast(reinterpret_cast(userDataA)); - int indexB = static_cast(reinterpret_cast(userDataB)); + int indexA = static_cast( reinterpret_cast( userDataA ) ); + int indexB = static_cast( reinterpret_cast( userDataB ) ); - return ((indexA & 1) + (indexB & 1)) != 1; + return ( ( indexA & 1 ) + ( indexB & 1 ) ) != 1; } - static bool CustomFilterStatic(b2ShapeId shapeIdA, b2ShapeId shapeIdB, void* context) + static bool CustomFilterStatic( b2ShapeId shapeIdA, b2ShapeId shapeIdB, void* context ) { - CustomFilter* customFilter = static_cast(context); - return customFilter->ShouldCollide(shapeIdA, shapeIdB); + CustomFilter* customFilter = static_cast( context ); + return customFilter->ShouldCollide( shapeIdA, shapeIdB ); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new CustomFilter(settings); + return new CustomFilter( settings ); } b2BodyId m_bodyIds[e_count]; b2ShapeId m_shapeIds[e_count]; }; -static int sampleCustomFilter = RegisterSample("Shapes", "Custom Filter", CustomFilter::Create); +static int sampleCustomFilter = RegisterSample( "Shapes", "Custom Filter", CustomFilter::Create ); // Restitution is approximate since Box2D uses speculative collision class Restitution : public Sample @@ -753,26 +753,26 @@ class Restitution : public Sample e_boxShape }; - explicit Restitution(Settings& settings) - : Sample(settings) + explicit Restitution( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {4.0f, 17.0f}; + g_camera.m_center = { 4.0f, 17.0f }; g_camera.m_zoom = 27.5f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); float h = 1.0f * e_count; - b2Segment segment = {{-h, 0.0f}, {h, 0.0f}}; + b2Segment segment = { { -h, 0.0f }, { h, 0.0f } }; b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2CreateSegmentShape( groundId, &shapeDef, &segment ); } - for (int i = 0; i < e_count; ++i) + for ( int i = 0; i < e_count; ++i ) { m_bodyIds[i] = b2_nullBodyId; } @@ -784,19 +784,19 @@ class Restitution : public Sample void CreateBodies() { - for (int i = 0; i < e_count; ++i) + for ( int i = 0; i < e_count; ++i ) { - if (B2_IS_NON_NULL(m_bodyIds[i])) + if ( B2_IS_NON_NULL( m_bodyIds[i] ) ) { - b2DestroyBody(m_bodyIds[i]); + b2DestroyBody( m_bodyIds[i] ); m_bodyIds[i] = b2_nullBodyId; } } - b2Circle circle = {0}; + b2Circle circle = { 0 }; circle.radius = 0.5f; - b2Polygon box = b2MakeBox(0.5f, 0.5f); + b2Polygon box = b2MakeBox( 0.5f, 0.5f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; @@ -805,24 +805,24 @@ class Restitution : public Sample b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - float dr = 1.0f / (e_count > 1 ? e_count - 1 : 1); - float x = -1.0f * (e_count - 1); + float dr = 1.0f / ( e_count > 1 ? e_count - 1 : 1 ); + float x = -1.0f * ( e_count - 1 ); float dx = 2.0f; - for (int i = 0; i < e_count; ++i) + for ( int i = 0; i < e_count; ++i ) { - bodyDef.position = {x, 40.0f}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { x, 40.0f }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); m_bodyIds[i] = bodyId; - if (m_shapeType == e_circleShape) + if ( m_shapeType == e_circleShape ) { - b2CreateCircleShape(bodyId, &shapeDef, &circle); + b2CreateCircleShape( bodyId, &shapeDef, &circle ); } else { - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); } shapeDef.restitution += dr; @@ -833,21 +833,21 @@ class Restitution : public Sample void UpdateUI() override { float height = 100.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(240.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); - ImGui::Begin("Restitution", nullptr, ImGuiWindowFlags_NoResize); + ImGui::Begin( "Restitution", nullptr, ImGuiWindowFlags_NoResize ); bool changed = false; - const char* shapeTypes[] = {"Circle", "Box"}; + const char* shapeTypes[] = { "Circle", "Box" }; - int shapeType = int(m_shapeType); - changed = changed || ImGui::Combo("Shape", &shapeType, shapeTypes, IM_ARRAYSIZE(shapeTypes)); - m_shapeType = ShapeType(shapeType); + int shapeType = int( m_shapeType ); + changed = changed || ImGui::Combo( "Shape", &shapeType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ); + m_shapeType = ShapeType( shapeType ); - changed = changed || ImGui::Button("Reset"); + changed = changed || ImGui::Button( "Reset" ); - if (changed) + if ( changed ) { CreateBodies(); } @@ -855,228 +855,228 @@ class Restitution : public Sample ImGui::End(); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new Restitution(settings); + return new Restitution( settings ); } b2BodyId m_bodyIds[e_count]; ShapeType m_shapeType; }; -static int sampleIndex = RegisterSample("Shapes", "Restitution", Restitution::Create); +static int sampleIndex = RegisterSample( "Shapes", "Restitution", Restitution::Create ); class Friction : public Sample { public: - explicit Friction(Settings& settings) - : Sample(settings) + explicit Friction( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 14.0f}; + g_camera.m_center = { 0.0f, 14.0f }; g_camera.m_zoom = 25.0f * 0.6f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.friction = 0.2f; - b2Segment segment = {{-40.0f, 0.0f}, {40.0f, 0.0f}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2Segment segment = { { -40.0f, 0.0f }, { 40.0f, 0.0f } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment ); - b2Polygon box = b2MakeOffsetBox(13.0f, 0.25f, {-4.0f, 22.0f}, -0.25f); - b2CreatePolygonShape(groundId, &shapeDef, &box); + b2Polygon box = b2MakeOffsetBox( 13.0f, 0.25f, { -4.0f, 22.0f }, -0.25f ); + b2CreatePolygonShape( groundId, &shapeDef, &box ); - box = b2MakeOffsetBox(0.25f, 1.0f, {10.5f, 19.0f}, 0.0f); - b2CreatePolygonShape(groundId, &shapeDef, &box); + box = b2MakeOffsetBox( 0.25f, 1.0f, { 10.5f, 19.0f }, 0.0f ); + b2CreatePolygonShape( groundId, &shapeDef, &box ); - box = b2MakeOffsetBox(13.0f, 0.25f, {4.0f, 14.0f}, 0.25f); - b2CreatePolygonShape(groundId, &shapeDef, &box); + box = b2MakeOffsetBox( 13.0f, 0.25f, { 4.0f, 14.0f }, 0.25f ); + b2CreatePolygonShape( groundId, &shapeDef, &box ); - box = b2MakeOffsetBox(0.25f, 1.0f, {-10.5f, 11.0f}, 0.0f); - b2CreatePolygonShape(groundId, &shapeDef, &box); + box = b2MakeOffsetBox( 0.25f, 1.0f, { -10.5f, 11.0f }, 0.0f ); + b2CreatePolygonShape( groundId, &shapeDef, &box ); - box = b2MakeOffsetBox(13.0f, 0.25f, {-4.0f, 6.0f}, -0.25f); - b2CreatePolygonShape(groundId, &shapeDef, &box); + box = b2MakeOffsetBox( 13.0f, 0.25f, { -4.0f, 6.0f }, -0.25f ); + b2CreatePolygonShape( groundId, &shapeDef, &box ); } { - b2Polygon box = b2MakeBox(0.5f, 0.5f); + b2Polygon box = b2MakeBox( 0.5f, 0.5f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 25.0f; - float friction[5] = {0.75f, 0.5f, 0.35f, 0.1f, 0.0f}; + float friction[5] = { 0.75f, 0.5f, 0.35f, 0.1f, 0.0f }; - for (int i = 0; i < 5; ++i) + for ( int i = 0; i < 5; ++i ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {-15.0f + 4.0f * i, 28.0f}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { -15.0f + 4.0f * i, 28.0f }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); shapeDef.friction = friction[i]; - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); } } } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new Friction(settings); + return new Friction( settings ); } }; -static int sampleIndex3 = RegisterSample("Shapes", "Friction", Friction::Create); +static int sampleIndex3 = RegisterSample( "Shapes", "Friction", Friction::Create ); // This sample shows how to modify the geometry on an existing shape. This is only supported on // dynamic and kinematic shapes because static shapes don't look for new collisions. class ModifyGeometry : public Sample { public: - explicit ModifyGeometry(Settings& settings) - : Sample(settings) + explicit ModifyGeometry( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { g_camera.m_zoom = 25.0f * 0.25f; - g_camera.m_center = {0.0f, 5.0f}; + g_camera.m_center = { 0.0f, 5.0f }; } { b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Polygon box = b2MakeOffsetBox(10.0f, 1.0f, {0.0f, -1.0f}, 0.0f); - b2CreatePolygonShape(groundId, &shapeDef, &box); + b2Polygon box = b2MakeOffsetBox( 10.0f, 1.0f, { 0.0f, -1.0f }, 0.0f ); + b2CreatePolygonShape( groundId, &shapeDef, &box ); } { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {0.0f, 4.0f}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { 0.0f, 4.0f }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Polygon box = b2MakeBox(1.0f, 1.0f); - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2Polygon box = b2MakeBox( 1.0f, 1.0f ); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); } { m_shapeType = b2_circleShape; m_scale = 1.0f; - m_circle = {{0.0f, 0.0f}, 0.5f}; + m_circle = { { 0.0f, 0.0f }, 0.5f }; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_kinematicBody; - bodyDef.position = {0.0f, 1.0f}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { 0.0f, 1.0f }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - m_shapeId = b2CreateCircleShape(bodyId, &shapeDef, &m_circle); + m_shapeId = b2CreateCircleShape( bodyId, &shapeDef, &m_circle ); } } void UpdateShape() { - switch (m_shapeType) + switch ( m_shapeType ) { case b2_circleShape: - m_circle = {{0.0f, 0.0f}, 0.5f * m_scale}; - b2Shape_SetCircle(m_shapeId, &m_circle); + m_circle = { { 0.0f, 0.0f }, 0.5f * m_scale }; + b2Shape_SetCircle( m_shapeId, &m_circle ); break; case b2_capsuleShape: - m_capsule = {{-0.5f * m_scale, 0.0f}, {0.0f, 0.5f * m_scale}, 0.5f * m_scale}; - b2Shape_SetCapsule(m_shapeId, &m_capsule); + m_capsule = { { -0.5f * m_scale, 0.0f }, { 0.0f, 0.5f * m_scale }, 0.5f * m_scale }; + b2Shape_SetCapsule( m_shapeId, &m_capsule ); break; case b2_segmentShape: - m_segment = {{-0.5f * m_scale, 0.0f}, {0.75f * m_scale, 0.0f}}; - b2Shape_SetSegment(m_shapeId, &m_segment); + m_segment = { { -0.5f * m_scale, 0.0f }, { 0.75f * m_scale, 0.0f } }; + b2Shape_SetSegment( m_shapeId, &m_segment ); break; case b2_polygonShape: - m_polygon = b2MakeBox(0.5f * m_scale, 0.75f * m_scale); - b2Shape_SetPolygon(m_shapeId, &m_polygon); + m_polygon = b2MakeBox( 0.5f * m_scale, 0.75f * m_scale ); + b2Shape_SetPolygon( m_shapeId, &m_polygon ); break; default: - assert(false); + assert( false ); break; } - b2BodyId bodyId = b2Shape_GetBody(m_shapeId); - b2Body_ApplyMassFromShapes(bodyId); + b2BodyId bodyId = b2Shape_GetBody( m_shapeId ); + b2Body_ApplyMassFromShapes( bodyId ); } void UpdateUI() override { float height = 230.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(200.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 200.0f, height ) ); - ImGui::Begin("Modify Geometry", nullptr, ImGuiWindowFlags_NoResize); + ImGui::Begin( "Modify Geometry", nullptr, ImGuiWindowFlags_NoResize ); - if (ImGui::RadioButton("Circle", m_shapeType == b2_circleShape)) + if ( ImGui::RadioButton( "Circle", m_shapeType == b2_circleShape ) ) { m_shapeType = b2_circleShape; UpdateShape(); } - if (ImGui::RadioButton("Capsule", m_shapeType == b2_capsuleShape)) + if ( ImGui::RadioButton( "Capsule", m_shapeType == b2_capsuleShape ) ) { m_shapeType = b2_capsuleShape; UpdateShape(); } - if (ImGui::RadioButton("Segment", m_shapeType == b2_segmentShape)) + if ( ImGui::RadioButton( "Segment", m_shapeType == b2_segmentShape ) ) { m_shapeType = b2_segmentShape; UpdateShape(); } - if (ImGui::RadioButton("Polygon", m_shapeType == b2_polygonShape)) + if ( ImGui::RadioButton( "Polygon", m_shapeType == b2_polygonShape ) ) { m_shapeType = b2_polygonShape; UpdateShape(); } - if (ImGui::SliderFloat("Scale", &m_scale, 0.1f, 10.0f, "%.2f")) + if ( ImGui::SliderFloat( "Scale", &m_scale, 0.1f, 10.0f, "%.2f" ) ) { UpdateShape(); } - b2BodyId bodyId = b2Shape_GetBody(m_shapeId); - b2BodyType bodyType = b2Body_GetType(bodyId); + b2BodyId bodyId = b2Shape_GetBody( m_shapeId ); + b2BodyType bodyType = b2Body_GetType( bodyId ); - if (ImGui::RadioButton("Static", bodyType == b2_staticBody)) + if ( ImGui::RadioButton( "Static", bodyType == b2_staticBody ) ) { - b2Body_SetType(bodyId, b2_staticBody); + b2Body_SetType( bodyId, b2_staticBody ); } - if (ImGui::RadioButton("Kinematic", bodyType == b2_kinematicBody)) + if ( ImGui::RadioButton( "Kinematic", bodyType == b2_kinematicBody ) ) { - b2Body_SetType(bodyId, b2_kinematicBody); + b2Body_SetType( bodyId, b2_kinematicBody ); } - if (ImGui::RadioButton("Dynamic", bodyType == b2_dynamicBody)) + if ( ImGui::RadioButton( "Dynamic", bodyType == b2_dynamicBody ) ) { - b2Body_SetType(bodyId, b2_dynamicBody); + b2Body_SetType( bodyId, b2_dynamicBody ); } ImGui::End(); } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - Sample::Step(settings); + Sample::Step( settings ); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new ModifyGeometry(settings); + return new ModifyGeometry( settings ); } b2ShapeId m_shapeId; @@ -1092,36 +1092,38 @@ class ModifyGeometry : public Sample }; }; -static int sampleModifyGeometry = RegisterSample("Shapes", "Modify Geometry", ModifyGeometry::Create); +static int sampleModifyGeometry = RegisterSample( "Shapes", "Modify Geometry", ModifyGeometry::Create ); // Shows how to link to chain shapes together. This is a useful technique for building large game levels with smooth collision. class ChainLink : public Sample { public: - explicit ChainLink(Settings& settings) - : Sample(settings) + explicit ChainLink( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 5.0f}; + g_camera.m_center = { 0.0f, 5.0f }; g_camera.m_zoom = 25.0f * 0.5f; } - b2Vec2 points1[] = {{40.0f, 1.0f}, {0.0f, 0.0f}, {-40.0f, 0.0f}, {-40.0f, -1.0f}, {0.0f, -1.0f}, {40.0f, -1.0f}}; - b2Vec2 points2[] = {{-40.0f, -1.0f}, {0.0f, -1.0f}, {40.0f, -1.0f}, {40.0f, 0.0f}, {0.0f, 0.0f}, {-40.0f, 0.0f}}; + b2Vec2 points1[] = { { 40.0f, 1.0f }, { 0.0f, 0.0f }, { -40.0f, 0.0f }, + { -40.0f, -1.0f }, { 0.0f, -1.0f }, { 40.0f, -1.0f } }; + b2Vec2 points2[] = { { -40.0f, -1.0f }, { 0.0f, -1.0f }, { 40.0f, -1.0f }, + { 40.0f, 0.0f }, { 0.0f, 0.0f }, { -40.0f, 0.0f } }; - int count1 = std::size(points1); - int count2 = std::size(points2); + int count1 = std::size( points1 ); + int count2 = std::size( points2 ); b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); { b2ChainDef chainDef = b2DefaultChainDef(); chainDef.points = points1; chainDef.count = count1; chainDef.isLoop = false; - b2CreateChain(groundId, &chainDef); + b2CreateChain( groundId, &chainDef ); } { @@ -1129,85 +1131,85 @@ class ChainLink : public Sample chainDef.points = points2; chainDef.count = count2; chainDef.isLoop = false; - b2CreateChain(groundId, &chainDef); + b2CreateChain( groundId, &chainDef ); } bodyDef.type = b2_dynamicBody; b2ShapeDef shapeDef = b2DefaultShapeDef(); { - bodyDef.position = {-5.0f, 2.0f}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2Circle circle = {{0.0f, 0.0f}, 0.5f}; - b2CreateCircleShape(bodyId, &shapeDef, &circle); + bodyDef.position = { -5.0f, 2.0f }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; + b2CreateCircleShape( bodyId, &shapeDef, &circle ); } { - bodyDef.position = {0.0f, 2.0f}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2Capsule capsule = {{-0.5f, 0.0f}, {0.5f, 0.0}, 0.25f}; - b2CreateCapsuleShape(bodyId, &shapeDef, &capsule); + bodyDef.position = { 0.0f, 2.0f }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2Capsule capsule = { { -0.5f, 0.0f }, { 0.5f, 0.0 }, 0.25f }; + b2CreateCapsuleShape( bodyId, &shapeDef, &capsule ); } { - bodyDef.position = {5.0f, 2.0f}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { 5.0f, 2.0f }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); float h = 0.5f; - b2Polygon box = b2MakeBox(h, h); - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2Polygon box = b2MakeBox( h, h ); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); } } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - Sample::Step(settings); + Sample::Step( settings ); - g_draw.DrawString(5, m_textLine, "This shows how to link together two chain shapes"); + g_draw.DrawString( 5, m_textLine, "This shows how to link together two chain shapes" ); m_textLine += m_textIncrement; } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new ChainLink(settings); + return new ChainLink( settings ); } }; -static int sampleChainLink = RegisterSample("Shapes", "Chain Link", ChainLink::Create); +static int sampleChainLink = RegisterSample( "Shapes", "Chain Link", ChainLink::Create ); class RoundedShapes : public Sample { public: - explicit RoundedShapes(Settings& settings) - : Sample(settings) + explicit RoundedShapes( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { g_camera.m_zoom = 25.0f * 0.55f; - g_camera.m_center = {2.0f, 8.0f}; + g_camera.m_center = { 2.0f, 8.0f }; } { b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Polygon box = b2MakeOffsetBox(20.0f, 1.0f, {0.0f, -1.0f}, 0.0f); - b2CreatePolygonShape(groundId, &shapeDef, &box); + b2Polygon box = b2MakeOffsetBox( 20.0f, 1.0f, { 0.0f, -1.0f }, 0.0f ); + b2CreatePolygonShape( groundId, &shapeDef, &box ); - box = b2MakeOffsetBox(1.0f, 5.0f, {19.0f, 5.0f}, 0.0f); - b2CreatePolygonShape(groundId, &shapeDef, &box); + box = b2MakeOffsetBox( 1.0f, 5.0f, { 19.0f, 5.0f }, 0.0f ); + b2CreatePolygonShape( groundId, &shapeDef, &box ); - box = b2MakeOffsetBox(1.0f, 5.0f, {-19.0f, 5.0f}, 0.0f); - b2CreatePolygonShape(groundId, &shapeDef, &box); + box = b2MakeOffsetBox( 1.0f, 5.0f, { -19.0f, 5.0f }, 0.0f ); + b2CreatePolygonShape( groundId, &shapeDef, &box ); } - //b2Capsule capsule = {{-0.25f, 0.0f}, {0.25f, 0.0f}, 0.25f}; - //b2Circle circle = {{0.0f, 0.0f}, 0.35f}; - //b2Polygon square = b2MakeSquare(0.35f); + // b2Capsule capsule = {{-0.25f, 0.0f}, {0.25f, 0.0f}, 0.25f}; + // b2Circle circle = {{0.0f, 0.0f}, 0.35f}; + // b2Polygon square = b2MakeSquare(0.35f); - //b2Vec2 points[3] = {{-0.1f, -0.5f}, {0.1f, -0.5f}, {0.0f, 0.5f}}; - //b2Hull wedgeHull = b2ComputeHull(points, 3); - //b2Polygon wedge = b2MakePolygon(&wedgeHull, 0.0f); + // b2Vec2 points[3] = {{-0.1f, -0.5f}, {0.1f, -0.5f}, {0.0f, 0.5f}}; + // b2Hull wedgeHull = b2ComputeHull(points, 3); + // b2Polygon wedge = b2MakePolygon(&wedgeHull, 0.0f); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; @@ -1216,17 +1218,17 @@ class RoundedShapes : public Sample float y = 2.0f; int xcount = 10, ycount = 10; - for (int i = 0; i < ycount; ++i) + for ( int i = 0; i < ycount; ++i ) { float x = -5.0f; - for (int j = 0; j < xcount; ++j) + for ( int j = 0; j < xcount; ++j ) { - bodyDef.position = {x, y}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { x, y }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); - b2Polygon poly = RandomPolygon(0.5f); - poly.radius = RandomFloat(0.05f, 0.25f); - b2CreatePolygonShape(bodyId, &shapeDef, &poly); + b2Polygon poly = RandomPolygon( 0.5f ); + poly.radius = RandomFloat( 0.05f, 0.25f ); + b2CreatePolygonShape( bodyId, &shapeDef, &poly ); x += 1.0f; } @@ -1235,68 +1237,68 @@ class RoundedShapes : public Sample } } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new RoundedShapes(settings); + return new RoundedShapes( settings ); } }; -static int sampleRoundedShapes = RegisterSample("Shapes", "Rounded", RoundedShapes::Create); +static int sampleRoundedShapes = RegisterSample( "Shapes", "Rounded", RoundedShapes::Create ); class OffsetShapes : public Sample { public: - explicit OffsetShapes(Settings& settings) - : Sample(settings) + explicit OffsetShapes( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { g_camera.m_zoom = 25.0f * 0.55f; - g_camera.m_center = {2.0f, 8.0f}; + g_camera.m_center = { 2.0f, 8.0f }; } { b2BodyDef bodyDef = b2DefaultBodyDef(); - bodyDef.position = {-1.0f, 1.0f}; - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { -1.0f, 1.0f }; + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Polygon box = b2MakeOffsetBox(1.0f, 1.0f, {10.0f, -2.0f}, 0.5f * b2_pi); - b2CreatePolygonShape(groundId, &shapeDef, &box); + b2Polygon box = b2MakeOffsetBox( 1.0f, 1.0f, { 10.0f, -2.0f }, 0.5f * b2_pi ); + b2CreatePolygonShape( groundId, &shapeDef, &box ); } { - b2Capsule capsule = {{-5.0f, 1.0f}, {-4.0f, 1.0f}, 0.25f}; + b2Capsule capsule = { { -5.0f, 1.0f }, { -4.0f, 1.0f }, 0.25f }; b2BodyDef bodyDef = b2DefaultBodyDef(); - bodyDef.position = {13.5f, -0.75f}; + bodyDef.position = { 13.5f, -0.75f }; bodyDef.type = b2_dynamicBody; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreateCapsuleShape(bodyId, &shapeDef, &capsule); + b2CreateCapsuleShape( bodyId, &shapeDef, &capsule ); } { - b2Polygon box = b2MakeOffsetBox(0.75f, 0.5f, {9.0f, 2.0f}, 0.5f * b2_pi); + b2Polygon box = b2MakeOffsetBox( 0.75f, 0.5f, { 9.0f, 2.0f }, 0.5f * b2_pi ); b2BodyDef bodyDef = b2DefaultBodyDef(); - bodyDef.position = {0.0f, 0.0f}; + bodyDef.position = { 0.0f, 0.0f }; bodyDef.type = b2_dynamicBody; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); } } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - Sample::Step(settings); + Sample::Step( settings ); - g_draw.DrawTransform(b2Transform_identity); + g_draw.DrawTransform( b2Transform_identity ); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new OffsetShapes(settings); + return new OffsetShapes( settings ); } }; -static int sampleOffsetShapes = RegisterSample("Shapes", "Offset", OffsetShapes::Create); +static int sampleOffsetShapes = RegisterSample( "Shapes", "Offset", OffsetShapes::Create ); diff --git a/samples/sample_stacking.cpp b/samples/sample_stacking.cpp index cc251969..84115e38 100644 --- a/samples/sample_stacking.cpp +++ b/samples/sample_stacking.cpp @@ -14,48 +14,48 @@ class SingleBox : public Sample { public: - explicit SingleBox(Settings& settings) - : Sample(settings) + explicit SingleBox( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 2.5f}; + g_camera.m_center = { 0.0f, 2.5f }; g_camera.m_zoom = 3.5f; } float extent = 1.0f; b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); float groundWidth = 66.0f * extent; b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.friction = 0.5f; - b2Segment segment = {{-0.5f * 2.0f * groundWidth, 0.0f}, {0.5f * 2.0f * groundWidth, 0.0f}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2Segment segment = { { -0.5f * 2.0f * groundWidth, 0.0f }, { 0.5f * 2.0f * groundWidth, 0.0f } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment ); bodyDef.type = b2_dynamicBody; - b2Polygon box = b2MakeBox(extent, extent); - bodyDef.position = {0.0f, 4.0f}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2Polygon box = b2MakeBox( extent, extent ); + bodyDef.position = { 0.0f, 4.0f }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - Sample::Step(settings); + Sample::Step( settings ); - //g_draw.DrawCircle({0.0f, 2.0f}, 1.0f, b2_colorWhite); + // g_draw.DrawCircle({0.0f, 2.0f}, 1.0f, b2_colorWhite); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new SingleBox(settings); + return new SingleBox( settings ); } }; -static int sampleSingleBox = RegisterSample("Stacking", "Single Box", SingleBox::Create); +static int sampleSingleBox = RegisterSample( "Stacking", "Single Box", SingleBox::Create ); class TiltedStack : public Sample { @@ -66,31 +66,31 @@ class TiltedStack : public Sample e_rows = 10, }; - explicit TiltedStack(Settings& settings) - : Sample(settings) + explicit TiltedStack( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {7.5f, 7.5f}; + g_camera.m_center = { 7.5f, 7.5f }; g_camera.m_zoom = 20.0f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); - bodyDef.position = {0.0f, -1.0f}; - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { 0.0f, -1.0f }; + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); - b2Polygon box = b2MakeBox(1000.0f, 1.0f); + b2Polygon box = b2MakeBox( 1000.0f, 1.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreatePolygonShape(groundId, &shapeDef, &box); + b2CreatePolygonShape( groundId, &shapeDef, &box ); } - for (int i = 0; i < e_rows * e_columns; ++i) + for ( int i = 0; i < e_rows * e_columns; ++i ) { m_bodies[i] = b2_nullBodyId; } - b2Polygon box = b2MakeRoundedBox(0.45f, 0.45f, 0.05f); + b2Polygon box = b2MakeRoundedBox( 0.45f, 0.45f, 0.05f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 1.0f; @@ -98,38 +98,38 @@ class TiltedStack : public Sample float offset = 0.2f; float dx = 5.0f; - float xroot = -0.5f * dx * (e_columns - 1.0f); + float xroot = -0.5f * dx * ( e_columns - 1.0f ); - for (int j = 0; j < e_columns; ++j) + for ( int j = 0; j < e_columns; ++j ) { float x = xroot + j * dx; - for (int i = 0; i < e_rows; ++i) + for ( int i = 0; i < e_rows; ++i ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; int n = j * e_rows + i; - bodyDef.position = {x + offset * i, 0.5f + 1.0f * i}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { x + offset * i, 0.5f + 1.0f * i }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); m_bodies[n] = bodyId; - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); } } } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new TiltedStack(settings); + return new TiltedStack( settings ); } b2BodyId m_bodies[e_rows * e_columns]; }; -static int sampleTiltedStack = RegisterSample("Stacking", "Tilted Stack", TiltedStack::Create); +static int sampleTiltedStack = RegisterSample( "Stacking", "Tilted Stack", TiltedStack::Create ); class VerticalStack : public Sample { @@ -147,34 +147,34 @@ class VerticalStack : public Sample e_boxShape }; - explicit VerticalStack(Settings& settings) - : Sample(settings) + explicit VerticalStack( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {-7.0f, 9.0f}; + g_camera.m_center = { -7.0f, 9.0f }; g_camera.m_zoom = 14.0f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); - bodyDef.position = {0.0f, -1.0f}; - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { 0.0f, -1.0f }; + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); - b2Polygon box = b2MakeBox(100.0f, 1.0f); + b2Polygon box = b2MakeBox( 100.0f, 1.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreatePolygonShape(groundId, &shapeDef, &box); + b2CreatePolygonShape( groundId, &shapeDef, &box ); - b2Segment segment = {{10.0f, 1.0f}, {10.0f, 21.0f}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2Segment segment = { { 10.0f, 1.0f }, { 10.0f, 21.0f } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment ); } - for (int i = 0; i < e_maxRows * e_maxColumns; ++i) + for ( int i = 0; i < e_maxRows * e_maxColumns; ++i ) { m_bodies[i] = b2_nullBodyId; } - for (int i = 0; i < e_maxBullets; ++i) + for ( int i = 0; i < e_maxBullets; ++i ) { m_bullets[i] = b2_nullBodyId; } @@ -190,19 +190,19 @@ class VerticalStack : public Sample void CreateStacks() { - for (int i = 0; i < e_maxRows * e_maxColumns; ++i) + for ( int i = 0; i < e_maxRows * e_maxColumns; ++i ) { - if (B2_IS_NON_NULL(m_bodies[i])) + if ( B2_IS_NON_NULL( m_bodies[i] ) ) { - b2DestroyBody(m_bodies[i]); + b2DestroyBody( m_bodies[i] ); m_bodies[i] = b2_nullBodyId; } } - b2Circle circle = {0}; + b2Circle circle = { 0 }; circle.radius = 0.5f; - b2Polygon box = b2MakeBox(0.5f, 0.5f); + b2Polygon box = b2MakeBox( 0.5f, 0.5f ); // b2Polygon box = b2MakeRoundedBox(0.45f, 0.45f, 0.05f); b2ShapeDef shapeDef = b2DefaultShapeDef(); @@ -211,7 +211,7 @@ class VerticalStack : public Sample float offset; - if (m_shapeType == e_circleShape) + if ( m_shapeType == e_circleShape ) { offset = 0.0f; } @@ -223,31 +223,31 @@ class VerticalStack : public Sample float dx = -3.0f; float xroot = 8.0f; - for (int j = 0; j < m_columnCount; ++j) + for ( int j = 0; j < m_columnCount; ++j ) { float x = xroot + j * dx; - for (int i = 0; i < m_rowCount; ++i) + for ( int i = 0; i < m_rowCount; ++i ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; int n = j * m_rowCount + i; - float shift = (i % 2 == 0 ? -offset : offset); - bodyDef.position = {x + shift, 0.5f + 1.0f * i}; + float shift = ( i % 2 == 0 ? -offset : offset ); + bodyDef.position = { x + shift, 0.5f + 1.0f * i }; // bodyDef.position = {x + shift, 1.0f + 1.51f * i}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); m_bodies[n] = bodyId; - if (m_shapeType == e_circleShape) + if ( m_shapeType == e_circleShape ) { - b2CreateCircleShape(bodyId, &shapeDef, &circle); + b2CreateCircleShape( bodyId, &shapeDef, &circle ); } else { - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); } } } @@ -255,15 +255,15 @@ class VerticalStack : public Sample void DestroyBody() { - for (int j = 0; j < m_columnCount; ++j) + for ( int j = 0; j < m_columnCount; ++j ) { - for (int i = 0; i < m_rowCount; ++i) + for ( int i = 0; i < m_rowCount; ++i ) { int n = j * m_rowCount + i; - if (B2_IS_NON_NULL(m_bodies[n])) + if ( B2_IS_NON_NULL( m_bodies[n] ) ) { - b2DestroyBody(m_bodies[n]); + b2DestroyBody( m_bodies[n] ); m_bodies[n] = b2_nullBodyId; break; } @@ -273,13 +273,13 @@ class VerticalStack : public Sample void DestroyBullets() { - for (int i = 0; i < e_maxBullets; ++i) + for ( int i = 0; i < e_maxBullets; ++i ) { b2BodyId bullet = m_bullets[i]; - if (B2_IS_NON_NULL(bullet)) + if ( B2_IS_NON_NULL( bullet ) ) { - b2DestroyBody(bullet); + b2DestroyBody( bullet ); m_bullets[i] = b2_nullBodyId; } } @@ -287,32 +287,32 @@ class VerticalStack : public Sample void FireBullets() { - b2Circle circle = {{0.0f, 0.0f}, 0.25f}; - b2Polygon box = b2MakeBox(0.25f, 0.25f); + b2Circle circle = { { 0.0f, 0.0f }, 0.25f }; + b2Polygon box = b2MakeBox( 0.25f, 0.25f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.density = 4.0f; - for (int i = 0; i < m_bulletCount; ++i) + for ( int i = 0; i < m_bulletCount; ++i ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {-25.0f - i, 6.0f}; - float speed = RandomFloat(200.0f, 300.0f); - bodyDef.linearVelocity = {speed, 0.0f}; + bodyDef.position = { -25.0f - i, 6.0f }; + float speed = RandomFloat( 200.0f, 300.0f ); + bodyDef.linearVelocity = { speed, 0.0f }; bodyDef.isBullet = true; - b2BodyId bullet = b2CreateBody(m_worldId, &bodyDef); + b2BodyId bullet = b2CreateBody( m_worldId, &bodyDef ); - if (m_bulletType == e_boxShape) + if ( m_bulletType == e_boxShape ) { - b2CreatePolygonShape(bullet, &shapeDef, &box); + b2CreatePolygonShape( bullet, &shapeDef, &box ); } else { - b2CreateCircleShape(bullet, &shapeDef, &circle); + b2CreateCircleShape( bullet, &shapeDef, &circle ); } - assert(B2_IS_NULL(m_bullets[i])); + assert( B2_IS_NULL( m_bullets[i] ) ); m_bullets[i] = bullet; } } @@ -320,45 +320,45 @@ class VerticalStack : public Sample void UpdateUI() override { float height = 230.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(240.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); - ImGui::Begin("Vertical Stack", nullptr, ImGuiWindowFlags_NoResize); + ImGui::Begin( "Vertical Stack", nullptr, ImGuiWindowFlags_NoResize ); - ImGui::PushItemWidth(120.0f); + ImGui::PushItemWidth( 120.0f ); bool changed = false; - const char* shapeTypes[] = {"Circle", "Box"}; + const char* shapeTypes[] = { "Circle", "Box" }; - int shapeType = int(m_shapeType); - changed = changed || ImGui::Combo("Shape", &shapeType, shapeTypes, IM_ARRAYSIZE(shapeTypes)); - m_shapeType = ShapeType(shapeType); + int shapeType = int( m_shapeType ); + changed = changed || ImGui::Combo( "Shape", &shapeType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ); + m_shapeType = ShapeType( shapeType ); - changed = changed || ImGui::SliderInt("Rows", &m_rowCount, 1, e_maxRows); - changed = changed || ImGui::SliderInt("Columns", &m_columnCount, 1, e_maxColumns); + changed = changed || ImGui::SliderInt( "Rows", &m_rowCount, 1, e_maxRows ); + changed = changed || ImGui::SliderInt( "Columns", &m_columnCount, 1, e_maxColumns ); - ImGui::SliderInt("Bullets", &m_bulletCount, 1, e_maxBullets); + ImGui::SliderInt( "Bullets", &m_bulletCount, 1, e_maxBullets ); - int bulletType = int(m_bulletType); - ImGui::Combo("Bullet Shape", &bulletType, shapeTypes, IM_ARRAYSIZE(shapeTypes)); - m_bulletType = ShapeType(bulletType); + int bulletType = int( m_bulletType ); + ImGui::Combo( "Bullet Shape", &bulletType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ); + m_bulletType = ShapeType( bulletType ); ImGui::PopItemWidth(); - if (ImGui::Button("Fire Bullets") || glfwGetKey(g_mainWindow, GLFW_KEY_B) == GLFW_PRESS) + if ( ImGui::Button( "Fire Bullets" ) || glfwGetKey( g_mainWindow, GLFW_KEY_B ) == GLFW_PRESS ) { DestroyBullets(); FireBullets(); } - if (ImGui::Button("Destroy Body")) + if ( ImGui::Button( "Destroy Body" ) ) { DestroyBody(); } - changed = changed || ImGui::Button("Reset Stack"); + changed = changed || ImGui::Button( "Reset Stack" ); - if (changed) + if ( changed ) { DestroyBullets(); CreateStacks(); @@ -367,9 +367,9 @@ class VerticalStack : public Sample ImGui::End(); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new VerticalStack(settings); + return new VerticalStack( settings ); } b2BodyId m_bullets[e_maxBullets]; @@ -381,32 +381,32 @@ class VerticalStack : public Sample ShapeType m_bulletType; }; -static int sampleVerticalStack = RegisterSample("Stacking", "Vertical Stack", VerticalStack::Create); +static int sampleVerticalStack = RegisterSample( "Stacking", "Vertical Stack", VerticalStack::Create ); // This shows how to handle high gravity and small shapes using a small time step class CircleStack : public Sample { public: - explicit CircleStack(Settings& settings) - : Sample(settings) + explicit CircleStack( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 2.0f}; + g_camera.m_center = { 0.0f, 2.0f }; g_camera.m_zoom = 3.0f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Segment segment = {{-10.0f, 0.0f}, {10.0f, 0.0f}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2Segment segment = { { -10.0f, 0.0f }, { 10.0f, 0.0f } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment ); } - b2World_SetGravity(m_worldId, {0.0f, -20.0f}); - b2World_SetContactTuning(m_worldId, 0.25f * 360.0f, 10.0f, 3.0f); + b2World_SetGravity( m_worldId, { 0.0f, -20.0f } ); + b2World_SetContactTuning( m_worldId, 0.25f * 360.0f, 10.0f, 3.0f ); b2Circle circle = {}; circle.radius = 0.1f; @@ -417,60 +417,59 @@ class CircleStack : public Sample float y = 0.5f; - for (int i = 0; i < 20; ++i) + for ( int i = 0; i < 20; ++i ) { bodyDef.position.y = y; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreateCircleShape(bodyId, &shapeDef, &circle); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreateCircleShape( bodyId, &shapeDef, &circle ); y += 1.0f; } } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new CircleStack(settings); + return new CircleStack( settings ); } }; -static int sampleCircleStack = RegisterSample("Stacking", "Circle Stack", CircleStack::Create); - +static int sampleCircleStack = RegisterSample( "Stacking", "Circle Stack", CircleStack::Create ); class Cliff : public Sample { public: - explicit Cliff(Settings& settings) - : Sample(settings) + explicit Cliff( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { g_camera.m_zoom = 25.0f * 0.5f; - g_camera.m_center = {0.0f, 5.0f}; + g_camera.m_center = { 0.0f, 5.0f }; } { b2BodyDef bodyDef = b2DefaultBodyDef(); - bodyDef.position = {0.0f, 0.0f}; - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { 0.0f, 0.0f }; + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Polygon box = b2MakeOffsetBox(100.0f, 1.0f, {0.0f, -1.0f}, 0.0f); - b2CreatePolygonShape(groundId, &shapeDef, &box); + b2Polygon box = b2MakeOffsetBox( 100.0f, 1.0f, { 0.0f, -1.0f }, 0.0f ); + b2CreatePolygonShape( groundId, &shapeDef, &box ); - b2Segment segment = {{-14.0f, 4.0f}, {-8.0f, 4.0f}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2Segment segment = { { -14.0f, 4.0f }, { -8.0f, 4.0f } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment ); - box = b2MakeOffsetBox(3.0f, 0.5f, {0.0f, 4.0f}, 0.0f); - b2CreatePolygonShape(groundId, &shapeDef, &box); + box = b2MakeOffsetBox( 3.0f, 0.5f, { 0.0f, 4.0f }, 0.0f ); + b2CreatePolygonShape( groundId, &shapeDef, &box ); - b2Capsule capsule = {{8.5f, 4.0f}, {13.5f, 4.0f}, 0.5f}; - b2CreateCapsuleShape(groundId, &shapeDef, &capsule); + b2Capsule capsule = { { 8.5f, 4.0f }, { 13.5f, 4.0f }, 0.5f }; + b2CreateCapsuleShape( groundId, &shapeDef, &capsule ); } m_flip = false; - for (int i = 0; i < 9; ++i) + for ( int i = 0; i < 9; ++i ) { m_bodyIds[i] = b2_nullBodyId; } @@ -480,20 +479,20 @@ class Cliff : public Sample void CreateBodies() { - for (int i = 0; i < 9; ++i) + for ( int i = 0; i < 9; ++i ) { - if (B2_IS_NON_NULL(m_bodyIds[i])) + if ( B2_IS_NON_NULL( m_bodyIds[i] ) ) { - b2DestroyBody(m_bodyIds[i]); + b2DestroyBody( m_bodyIds[i] ); m_bodyIds[i] = b2_nullBodyId; } } float sign = m_flip ? -1.0f : 1.0f; - b2Capsule capsule = {{-0.25f, 0.0f}, {0.25f, 0.0f}, 0.25f}; - b2Circle circle = {{0.0f, 0.0f}, 0.5f}; - b2Polygon square = b2MakeSquare(0.5f); + b2Capsule capsule = { { -0.25f, 0.0f }, { 0.25f, 0.0f }, 0.25f }; + b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; + b2Polygon square = b2MakeSquare( 0.5f ); b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; @@ -501,71 +500,71 @@ class Cliff : public Sample { b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.friction = 0.01f; - bodyDef.linearVelocity = {2.0f * sign, 0.0f}; + bodyDef.linearVelocity = { 2.0f * sign, 0.0f }; float offset = m_flip ? -4.0f : 0.0f; - bodyDef.position = {-9.0f + offset, 4.25f}; - m_bodyIds[0] = b2CreateBody(m_worldId, &bodyDef); - b2CreateCapsuleShape(m_bodyIds[0], &shapeDef, &capsule); + bodyDef.position = { -9.0f + offset, 4.25f }; + m_bodyIds[0] = b2CreateBody( m_worldId, &bodyDef ); + b2CreateCapsuleShape( m_bodyIds[0], &shapeDef, &capsule ); - bodyDef.position = {2.0f + offset, 4.75f}; - m_bodyIds[1] = b2CreateBody(m_worldId, &bodyDef); - b2CreateCapsuleShape(m_bodyIds[1], &shapeDef, &capsule); + bodyDef.position = { 2.0f + offset, 4.75f }; + m_bodyIds[1] = b2CreateBody( m_worldId, &bodyDef ); + b2CreateCapsuleShape( m_bodyIds[1], &shapeDef, &capsule ); - bodyDef.position = {13.0f + offset, 4.75f}; - m_bodyIds[2] = b2CreateBody(m_worldId, &bodyDef); - b2CreateCapsuleShape(m_bodyIds[2], &shapeDef, &capsule); + bodyDef.position = { 13.0f + offset, 4.75f }; + m_bodyIds[2] = b2CreateBody( m_worldId, &bodyDef ); + b2CreateCapsuleShape( m_bodyIds[2], &shapeDef, &capsule ); } { b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.friction = 0.01f; - bodyDef.linearVelocity = {2.5f * sign, 0.0f}; + bodyDef.linearVelocity = { 2.5f * sign, 0.0f }; - bodyDef.position = {-11.0f, 4.5f}; - m_bodyIds[3] = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(m_bodyIds[3], &shapeDef, &square); + bodyDef.position = { -11.0f, 4.5f }; + m_bodyIds[3] = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( m_bodyIds[3], &shapeDef, &square ); - bodyDef.position = {0.0f, 5.0f}; - m_bodyIds[4] = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(m_bodyIds[4], &shapeDef, &square); + bodyDef.position = { 0.0f, 5.0f }; + m_bodyIds[4] = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( m_bodyIds[4], &shapeDef, &square ); - bodyDef.position = {11.0f, 5.0f}; - m_bodyIds[5] = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(m_bodyIds[5], &shapeDef, &square); + bodyDef.position = { 11.0f, 5.0f }; + m_bodyIds[5] = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( m_bodyIds[5], &shapeDef, &square ); } { b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.friction = 0.2f; - bodyDef.linearVelocity = {1.5f * sign, 0.0f}; + bodyDef.linearVelocity = { 1.5f * sign, 0.0f }; float offset = m_flip ? 4.0f : 0.0f; - bodyDef.position = {-13.0f + offset, 4.5f}; - m_bodyIds[6] = b2CreateBody(m_worldId, &bodyDef); - b2CreateCircleShape(m_bodyIds[6], &shapeDef, &circle); + bodyDef.position = { -13.0f + offset, 4.5f }; + m_bodyIds[6] = b2CreateBody( m_worldId, &bodyDef ); + b2CreateCircleShape( m_bodyIds[6], &shapeDef, &circle ); - bodyDef.position = {-2.0f + offset, 5.0f}; - m_bodyIds[7] = b2CreateBody(m_worldId, &bodyDef); - b2CreateCircleShape(m_bodyIds[7], &shapeDef, &circle); + bodyDef.position = { -2.0f + offset, 5.0f }; + m_bodyIds[7] = b2CreateBody( m_worldId, &bodyDef ); + b2CreateCircleShape( m_bodyIds[7], &shapeDef, &circle ); - bodyDef.position = {9.0f + offset, 5.0f}; - m_bodyIds[8] = b2CreateBody(m_worldId, &bodyDef); - b2CreateCircleShape(m_bodyIds[8], &shapeDef, &circle); + bodyDef.position = { 9.0f + offset, 5.0f }; + m_bodyIds[8] = b2CreateBody( m_worldId, &bodyDef ); + b2CreateCircleShape( m_bodyIds[8], &shapeDef, &circle ); } } void UpdateUI() override { float height = 60.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(160.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 160.0f, height ) ); - ImGui::Begin("Cliff", nullptr, ImGuiWindowFlags_NoResize); + ImGui::Begin( "Cliff", nullptr, ImGuiWindowFlags_NoResize ); - if (ImGui::Button("Flip")) + if ( ImGui::Button( "Flip" ) ) { m_flip = !m_flip; CreateBodies(); @@ -574,54 +573,54 @@ class Cliff : public Sample ImGui::End(); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new Cliff(settings); + return new Cliff( settings ); } b2BodyId m_bodyIds[9]; bool m_flip; }; -static int sampleCliff = RegisterSample("Stacking", "Cliff", Cliff::Create); +static int sampleCliff = RegisterSample( "Stacking", "Cliff", Cliff::Create ); class Arch : public Sample { public: - explicit Arch(Settings& settings) - : Sample(settings) + explicit Arch( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 8.0f}; + g_camera.m_center = { 0.0f, 8.0f }; g_camera.m_zoom = 25.0f * 0.35f; } - b2Vec2 ps1[9] = {{16.0f, 0.0f}, - {14.93803712795643f, 5.133601056842984f}, - {13.79871746027416f, 10.24928069555078f}, - {12.56252963284711f, 15.34107019122473f}, - {11.20040987372525f, 20.39856541571217f}, - {9.66521217819836f, 25.40369899225096f}, - {7.87179930638133f, 30.3179337000085f}, - {5.635199558196225f, 35.03820717801641f}, - {2.405937953536585f, 39.09554102558315f}}; - - b2Vec2 ps2[9] = {{24.0f, 0.0f}, - {22.33619528222415f, 6.02299846205841f}, - {20.54936888969905f, 12.00964361211476f}, - {18.60854610798073f, 17.9470321677465f}, - {16.46769273811807f, 23.81367936585418f}, - {14.05325025774858f, 29.57079353071012f}, - {11.23551045834022f, 35.13775818285372f}, - {7.752568160730571f, 40.30450679009583f}, - {3.016931552701656f, 44.28891593799322f}}; + b2Vec2 ps1[9] = { { 16.0f, 0.0f }, + { 14.93803712795643f, 5.133601056842984f }, + { 13.79871746027416f, 10.24928069555078f }, + { 12.56252963284711f, 15.34107019122473f }, + { 11.20040987372525f, 20.39856541571217f }, + { 9.66521217819836f, 25.40369899225096f }, + { 7.87179930638133f, 30.3179337000085f }, + { 5.635199558196225f, 35.03820717801641f }, + { 2.405937953536585f, 39.09554102558315f } }; + + b2Vec2 ps2[9] = { { 24.0f, 0.0f }, + { 22.33619528222415f, 6.02299846205841f }, + { 20.54936888969905f, 12.00964361211476f }, + { 18.60854610798073f, 17.9470321677465f }, + { 16.46769273811807f, 23.81367936585418f }, + { 14.05325025774858f, 29.57079353071012f }, + { 11.23551045834022f, 35.13775818285372f }, + { 7.752568160730571f, 40.30450679009583f }, + { 3.016931552701656f, 44.28891593799322f } }; float scale = 0.25f; - for (int i = 0; i < 9; ++i) + for ( int i = 0; i < 9; ++i ) { - ps1[i] = b2MulSV(scale, ps1[i]); - ps2[i] = b2MulSV(scale, ps2[i]); + ps1[i] = b2MulSV( scale, ps1[i] ); + ps2[i] = b2MulSV( scale, ps2[i] ); } b2ShapeDef shapeDef = b2DefaultShapeDef(); @@ -629,81 +628,83 @@ class Arch : public Sample { b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); - b2Segment segment = {{-100.0f, 0.0f}, {100.0f, 0.0f}}; - b2CreateSegmentShape(groundId, &shapeDef, &segment); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); + b2Segment segment = { { -100.0f, 0.0f }, { 100.0f, 0.0f } }; + b2CreateSegmentShape( groundId, &shapeDef, &segment ); } b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - for (int i = 0; i < 8; ++i) + for ( int i = 0; i < 8; ++i ) { - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2Vec2 ps[4] = {ps1[i], ps2[i], ps2[i + 1], ps1[i + 1]}; - b2Hull hull = b2ComputeHull(ps, 4); - b2Polygon polygon = b2MakePolygon(&hull, 0.0f); - b2CreatePolygonShape(bodyId, &shapeDef, &polygon); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2Vec2 ps[4] = { ps1[i], ps2[i], ps2[i + 1], ps1[i + 1] }; + b2Hull hull = b2ComputeHull( ps, 4 ); + b2Polygon polygon = b2MakePolygon( &hull, 0.0f ); + b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); } - for (int i = 0; i < 8; ++i) + for ( int i = 0; i < 8; ++i ) { - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2Vec2 ps[4] = { - {-ps2[i].x, ps2[i].y}, {-ps1[i].x, ps1[i].y}, {-ps1[i + 1].x, ps1[i + 1].y}, {-ps2[i + 1].x, ps2[i + 1].y}}; - b2Hull hull = b2ComputeHull(ps, 4); - b2Polygon polygon = b2MakePolygon(&hull, 0.0f); - b2CreatePolygonShape(bodyId, &shapeDef, &polygon); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2Vec2 ps[4] = { { -ps2[i].x, ps2[i].y }, + { -ps1[i].x, ps1[i].y }, + { -ps1[i + 1].x, ps1[i + 1].y }, + { -ps2[i + 1].x, ps2[i + 1].y } }; + b2Hull hull = b2ComputeHull( ps, 4 ); + b2Polygon polygon = b2MakePolygon( &hull, 0.0f ); + b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); } { - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2Vec2 ps[4] = {ps1[8], ps2[8], {-ps2[8].x, ps2[8].y}, {-ps1[8].x, ps1[8].y}}; - b2Hull hull = b2ComputeHull(ps, 4); - b2Polygon polygon = b2MakePolygon(&hull, 0.0f); - b2CreatePolygonShape(bodyId, &shapeDef, &polygon); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2Vec2 ps[4] = { ps1[8], ps2[8], { -ps2[8].x, ps2[8].y }, { -ps1[8].x, ps1[8].y } }; + b2Hull hull = b2ComputeHull( ps, 4 ); + b2Polygon polygon = b2MakePolygon( &hull, 0.0f ); + b2CreatePolygonShape( bodyId, &shapeDef, &polygon ); } - for (int i = 0; i < 4; ++i) + for ( int i = 0; i < 4; ++i ) { - b2Polygon box = b2MakeBox(2.0f, 0.5f); - bodyDef.position = {0.0f, 0.5f + ps2[8].y + 1.0f * i}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2Polygon box = b2MakeBox( 2.0f, 0.5f ); + bodyDef.position = { 0.0f, 0.5f + ps2[8].y + 1.0f * i }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); } } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new Arch(settings); + return new Arch( settings ); } }; -static int sampleArch = RegisterSample("Stacking", "Arch", Arch::Create); +static int sampleArch = RegisterSample( "Stacking", "Arch", Arch::Create ); class DoubleDomino : public Sample { public: - explicit DoubleDomino(Settings& settings) - : Sample(settings) + explicit DoubleDomino( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 4.0f}; + g_camera.m_center = { 0.0f, 4.0f }; g_camera.m_zoom = 25.0f * 0.25f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); - bodyDef.position = {0.0f, -1.0f}; - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { 0.0f, -1.0f }; + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); - b2Polygon box = b2MakeBox(100.0f, 1.0f); + b2Polygon box = b2MakeBox( 100.0f, 1.0f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreatePolygonShape(groundId, &shapeDef, &box); + b2CreatePolygonShape( groundId, &shapeDef, &box ); } - b2Polygon box = b2MakeBox(0.125f, 0.5f); + b2Polygon box = b2MakeBox( 0.125f, 0.5f ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.friction = 0.6f; @@ -712,27 +713,27 @@ class DoubleDomino : public Sample int count = 15; float x = -0.5f * count; - for (int i = 0; i < count; ++i) + for ( int i = 0; i < count; ++i ) { - bodyDef.position = {x, 0.5f}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &box); - if (i == 0) + bodyDef.position = { x, 0.5f }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); + if ( i == 0 ) { - b2Body_ApplyLinearImpulse(bodyId, b2Vec2{0.2f, 0.0f}, b2Vec2{x, 1.0f}, true); + b2Body_ApplyLinearImpulse( bodyId, b2Vec2{ 0.2f, 0.0f }, b2Vec2{ x, 1.0f }, true ); } x += 1.0f; } } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new DoubleDomino(settings); + return new DoubleDomino( settings ); } }; -static int sampleDoubleDomino = RegisterSample("Stacking", "Double Domino", DoubleDomino::Create); +static int sampleDoubleDomino = RegisterSample( "Stacking", "Double Domino", DoubleDomino::Create ); class Confined : public Sample { @@ -743,29 +744,29 @@ class Confined : public Sample e_maxCount = e_gridCount * e_gridCount }; - explicit Confined(Settings& settings) - : Sample(settings) + explicit Confined( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.0f, 10.0f}; + g_camera.m_center = { 0.0f, 10.0f }; g_camera.m_zoom = 25.0f * 0.5f; } { b2BodyDef bodyDef = b2DefaultBodyDef(); - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); b2Capsule capsule; - capsule = {{-10.5f, 0.0f}, {10.5f, 0.0f}, 0.5f}; - b2CreateCapsuleShape(groundId, &shapeDef, &capsule); - capsule = {{-10.5f, 0.0f}, {-10.5f, 20.5f}, 0.5f}; - b2CreateCapsuleShape(groundId, &shapeDef, &capsule); - capsule = {{10.5f, 0.0f}, {10.5f, 20.5f}, 0.5f}; - b2CreateCapsuleShape(groundId, &shapeDef, &capsule); - capsule = {{-10.5f, 20.5f}, {10.5f, 20.5f}, 0.5f}; - b2CreateCapsuleShape(groundId, &shapeDef, &capsule); + capsule = { { -10.5f, 0.0f }, { 10.5f, 0.0f }, 0.5f }; + b2CreateCapsuleShape( groundId, &shapeDef, &capsule ); + capsule = { { -10.5f, 0.0f }, { -10.5f, 20.5f }, 0.5f }; + b2CreateCapsuleShape( groundId, &shapeDef, &capsule ); + capsule = { { 10.5f, 0.0f }, { 10.5f, 20.5f }, 0.5f }; + b2CreateCapsuleShape( groundId, &shapeDef, &capsule ); + capsule = { { -10.5f, 20.5f }, { 10.5f, 20.5f }, 0.5f }; + b2CreateCapsuleShape( groundId, &shapeDef, &capsule ); } m_row = 0; @@ -777,19 +778,19 @@ class Confined : public Sample bodyDef.gravityScale = 0.0f; b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Circle circle = {{0.0f, 0.0f}, 0.5f}; + b2Circle circle = { { 0.0f, 0.0f }, 0.5f }; - while (m_count < e_maxCount) + while ( m_count < e_maxCount ) { m_row = 0; - for (int i = 0; i < e_gridCount; ++i) + for ( int i = 0; i < e_gridCount; ++i ) { float x = -8.75f + m_column * 18.0f / e_gridCount; float y = 1.5f + m_row * 18.0f / e_gridCount; - bodyDef.position = {x, y}; - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreateCircleShape(bodyId, &shapeDef, &circle); + bodyDef.position = { x, y }; + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreateCircleShape( bodyId, &shapeDef, &circle ); m_count += 1; m_row += 1; @@ -798,9 +799,9 @@ class Confined : public Sample } } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new Confined(settings); + return new Confined( settings ); } int m_row; @@ -808,30 +809,30 @@ class Confined : public Sample int m_count; }; -static int sampleConfined = RegisterSample("Stacking", "Confined", Confined::Create); +static int sampleConfined = RegisterSample( "Stacking", "Confined", Confined::Create ); // From PEEL class CardHouse : public Sample { public: - explicit CardHouse(Settings& settings) - : Sample(settings) + explicit CardHouse( Settings& settings ) + : Sample( settings ) { - if (settings.restart == false) + if ( settings.restart == false ) { - g_camera.m_center = {0.75f, 0.9f}; + g_camera.m_center = { 0.75f, 0.9f }; g_camera.m_zoom = 25.0f * 0.05f; } b2BodyDef bodyDef = b2DefaultBodyDef(); - bodyDef.position = {0.0f, -2.0f}; - b2BodyId groundId = b2CreateBody(m_worldId, &bodyDef); + bodyDef.position = { 0.0f, -2.0f }; + b2BodyId groundId = b2CreateBody( m_worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); shapeDef.friction = 0.7f; - b2Polygon groundBox = b2MakeBox(40.0f, 2.0f); - b2CreatePolygonShape(groundId, &shapeDef, &groundBox); + b2Polygon groundBox = b2MakeBox( 40.0f, 2.0f ); + b2CreatePolygonShape( groundId, &shapeDef, &groundBox ); float cardHeight = 0.2f; float cardThickness = 0.001f; @@ -840,36 +841,36 @@ class CardHouse : public Sample float angle1 = -25.0f * b2_pi / 180.0f; float angle2 = 0.5f * b2_pi; - b2Polygon cardBox = b2MakeBox(cardThickness, cardHeight); + b2Polygon cardBox = b2MakeBox( cardThickness, cardHeight ); bodyDef.type = b2_dynamicBody; int Nb = 5; float z0 = 0.0f; float y = cardHeight - 0.02f; - while (Nb) + while ( Nb ) { float z = z0; - for (int i = 0; i < Nb; i++) + for ( int i = 0; i < Nb; i++ ) { - if (i != Nb - 1) + if ( i != Nb - 1 ) { - bodyDef.position = {z + 0.25f, y + cardHeight - 0.015f}; - bodyDef.rotation = b2MakeRot(angle2); - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &cardBox); + bodyDef.position = { z + 0.25f, y + cardHeight - 0.015f }; + bodyDef.rotation = b2MakeRot( angle2 ); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &cardBox ); } - bodyDef.position = {z, y}; - bodyDef.rotation = b2MakeRot(angle1); - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &cardBox); + bodyDef.position = { z, y }; + bodyDef.rotation = b2MakeRot( angle1 ); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &cardBox ); z += 0.175f; - bodyDef.position = {z, y}; - bodyDef.rotation = b2MakeRot(angle0); - bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &cardBox); + bodyDef.position = { z, y }; + bodyDef.rotation = b2MakeRot( angle0 ); + bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &cardBox ); z += 0.175f; } @@ -879,10 +880,10 @@ class CardHouse : public Sample } } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new CardHouse(settings); + return new CardHouse( settings ); } }; -static int sampleCardHouse = RegisterSample("Stacking", "Card House", CardHouse::Create); +static int sampleCardHouse = RegisterSample( "Stacking", "Card House", CardHouse::Create ); diff --git a/samples/sample_world.cpp b/samples/sample_world.cpp index 14323d51..9cc585f6 100644 --- a/samples/sample_world.cpp +++ b/samples/sample_world.cpp @@ -17,20 +17,20 @@ class LargeWorld : public Sample { public: - explicit LargeWorld(Settings& settings) - : Sample(settings) + explicit LargeWorld( Settings& settings ) + : Sample( settings ) { m_period = 40.0f; float omega = 2.0 * b2_pi / m_period; m_cycleCount = g_sampleDebug ? 10 : 600; m_gridSize = 1.0f; - m_gridCount = (int)(m_cycleCount * m_period / m_gridSize); + m_gridCount = (int)( m_cycleCount * m_period / m_gridSize ); - float xStart = -0.5f * (m_cycleCount * m_period); + float xStart = -0.5f * ( m_cycleCount * m_period ); - m_viewPosition = {xStart, 15.0f}; + m_viewPosition = { xStart, 15.0f }; - if (settings.restart == false) + if ( settings.restart == false ) { g_camera.m_center = m_viewPosition; g_camera.m_zoom = 25.0f * 1.0f; @@ -52,28 +52,28 @@ class LargeWorld : public Sample b2BodyId groundId; - for (int i = 0; i < m_gridCount; ++i) + for ( int i = 0; i < m_gridCount; ++i ) { // Create a new body regularly so that shapes are not too far from the body origin. // Most algorithms in Box2D work in local coordinates, but contact points are computed // relative to the body origin. // This makes a noticeable improvement in stability far from the origin. - if (i % 10 == 0) + if ( i % 10 == 0 ) { bodyDef.position.x = xBody; - groundId = b2CreateBody(m_worldId, &bodyDef); + groundId = b2CreateBody( m_worldId, &bodyDef ); xShape = 0.0f; } float y = 0.0f; - int ycount = (int)roundf(height * cosf(omega * xBody)) + 12; + int ycount = (int)roundf( height * cosf( omega * xBody ) ) + 12; - for (int j = 0; j < ycount; ++j) + for ( int j = 0; j < ycount; ++j ) { - b2Polygon square = b2MakeOffsetBox(0.4f * m_gridSize, 0.4f * m_gridSize, {xShape, y}, 0.0f); + b2Polygon square = b2MakeOffsetBox( 0.4f * m_gridSize, 0.4f * m_gridSize, { xShape, y }, 0.0f ); square.radius = 0.1f; - b2CreatePolygonShape(groundId, &shapeDef, &square); + b2CreatePolygonShape( groundId, &shapeDef, &square ); y += m_gridSize; } @@ -85,63 +85,62 @@ class LargeWorld : public Sample int humanIndex = 0; int donutIndex = 0; - for (int cycleIndex = 0; cycleIndex < m_cycleCount; ++cycleIndex) + for ( int cycleIndex = 0; cycleIndex < m_cycleCount; ++cycleIndex ) { - float xbase = (0.5f + cycleIndex) * m_period + xStart; + float xbase = ( 0.5f + cycleIndex ) * m_period + xStart; int remainder = cycleIndex % 3; - if (remainder == 0) + if ( remainder == 0 ) { b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = {xbase - 3.0f, 10.0f}; + bodyDef.position = { xbase - 3.0f, 10.0f }; b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2Polygon box = b2MakeBox(0.3f, 0.2f); + b2Polygon box = b2MakeBox( 0.3f, 0.2f ); - for (int i = 0; i < 10; ++i) + for ( int i = 0; i < 10; ++i ) { bodyDef.position.y = 10.0f; - for (int j = 0; j < 5; ++j) + for ( int j = 0; j < 5; ++j ) { - b2BodyId bodyId = b2CreateBody(m_worldId, &bodyDef); - b2CreatePolygonShape(bodyId, &shapeDef, &box); + b2BodyId bodyId = b2CreateBody( m_worldId, &bodyDef ); + b2CreatePolygonShape( bodyId, &shapeDef, &box ); bodyDef.position.y += 0.5f; } bodyDef.position.x += 0.6f; } } - else if (remainder == 1) + else if ( remainder == 1 ) { - b2Vec2 position = {xbase - 2.0f, 10.0f}; - for (int i = 0; i < 5; ++i) + b2Vec2 position = { xbase - 2.0f, 10.0f }; + for ( int i = 0; i < 5; ++i ) { - // Abusing this class a bit since it doesn't allocate memory Human human; - human.Spawn(m_worldId, position, 1.5f, humanIndex + 1, NULL); + human.Spawn( m_worldId, position, 1.5f, 0.05f, 0.0f, 0.0f, humanIndex + 1, NULL, false ); humanIndex += 1; position.x += 1.0f; } } else { - b2Vec2 position = {xbase - 4.0f, 12.0f}; + b2Vec2 position = { xbase - 4.0f, 12.0f }; - for (int i = 0; i < 5; ++i) + for ( int i = 0; i < 5; ++i ) { Donut donut; - donut.Spawn(m_worldId, position, 0.75f, 0, NULL); + donut.Spawn( m_worldId, position, 0.75f, 0, NULL ); donutIndex += 1; position.x += 2.0f; } } } - m_car.Spawn(m_worldId, {xStart + 20.0f, 40.0f}, 10.0f, 2.0f, 0.7f, 2000.0f, nullptr); + m_car.Spawn( m_worldId, { xStart + 20.0f, 40.0f }, 10.0f, 2.0f, 0.7f, 2000.0f, nullptr ); m_cycleIndex = 0; m_speed = 0.0f; - m_explosionPosition = {(0.5f + m_cycleIndex) * m_period + xStart, 7.0f}; + m_explosionPosition = { ( 0.5f + m_cycleIndex ) * m_period + xStart, 7.0f }; m_explode = true; m_followCar = false; } @@ -149,81 +148,81 @@ class LargeWorld : public Sample void UpdateUI() override { float height = 160.0f; - ImGui::SetNextWindowPos(ImVec2(10.0f, g_camera.m_height - height - 50.0f), ImGuiCond_Once); - ImGui::SetNextWindowSize(ImVec2(240.0f, height)); + ImGui::SetNextWindowPos( ImVec2( 10.0f, g_camera.m_height - height - 50.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) ); - ImGui::Begin("Large World", nullptr, ImGuiWindowFlags_NoResize); + ImGui::Begin( "Large World", nullptr, ImGuiWindowFlags_NoResize ); - ImGui::SliderFloat("speed", &m_speed, -400.0f, 400.0f, "%.0f"); - if (ImGui::Button("stop")) + ImGui::SliderFloat( "speed", &m_speed, -400.0f, 400.0f, "%.0f" ); + if ( ImGui::Button( "stop" ) ) { m_speed = 0.0f; } - ImGui::Checkbox("explode", &m_explode); - ImGui::Checkbox("follow car", &m_followCar); + ImGui::Checkbox( "explode", &m_explode ); + ImGui::Checkbox( "follow car", &m_followCar ); - ImGui::Text("world size = %g kilometers", m_gridSize * m_gridCount / 1000.0f); + ImGui::Text( "world size = %g kilometers", m_gridSize * m_gridCount / 1000.0f ); ImGui::End(); } - void Step(Settings& settings) override + void Step( Settings& settings ) override { - float span = 0.5f * (m_period * m_cycleCount); + float span = 0.5f * ( m_period * m_cycleCount ); float timeStep = settings.hertz > 0.0f ? 1.0f / settings.hertz : 0.0f; - if (settings.pause) + if ( settings.pause ) { timeStep = 0.0f; } m_viewPosition.x += timeStep * m_speed; - m_viewPosition.x = b2ClampFloat(m_viewPosition.x, -span, span); + m_viewPosition.x = b2ClampFloat( m_viewPosition.x, -span, span ); - if (m_speed != 0.0f) + if ( m_speed != 0.0f ) { g_camera.m_center = m_viewPosition; } - if (m_followCar) + if ( m_followCar ) { - g_camera.m_center.x = b2Body_GetPosition(m_car.m_chassisId).x; + g_camera.m_center.x = b2Body_GetPosition( m_car.m_chassisId ).x; } float radius = 2.0f; - if ((m_stepCount & 0x1) == 0x1 && m_explode) + if ( ( m_stepCount & 0x1 ) == 0x1 && m_explode ) { - m_explosionPosition.x = (0.5f + m_cycleIndex) * m_period - span; - b2World_Explode(m_worldId, m_explosionPosition, radius, 1.0f); - m_cycleIndex = (m_cycleIndex + 1) % m_cycleCount; + m_explosionPosition.x = ( 0.5f + m_cycleIndex ) * m_period - span; + b2World_Explode( m_worldId, m_explosionPosition, radius, 1.0f ); + m_cycleIndex = ( m_cycleIndex + 1 ) % m_cycleCount; } - if (m_explode) + if ( m_explode ) { - g_draw.DrawCircle(m_explosionPosition, radius, b2_colorAzure); + g_draw.DrawCircle( m_explosionPosition, radius, b2_colorAzure ); } - if (glfwGetKey(g_mainWindow, GLFW_KEY_A) == GLFW_PRESS) + if ( glfwGetKey( g_mainWindow, GLFW_KEY_A ) == GLFW_PRESS ) { - m_car.SetSpeed(5.0f); + m_car.SetSpeed( 20.0f ); } - if (glfwGetKey(g_mainWindow, GLFW_KEY_S) == GLFW_PRESS) + if ( glfwGetKey( g_mainWindow, GLFW_KEY_S ) == GLFW_PRESS ) { - m_car.SetSpeed(0.0f); + m_car.SetSpeed( 0.0f ); } - if (glfwGetKey(g_mainWindow, GLFW_KEY_D) == GLFW_PRESS) + if ( glfwGetKey( g_mainWindow, GLFW_KEY_D ) == GLFW_PRESS ) { - m_car.SetSpeed(-5.0f); + m_car.SetSpeed( -5.0f ); } - Sample::Step(settings); + Sample::Step( settings ); } - static Sample* Create(Settings& settings) + static Sample* Create( Settings& settings ) { - return new LargeWorld(settings); + return new LargeWorld( settings ); } Car m_car; @@ -240,4 +239,4 @@ class LargeWorld : public Sample bool m_followCar; }; -static int sampleLargeWorld = RegisterSample("World", "Large World", LargeWorld::Create); +static int sampleLargeWorld = RegisterSample( "World", "Large World", LargeWorld::Create ); diff --git a/samples/settings.cpp b/samples/settings.cpp index 7e760d52..c7c25154 100644 --- a/samples/settings.cpp +++ b/samples/settings.cpp @@ -5,9 +5,8 @@ #include "settings.h" // todo consider using https://github.com/skeeto/pdjson -#include - #include +#include #include #include #include @@ -15,26 +14,26 @@ static const char* fileName = "settings.ini"; // Load a file. You must free the character array. -static bool ReadFile(char*& data, int& size, const char* filename) +static bool ReadFile( char*& data, int& size, const char* filename ) { - FILE* file = fopen(filename, "rb"); - if (file == nullptr) + FILE* file = fopen( filename, "rb" ); + if ( file == nullptr ) { return false; } - fseek(file, 0, SEEK_END); - size = (int)ftell(file); - fseek(file, 0, SEEK_SET); + fseek( file, 0, SEEK_END ); + size = (int)ftell( file ); + fseek( file, 0, SEEK_SET ); - if (size == 0) + if ( size == 0 ) { return false; } - data = (char*)malloc(size + 1); - fread(data, size, 1, file); - fclose(file); + data = (char*)malloc( size + 1 ); + fread( data, size, 1, file ); + fclose( file ); data[size] = 0; return true; @@ -42,29 +41,30 @@ static bool ReadFile(char*& data, int& size, const char* filename) void Settings::Save() { - FILE* file = fopen(fileName, "w"); - fprintf(file, "{\n"); - fprintf(file, " \"sampleIndex\": %d,\n", sampleIndex); - fprintf(file, " \"drawShapes\": %s,\n", drawShapes ? "true" : "false"); - fprintf(file, " \"drawJoints\": %s,\n", drawJoints ? "true" : "false"); - fprintf(file, " \"drawAABBs\": %s,\n", drawAABBs ? "true" : "false"); - fprintf(file, " \"drawContactPoints\": %s,\n", drawContactPoints ? "true" : "false"); - fprintf(file, " \"drawContactNormals\": %s,\n", drawContactNormals ? "true" : "false"); - fprintf(file, " \"drawContactImpulses\": %s,\n", drawContactImpulses ? "true" : "false"); - fprintf(file, " \"drawFrictionImpulse\": %s,\n", drawFrictionImpulses ? "true" : "false"); - fprintf(file, " \"drawMass\": %s,\n", drawMass ? "true" : "false"); - fprintf(file, " \"drawCounters\": %s,\n", drawCounters ? "true" : "false"); - fprintf(file, " \"drawProfile\": %s,\n", drawProfile ? "true" : "false"); - fprintf(file, " \"enableWarmStarting\": %s,\n", enableWarmStarting ? "true" : "false"); - fprintf(file, " \"enableContinuous\": %s,\n", enableContinuous ? "true" : "false"); - fprintf(file, " \"enableSleep\": %s\n", enableSleep ? "true" : "false"); - fprintf(file, "}\n"); - fclose(file); + FILE* file = fopen( fileName, "w" ); + fprintf( file, "{\n" ); + fprintf( file, " \"sampleIndex\": %d,\n", sampleIndex ); + fprintf( file, " \"drawShapes\": %s,\n", drawShapes ? "true" : "false" ); + fprintf( file, " \"drawJoints\": %s,\n", drawJoints ? "true" : "false" ); + fprintf( file, " \"drawAABBs\": %s,\n", drawAABBs ? "true" : "false" ); + fprintf( file, " \"drawContactPoints\": %s,\n", drawContactPoints ? "true" : "false" ); + fprintf( file, " \"drawContactNormals\": %s,\n", drawContactNormals ? "true" : "false" ); + fprintf( file, " \"drawContactImpulses\": %s,\n", drawContactImpulses ? "true" : "false" ); + fprintf( file, " \"drawFrictionImpulse\": %s,\n", drawFrictionImpulses ? "true" : "false" ); + fprintf( file, " \"drawMass\": %s,\n", drawMass ? "true" : "false" ); + fprintf( file, " \"drawCounters\": %s,\n", drawCounters ? "true" : "false" ); + fprintf( file, " \"drawProfile\": %s,\n", drawProfile ? "true" : "false" ); + fprintf( file, " \"enableWarmStarting\": %s,\n", enableWarmStarting ? "true" : "false" ); + fprintf( file, " \"enableContinuous\": %s,\n", enableContinuous ? "true" : "false" ); + fprintf( file, " \"enableSleep\": %s\n", enableSleep ? "true" : "false" ); + fprintf( file, "}\n" ); + fclose( file ); } -static int jsoneq(const char* json, jsmntok_t* tok, const char* s) +static int jsoneq( const char* json, jsmntok_t* tok, const char* s ) { - if (tok->type == JSMN_STRING && (int)strlen(s) == tok->end - tok->start && strncmp(json + tok->start, s, tok->end - tok->start) == 0) + if ( tok->type == JSMN_STRING && (int)strlen( s ) == tok->end - tok->start && + strncmp( json + tok->start, s, tok->end - tok->start ) == 0 ) { return 0; } @@ -77,8 +77,8 @@ void Settings::Load() { char* data = nullptr; int size = 0; - bool found = ReadFile(data, size, fileName); - if (found == false) + bool found = ReadFile( data, size, fileName ); + if ( found == false ) { return; } @@ -86,51 +86,51 @@ void Settings::Load() jsmn_parser parser; jsmntok_t tokens[MAX_TOKENS]; - jsmn_init(&parser); + jsmn_init( &parser ); // js - pointer to JSON string // tokens - an array of tokens available // 10 - number of tokens available - int tokenCount = jsmn_parse(&parser, data, size, tokens, MAX_TOKENS); + int tokenCount = jsmn_parse( &parser, data, size, tokens, MAX_TOKENS ); char buffer[32]; - for (int i = 0; i < tokenCount; ++i) + for ( int i = 0; i < tokenCount; ++i ) { - if (jsoneq(data, &tokens[i], "sampleIndex") == 0) + if ( jsoneq( data, &tokens[i], "sampleIndex" ) == 0 ) { int count = tokens[i + 1].end - tokens[i + 1].start; - assert(count < 32); + assert( count < 32 ); const char* s = data + tokens[i + 1].start; - strncpy(buffer, s, count); + strncpy( buffer, s, count ); buffer[count] = 0; char* dummy; - sampleIndex = (int)strtol(buffer, &dummy, 10); + sampleIndex = (int)strtol( buffer, &dummy, 10 ); } - else if (jsoneq(data, &tokens[i], "drawShapes") == 0) + else if ( jsoneq( data, &tokens[i], "drawShapes" ) == 0 ) { const char* s = data + tokens[i + 1].start; - if (strncmp(s, "true", 4) == 0) + if ( strncmp( s, "true", 4 ) == 0 ) { drawShapes = true; } - else if (strncmp(s, "false", 5) == 0) + else if ( strncmp( s, "false", 5 ) == 0 ) { drawShapes = false; } } - else if (jsoneq(data, &tokens[i], "drawJoints") == 0) + else if ( jsoneq( data, &tokens[i], "drawJoints" ) == 0 ) { const char* s = data + tokens[i + 1].start; - if (strncmp(s, "true", 4) == 0) + if ( strncmp( s, "true", 4 ) == 0 ) { drawJoints = true; } - else if (strncmp(s, "false", 5) == 0) + else if ( strncmp( s, "false", 5 ) == 0 ) { drawJoints = false; } } } - free(data); + free( data ); } diff --git a/samples/settings.h b/samples/settings.h index 47524664..04a16a47 100644 --- a/samples/settings.h +++ b/samples/settings.h @@ -10,12 +10,14 @@ struct Settings void Load(); int sampleIndex = 0; + // int windowWidth = 3840; + // int windowHeight = 2160; int windowWidth = 1920; int windowHeight = 1080; - //int windowWidth = 1280; - //int windowHeight = 720; - //int windowWidth = 800; - //int windowHeight = 600; + // int windowWidth = 1280; + // int windowHeight = 720; + // int windowWidth = 800; + // int windowHeight = 600; float hertz = 60.0f; int subStepCount = 4; int workerCount = 1; diff --git a/samples/shader.cpp b/samples/shader.cpp index 3de18f35..81596443 100644 --- a/samples/shader.cpp +++ b/samples/shader.cpp @@ -5,12 +5,11 @@ #include "shader.h" -#include - #include +#include #include -#if defined(_WIN32) +#if defined( _WIN32 ) #define _CRTDBG_MAP_ALLOC #include #include @@ -20,192 +19,192 @@ void DumpInfoGL() { - const char* renderer = (const char*)glGetString(GL_RENDERER); - const char* vendor = (const char*)glGetString(GL_VENDOR); - const char* version = (const char*)glGetString(GL_VERSION); - const char* glslVersion = (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION); + const char* renderer = (const char*)glGetString( GL_RENDERER ); + const char* vendor = (const char*)glGetString( GL_VENDOR ); + const char* version = (const char*)glGetString( GL_VERSION ); + const char* glslVersion = (const char*)glGetString( GL_SHADING_LANGUAGE_VERSION ); int major, minor; - glGetIntegerv(GL_MAJOR_VERSION, &major); - glGetIntegerv(GL_MINOR_VERSION, &minor); - - printf("-------------------------------------------------------------\n"); - printf("GL Vendor : %s\n", vendor); - printf("GL Renderer : %s\n", renderer); - printf("GL Version : %s\n", version); - printf("GL Version : %d.%d\n", major, minor); - printf("GLSL Version : %s\n", glslVersion); - printf("-------------------------------------------------------------\n"); + glGetIntegerv( GL_MAJOR_VERSION, &major ); + glGetIntegerv( GL_MINOR_VERSION, &minor ); + + printf( "-------------------------------------------------------------\n" ); + printf( "GL Vendor : %s\n", vendor ); + printf( "GL Renderer : %s\n", renderer ); + printf( "GL Version : %s\n", version ); + printf( "GL Version : %d.%d\n", major, minor ); + printf( "GLSL Version : %s\n", glslVersion ); + printf( "-------------------------------------------------------------\n" ); } void CheckErrorGL() { GLenum errCode = glGetError(); - if (errCode != GL_NO_ERROR) + if ( errCode != GL_NO_ERROR ) { - printf("OpenGL error = %d\n", errCode); - assert(false); + printf( "OpenGL error = %d\n", errCode ); + assert( false ); } } -void PrintLogGL(uint32_t object) +void PrintLogGL( uint32_t object ) { GLint log_length = 0; - if (glIsShader(object)) + if ( glIsShader( object ) ) { - glGetShaderiv(object, GL_INFO_LOG_LENGTH, &log_length); + glGetShaderiv( object, GL_INFO_LOG_LENGTH, &log_length ); } - else if (glIsProgram(object)) + else if ( glIsProgram( object ) ) { - glGetProgramiv(object, GL_INFO_LOG_LENGTH, &log_length); + glGetProgramiv( object, GL_INFO_LOG_LENGTH, &log_length ); } else { - printf("PrintLogGL: Not a shader or a program\n"); + printf( "PrintLogGL: Not a shader or a program\n" ); return; } - char* log = (char*)malloc(log_length); + char* log = (char*)malloc( log_length ); - if (glIsShader(object)) + if ( glIsShader( object ) ) { - glGetShaderInfoLog(object, log_length, nullptr, log); + glGetShaderInfoLog( object, log_length, nullptr, log ); } - else if (glIsProgram(object)) + else if ( glIsProgram( object ) ) { - glGetProgramInfoLog(object, log_length, nullptr, log); + glGetProgramInfoLog( object, log_length, nullptr, log ); } - printf("PrintLogGL: %s", log); - free(log); + printf( "PrintLogGL: %s", log ); + free( log ); } -static GLuint sCreateShaderFromString(const char* source, GLenum type) +static GLuint sCreateShaderFromString( const char* source, GLenum type ) { - GLuint shader = glCreateShader(type); - const char* sources[] = {source}; + GLuint shader = glCreateShader( type ); + const char* sources[] = { source }; - glShaderSource(shader, 1, sources, nullptr); - glCompileShader(shader); + glShaderSource( shader, 1, sources, nullptr ); + glCompileShader( shader ); int success = GL_FALSE; - glGetShaderiv(shader, GL_COMPILE_STATUS, &success); + glGetShaderiv( shader, GL_COMPILE_STATUS, &success ); - if (success == GL_FALSE) + if ( success == GL_FALSE ) { - printf("Error compiling shader of type %d!\n", type); - PrintLogGL(shader); - glDeleteShader(shader); + printf( "Error compiling shader of type %d!\n", type ); + PrintLogGL( shader ); + glDeleteShader( shader ); return 0; } return shader; } -uint32_t CreateProgramFromStrings(const char* vertexString, const char* fragmentString) +uint32_t CreateProgramFromStrings( const char* vertexString, const char* fragmentString ) { - GLuint vertex = sCreateShaderFromString(vertexString, GL_VERTEX_SHADER); - if (vertex == 0) + GLuint vertex = sCreateShaderFromString( vertexString, GL_VERTEX_SHADER ); + if ( vertex == 0 ) { return 0; } - GLuint fragment = sCreateShaderFromString(fragmentString, GL_FRAGMENT_SHADER); - if (fragment == 0) + GLuint fragment = sCreateShaderFromString( fragmentString, GL_FRAGMENT_SHADER ); + if ( fragment == 0 ) { return 0; } GLuint program = glCreateProgram(); - glAttachShader(program, vertex); - glAttachShader(program, fragment); + glAttachShader( program, vertex ); + glAttachShader( program, fragment ); - glLinkProgram(program); + glLinkProgram( program ); int success = GL_FALSE; - glGetProgramiv(program, GL_LINK_STATUS, &success); - if (success == GL_FALSE) + glGetProgramiv( program, GL_LINK_STATUS, &success ); + if ( success == GL_FALSE ) { - printf("glLinkProgram:"); - PrintLogGL(program); + printf( "glLinkProgram:" ); + PrintLogGL( program ); return 0; } - glDeleteShader(vertex); - glDeleteShader(fragment); + glDeleteShader( vertex ); + glDeleteShader( fragment ); return program; } -static GLuint sCreateShaderFromFile(const char* filename, GLenum type) +static GLuint sCreateShaderFromFile( const char* filename, GLenum type ) { - FILE* file = fopen(filename, "rb"); - if (file == nullptr) + FILE* file = fopen( filename, "rb" ); + if ( file == nullptr ) { - fprintf(stderr, "Error opening %s\n", filename); + fprintf( stderr, "Error opening %s\n", filename ); return 0; } - fseek(file, 0, SEEK_END); - long size = ftell(file); - fseek(file, 0, SEEK_SET); + fseek( file, 0, SEEK_END ); + long size = ftell( file ); + fseek( file, 0, SEEK_SET ); - char* source = static_cast(malloc(size + 1)); - fread(source, size, 1, file); - fclose(file); + char* source = static_cast( malloc( size + 1 ) ); + fread( source, size, 1, file ); + fclose( file ); source[size] = 0; - GLuint shader = glCreateShader(type); - const char* sources[] = {source}; + GLuint shader = glCreateShader( type ); + const char* sources[] = { source }; - glShaderSource(shader, 1, sources, nullptr); - glCompileShader(shader); + glShaderSource( shader, 1, sources, nullptr ); + glCompileShader( shader ); int success = GL_FALSE; - glGetShaderiv(shader, GL_COMPILE_STATUS, &success); + glGetShaderiv( shader, GL_COMPILE_STATUS, &success ); - if (success == GL_FALSE) + if ( success == GL_FALSE ) { - fprintf(stderr, "Error compiling shader of type %d!\n", type); - PrintLogGL(shader); + fprintf( stderr, "Error compiling shader of type %d!\n", type ); + PrintLogGL( shader ); } - free(source); + free( source ); return shader; } -uint32_t CreateProgramFromFiles(const char* vertexPath, const char* fragmentPath) +uint32_t CreateProgramFromFiles( const char* vertexPath, const char* fragmentPath ) { - GLuint vertex = sCreateShaderFromFile(vertexPath, GL_VERTEX_SHADER); - if (vertex == 0) + GLuint vertex = sCreateShaderFromFile( vertexPath, GL_VERTEX_SHADER ); + if ( vertex == 0 ) { return 0; } - GLuint fragment = sCreateShaderFromFile(fragmentPath, GL_FRAGMENT_SHADER); - if (fragment == 0) + GLuint fragment = sCreateShaderFromFile( fragmentPath, GL_FRAGMENT_SHADER ); + if ( fragment == 0 ) { return 0; } GLuint program = glCreateProgram(); - glAttachShader(program, vertex); - glAttachShader(program, fragment); + glAttachShader( program, vertex ); + glAttachShader( program, fragment ); - glLinkProgram(program); + glLinkProgram( program ); int success = GL_FALSE; - glGetProgramiv(program, GL_LINK_STATUS, &success); - if (success == GL_FALSE) + glGetProgramiv( program, GL_LINK_STATUS, &success ); + if ( success == GL_FALSE ) { - printf("glLinkProgram:"); - PrintLogGL(program); + printf( "glLinkProgram:" ); + PrintLogGL( program ); return 0; } - glDeleteShader(vertex); - glDeleteShader(fragment); + glDeleteShader( vertex ); + glDeleteShader( fragment ); return program; } diff --git a/samples/shader.h b/samples/shader.h index 8787963c..28202f1f 100644 --- a/samples/shader.h +++ b/samples/shader.h @@ -5,9 +5,9 @@ #include -uint32_t CreateProgramFromFiles(const char* vertexPath, const char* fragmentPath); -uint32_t CreateProgramFromStrings(const char* vertexString, const char* fragmentString); +uint32_t CreateProgramFromFiles( const char* vertexPath, const char* fragmentPath ); +uint32_t CreateProgramFromStrings( const char* vertexString, const char* fragmentString ); void CheckErrorGL(); void DumpInfoGL(); -void PrintLogGL(int object); +void PrintLogGL( int object ); diff --git a/src/aabb.c b/src/aabb.c index a887a4a0..2fabfa50 100644 --- a/src/aabb.c +++ b/src/aabb.c @@ -7,34 +7,34 @@ #include -bool b2AABB_IsValid(b2AABB a) +bool b2AABB_IsValid( b2AABB a ) { - b2Vec2 d = b2Sub(a.upperBound, a.lowerBound); + b2Vec2 d = b2Sub( a.upperBound, a.lowerBound ); bool valid = d.x >= 0.0f && d.y >= 0.0f; - valid = valid && b2Vec2_IsValid(a.lowerBound) && b2Vec2_IsValid(a.upperBound); + valid = valid && b2Vec2_IsValid( a.lowerBound ) && b2Vec2_IsValid( a.upperBound ); return valid; } // From Real-time Collision Detection, p179. -b2CastOutput b2AABB_RayCast(b2AABB a, b2Vec2 p1, b2Vec2 p2) +b2CastOutput b2AABB_RayCast( b2AABB a, b2Vec2 p1, b2Vec2 p2 ) { // Radius not handled - b2CastOutput output = {0}; + b2CastOutput output = { 0 }; float tmin = -FLT_MAX; float tmax = FLT_MAX; b2Vec2 p = p1; - b2Vec2 d = b2Sub(p2, p1); - b2Vec2 absD = b2Abs(d); + b2Vec2 d = b2Sub( p2, p1 ); + b2Vec2 absD = b2Abs( d ); b2Vec2 normal = b2Vec2_zero; // x-coordinate - if (absD.x < FLT_EPSILON) + if ( absD.x < FLT_EPSILON ) { // parallel - if (p.x < a.lowerBound.x || a.upperBound.x < p.x) + if ( p.x < a.lowerBound.x || a.upperBound.x < p.x ) { return output; } @@ -42,13 +42,13 @@ b2CastOutput b2AABB_RayCast(b2AABB a, b2Vec2 p1, b2Vec2 p2) else { float inv_d = 1.0f / d.x; - float t1 = (a.lowerBound.x - p.x) * inv_d; - float t2 = (a.upperBound.x - p.x) * inv_d; + float t1 = ( a.lowerBound.x - p.x ) * inv_d; + float t2 = ( a.upperBound.x - p.x ) * inv_d; // Sign of the normal vector. float s = -1.0f; - if (t1 > t2) + if ( t1 > t2 ) { float tmp = t1; t1 = t2; @@ -57,7 +57,7 @@ b2CastOutput b2AABB_RayCast(b2AABB a, b2Vec2 p1, b2Vec2 p2) } // Push the min up - if (t1 > tmin) + if ( t1 > tmin ) { normal.y = 0.0f; normal.x = s; @@ -65,19 +65,19 @@ b2CastOutput b2AABB_RayCast(b2AABB a, b2Vec2 p1, b2Vec2 p2) } // Pull the max down - tmax = b2MinFloat(tmax, t2); + tmax = b2MinFloat( tmax, t2 ); - if (tmin > tmax) + if ( tmin > tmax ) { return output; } } // y-coordinate - if (absD.y < FLT_EPSILON) + if ( absD.y < FLT_EPSILON ) { // parallel - if (p.y < a.lowerBound.y || a.upperBound.y < p.y) + if ( p.y < a.lowerBound.y || a.upperBound.y < p.y ) { return output; } @@ -85,13 +85,13 @@ b2CastOutput b2AABB_RayCast(b2AABB a, b2Vec2 p1, b2Vec2 p2) else { float inv_d = 1.0f / d.y; - float t1 = (a.lowerBound.y - p.y) * inv_d; - float t2 = (a.upperBound.y - p.y) * inv_d; + float t1 = ( a.lowerBound.y - p.y ) * inv_d; + float t2 = ( a.upperBound.y - p.y ) * inv_d; // Sign of the normal vector. float s = -1.0f; - if (t1 > t2) + if ( t1 > t2 ) { float tmp = t1; t1 = t2; @@ -100,7 +100,7 @@ b2CastOutput b2AABB_RayCast(b2AABB a, b2Vec2 p1, b2Vec2 p2) } // Push the min up - if (t1 > tmin) + if ( t1 > tmin ) { normal.x = 0.0f; normal.y = s; @@ -108,9 +108,9 @@ b2CastOutput b2AABB_RayCast(b2AABB a, b2Vec2 p1, b2Vec2 p2) } // Pull the max down - tmax = b2MinFloat(tmax, t2); + tmax = b2MinFloat( tmax, t2 ); - if (tmin > tmax) + if ( tmin > tmax ) { return output; } @@ -118,7 +118,7 @@ b2CastOutput b2AABB_RayCast(b2AABB a, b2Vec2 p1, b2Vec2 p2) // Does the ray start inside the box? // Does the ray intersect beyond the max fraction? - if (tmin < 0.0f || 1.0f < tmin) + if ( tmin < 0.0f || 1.0f < tmin ) { return output; } @@ -126,7 +126,7 @@ b2CastOutput b2AABB_RayCast(b2AABB a, b2Vec2 p1, b2Vec2 p2) // Intersection. output.fraction = tmin; output.normal = normal; - output.point = b2Lerp(p1, p2, tmin); + output.point = b2Lerp( p1, p2, tmin ); output.hit = true; return output; } diff --git a/src/aabb.h b/src/aabb.h index 30671d6f..234e722f 100644 --- a/src/aabb.h +++ b/src/aabb.h @@ -6,40 +6,40 @@ #include "box2d/types.h" // Ray cast an AABB -b2CastOutput b2AABB_RayCast(b2AABB a, b2Vec2 p1, b2Vec2 p2); +b2CastOutput b2AABB_RayCast( b2AABB a, b2Vec2 p1, b2Vec2 p2 ); // Get the perimeter length -static inline float b2Perimeter(b2AABB a) +static inline float b2Perimeter( b2AABB a ) { float wx = a.upperBound.x - a.lowerBound.x; float wy = a.upperBound.y - a.lowerBound.y; - return 2.0f * (wx + wy); + return 2.0f * ( wx + wy ); } /// Enlarge a to contain b /// @return true if the AABB grew -static inline bool b2EnlargeAABB(b2AABB* a, b2AABB b) +static inline bool b2EnlargeAABB( b2AABB* a, b2AABB b ) { bool changed = false; - if (b.lowerBound.x < a->lowerBound.x) + if ( b.lowerBound.x < a->lowerBound.x ) { a->lowerBound.x = b.lowerBound.x; changed = true; } - if (b.lowerBound.y < a->lowerBound.y) + if ( b.lowerBound.y < a->lowerBound.y ) { a->lowerBound.y = b.lowerBound.y; changed = true; } - if (a->upperBound.x < b.upperBound.x) + if ( a->upperBound.x < b.upperBound.x ) { a->upperBound.x = b.upperBound.x; changed = true; } - if (a->upperBound.y < b.upperBound.y) + if ( a->upperBound.y < b.upperBound.y ) { a->upperBound.y = b.upperBound.y; changed = true; @@ -48,23 +48,23 @@ static inline bool b2EnlargeAABB(b2AABB* a, b2AABB b) return changed; } -static inline bool b2AABB_ContainsWithMargin(b2AABB a, b2AABB b, float margin) +static inline bool b2AABB_ContainsWithMargin( b2AABB a, b2AABB b, float margin ) { - bool s = (a.lowerBound.x <= b.lowerBound.x - margin) & (a.lowerBound.y <= b.lowerBound.y - margin) & - (b.upperBound.x + margin <= a.upperBound.x) & (b.upperBound.y + margin <= a.upperBound.y); + bool s = ( a.lowerBound.x <= b.lowerBound.x - margin ) & ( a.lowerBound.y <= b.lowerBound.y - margin ) & + ( b.upperBound.x + margin <= a.upperBound.x ) & ( b.upperBound.y + margin <= a.upperBound.y ); return s; } /// Do a and b overlap -static inline bool b2AABB_Overlaps(b2AABB a, b2AABB b) +static inline bool b2AABB_Overlaps( b2AABB a, b2AABB b ) { - b2Vec2 d1 = {b.lowerBound.x - a.upperBound.x, b.lowerBound.y - a.upperBound.y}; - b2Vec2 d2 = {a.lowerBound.x - b.upperBound.x, a.lowerBound.y - b.upperBound.y}; + b2Vec2 d1 = { b.lowerBound.x - a.upperBound.x, b.lowerBound.y - a.upperBound.y }; + b2Vec2 d2 = { a.lowerBound.x - b.upperBound.x, a.lowerBound.y - b.upperBound.y }; - if (d1.x > 0.0f || d1.y > 0.0f) + if ( d1.x > 0.0f || d1.y > 0.0f ) return false; - if (d2.x > 0.0f || d2.y > 0.0f) + if ( d2.x > 0.0f || d2.y > 0.0f ) return false; return true; diff --git a/src/allocate.c b/src/allocate.c index 2c6c7f5e..5e832eff 100644 --- a/src/allocate.c +++ b/src/allocate.c @@ -7,12 +7,12 @@ #include "box2d/base.h" -#if defined(B2_COMPILER_MSVC) -#define _CRTDBG_MAP_ALLOC -#include -#include +#if defined( B2_COMPILER_MSVC ) + #define _CRTDBG_MAP_ALLOC + #include + #include #else -#include + #include #endif #include @@ -20,14 +20,14 @@ #ifdef BOX2D_PROFILE -#include -#define b2TracyCAlloc(ptr, size) TracyCAlloc(ptr, size) -#define b2TracyCFree(ptr) TracyCFree(ptr) + #include + #define b2TracyCAlloc( ptr, size ) TracyCAlloc( ptr, size ) + #define b2TracyCFree( ptr ) TracyCFree( ptr ) #else -#define b2TracyCAlloc(ptr, size) -#define b2TracyCFree(ptr) + #define b2TracyCAlloc( ptr, size ) + #define b2TracyCFree( ptr ) #endif @@ -36,7 +36,7 @@ static b2FreeFcn* b2_freeFcn = NULL; static _Atomic int b2_byteCount; -void b2SetAllocator(b2AllocFcn* allocFcn, b2FreeFcn* freeFcn) +void b2SetAllocator( b2AllocFcn* allocFcn, b2FreeFcn* freeFcn ) { b2_allocFcn = allocFcn; b2_freeFcn = freeFcn; @@ -45,66 +45,66 @@ void b2SetAllocator(b2AllocFcn* allocFcn, b2FreeFcn* freeFcn) // Use 32 byte alignment for everything. Works with 256bit SIMD. #define B2_ALIGNMENT 32 -void* b2Alloc(uint32_t size) +void* b2Alloc( uint32_t size ) { // This could cause some sharing issues, however Box2D rarely calls b2Alloc. - atomic_fetch_add_explicit(&b2_byteCount, size, memory_order_relaxed); + atomic_fetch_add_explicit( &b2_byteCount, size, memory_order_relaxed ); // Allocation must be a multiple of 32 or risk a seg fault // https://en.cppreference.com/w/c/memory/aligned_alloc - uint32_t size32 = ((size - 1) | 0x1F) + 1; + uint32_t size32 = ( ( size - 1 ) | 0x1F ) + 1; - if (b2_allocFcn != NULL) + if ( b2_allocFcn != NULL ) { - void* ptr = b2_allocFcn(size32, B2_ALIGNMENT); - b2TracyCAlloc(ptr, size); + void* ptr = b2_allocFcn( size32, B2_ALIGNMENT ); + b2TracyCAlloc( ptr, size ); - B2_ASSERT(ptr != NULL); - B2_ASSERT(((uintptr_t)ptr & 0x1F) == 0); + B2_ASSERT( ptr != NULL ); + B2_ASSERT( ( (uintptr_t)ptr & 0x1F ) == 0 ); return ptr; } #ifdef B2_PLATFORM_WINDOWS - void* ptr = _aligned_malloc(size32, B2_ALIGNMENT); + void* ptr = _aligned_malloc( size32, B2_ALIGNMENT ); #else - void* ptr = aligned_alloc(B2_ALIGNMENT, size32); + void* ptr = aligned_alloc( B2_ALIGNMENT, size32 ); #endif - b2TracyCAlloc(ptr, size); + b2TracyCAlloc( ptr, size ); + + B2_ASSERT( ptr != NULL ); + B2_ASSERT( ( (uintptr_t)ptr & 0x1F ) == 0 ); - B2_ASSERT(ptr != NULL); - B2_ASSERT(((uintptr_t)ptr & 0x1F) == 0); - return ptr; } -void b2Free(void* mem, uint32_t size) +void b2Free( void* mem, uint32_t size ) { - if (mem == NULL) + if ( mem == NULL ) { return; } - b2TracyCFree(mem); + b2TracyCFree( mem ); - if (b2_freeFcn != NULL) + if ( b2_freeFcn != NULL ) { - b2_freeFcn(mem); + b2_freeFcn( mem ); } else { #ifdef B2_PLATFORM_WINDOWS - _aligned_free(mem); + _aligned_free( mem ); #else - free(mem); + free( mem ); #endif } - atomic_fetch_sub_explicit(&b2_byteCount, size, memory_order_relaxed); + atomic_fetch_sub_explicit( &b2_byteCount, size, memory_order_relaxed ); } -int b2GetByteCount(void) +int b2GetByteCount( void ) { - return atomic_load_explicit(&b2_byteCount, memory_order_relaxed); + return atomic_load_explicit( &b2_byteCount, memory_order_relaxed ); } diff --git a/src/allocate.h b/src/allocate.h index 5133251c..125430d8 100644 --- a/src/allocate.h +++ b/src/allocate.h @@ -4,5 +4,5 @@ #pragma once #include -void* b2Alloc(uint32_t size); -void b2Free(void* mem, uint32_t size); +void* b2Alloc( uint32_t size ); +void b2Free( void* mem, uint32_t size ); diff --git a/src/array.c b/src/array.c index 3ca5476c..9080d498 100644 --- a/src/array.c +++ b/src/array.c @@ -8,57 +8,57 @@ #include -void* b2CreateArray(int elementSize, int capacity) +void* b2CreateArray( int elementSize, int capacity ) { - void* result = (b2ArrayHeader*)b2Alloc(sizeof(b2ArrayHeader) + elementSize * capacity) + 1; - b2Array(result).count = 0; - b2Array(result).capacity = capacity; + void* result = (b2ArrayHeader*)b2Alloc( sizeof( b2ArrayHeader ) + elementSize * capacity ) + 1; + b2Array( result ).count = 0; + b2Array( result ).capacity = capacity; return result; } -void b2DestroyArray(void* a, int elementSize) +void b2DestroyArray( void* a, int elementSize ) { - int capacity = b2Array(a).capacity; - int size = sizeof(b2ArrayHeader) + elementSize * capacity; - b2Free(((b2ArrayHeader*)a) - 1, size); + int capacity = b2Array( a ).capacity; + int size = sizeof( b2ArrayHeader ) + elementSize * capacity; + b2Free( ( (b2ArrayHeader*)a ) - 1, size ); } -void b2Array_Grow(void** a, int elementSize) +void b2Array_Grow( void** a, int elementSize ) { - int capacity = b2Array(*a).capacity; - B2_ASSERT(capacity == b2Array(*a).count); + int capacity = b2Array( *a ).capacity; + B2_ASSERT( capacity == b2Array( *a ).count ); // grow by 50% - int newCapacity = capacity + (capacity >> 1); + int newCapacity = capacity + ( capacity >> 1 ); newCapacity = newCapacity >= 2 ? newCapacity : 2; void* tmp = *a; - *a = (b2ArrayHeader*)b2Alloc(sizeof(b2ArrayHeader) + elementSize * newCapacity) + 1; - b2Array(*a).capacity = newCapacity; - b2Array(*a).count = capacity; - memcpy(*a, tmp, capacity * elementSize); - b2DestroyArray(tmp, elementSize); + *a = (b2ArrayHeader*)b2Alloc( sizeof( b2ArrayHeader ) + elementSize * newCapacity ) + 1; + b2Array( *a ).capacity = newCapacity; + b2Array( *a ).count = capacity; + memcpy( *a, tmp, capacity * elementSize ); + b2DestroyArray( tmp, elementSize ); } -void b2Array_Resize(void** a, int elementSize, int count) +void b2Array_Resize( void** a, int elementSize, int count ) { - int capacity = b2Array(*a).capacity; - if (capacity >= count) + int capacity = b2Array( *a ).capacity; + if ( capacity >= count ) { - b2Array(*a).count = count; + b2Array( *a ).count = count; return; } - int originalCount = b2Array(*a).count; + int originalCount = b2Array( *a ).count; // grow by 50% - int newCapacity = count + (count >> 1); + int newCapacity = count + ( count >> 1 ); newCapacity = newCapacity >= 2 ? newCapacity : 2; void* tmp = *a; - *a = (b2ArrayHeader*)b2Alloc(sizeof(b2ArrayHeader) + elementSize * newCapacity) + 1; - b2Array(*a).capacity = newCapacity; - b2Array(*a).count = count; + *a = (b2ArrayHeader*)b2Alloc( sizeof( b2ArrayHeader ) + elementSize * newCapacity ) + 1; + b2Array( *a ).capacity = newCapacity; + b2Array( *a ).count = count; // copy existing elements - memcpy(*a, tmp, originalCount * elementSize); - b2DestroyArray(tmp, elementSize); + memcpy( *a, tmp, originalCount * elementSize ); + b2DestroyArray( tmp, elementSize ); } diff --git a/src/array.h b/src/array.h index d7d7d529..a8b3efe4 100644 --- a/src/array.h +++ b/src/array.h @@ -13,35 +13,37 @@ typedef struct b2ArrayHeader int capacity; } b2ArrayHeader; -#define b2Array(a) ((b2ArrayHeader*)(a))[-1] +#define b2Array( a ) ( (b2ArrayHeader*)( a ) )[-1] -void* b2CreateArray(int elementSize, int capacity); -void b2DestroyArray(void* a, int elementSize); -void b2Array_Grow(void** a, int elementSize); -void b2Array_Resize(void** a, int elementSize, int count); +void* b2CreateArray( int elementSize, int capacity ); +void b2DestroyArray( void* a, int elementSize ); +void b2Array_Grow( void** a, int elementSize ); +void b2Array_Resize( void** a, int elementSize, int count ); -#define b2CheckIndex(a, index) B2_ASSERT(0 <= index && index < b2Array(a).count) -#define b2CheckId(ARRAY, ID) B2_ASSERT(0 <= ID && ID < b2Array(ARRAY).count && ARRAY[ID].id == ID) -#define b2CheckIdAndRevision(ARRAY, ID, REV) B2_ASSERT(0 <= ID && ID < b2Array(ARRAY).count && ARRAY[ID].id == ID && ARRAY[ID].revision == REV) +#define b2CheckIndex( a, index ) B2_ASSERT( 0 <= index && index < b2Array( a ).count ) +#define b2CheckId( ARRAY, ID ) B2_ASSERT( 0 <= ID && ID < b2Array( ARRAY ).count && ARRAY[ID].id == ID ) +#define b2CheckIdAndRevision( ARRAY, ID, REV ) \ + B2_ASSERT( 0 <= ID && ID < b2Array( ARRAY ).count && ARRAY[ID].id == ID && ARRAY[ID].revision == REV ) -#define b2Array_Clear(a) b2Array(a).count = 0 +#define b2Array_Clear( a ) b2Array( a ).count = 0 -#define b2Array_Push(a, element) \ - if (b2Array(a).count == b2Array(a).capacity) b2Array_Grow((void**)&a, sizeof(element)); \ - B2_ASSERT(b2Array(a).count < b2Array(a).capacity); \ - a[b2Array(a).count++] = element +#define b2Array_Push( a, element ) \ + if ( b2Array( a ).count == b2Array( a ).capacity ) \ + b2Array_Grow( (void**)&a, sizeof( element ) ); \ + B2_ASSERT( b2Array( a ).count < b2Array( a ).capacity ); \ + a[b2Array( a ).count++] = element -#define b2Array_RemoveSwap(a, index) \ - B2_ASSERT(0 <= index && index < b2Array(a).count); \ - a[index] = a[b2Array(a).count - 1]; \ - b2Array(a).count-- +#define b2Array_RemoveSwap( a, index ) \ + B2_ASSERT( 0 <= index && index < b2Array( a ).count ); \ + a[index] = a[b2Array( a ).count - 1]; \ + b2Array( a ).count-- -#define b2Array_Last(a) (a)[b2Array(a).count - 1]; +#define b2Array_Last( a ) ( a )[b2Array( a ).count - 1]; -#define b2Array_Pop(a) \ - B2_ASSERT(0 < b2Array(a).count); \ - b2Array(a).count-- +#define b2Array_Pop( a ) \ + B2_ASSERT( 0 < b2Array( a ).count ); \ + b2Array( a ).count-- -#define b2GetArrayCount(a) (b2Array(a).count) -#define b2GetArrayCapacity(a) (b2Array(a).capacity) -#define b2GetArrayBytes(a, elementSize) ((int)elementSize * b2Array(a).capacity) +#define b2GetArrayCount( a ) ( b2Array( a ).count ) +#define b2GetArrayCapacity( a ) ( b2Array( a ).capacity ) +#define b2GetArrayBytes( a, elementSize ) ( (int)elementSize * b2Array( a ).capacity ) diff --git a/src/bitset.c b/src/bitset.c index ca90df42..413ac570 100644 --- a/src/bitset.c +++ b/src/bitset.c @@ -7,61 +7,61 @@ #include -b2BitSet b2CreateBitSet(uint32_t bitCapacity) +b2BitSet b2CreateBitSet( uint32_t bitCapacity ) { - b2BitSet bitSet = {0}; + b2BitSet bitSet = { 0 }; - bitSet.blockCapacity = (bitCapacity + sizeof(uint64_t) * 8 - 1) / (sizeof(uint64_t) * 8); + bitSet.blockCapacity = ( bitCapacity + sizeof( uint64_t ) * 8 - 1 ) / ( sizeof( uint64_t ) * 8 ); bitSet.blockCount = 0; - bitSet.bits = b2Alloc(bitSet.blockCapacity * sizeof(uint64_t)); - memset(bitSet.bits, 0, bitSet.blockCapacity * sizeof(uint64_t)); + bitSet.bits = b2Alloc( bitSet.blockCapacity * sizeof( uint64_t ) ); + memset( bitSet.bits, 0, bitSet.blockCapacity * sizeof( uint64_t ) ); return bitSet; } -void b2DestroyBitSet(b2BitSet* bitSet) +void b2DestroyBitSet( b2BitSet* bitSet ) { - b2Free(bitSet->bits, bitSet->blockCapacity * sizeof(uint64_t)); + b2Free( bitSet->bits, bitSet->blockCapacity * sizeof( uint64_t ) ); bitSet->blockCapacity = 0; bitSet->blockCount = 0; bitSet->bits = NULL; } -void b2SetBitCountAndClear(b2BitSet* bitSet, uint32_t bitCount) +void b2SetBitCountAndClear( b2BitSet* bitSet, uint32_t bitCount ) { - uint32_t blockCount = (bitCount + sizeof(uint64_t) * 8 - 1) / (sizeof(uint64_t) * 8); - if (bitSet->blockCapacity < blockCount) + uint32_t blockCount = ( bitCount + sizeof( uint64_t ) * 8 - 1 ) / ( sizeof( uint64_t ) * 8 ); + if ( bitSet->blockCapacity < blockCount ) { - b2DestroyBitSet(bitSet); - uint32_t newBitCapacity = bitCount + (bitCount >> 1); - *bitSet = b2CreateBitSet(newBitCapacity); + b2DestroyBitSet( bitSet ); + uint32_t newBitCapacity = bitCount + ( bitCount >> 1 ); + *bitSet = b2CreateBitSet( newBitCapacity ); } bitSet->blockCount = blockCount; - memset(bitSet->bits, 0, bitSet->blockCount * sizeof(uint64_t)); + memset( bitSet->bits, 0, bitSet->blockCount * sizeof( uint64_t ) ); } -void b2GrowBitSet(b2BitSet* bitSet, uint32_t blockCount) +void b2GrowBitSet( b2BitSet* bitSet, uint32_t blockCount ) { - B2_ASSERT(blockCount > bitSet->blockCount); - if (blockCount > bitSet->blockCapacity) + B2_ASSERT( blockCount > bitSet->blockCount ); + if ( blockCount > bitSet->blockCapacity ) { uint32_t oldCapacity = bitSet->blockCapacity; bitSet->blockCapacity = blockCount + blockCount / 2; - uint64_t* newBits = b2Alloc(bitSet->blockCapacity * sizeof(uint64_t)); - memset(newBits, 0, bitSet->blockCapacity * sizeof(uint64_t)); - memcpy(newBits, bitSet->bits, bitSet->blockCount * sizeof(uint64_t)); - b2Free(bitSet->bits, oldCapacity * sizeof(uint64_t)); + uint64_t* newBits = b2Alloc( bitSet->blockCapacity * sizeof( uint64_t ) ); + memset( newBits, 0, bitSet->blockCapacity * sizeof( uint64_t ) ); + memcpy( newBits, bitSet->bits, bitSet->blockCount * sizeof( uint64_t ) ); + b2Free( bitSet->bits, oldCapacity * sizeof( uint64_t ) ); bitSet->bits = newBits; } bitSet->blockCount = blockCount; } -void b2InPlaceUnion(b2BitSet* restrict setA, const b2BitSet* restrict setB) +void b2InPlaceUnion( b2BitSet* restrict setA, const b2BitSet* restrict setB ) { - B2_ASSERT(setA->blockCount == setB->blockCount); + B2_ASSERT( setA->blockCount == setB->blockCount ); uint32_t blockCount = setA->blockCount; - for (uint32_t i = 0; i < blockCount; ++i) + for ( uint32_t i = 0; i < blockCount; ++i ) { setA->bits[i] |= setB->bits[i]; } diff --git a/src/bitset.h b/src/bitset.h index be85b825..0a76f644 100644 --- a/src/bitset.h +++ b/src/bitset.h @@ -16,50 +16,50 @@ typedef struct b2BitSet uint32_t blockCount; } b2BitSet; -b2BitSet b2CreateBitSet(uint32_t bitCapacity); -void b2DestroyBitSet(b2BitSet* bitSet); -void b2SetBitCountAndClear(b2BitSet* bitSet, uint32_t bitCount); -void b2InPlaceUnion(b2BitSet* setA, const b2BitSet* setB); -void b2GrowBitSet(b2BitSet* bitSet, uint32_t blockCount); +b2BitSet b2CreateBitSet( uint32_t bitCapacity ); +void b2DestroyBitSet( b2BitSet* bitSet ); +void b2SetBitCountAndClear( b2BitSet* bitSet, uint32_t bitCount ); +void b2InPlaceUnion( b2BitSet* setA, const b2BitSet* setB ); +void b2GrowBitSet( b2BitSet* bitSet, uint32_t blockCount ); -static inline void b2SetBit(b2BitSet* bitSet, uint32_t bitIndex) +static inline void b2SetBit( b2BitSet* bitSet, uint32_t bitIndex ) { uint32_t blockIndex = bitIndex / 64; - B2_ASSERT(blockIndex < bitSet->blockCount); - bitSet->bits[blockIndex] |= ((uint64_t)1 << bitIndex % 64); + B2_ASSERT( blockIndex < bitSet->blockCount ); + bitSet->bits[blockIndex] |= ( (uint64_t)1 << bitIndex % 64 ); } -static inline void b2SetBitGrow(b2BitSet* bitSet, uint32_t bitIndex) +static inline void b2SetBitGrow( b2BitSet* bitSet, uint32_t bitIndex ) { uint32_t blockIndex = bitIndex / 64; - if (blockIndex >= bitSet->blockCount) + if ( blockIndex >= bitSet->blockCount ) { - b2GrowBitSet(bitSet, blockIndex + 1); + b2GrowBitSet( bitSet, blockIndex + 1 ); } - bitSet->bits[blockIndex] |= ((uint64_t)1 << bitIndex % 64); + bitSet->bits[blockIndex] |= ( (uint64_t)1 << bitIndex % 64 ); } -static inline void b2ClearBit(b2BitSet* bitSet, uint32_t bitIndex) +static inline void b2ClearBit( b2BitSet* bitSet, uint32_t bitIndex ) { uint32_t blockIndex = bitIndex / 64; - if (blockIndex >= bitSet->blockCount) + if ( blockIndex >= bitSet->blockCount ) { return; } - bitSet->bits[blockIndex] &= ~((uint64_t)1 << bitIndex % 64); + bitSet->bits[blockIndex] &= ~( (uint64_t)1 << bitIndex % 64 ); } -static inline bool b2GetBit(const b2BitSet* bitSet, uint32_t bitIndex) +static inline bool b2GetBit( const b2BitSet* bitSet, uint32_t bitIndex ) { uint32_t blockIndex = bitIndex / 64; - if (blockIndex >= bitSet->blockCount) + if ( blockIndex >= bitSet->blockCount ) { return false; } - return (bitSet->bits[blockIndex] & ((uint64_t)1 << bitIndex % 64)) != 0; + return ( bitSet->bits[blockIndex] & ( (uint64_t)1 << bitIndex % 64 ) ) != 0; } -static inline int b2GetBitSetBytes(b2BitSet* bitSet) +static inline int b2GetBitSetBytes( b2BitSet* bitSet ) { - return bitSet->blockCapacity * sizeof(uint64_t); + return bitSet->blockCapacity * sizeof( uint64_t ); } diff --git a/src/block_array.c b/src/block_array.c index 17af59f6..8ca09c53 100644 --- a/src/block_array.c +++ b/src/block_array.c @@ -14,96 +14,96 @@ #define B2_INITIAL_CAPACITY 16 -b2BodySimArray b2CreateBodySimArray(int capacity) +b2BodySimArray b2CreateBodySimArray( int capacity ) { - if (capacity > 0) + if ( capacity > 0 ) { - return (b2BodySimArray){b2Alloc(capacity * sizeof(b2BodySim)), 0, capacity}; + return ( b2BodySimArray ){ b2Alloc( capacity * sizeof( b2BodySim ) ), 0, capacity }; } - return (b2BodySimArray){0}; + return ( b2BodySimArray ){ 0 }; } -b2BodyStateArray b2CreateBodyStateArray(int capacity) +b2BodyStateArray b2CreateBodyStateArray( int capacity ) { - if (capacity > 0) + if ( capacity > 0 ) { - return (b2BodyStateArray){b2Alloc(capacity * sizeof(b2BodyState)), 0, capacity}; + return ( b2BodyStateArray ){ b2Alloc( capacity * sizeof( b2BodyState ) ), 0, capacity }; } - return (b2BodyStateArray){0}; + return ( b2BodyStateArray ){ 0 }; } -b2ContactArray b2CreateContactArray(int capacity) +b2ContactArray b2CreateContactArray( int capacity ) { - if (capacity > 0) + if ( capacity > 0 ) { - return (b2ContactArray){b2Alloc(capacity * sizeof(b2ContactSim)), 0, capacity}; + return ( b2ContactArray ){ b2Alloc( capacity * sizeof( b2ContactSim ) ), 0, capacity }; } - return (b2ContactArray){0}; + return ( b2ContactArray ){ 0 }; } -b2JointArray b2CreateJointArray(int capacity) +b2JointArray b2CreateJointArray( int capacity ) { - if (capacity > 0) + if ( capacity > 0 ) { - return (b2JointArray){b2Alloc(capacity * sizeof(b2JointSim)), 0, capacity}; + return ( b2JointArray ){ b2Alloc( capacity * sizeof( b2JointSim ) ), 0, capacity }; } - return (b2JointArray){0}; + return ( b2JointArray ){ 0 }; } -b2IslandArray b2CreateIslandArray(int capacity) +b2IslandArray b2CreateIslandArray( int capacity ) { - if (capacity > 0) + if ( capacity > 0 ) { - return (b2IslandArray){b2Alloc(capacity * sizeof(b2IslandSim)), 0, capacity}; + return ( b2IslandArray ){ b2Alloc( capacity * sizeof( b2IslandSim ) ), 0, capacity }; } - return (b2IslandArray){0}; + return ( b2IslandArray ){ 0 }; } -void b2DestroyBodySimArray(b2BodySimArray* array) +void b2DestroyBodySimArray( b2BodySimArray* array ) { - b2Free(array->data, array->capacity * sizeof(b2BodySim)); + b2Free( array->data, array->capacity * sizeof( b2BodySim ) ); } -void b2DestroyBodyStateArray(b2BodyStateArray* array) +void b2DestroyBodyStateArray( b2BodyStateArray* array ) { - b2Free(array->data, array->capacity * sizeof(b2BodyState)); + b2Free( array->data, array->capacity * sizeof( b2BodyState ) ); } -void b2DestroyContactArray(b2ContactArray* array) +void b2DestroyContactArray( b2ContactArray* array ) { - b2Free(array->data, array->capacity * sizeof(b2ContactSim)); + b2Free( array->data, array->capacity * sizeof( b2ContactSim ) ); } -void b2DestroyJointArray(b2JointArray* array) +void b2DestroyJointArray( b2JointArray* array ) { - b2Free(array->data, array->capacity * sizeof(b2JointSim)); + b2Free( array->data, array->capacity * sizeof( b2JointSim ) ); } -void b2DestroyIslandArray(b2IslandArray* array) +void b2DestroyIslandArray( b2IslandArray* array ) { - b2Free(array->data, array->capacity * sizeof(b2IslandSim)); + b2Free( array->data, array->capacity * sizeof( b2IslandSim ) ); } -b2BodySim* b2AddBodySim(b2BodySimArray* array) +b2BodySim* b2AddBodySim( b2BodySimArray* array ) { - int elementSize = sizeof(b2BodySim); - if (array->capacity == 0) + int elementSize = sizeof( b2BodySim ); + if ( array->capacity == 0 ) { - B2_ASSERT(array->count == 0); - array->data = b2Alloc(B2_INITIAL_CAPACITY * elementSize); + B2_ASSERT( array->count == 0 ); + array->data = b2Alloc( B2_INITIAL_CAPACITY * elementSize ); array->capacity = B2_INITIAL_CAPACITY; } - else if (array->count == array->capacity) + else if ( array->count == array->capacity ) { int newCapacity = 2 * array->capacity; - b2BodySim* newElements = b2Alloc(newCapacity * elementSize); - memcpy(newElements, array->data, array->capacity * elementSize); - b2Free(array->data, array->capacity * elementSize); + b2BodySim* newElements = b2Alloc( newCapacity * elementSize ); + memcpy( newElements, array->data, array->capacity * elementSize ); + b2Free( array->data, array->capacity * elementSize ); array->data = newElements; array->capacity = newCapacity; } @@ -113,21 +113,21 @@ b2BodySim* b2AddBodySim(b2BodySimArray* array) return element; } -b2BodyState* b2AddBodyState(b2BodyStateArray* array) +b2BodyState* b2AddBodyState( b2BodyStateArray* array ) { - int elementSize = sizeof(b2BodyState); - if (array->capacity == 0) + int elementSize = sizeof( b2BodyState ); + if ( array->capacity == 0 ) { - B2_ASSERT(array->count == 0); - array->data = b2Alloc(B2_INITIAL_CAPACITY * elementSize); + B2_ASSERT( array->count == 0 ); + array->data = b2Alloc( B2_INITIAL_CAPACITY * elementSize ); array->capacity = B2_INITIAL_CAPACITY; } - else if (array->count == array->capacity) + else if ( array->count == array->capacity ) { int newCapacity = 2 * array->capacity; - b2BodyState* newElements = b2Alloc(newCapacity * elementSize); - memcpy(newElements, array->data, array->capacity * elementSize); - b2Free(array->data, array->capacity * elementSize); + b2BodyState* newElements = b2Alloc( newCapacity * elementSize ); + memcpy( newElements, array->data, array->capacity * elementSize ); + b2Free( array->data, array->capacity * elementSize ); array->data = newElements; array->capacity = newCapacity; } @@ -137,21 +137,21 @@ b2BodyState* b2AddBodyState(b2BodyStateArray* array) return element; } -b2ContactSim* b2AddContact(b2ContactArray* array) +b2ContactSim* b2AddContact( b2ContactArray* array ) { - int elementSize = sizeof(b2ContactSim); - if (array->capacity == 0) + int elementSize = sizeof( b2ContactSim ); + if ( array->capacity == 0 ) { - B2_ASSERT(array->count == 0); - array->data = b2Alloc(B2_INITIAL_CAPACITY * elementSize); + B2_ASSERT( array->count == 0 ); + array->data = b2Alloc( B2_INITIAL_CAPACITY * elementSize ); array->capacity = B2_INITIAL_CAPACITY; } - else if (array->count == array->capacity) + else if ( array->count == array->capacity ) { int newCapacity = 2 * array->capacity; - b2ContactSim* newElements = b2Alloc(newCapacity * elementSize); - memcpy(newElements, array->data, array->capacity * elementSize); - b2Free(array->data, array->capacity * elementSize); + b2ContactSim* newElements = b2Alloc( newCapacity * elementSize ); + memcpy( newElements, array->data, array->capacity * elementSize ); + b2Free( array->data, array->capacity * elementSize ); array->data = newElements; array->capacity = newCapacity; } @@ -161,21 +161,21 @@ b2ContactSim* b2AddContact(b2ContactArray* array) return element; } -b2JointSim* b2AddJoint(b2JointArray* array) +b2JointSim* b2AddJoint( b2JointArray* array ) { - int elementSize = sizeof(b2JointSim); - if (array->capacity == 0) + int elementSize = sizeof( b2JointSim ); + if ( array->capacity == 0 ) { - B2_ASSERT(array->count == 0); - array->data = b2Alloc(B2_INITIAL_CAPACITY * elementSize); + B2_ASSERT( array->count == 0 ); + array->data = b2Alloc( B2_INITIAL_CAPACITY * elementSize ); array->capacity = B2_INITIAL_CAPACITY; } - else if (array->count == array->capacity) + else if ( array->count == array->capacity ) { int newCapacity = 2 * array->capacity; - b2JointSim* newElements = b2Alloc(newCapacity * elementSize); - memcpy(newElements, array->data, array->capacity * elementSize); - b2Free(array->data, array->capacity * elementSize); + b2JointSim* newElements = b2Alloc( newCapacity * elementSize ); + memcpy( newElements, array->data, array->capacity * elementSize ); + b2Free( array->data, array->capacity * elementSize ); array->data = newElements; array->capacity = newCapacity; } @@ -185,21 +185,21 @@ b2JointSim* b2AddJoint(b2JointArray* array) return element; } -b2IslandSim* b2AddIsland(b2IslandArray* array) +b2IslandSim* b2AddIsland( b2IslandArray* array ) { - int elementSize = sizeof(b2IslandSim); - if (array->capacity == 0) + int elementSize = sizeof( b2IslandSim ); + if ( array->capacity == 0 ) { - B2_ASSERT(array->count == 0); - array->data = b2Alloc(B2_INITIAL_CAPACITY * elementSize); + B2_ASSERT( array->count == 0 ); + array->data = b2Alloc( B2_INITIAL_CAPACITY * elementSize ); array->capacity = B2_INITIAL_CAPACITY; } - else if (array->count == array->capacity) + else if ( array->count == array->capacity ) { int newCapacity = 2 * array->capacity; - b2IslandSim* newElements = b2Alloc(newCapacity * elementSize); - memcpy(newElements, array->data, array->capacity * elementSize); - b2Free(array->data, array->capacity * elementSize); + b2IslandSim* newElements = b2Alloc( newCapacity * elementSize ); + memcpy( newElements, array->data, array->capacity * elementSize ); + b2Free( array->data, array->capacity * elementSize ); array->data = newElements; array->capacity = newCapacity; } @@ -211,10 +211,10 @@ b2IslandSim* b2AddIsland(b2IslandArray* array) } // Returns the index of the element moved into the empty slot (or B2_NULL_INDEX) -int b2RemoveBodySim(b2BodySimArray* array, int index) +int b2RemoveBodySim( b2BodySimArray* array, int index ) { - B2_ASSERT(0 <= index && index < array->count); - if (index < array->count - 1) + B2_ASSERT( 0 <= index && index < array->count ); + if ( index < array->count - 1 ) { int removed = array->count - 1; array->data[index] = array->data[removed]; @@ -226,10 +226,10 @@ int b2RemoveBodySim(b2BodySimArray* array, int index) return B2_NULL_INDEX; } -int b2RemoveBodyState(b2BodyStateArray* array, int index) +int b2RemoveBodyState( b2BodyStateArray* array, int index ) { - B2_ASSERT(0 <= index && index < array->count); - if (index < array->count - 1) + B2_ASSERT( 0 <= index && index < array->count ); + if ( index < array->count - 1 ) { int removed = array->count - 1; array->data[index] = array->data[removed]; @@ -241,10 +241,10 @@ int b2RemoveBodyState(b2BodyStateArray* array, int index) return B2_NULL_INDEX; } -int b2RemoveContact(b2ContactArray* array, int index) +int b2RemoveContact( b2ContactArray* array, int index ) { - B2_ASSERT(0 <= index && index < array->count); - if (index < array->count - 1) + B2_ASSERT( 0 <= index && index < array->count ); + if ( index < array->count - 1 ) { int removed = array->count - 1; array->data[index] = array->data[removed]; @@ -256,10 +256,10 @@ int b2RemoveContact(b2ContactArray* array, int index) return B2_NULL_INDEX; } -int b2RemoveJoint(b2JointArray* array, int index) +int b2RemoveJoint( b2JointArray* array, int index ) { - B2_ASSERT(0 <= index && index < array->count); - if (index < array->count - 1) + B2_ASSERT( 0 <= index && index < array->count ); + if ( index < array->count - 1 ) { int removed = array->count - 1; array->data[index] = array->data[removed]; @@ -271,10 +271,10 @@ int b2RemoveJoint(b2JointArray* array, int index) return B2_NULL_INDEX; } -int b2RemoveIsland(b2IslandArray* array, int index) +int b2RemoveIsland( b2IslandArray* array, int index ) { - B2_ASSERT(0 <= index && index < array->count); - if (index < array->count - 1) + B2_ASSERT( 0 <= index && index < array->count ); + if ( index < array->count - 1 ) { int removed = array->count - 1; array->data[index] = array->data[removed]; diff --git a/src/block_array.h b/src/block_array.h index a4b31ca5..813913d3 100644 --- a/src/block_array.h +++ b/src/block_array.h @@ -46,28 +46,28 @@ typedef struct b2JointArray // These provide a way to create an array with a specified capacity. If the capacity is not // known, you may use zero initialization. -b2BodySimArray b2CreateBodySimArray(int capacity); -b2BodyStateArray b2CreateBodyStateArray(int capacity); -b2ContactArray b2CreateContactArray(int capacity); -b2IslandArray b2CreateIslandArray(int capacity); -b2JointArray b2CreateJointArray(int capacity); +b2BodySimArray b2CreateBodySimArray( int capacity ); +b2BodyStateArray b2CreateBodyStateArray( int capacity ); +b2ContactArray b2CreateContactArray( int capacity ); +b2IslandArray b2CreateIslandArray( int capacity ); +b2JointArray b2CreateJointArray( int capacity ); -void b2DestroyBodySimArray(b2BodySimArray* array); -void b2DestroyBodyStateArray(b2BodyStateArray* array); -void b2DestroyContactArray(b2ContactArray* array); -void b2DestroyIslandArray(b2IslandArray* array); -void b2DestroyJointArray(b2JointArray* array); +void b2DestroyBodySimArray( b2BodySimArray* array ); +void b2DestroyBodyStateArray( b2BodyStateArray* array ); +void b2DestroyContactArray( b2ContactArray* array ); +void b2DestroyIslandArray( b2IslandArray* array ); +void b2DestroyJointArray( b2JointArray* array ); -b2BodySim* b2AddBodySim(b2BodySimArray* array); -b2BodyState* b2AddBodyState(b2BodyStateArray* array); -b2ContactSim* b2AddContact(b2ContactArray* array); -b2IslandSim* b2AddIsland(b2IslandArray* array); -b2JointSim* b2AddJoint(b2JointArray* array); +b2BodySim* b2AddBodySim( b2BodySimArray* array ); +b2BodyState* b2AddBodyState( b2BodyStateArray* array ); +b2ContactSim* b2AddContact( b2ContactArray* array ); +b2IslandSim* b2AddIsland( b2IslandArray* array ); +b2JointSim* b2AddJoint( b2JointArray* array ); // Returns the index of the element moved into the empty slot (or B2_NULL_INDEX) // todo have these return the id directly? -int b2RemoveBodySim(b2BodySimArray* array, int index); -int b2RemoveBodyState(b2BodyStateArray* array, int index); -int b2RemoveContact(b2ContactArray* array, int index); -int b2RemoveIsland(b2IslandArray* array, int index); -int b2RemoveJoint(b2JointArray* array, int index); +int b2RemoveBodySim( b2BodySimArray* array, int index ); +int b2RemoveBodyState( b2BodyStateArray* array, int index ); +int b2RemoveContact( b2ContactArray* array, int index ); +int b2RemoveIsland( b2IslandArray* array, int index ); +int b2RemoveJoint( b2JointArray* array, int index ); diff --git a/src/body.c b/src/body.c index 488b2df4..d1149666 100644 --- a/src/body.c +++ b/src/body.c @@ -21,74 +21,74 @@ #include -b2Body* b2GetBody(b2World* world, int bodyId) +b2Body* b2GetBody( b2World* world, int bodyId ) { - b2CheckIndex(world->bodyArray, bodyId); + b2CheckIndex( world->bodyArray, bodyId ); return world->bodyArray + bodyId; } // Get a validated body from a world using an id. -b2Body* b2GetBodyFullId(b2World* world, b2BodyId bodyId) +b2Body* b2GetBodyFullId( b2World* world, b2BodyId bodyId ) { - B2_ASSERT(b2Body_IsValid(bodyId)); + B2_ASSERT( b2Body_IsValid( bodyId ) ); // id index starts at one so that zero can represent null - return b2GetBody(world, bodyId.index1 - 1); + return b2GetBody( world, bodyId.index1 - 1 ); } -b2Transform b2GetBodyTransformQuick(b2World* world, b2Body* body) +b2Transform b2GetBodyTransformQuick( b2World* world, b2Body* body ) { - b2CheckIndex(world->solverSetArray, body->setIndex); + b2CheckIndex( world->solverSetArray, body->setIndex ); b2SolverSet* set = world->solverSetArray + body->setIndex; - B2_ASSERT(0 <= body->localIndex && body->localIndex <= set->sims.count); + B2_ASSERT( 0 <= body->localIndex && body->localIndex <= set->sims.count ); b2BodySim* bodySim = set->sims.data + body->localIndex; return bodySim->transform; } -b2Transform b2GetBodyTransform(b2World* world, int bodyId) +b2Transform b2GetBodyTransform( b2World* world, int bodyId ) { - b2CheckIndex(world->bodyArray, bodyId); + b2CheckIndex( world->bodyArray, bodyId ); b2Body* body = world->bodyArray + bodyId; - return b2GetBodyTransformQuick(world, body); + return b2GetBodyTransformQuick( world, body ); } // Create a b2BodyId from a raw id. -b2BodyId b2MakeBodyId(b2World* world, int bodyId) +b2BodyId b2MakeBodyId( b2World* world, int bodyId ) { - b2CheckIndex(world->bodyArray, bodyId); + b2CheckIndex( world->bodyArray, bodyId ); b2Body* body = world->bodyArray + bodyId; - return (b2BodyId){bodyId + 1, world->worldId, body->revision}; + return ( b2BodyId ){ bodyId + 1, world->worldId, body->revision }; } -b2BodySim* b2GetBodySim(b2World* world, b2Body* body) +b2BodySim* b2GetBodySim( b2World* world, b2Body* body ) { - b2CheckIndex(world->solverSetArray, body->setIndex); + b2CheckIndex( world->solverSetArray, body->setIndex ); b2SolverSet* set = world->solverSetArray + body->setIndex; - B2_ASSERT(0 <= body->localIndex && body->localIndex < set->sims.count); + B2_ASSERT( 0 <= body->localIndex && body->localIndex < set->sims.count ); return set->sims.data + body->localIndex; } -b2BodyState* b2GetBodyState(b2World* world, b2Body* body) +b2BodyState* b2GetBodyState( b2World* world, b2Body* body ) { - b2CheckIndex(world->solverSetArray, body->setIndex); - if (body->setIndex == b2_awakeSet) + b2CheckIndex( world->solverSetArray, body->setIndex ); + if ( body->setIndex == b2_awakeSet ) { b2SolverSet* set = world->solverSetArray + b2_awakeSet; - B2_ASSERT(0 <= body->localIndex && body->localIndex < set->states.count); + B2_ASSERT( 0 <= body->localIndex && body->localIndex < set->states.count ); return set->states.data + body->localIndex; } return NULL; } -static void b2CreateIslandForBody(b2World* world, int setIndex, b2Body* body) +static void b2CreateIslandForBody( b2World* world, int setIndex, b2Body* body ) { - B2_ASSERT(body->islandId == B2_NULL_INDEX); - B2_ASSERT(body->islandPrev == B2_NULL_INDEX); - B2_ASSERT(body->islandNext == B2_NULL_INDEX); - B2_ASSERT(setIndex != b2_disabledSet); + B2_ASSERT( body->islandId == B2_NULL_INDEX ); + B2_ASSERT( body->islandPrev == B2_NULL_INDEX ); + B2_ASSERT( body->islandNext == B2_NULL_INDEX ); + B2_ASSERT( setIndex != b2_disabledSet ); - b2Island* island = b2CreateIsland(world, setIndex); + b2Island* island = b2CreateIsland( world, setIndex ); body->islandId = island->islandId; island->headBody = body->id; @@ -96,61 +96,61 @@ static void b2CreateIslandForBody(b2World* world, int setIndex, b2Body* body) island->bodyCount = 1; } -static void b2RemoveBodyFromIsland(b2World* world, b2Body* body) +static void b2RemoveBodyFromIsland( b2World* world, b2Body* body ) { - if (body->islandId == B2_NULL_INDEX) + if ( body->islandId == B2_NULL_INDEX ) { - B2_ASSERT(body->islandPrev == B2_NULL_INDEX); - B2_ASSERT(body->islandNext == B2_NULL_INDEX); + B2_ASSERT( body->islandPrev == B2_NULL_INDEX ); + B2_ASSERT( body->islandNext == B2_NULL_INDEX ); return; } int islandId = body->islandId; - b2CheckIndex(world->islandArray, islandId); + b2CheckIndex( world->islandArray, islandId ); b2Island* island = world->islandArray + islandId; // Fix the island's linked list of sims - if (body->islandPrev != B2_NULL_INDEX) + if ( body->islandPrev != B2_NULL_INDEX ) { - b2Body* prevBody = b2GetBody(world, body->islandPrev); + b2Body* prevBody = b2GetBody( world, body->islandPrev ); prevBody->islandNext = body->islandNext; } - if (body->islandNext != B2_NULL_INDEX) + if ( body->islandNext != B2_NULL_INDEX ) { - b2Body* nextBody = b2GetBody(world, body->islandNext); + b2Body* nextBody = b2GetBody( world, body->islandNext ); nextBody->islandPrev = body->islandPrev; } - B2_ASSERT(island->bodyCount > 0); + B2_ASSERT( island->bodyCount > 0 ); island->bodyCount -= 1; bool islandDestroyed = false; - if (island->headBody == body->id) + if ( island->headBody == body->id ) { island->headBody = body->islandNext; - if (island->headBody == B2_NULL_INDEX) + if ( island->headBody == B2_NULL_INDEX ) { // Destroy empty island - B2_ASSERT(island->tailBody == body->id); - B2_ASSERT(island->bodyCount == 0); - B2_ASSERT(island->contactCount == 0); - B2_ASSERT(island->jointCount == 0); + B2_ASSERT( island->tailBody == body->id ); + B2_ASSERT( island->bodyCount == 0 ); + B2_ASSERT( island->contactCount == 0 ); + B2_ASSERT( island->jointCount == 0 ); // Free the island - b2DestroyIsland(world, island->islandId); + b2DestroyIsland( world, island->islandId ); islandDestroyed = true; } } - else if (island->tailBody == body->id) + else if ( island->tailBody == body->id ) { island->tailBody = body->islandPrev; } - if (islandDestroyed == false) + if ( islandDestroyed == false ) { - b2ValidateIsland(world, islandId); + b2ValidateIsland( world, islandId ); } body->islandId = B2_NULL_INDEX; @@ -158,83 +158,83 @@ static void b2RemoveBodyFromIsland(b2World* world, b2Body* body) body->islandNext = B2_NULL_INDEX; } -static void b2DestroyBodyContacts(b2World* world, b2Body* body, bool wakeBodies) +static void b2DestroyBodyContacts( b2World* world, b2Body* body, bool wakeBodies ) { // Destroy the attached contacts int edgeKey = body->headContactKey; - while (edgeKey != B2_NULL_INDEX) + while ( edgeKey != B2_NULL_INDEX ) { int contactId = edgeKey >> 1; int edgeIndex = edgeKey & 1; b2Contact* contact = world->contactArray + contactId; edgeKey = contact->edges[edgeIndex].nextKey; - b2DestroyContact(world, contact, wakeBodies); + b2DestroyContact( world, contact, wakeBodies ); } - b2ValidateSolverSets(world); + b2ValidateSolverSets( world ); } -b2BodyId b2CreateBody(b2WorldId worldId, const b2BodyDef* def) +b2BodyId b2CreateBody( b2WorldId worldId, const b2BodyDef* def ) { - b2CheckDef(def); - B2_ASSERT(b2Vec2_IsValid(def->position)); - B2_ASSERT(b2Rot_IsValid(def->rotation)); - B2_ASSERT(b2Vec2_IsValid(def->linearVelocity)); - B2_ASSERT(b2IsValid(def->angularVelocity)); - B2_ASSERT(b2IsValid(def->linearDamping) && def->linearDamping >= 0.0f); - B2_ASSERT(b2IsValid(def->angularDamping) && def->angularDamping >= 0.0f); - B2_ASSERT(b2IsValid(def->sleepThreshold) && def->sleepThreshold >= 0.0f); - B2_ASSERT(b2IsValid(def->gravityScale)); + b2CheckDef( def ); + B2_ASSERT( b2Vec2_IsValid( def->position ) ); + B2_ASSERT( b2Rot_IsValid( def->rotation ) ); + B2_ASSERT( b2Vec2_IsValid( def->linearVelocity ) ); + B2_ASSERT( b2IsValid( def->angularVelocity ) ); + B2_ASSERT( b2IsValid( def->linearDamping ) && def->linearDamping >= 0.0f ); + B2_ASSERT( b2IsValid( def->angularDamping ) && def->angularDamping >= 0.0f ); + B2_ASSERT( b2IsValid( def->sleepThreshold ) && def->sleepThreshold >= 0.0f ); + B2_ASSERT( b2IsValid( def->gravityScale ) ); - b2World* world = b2GetWorldFromId(worldId); - B2_ASSERT(world->locked == false); + b2World* world = b2GetWorldFromId( worldId ); + B2_ASSERT( world->locked == false ); - if (world->locked) + if ( world->locked ) { return b2_nullBodyId; } - bool isAwake = (def->isAwake || def->enableSleep == false) && def->isEnabled; + bool isAwake = ( def->isAwake || def->enableSleep == false ) && def->isEnabled; // determine the solver set int setId; - if (def->isEnabled == false) + if ( def->isEnabled == false ) { // any body type can be disabled setId = b2_disabledSet; } - else if (def->type == b2_staticBody) + else if ( def->type == b2_staticBody ) { setId = b2_staticSet; } - else if (isAwake == true ) + else if ( isAwake == true ) { setId = b2_awakeSet; } else { // new set for a sleeping body in its own island - setId = b2AllocId(&world->solverSetIdPool); - if (setId == b2Array(world->solverSetArray).count) + setId = b2AllocId( &world->solverSetIdPool ); + if ( setId == b2Array( world->solverSetArray ).count ) { - b2Array_Push(world->solverSetArray, (b2SolverSet){0}); + b2Array_Push( world->solverSetArray, ( b2SolverSet ){ 0 } ); } else { - B2_ASSERT(world->solverSetArray[setId].setIndex == B2_NULL_INDEX); + B2_ASSERT( world->solverSetArray[setId].setIndex == B2_NULL_INDEX ); } world->solverSetArray[setId].setIndex = setId; } - B2_ASSERT(0 <= setId && setId < b2Array(world->solverSetArray).count); - - int bodyId = b2AllocId(&world->bodyIdPool); + B2_ASSERT( 0 <= setId && setId < b2Array( world->solverSetArray ).count ); + + int bodyId = b2AllocId( &world->bodyIdPool ); b2SolverSet* set = world->solverSetArray + setId; - b2BodySim* bodySim = b2AddBodySim(&set->sims); - *bodySim = (b2BodySim){0}; + b2BodySim* bodySim = b2AddBodySim( &set->sims ); + *bodySim = ( b2BodySim ){ 0 }; bodySim->transform.p = def->position; bodySim->transform.q = def->rotation; bodySim->center = def->position; @@ -258,27 +258,27 @@ b2BodyId b2CreateBody(b2WorldId worldId, const b2BodyDef* def) bodySim->isFast = false; bodySim->isSpeedCapped = false; - if (setId == b2_awakeSet) + if ( setId == b2_awakeSet ) { - b2BodyState* bodyState = b2AddBodyState(&set->states); - B2_ASSERT(((uintptr_t)bodyState & 0x1F) == 0); + b2BodyState* bodyState = b2AddBodyState( &set->states ); + B2_ASSERT( ( (uintptr_t)bodyState & 0x1F ) == 0 ); - *bodyState = (b2BodyState){0}; + *bodyState = ( b2BodyState ){ 0 }; bodyState->linearVelocity = def->linearVelocity; bodyState->angularVelocity = def->angularVelocity; bodyState->deltaRotation = b2Rot_identity; } - if (bodyId == b2Array(world->bodyArray).count) + if ( bodyId == b2Array( world->bodyArray ).count ) { - b2Array_Push(world->bodyArray, (b2Body){0}); + b2Array_Push( world->bodyArray, ( b2Body ){ 0 } ); } else { - B2_ASSERT(world->bodyArray[bodyId].id == B2_NULL_INDEX); + B2_ASSERT( world->bodyArray[bodyId].id == B2_NULL_INDEX ); } - b2CheckIndex(world->bodyArray, bodyId); + b2CheckIndex( world->bodyArray, bodyId ); b2Body* body = world->bodyArray + bodyId; body->userData = def->userData; body->setIndex = setId; @@ -306,49 +306,49 @@ b2BodyId b2CreateBody(b2WorldId worldId, const b2BodyDef* def) body->automaticMass = def->automaticMass; // dynamic and kinematic bodies that are enabled need a island - if (setId >= b2_awakeSet) + if ( setId >= b2_awakeSet ) { - b2CreateIslandForBody(world, setId, body); + b2CreateIslandForBody( world, setId, body ); } - b2ValidateSolverSets(world); + b2ValidateSolverSets( world ); - b2BodyId id = {bodyId + 1, world->worldId, body->revision}; + b2BodyId id = { bodyId + 1, world->worldId, body->revision }; return id; } -bool b2IsBodyAwake(b2World* world, b2Body* body) +bool b2IsBodyAwake( b2World* world, b2Body* body ) { return body->setIndex == b2_awakeSet; } -bool b2WakeBody(b2World* world, b2Body* body) +bool b2WakeBody( b2World* world, b2Body* body ) { - if (body->setIndex >= b2_firstSleepingSet) + if ( body->setIndex >= b2_firstSleepingSet ) { - b2WakeSolverSet(world, body->setIndex); + b2WakeSolverSet( world, body->setIndex ); return true; } return false; } -void b2DestroyBody(b2BodyId bodyId) +void b2DestroyBody( b2BodyId bodyId ) { - b2World* world = b2GetWorldLocked(bodyId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( bodyId.world0 ); + if ( world == NULL ) { return; } - b2Body* body = b2GetBodyFullId(world, bodyId); + b2Body* body = b2GetBodyFullId( world, bodyId ); // Wake bodies attached to this body, even if this body is static. bool wakeBodies = true; // Destroy the attached joints int edgeKey = body->headJointKey; - while (edgeKey != B2_NULL_INDEX) + while ( edgeKey != B2_NULL_INDEX ) { int jointId = edgeKey >> 1; int edgeIndex = edgeKey & 1; @@ -357,22 +357,22 @@ void b2DestroyBody(b2BodyId bodyId) edgeKey = joint->edges[edgeIndex].nextKey; // Careful because this modifies the list being traversed - b2DestroyJointInternal(world, joint, wakeBodies); + b2DestroyJointInternal( world, joint, wakeBodies ); } // Destroy all contacts attached to this body. - b2DestroyBodyContacts(world, body, wakeBodies); + b2DestroyBodyContacts( world, body, wakeBodies ); // Destroy the attached shapes and their broad-phase proxies. int shapeId = body->headShapeId; - while (shapeId != B2_NULL_INDEX) + while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = world->shapeArray + shapeId; - b2DestroyShapeProxy(shape, &world->broadPhase); + b2DestroyShapeProxy( shape, &world->broadPhase ); // Return shape to free list. - b2FreeId(&world->shapeIdPool, shapeId); + b2FreeId( &world->shapeIdPool, shapeId ); shape->id = B2_NULL_INDEX; shapeId = shape->nextShapeId; @@ -380,63 +380,63 @@ void b2DestroyBody(b2BodyId bodyId) // Destroy the attached chains. The associated shapes have already been destroyed above. int chainId = body->headChainId; - while (chainId != B2_NULL_INDEX) + while ( chainId != B2_NULL_INDEX ) { b2ChainShape* chain = world->chainArray + chainId; - b2Free(chain->shapeIndices, chain->count * sizeof(int)); + b2Free( chain->shapeIndices, chain->count * sizeof( int ) ); chain->shapeIndices = NULL; // Return chain to free list. - b2FreeId(&world->chainIdPool, chainId); + b2FreeId( &world->chainIdPool, chainId ); chain->id = B2_NULL_INDEX; chainId = chain->nextChainId; } - b2RemoveBodyFromIsland(world, body); + b2RemoveBodyFromIsland( world, body ); // Remove body sim from solver set that owns it - b2CheckIndex(world->solverSetArray, body->setIndex); + b2CheckIndex( world->solverSetArray, body->setIndex ); b2SolverSet* set = world->solverSetArray + body->setIndex; - int movedIndex = b2RemoveBodySim(&set->sims, body->localIndex); - if (movedIndex != B2_NULL_INDEX) + int movedIndex = b2RemoveBodySim( &set->sims, body->localIndex ); + if ( movedIndex != B2_NULL_INDEX ) { // Fix moved body index b2BodySim* movedSim = set->sims.data + body->localIndex; int movedId = movedSim->bodyId; b2Body* movedBody = world->bodyArray + movedId; - B2_ASSERT(movedBody->localIndex == movedIndex); + B2_ASSERT( movedBody->localIndex == movedIndex ); movedBody->localIndex = body->localIndex; } // Remove body state from awake set - if (body->setIndex == b2_awakeSet) + if ( body->setIndex == b2_awakeSet ) { - int result = b2RemoveBodyState(&set->states, body->localIndex); - B2_MAYBE_UNUSED(result); - B2_ASSERT(result == movedIndex); + int result = b2RemoveBodyState( &set->states, body->localIndex ); + B2_MAYBE_UNUSED( result ); + B2_ASSERT( result == movedIndex ); } // Free body and id (preserve body revision) - b2FreeId(&world->bodyIdPool, body->id); + b2FreeId( &world->bodyIdPool, body->id ); body->setIndex = B2_NULL_INDEX; body->localIndex = B2_NULL_INDEX; body->id = B2_NULL_INDEX; - b2ValidateSolverSets(world); + b2ValidateSolverSets( world ); } -int b2Body_GetContactCapacity(b2BodyId bodyId) +int b2Body_GetContactCapacity( b2BodyId bodyId ) { - b2World* world = b2GetWorldLocked(bodyId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( bodyId.world0 ); + if ( world == NULL ) { return 0; } - b2Body* body = b2GetBodyFullId(world, bodyId); + b2Body* body = b2GetBodyFullId( world, bodyId ); // Conservative and fast return body->contactCount; @@ -444,78 +444,78 @@ int b2Body_GetContactCapacity(b2BodyId bodyId) // todo what about sensors? // todo sample needed -int b2Body_GetContactData(b2BodyId bodyId, b2ContactData* contactData, int capacity) +int b2Body_GetContactData( b2BodyId bodyId, b2ContactData* contactData, int capacity ) { - b2World* world = b2GetWorldLocked(bodyId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( bodyId.world0 ); + if ( world == NULL ) { return 0; } - b2Body* body = b2GetBodyFullId(world, bodyId); + b2Body* body = b2GetBodyFullId( world, bodyId ); int contactKey = body->headContactKey; int index = 0; - while (contactKey != B2_NULL_INDEX && index < capacity) + while ( contactKey != B2_NULL_INDEX && index < capacity ) { int contactId = contactKey >> 1; int edgeIndex = contactKey & 1; - b2CheckIndex(world->contactArray, contactId); + b2CheckIndex( world->contactArray, contactId ); b2Contact* contact = world->contactArray + contactId; // Is contact touching? - if (contact->flags & b2_contactTouchingFlag) + if ( contact->flags & b2_contactTouchingFlag ) { b2Shape* shapeA = world->shapeArray + contact->shapeIdA; b2Shape* shapeB = world->shapeArray + contact->shapeIdB; - contactData[index].shapeIdA = (b2ShapeId){shapeA->id + 1, bodyId.world0, shapeA->revision}; - contactData[index].shapeIdB = (b2ShapeId){shapeB->id + 1, bodyId.world0, shapeB->revision}; + contactData[index].shapeIdA = ( b2ShapeId ){ shapeA->id + 1, bodyId.world0, shapeA->revision }; + contactData[index].shapeIdB = ( b2ShapeId ){ shapeB->id + 1, bodyId.world0, shapeB->revision }; - b2ContactSim* contactSim = b2GetContactSim(world, contact); + b2ContactSim* contactSim = b2GetContactSim( world, contact ); contactData[index].manifold = contactSim->manifold; - + index += 1; } contactKey = contact->edges[edgeIndex].nextKey; } - B2_ASSERT(index <= capacity); + B2_ASSERT( index <= capacity ); return index; } -b2AABB b2Body_ComputeAABB(b2BodyId bodyId) +b2AABB b2Body_ComputeAABB( b2BodyId bodyId ) { - b2World* world = b2GetWorldLocked(bodyId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( bodyId.world0 ); + if ( world == NULL ) { - return (b2AABB){0}; + return ( b2AABB ){ 0 }; } - b2Body* body = b2GetBodyFullId(world, bodyId); - if (body->headShapeId == B2_NULL_INDEX) + b2Body* body = b2GetBodyFullId( world, bodyId ); + if ( body->headShapeId == B2_NULL_INDEX ) { - b2Transform transform = b2GetBodyTransform(world, body->id); - return (b2AABB){transform.p, transform.p}; + b2Transform transform = b2GetBodyTransform( world, body->id ); + return ( b2AABB ){ transform.p, transform.p }; } b2Shape* shape = world->shapeArray + body->headShapeId; b2AABB aabb = shape->aabb; - while (shape->nextShapeId != B2_NULL_INDEX) + while ( shape->nextShapeId != B2_NULL_INDEX ) { shape = world->shapeArray + shape->nextShapeId; - aabb = b2AABB_Union(aabb, shape->aabb); + aabb = b2AABB_Union( aabb, shape->aabb ); } return aabb; } -void b2UpdateBodyMassData(b2World* world, b2Body* body) +void b2UpdateBodyMassData( b2World* world, b2Body* body ) { - b2BodySim* bodySim = b2GetBodySim(world, body); + b2BodySim* bodySim = b2GetBodySim( world, body ); // Compute mass data from shapes. Each shape has its own density. bodySim->mass = 0.0f; @@ -527,21 +527,21 @@ void b2UpdateBodyMassData(b2World* world, b2Body* body) bodySim->maxExtent = 0.0f; // Static and kinematic sims have zero mass. - if (body->type != b2_dynamicBody) + if ( body->type != b2_dynamicBody ) { bodySim->center = bodySim->transform.p; // Need extents for kinematic bodies for sleeping to work correctly. - if (body->type == b2_kinematicBody) + if ( body->type == b2_kinematicBody ) { int shapeId = body->headShapeId; - while (shapeId != B2_NULL_INDEX) + while ( shapeId != B2_NULL_INDEX ) { const b2Shape* s = world->shapeArray + shapeId; - b2ShapeExtent extent = b2ComputeShapeExtent(s, b2Vec2_zero); - bodySim->minExtent = b2MinFloat(bodySim->minExtent, extent.minExtent); - bodySim->maxExtent = b2MaxFloat(bodySim->maxExtent, extent.maxExtent); + b2ShapeExtent extent = b2ComputeShapeExtent( s, b2Vec2_zero ); + bodySim->minExtent = b2MinFloat( bodySim->minExtent, extent.minExtent ); + bodySim->maxExtent = b2MaxFloat( bodySim->maxExtent, extent.maxExtent ); shapeId = s->nextShapeId; } @@ -553,35 +553,34 @@ void b2UpdateBodyMassData(b2World* world, b2Body* body) // Accumulate mass over all shapes. b2Vec2 localCenter = b2Vec2_zero; int shapeId = body->headShapeId; - while (shapeId != B2_NULL_INDEX) + while ( shapeId != B2_NULL_INDEX ) { const b2Shape* s = world->shapeArray + shapeId; shapeId = s->nextShapeId; - if (s->density == 0.0f) + if ( s->density == 0.0f ) { continue; } - b2MassData massData = b2ComputeShapeMass(s); + b2MassData massData = b2ComputeShapeMass( s ); bodySim->mass += massData.mass; - localCenter = b2MulAdd(localCenter, massData.mass, massData.center); + localCenter = b2MulAdd( localCenter, massData.mass, massData.center ); bodySim->inertia += massData.rotationalInertia; - } // Compute center of mass. - if (bodySim->mass > 0.0f) + if ( bodySim->mass > 0.0f ) { bodySim->invMass = 1.0f / bodySim->mass; - localCenter = b2MulSV(bodySim->invMass, localCenter); + localCenter = b2MulSV( bodySim->invMass, localCenter ); } - if (bodySim->inertia > 0.0f && body->fixedRotation == false) + if ( bodySim->inertia > 0.0f && body->fixedRotation == false ) { // Center the inertia about the center of mass. - bodySim->inertia -= bodySim->mass * b2Dot(localCenter, localCenter); - B2_ASSERT(bodySim->inertia > 0.0f); + bodySim->inertia -= bodySim->mass * b2Dot( localCenter, localCenter ); + B2_ASSERT( bodySim->inertia > 0.0f ); bodySim->invInertia = 1.0f / bodySim->inertia; } else @@ -593,99 +592,99 @@ void b2UpdateBodyMassData(b2World* world, b2Body* body) // Move center of mass. b2Vec2 oldCenter = bodySim->center; bodySim->localCenter = localCenter; - bodySim->center = b2TransformPoint(bodySim->transform, bodySim->localCenter); + bodySim->center = b2TransformPoint( bodySim->transform, bodySim->localCenter ); // Update center of mass velocity - b2BodyState* state = b2GetBodyState(world, body); - if (state != NULL) + b2BodyState* state = b2GetBodyState( world, body ); + if ( state != NULL ) { - b2Vec2 deltaLinear = b2CrossSV(state->angularVelocity, b2Sub(bodySim->center, oldCenter)); - state->linearVelocity = b2Add(state->linearVelocity, deltaLinear); + b2Vec2 deltaLinear = b2CrossSV( state->angularVelocity, b2Sub( bodySim->center, oldCenter ) ); + state->linearVelocity = b2Add( state->linearVelocity, deltaLinear ); } // Compute body extents relative to center of mass shapeId = body->headShapeId; - while (shapeId != B2_NULL_INDEX) + while ( shapeId != B2_NULL_INDEX ) { const b2Shape* s = world->shapeArray + shapeId; - b2ShapeExtent extent = b2ComputeShapeExtent(s, localCenter); - bodySim->minExtent = b2MinFloat(bodySim->minExtent, extent.minExtent); - bodySim->maxExtent = b2MaxFloat(bodySim->maxExtent, extent.maxExtent); + b2ShapeExtent extent = b2ComputeShapeExtent( s, localCenter ); + bodySim->minExtent = b2MinFloat( bodySim->minExtent, extent.minExtent ); + bodySim->maxExtent = b2MaxFloat( bodySim->maxExtent, extent.maxExtent ); shapeId = s->nextShapeId; } } -b2Vec2 b2Body_GetPosition(b2BodyId bodyId) +b2Vec2 b2Body_GetPosition( b2BodyId bodyId ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); - b2Transform transform = b2GetBodyTransformQuick(world, body); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); + b2Transform transform = b2GetBodyTransformQuick( world, body ); return transform.p; } -b2Rot b2Body_GetRotation(b2BodyId bodyId) +b2Rot b2Body_GetRotation( b2BodyId bodyId ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); - b2Transform transform = b2GetBodyTransformQuick(world, body); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); + b2Transform transform = b2GetBodyTransformQuick( world, body ); return transform.q; } -b2Transform b2Body_GetTransform(b2BodyId bodyId) +b2Transform b2Body_GetTransform( b2BodyId bodyId ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); - return b2GetBodyTransformQuick(world, body); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); + return b2GetBodyTransformQuick( world, body ); } -b2Vec2 b2Body_GetLocalPoint(b2BodyId bodyId, b2Vec2 worldPoint) +b2Vec2 b2Body_GetLocalPoint( b2BodyId bodyId, b2Vec2 worldPoint ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); - b2Transform transform = b2GetBodyTransformQuick(world, body); - return b2InvTransformPoint(transform, worldPoint); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); + b2Transform transform = b2GetBodyTransformQuick( world, body ); + return b2InvTransformPoint( transform, worldPoint ); } -b2Vec2 b2Body_GetWorldPoint(b2BodyId bodyId, b2Vec2 localPoint) +b2Vec2 b2Body_GetWorldPoint( b2BodyId bodyId, b2Vec2 localPoint ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); - b2Transform transform = b2GetBodyTransformQuick(world, body); - return b2TransformPoint(transform, localPoint); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); + b2Transform transform = b2GetBodyTransformQuick( world, body ); + return b2TransformPoint( transform, localPoint ); } -b2Vec2 b2Body_GetLocalVector(b2BodyId bodyId, b2Vec2 worldVector) +b2Vec2 b2Body_GetLocalVector( b2BodyId bodyId, b2Vec2 worldVector ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); - b2Transform transform = b2GetBodyTransformQuick(world, body); - return b2InvRotateVector(transform.q, worldVector); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); + b2Transform transform = b2GetBodyTransformQuick( world, body ); + return b2InvRotateVector( transform.q, worldVector ); } -b2Vec2 b2Body_GetWorldVector(b2BodyId bodyId, b2Vec2 localVector) +b2Vec2 b2Body_GetWorldVector( b2BodyId bodyId, b2Vec2 localVector ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); - b2Transform transform = b2GetBodyTransformQuick(world, body); - return b2RotateVector(transform.q, localVector); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); + b2Transform transform = b2GetBodyTransformQuick( world, body ); + return b2RotateVector( transform.q, localVector ); } -void b2Body_SetTransform(b2BodyId bodyId, b2Vec2 position, b2Rot rotation) +void b2Body_SetTransform( b2BodyId bodyId, b2Vec2 position, b2Rot rotation ) { - B2_ASSERT(b2Vec2_IsValid(position)); - B2_ASSERT(b2Rot_IsValid(rotation)); - B2_ASSERT(b2Body_IsValid(bodyId)); - b2World* world = b2GetWorld(bodyId.world0); - B2_ASSERT(world->locked == false); + B2_ASSERT( b2Vec2_IsValid( position ) ); + B2_ASSERT( b2Rot_IsValid( rotation ) ); + B2_ASSERT( b2Body_IsValid( bodyId ) ); + b2World* world = b2GetWorld( bodyId.world0 ); + B2_ASSERT( world->locked == false ); - b2Body* body = b2GetBodyFullId(world, bodyId); - b2BodySim* bodySim = b2GetBodySim(world, body); + b2Body* body = b2GetBodyFullId( world, bodyId ); + b2BodySim* bodySim = b2GetBodySim( world, body ); bodySim->transform.p = position; bodySim->transform.q = rotation; - bodySim->center = b2TransformPoint(bodySim->transform, bodySim->localCenter); + bodySim->center = b2TransformPoint( bodySim->transform, bodySim->localCenter ); bodySim->rotation0 = bodySim->transform.q; bodySim->center0 = bodySim->center; @@ -697,17 +696,17 @@ void b2Body_SetTransform(b2BodyId bodyId, b2Vec2 position, b2Rot rotation) const float speculativeDistance = b2_speculativeDistance; int shapeId = body->headShapeId; - while (shapeId != B2_NULL_INDEX) + while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = world->shapeArray + shapeId; - b2AABB aabb = b2ComputeShapeAABB(shape, transform); + b2AABB aabb = b2ComputeShapeAABB( shape, transform ); aabb.lowerBound.x -= speculativeDistance; aabb.lowerBound.y -= speculativeDistance; aabb.upperBound.x += speculativeDistance; aabb.upperBound.y += speculativeDistance; shape->aabb = aabb; - if (b2AABB_Contains(shape->fatAABB, aabb) == false) + if ( b2AABB_Contains( shape->fatAABB, aabb ) == false ) { b2AABB fatAABB; fatAABB.lowerBound.x = aabb.lowerBound.x - margin; @@ -717,9 +716,9 @@ void b2Body_SetTransform(b2BodyId bodyId, b2Vec2 position, b2Rot rotation) shape->fatAABB = fatAABB; // They body could be disabled - if (shape->proxyKey != B2_NULL_INDEX) + if ( shape->proxyKey != B2_NULL_INDEX ) { - b2BroadPhase_MoveProxy(broadPhase, shape->proxyKey, fatAABB); + b2BroadPhase_MoveProxy( broadPhase, shape->proxyKey, fatAABB ); } } @@ -727,42 +726,42 @@ void b2Body_SetTransform(b2BodyId bodyId, b2Vec2 position, b2Rot rotation) } } -b2Vec2 b2Body_GetLinearVelocity(b2BodyId bodyId) +b2Vec2 b2Body_GetLinearVelocity( b2BodyId bodyId ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); - b2BodyState* state = b2GetBodyState(world, body); - if (state != NULL) + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); + b2BodyState* state = b2GetBodyState( world, body ); + if ( state != NULL ) { return state->linearVelocity; } return b2Vec2_zero; } -float b2Body_GetAngularVelocity(b2BodyId bodyId) +float b2Body_GetAngularVelocity( b2BodyId bodyId ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); - b2BodyState* state = b2GetBodyState(world, body); - if (state != NULL) + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); + b2BodyState* state = b2GetBodyState( world, body ); + if ( state != NULL ) { return state->angularVelocity; } return 0.0; } -void b2Body_SetLinearVelocity(b2BodyId bodyId, b2Vec2 linearVelocity) +void b2Body_SetLinearVelocity( b2BodyId bodyId, b2Vec2 linearVelocity ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); - if (b2LengthSquared(linearVelocity) > 0.0f) + if ( b2LengthSquared( linearVelocity ) > 0.0f ) { - b2WakeBody(world, body); + b2WakeBody( world, body ); } - - b2BodyState* state = b2GetBodyState(world, body); - if (state == NULL) + + b2BodyState* state = b2GetBodyState( world, body ); + if ( state == NULL ) { return; } @@ -770,18 +769,18 @@ void b2Body_SetLinearVelocity(b2BodyId bodyId, b2Vec2 linearVelocity) state->linearVelocity = linearVelocity; } -void b2Body_SetAngularVelocity(b2BodyId bodyId, float angularVelocity) +void b2Body_SetAngularVelocity( b2BodyId bodyId, float angularVelocity ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); - if (angularVelocity != 0.0f) + if ( angularVelocity != 0.0f ) { - b2WakeBody(world, body); + b2WakeBody( world, body ); } - - b2BodyState* state = b2GetBodyState(world, body); - if (state == NULL) + + b2BodyState* state = b2GetBodyState( world, body ); + if ( state == NULL ) { return; } @@ -789,132 +788,132 @@ void b2Body_SetAngularVelocity(b2BodyId bodyId, float angularVelocity) state->angularVelocity = angularVelocity; } -void b2Body_ApplyForce(b2BodyId bodyId, b2Vec2 force, b2Vec2 point, bool wake) +void b2Body_ApplyForce( b2BodyId bodyId, b2Vec2 force, b2Vec2 point, bool wake ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); - if (wake && body->setIndex >= b2_firstSleepingSet) + if ( wake && body->setIndex >= b2_firstSleepingSet ) { - b2WakeBody(world, body); + b2WakeBody( world, body ); } - if (body->setIndex == b2_awakeSet) + if ( body->setIndex == b2_awakeSet ) { - b2BodySim* bodySim = b2GetBodySim(world, body); - bodySim->force = b2Add(bodySim->force, force); - bodySim->torque += b2Cross(b2Sub(point, bodySim->center), force); + b2BodySim* bodySim = b2GetBodySim( world, body ); + bodySim->force = b2Add( bodySim->force, force ); + bodySim->torque += b2Cross( b2Sub( point, bodySim->center ), force ); } } -void b2Body_ApplyForceToCenter(b2BodyId bodyId, b2Vec2 force, bool wake) +void b2Body_ApplyForceToCenter( b2BodyId bodyId, b2Vec2 force, bool wake ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); - if (wake && body->setIndex >= b2_firstSleepingSet) + if ( wake && body->setIndex >= b2_firstSleepingSet ) { - b2WakeBody(world, body); + b2WakeBody( world, body ); } - if (body->setIndex == b2_awakeSet) + if ( body->setIndex == b2_awakeSet ) { - b2BodySim* bodySim = b2GetBodySim(world, body); - bodySim->force = b2Add(bodySim->force, force); + b2BodySim* bodySim = b2GetBodySim( world, body ); + bodySim->force = b2Add( bodySim->force, force ); } } -void b2Body_ApplyTorque(b2BodyId bodyId, float torque, bool wake) +void b2Body_ApplyTorque( b2BodyId bodyId, float torque, bool wake ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); - if (wake && body->setIndex >= b2_firstSleepingSet) + if ( wake && body->setIndex >= b2_firstSleepingSet ) { - b2WakeBody(world, body); + b2WakeBody( world, body ); } - if (body->setIndex == b2_awakeSet) + if ( body->setIndex == b2_awakeSet ) { - b2BodySim* bodySim = b2GetBodySim(world, body); + b2BodySim* bodySim = b2GetBodySim( world, body ); bodySim->torque += torque; } } -void b2Body_ApplyLinearImpulse(b2BodyId bodyId, b2Vec2 impulse, b2Vec2 point, bool wake) +void b2Body_ApplyLinearImpulse( b2BodyId bodyId, b2Vec2 impulse, b2Vec2 point, bool wake ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); - if (wake && body->setIndex >= b2_firstSleepingSet) + if ( wake && body->setIndex >= b2_firstSleepingSet ) { - b2WakeBody(world, body); + b2WakeBody( world, body ); } - if (body->setIndex == b2_awakeSet) + if ( body->setIndex == b2_awakeSet ) { int localIndex = body->localIndex; b2SolverSet* set = world->solverSetArray + b2_awakeSet; - B2_ASSERT(0 <= localIndex && localIndex < set->states.count); + B2_ASSERT( 0 <= localIndex && localIndex < set->states.count ); b2BodyState* state = set->states.data + localIndex; b2BodySim* bodySim = set->sims.data + localIndex; - state->linearVelocity = b2MulAdd(state->linearVelocity, bodySim->invMass, impulse); - state->angularVelocity += bodySim->invInertia * b2Cross(b2Sub(point, bodySim->center), impulse); + state->linearVelocity = b2MulAdd( state->linearVelocity, bodySim->invMass, impulse ); + state->angularVelocity += bodySim->invInertia * b2Cross( b2Sub( point, bodySim->center ), impulse ); } } -void b2Body_ApplyLinearImpulseToCenter(b2BodyId bodyId, b2Vec2 impulse, bool wake) +void b2Body_ApplyLinearImpulseToCenter( b2BodyId bodyId, b2Vec2 impulse, bool wake ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); - if (wake && body->setIndex >= b2_firstSleepingSet) + if ( wake && body->setIndex >= b2_firstSleepingSet ) { - b2WakeBody(world, body); + b2WakeBody( world, body ); } - if (body->setIndex == b2_awakeSet) + if ( body->setIndex == b2_awakeSet ) { int localIndex = body->localIndex; b2SolverSet* set = world->solverSetArray + b2_awakeSet; - B2_ASSERT(0 <= localIndex && localIndex < set->states.count); + B2_ASSERT( 0 <= localIndex && localIndex < set->states.count ); b2BodyState* state = set->states.data + localIndex; b2BodySim* bodySim = set->sims.data + localIndex; - state->linearVelocity = b2MulAdd(state->linearVelocity, bodySim->invMass, impulse); + state->linearVelocity = b2MulAdd( state->linearVelocity, bodySim->invMass, impulse ); } } -void b2Body_ApplyAngularImpulse(b2BodyId bodyId, float impulse, bool wake) +void b2Body_ApplyAngularImpulse( b2BodyId bodyId, float impulse, bool wake ) { - B2_ASSERT(b2Body_IsValid(bodyId)); - b2World* world = b2GetWorld(bodyId.world0); + B2_ASSERT( b2Body_IsValid( bodyId ) ); + b2World* world = b2GetWorld( bodyId.world0 ); int id = bodyId.index1 - 1; - b2CheckIndex(world->bodyArray, id); + b2CheckIndex( world->bodyArray, id ); b2Body* body = world->bodyArray + id; - B2_ASSERT(body->revision == bodyId.revision); + B2_ASSERT( body->revision == bodyId.revision ); - if (wake && body->setIndex >= b2_firstSleepingSet) + if ( wake && body->setIndex >= b2_firstSleepingSet ) { // this will not invalidate body pointer - b2WakeBody(world, body); + b2WakeBody( world, body ); } - if (body->setIndex == b2_awakeSet) + if ( body->setIndex == b2_awakeSet ) { int localIndex = body->localIndex; b2SolverSet* set = world->solverSetArray + b2_awakeSet; - B2_ASSERT(0 <= localIndex && localIndex < set->states.count); + B2_ASSERT( 0 <= localIndex && localIndex < set->states.count ); b2BodyState* state = set->states.data + localIndex; b2BodySim* sim = set->sims.data + localIndex; state->angularVelocity += sim->invInertia * impulse; } } -b2BodyType b2Body_GetType(b2BodyId bodyId) +b2BodyType b2Body_GetType( b2BodyId bodyId ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); return body->type; } @@ -925,46 +924,46 @@ b2BodyType b2Body_GetType(b2BodyId bodyId) // - graph coloring must be correct // - any body connected to a joint may be disabled // - joints between static bodies must go into the static set -void b2Body_SetType(b2BodyId bodyId, b2BodyType type) +void b2Body_SetType( b2BodyId bodyId, b2BodyType type ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); b2BodyType originalType = body->type; - if (originalType == type) + if ( originalType == type ) { return; } - if (body->setIndex == b2_disabledSet) + if ( body->setIndex == b2_disabledSet ) { // Disabled bodies don't change solver sets or islands when they change type. body->type = type; // Body type affects the mass - b2UpdateBodyMassData(world, body); + b2UpdateBodyMassData( world, body ); return; } - // Destroy all contacts but don't wake bodies. + // Destroy all contacts but don't wake bodies. bool wakeBodies = false; - b2DestroyBodyContacts(world, body, wakeBodies); + b2DestroyBodyContacts( world, body, wakeBodies ); // Wake this body because we assume below that it is awake or static. - b2WakeBody(world, body); + b2WakeBody( world, body ); // Unlink all joints and wake attached bodies. { int jointKey = body->headJointKey; - while (jointKey != B2_NULL_INDEX) + while ( jointKey != B2_NULL_INDEX ) { int jointId = jointKey >> 1; int edgeIndex = jointKey & 1; b2Joint* joint = world->jointArray + jointId; - if (joint->islandId != B2_NULL_INDEX) + if ( joint->islandId != B2_NULL_INDEX ) { - b2UnlinkJoint(world, joint); + b2UnlinkJoint( world, joint ); } // A body going from static to dynamic or kinematic goes to the awake set @@ -972,8 +971,8 @@ void b2Body_SetType(b2BodyId bodyId, b2BodyType type) // done for all cases. b2Body* bodyA = world->bodyArray + joint->edges[0].bodyId; b2Body* bodyB = world->bodyArray + joint->edges[1].bodyId; - b2WakeBody(world, bodyA); - b2WakeBody(world, bodyB); + b2WakeBody( world, bodyA ); + b2WakeBody( world, bodyB ); jointKey = joint->edges[edgeIndex].nextKey; } @@ -981,23 +980,23 @@ void b2Body_SetType(b2BodyId bodyId, b2BodyType type) body->type = type; - if (originalType == b2_staticBody) + if ( originalType == b2_staticBody ) { // Body is going from static to dynamic or kinematic. It only makes sense to move it to the awake set. - B2_ASSERT(body->setIndex == b2_staticSet); + B2_ASSERT( body->setIndex == b2_staticSet ); b2SolverSet* staticSet = world->solverSetArray + b2_staticSet; b2SolverSet* awakeSet = world->solverSetArray + b2_awakeSet; // Transfer body to awake set - b2TransferBody(world, awakeSet, staticSet, body); + b2TransferBody( world, awakeSet, staticSet, body ); // Create island for body - b2CreateIslandForBody(world, b2_awakeSet, body); + b2CreateIslandForBody( world, b2_awakeSet, body ); // Transfer static joints to awake set int jointKey = body->headJointKey; - while (jointKey != B2_NULL_INDEX) + while ( jointKey != B2_NULL_INDEX ) { int jointId = jointKey >> 1; int edgeIndex = jointKey & 1; @@ -1005,60 +1004,60 @@ void b2Body_SetType(b2BodyId bodyId, b2BodyType type) b2Joint* joint = world->jointArray + jointId; // Transfer the joint if it is in the static set - if (joint->setIndex == b2_staticSet) + if ( joint->setIndex == b2_staticSet ) { - b2TransferJoint(world, awakeSet, staticSet, joint); + b2TransferJoint( world, awakeSet, staticSet, joint ); } - else if (joint->setIndex == b2_awakeSet) + else if ( joint->setIndex == b2_awakeSet ) { // In this case the joint must be re-inserted into the constraint graph to ensure the correct // graph color. // First transfer to the static set. - b2TransferJoint(world, staticSet, awakeSet, joint); + b2TransferJoint( world, staticSet, awakeSet, joint ); // Now transfer it back to the awake set and into the graph coloring. - b2TransferJoint(world, awakeSet, staticSet, joint); + b2TransferJoint( world, awakeSet, staticSet, joint ); } else { // Otherwise the joint must be disabled. - B2_ASSERT(joint->setIndex == b2_disabledSet); + B2_ASSERT( joint->setIndex == b2_disabledSet ); } jointKey = joint->edges[edgeIndex].nextKey; } // Recreate shape proxies in movable tree. - b2Transform transform = b2GetBodyTransformQuick(world, body); + b2Transform transform = b2GetBodyTransformQuick( world, body ); int shapeId = body->headShapeId; - while (shapeId != B2_NULL_INDEX) + while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = world->shapeArray + shapeId; shapeId = shape->nextShapeId; - b2DestroyShapeProxy(shape, &world->broadPhase); + b2DestroyShapeProxy( shape, &world->broadPhase ); bool forcePairCreation = true; b2BodyType proxyType = type; - b2CreateShapeProxy(shape, &world->broadPhase, proxyType, transform, forcePairCreation); + b2CreateShapeProxy( shape, &world->broadPhase, proxyType, transform, forcePairCreation ); } } - else if (type == b2_staticBody) + else if ( type == b2_staticBody ) { // The body is going from dynamic/kinematic to static. It should be awake. - B2_ASSERT(body->setIndex == b2_awakeSet); + B2_ASSERT( body->setIndex == b2_awakeSet ); b2SolverSet* staticSet = world->solverSetArray + b2_staticSet; b2SolverSet* awakeSet = world->solverSetArray + b2_awakeSet; // Transfer body to static set - b2TransferBody(world, staticSet, awakeSet, body); + b2TransferBody( world, staticSet, awakeSet, body ); // Remove body from island. - b2RemoveBodyFromIsland(world, body); + b2RemoveBodyFromIsland( world, body ); // Maybe transfer joints to static set. int jointKey = body->headJointKey; - while (jointKey != B2_NULL_INDEX) + while ( jointKey != B2_NULL_INDEX ) { int jointId = jointKey >> 1; int edgeIndex = jointKey & 1; @@ -1070,75 +1069,75 @@ void b2Body_SetType(b2BodyId bodyId, b2BodyType type) b2Body* otherBody = world->bodyArray + joint->edges[otherEdgeIndex].bodyId; // Skip disabled joint - if (joint->setIndex == b2_disabledSet) + if ( joint->setIndex == b2_disabledSet ) { // Joint is disable, should be connected to a disabled body - B2_ASSERT(otherBody->setIndex == b2_disabledSet); + B2_ASSERT( otherBody->setIndex == b2_disabledSet ); continue; } // Since the body was not static, the joint must be awake. - B2_ASSERT(joint->setIndex == b2_awakeSet); + B2_ASSERT( joint->setIndex == b2_awakeSet ); // Only transfer joint to static set if both bodies are static. - if (otherBody->setIndex == b2_staticSet) + if ( otherBody->setIndex == b2_staticSet ) { - b2TransferJoint(world, staticSet, awakeSet, joint); + b2TransferJoint( world, staticSet, awakeSet, joint ); } else { // The other body must be awake. - B2_ASSERT(otherBody->setIndex == b2_awakeSet); + B2_ASSERT( otherBody->setIndex == b2_awakeSet ); // The joint must live in a graph color. - B2_ASSERT(0 <= joint->colorIndex && joint->colorIndex < b2_graphColorCount); + B2_ASSERT( 0 <= joint->colorIndex && joint->colorIndex < b2_graphColorCount ); // In this case the joint must be re-inserted into the constraint graph to ensure the correct // graph color. // First transfer to the static set. - b2TransferJoint(world, staticSet, awakeSet, joint); + b2TransferJoint( world, staticSet, awakeSet, joint ); // Now transfer it back to the awake set and into the graph coloring. - b2TransferJoint(world, awakeSet, staticSet, joint); + b2TransferJoint( world, awakeSet, staticSet, joint ); } } - + // Recreate shape proxies in static tree. - b2Transform transform = b2GetBodyTransformQuick(world, body); + b2Transform transform = b2GetBodyTransformQuick( world, body ); int shapeId = body->headShapeId; - while (shapeId != B2_NULL_INDEX) + while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = world->shapeArray + shapeId; shapeId = shape->nextShapeId; - b2DestroyShapeProxy(shape, &world->broadPhase); + b2DestroyShapeProxy( shape, &world->broadPhase ); bool forcePairCreation = true; - b2CreateShapeProxy(shape, &world->broadPhase, b2_staticBody, transform, forcePairCreation); + b2CreateShapeProxy( shape, &world->broadPhase, b2_staticBody, transform, forcePairCreation ); } } else { - B2_ASSERT(originalType == b2_dynamicBody || originalType == b2_kinematicBody); - B2_ASSERT(type == b2_dynamicBody || type == b2_kinematicBody); + B2_ASSERT( originalType == b2_dynamicBody || originalType == b2_kinematicBody ); + B2_ASSERT( type == b2_dynamicBody || type == b2_kinematicBody ); // Recreate shape proxies in static tree. - b2Transform transform = b2GetBodyTransformQuick(world, body); + b2Transform transform = b2GetBodyTransformQuick( world, body ); int shapeId = body->headShapeId; - while (shapeId != B2_NULL_INDEX) + while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = world->shapeArray + shapeId; shapeId = shape->nextShapeId; - b2DestroyShapeProxy(shape, &world->broadPhase); + b2DestroyShapeProxy( shape, &world->broadPhase ); b2BodyType proxyType = type; bool forcePairCreation = true; - b2CreateShapeProxy(shape, &world->broadPhase, proxyType, transform, forcePairCreation); + b2CreateShapeProxy( shape, &world->broadPhase, proxyType, transform, forcePairCreation ); } } // Relink all joints { int jointKey = body->headJointKey; - while (jointKey != B2_NULL_INDEX) + while ( jointKey != B2_NULL_INDEX ) { int jointId = jointKey >> 1; int edgeIndex = jointKey & 1; @@ -1148,96 +1147,96 @@ void b2Body_SetType(b2BodyId bodyId, b2BodyType type) int otherEdgeIndex = edgeIndex ^ 1; int otherBodyId = joint->edges[otherEdgeIndex].bodyId; - b2CheckIndex(world->bodyArray, otherBodyId); + b2CheckIndex( world->bodyArray, otherBodyId ); b2Body* otherBody = world->bodyArray + otherBodyId; - if (otherBody->setIndex == b2_disabledSet) + if ( otherBody->setIndex == b2_disabledSet ) { continue; } - if (body->type == b2_staticBody && otherBody->type == b2_staticBody) + if ( body->type == b2_staticBody && otherBody->type == b2_staticBody ) { continue; } - b2LinkJoint(world, joint); + b2LinkJoint( world, joint ); } } - + // Body type affects the mass - b2UpdateBodyMassData(world, body); + b2UpdateBodyMassData( world, body ); - b2ValidateConnectivity(world); - b2ValidateSolverSets(world); + b2ValidateConnectivity( world ); + b2ValidateSolverSets( world ); } -void b2Body_SetUserData(b2BodyId bodyId, void* userData) +void b2Body_SetUserData( b2BodyId bodyId, void* userData ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); body->userData = userData; } -void* b2Body_GetUserData(b2BodyId bodyId) +void* b2Body_GetUserData( b2BodyId bodyId ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); return body->userData; } -float b2Body_GetMass(b2BodyId bodyId) +float b2Body_GetMass( b2BodyId bodyId ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); - b2BodySim* bodySim = b2GetBodySim(world, body); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); + b2BodySim* bodySim = b2GetBodySim( world, body ); return bodySim->mass; } -float b2Body_GetInertiaTensor(b2BodyId bodyId) +float b2Body_GetInertiaTensor( b2BodyId bodyId ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); - b2BodySim* bodySim = b2GetBodySim(world, body); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); + b2BodySim* bodySim = b2GetBodySim( world, body ); return bodySim->inertia; } -b2Vec2 b2Body_GetLocalCenterOfMass(b2BodyId bodyId) +b2Vec2 b2Body_GetLocalCenterOfMass( b2BodyId bodyId ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); - b2BodySim* bodySim = b2GetBodySim(world, body); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); + b2BodySim* bodySim = b2GetBodySim( world, body ); return bodySim->localCenter; } -b2Vec2 b2Body_GetWorldCenterOfMass(b2BodyId bodyId) +b2Vec2 b2Body_GetWorldCenterOfMass( b2BodyId bodyId ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); - b2BodySim* bodySim = b2GetBodySim(world, body); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); + b2BodySim* bodySim = b2GetBodySim( world, body ); return bodySim->center; } -void b2Body_SetMassData(b2BodyId bodyId, b2MassData massData) +void b2Body_SetMassData( b2BodyId bodyId, b2MassData massData ) { - B2_ASSERT(b2IsValid(massData.mass) && massData.mass >= 0.0f); - B2_ASSERT(b2IsValid(massData.rotationalInertia) && massData.rotationalInertia >= 0.0f); - B2_ASSERT(b2Vec2_IsValid(massData.center)); + B2_ASSERT( b2IsValid( massData.mass ) && massData.mass >= 0.0f ); + B2_ASSERT( b2IsValid( massData.rotationalInertia ) && massData.rotationalInertia >= 0.0f ); + B2_ASSERT( b2Vec2_IsValid( massData.center ) ); - b2World* world = b2GetWorldLocked(bodyId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( bodyId.world0 ); + if ( world == NULL ) { return; } - b2Body* body = b2GetBodyFullId(world, bodyId); - b2BodySim* bodySim = b2GetBodySim(world, body); + b2Body* body = b2GetBodyFullId( world, bodyId ); + b2BodySim* bodySim = b2GetBodySim( world, body ); bodySim->mass = massData.mass; bodySim->inertia = massData.rotationalInertia; bodySim->localCenter = massData.center; - b2Vec2 center = b2TransformPoint(bodySim->transform, massData.center); + b2Vec2 center = b2TransformPoint( bodySim->transform, massData.center ); bodySim->center = center; bodySim->center0 = center; @@ -1245,208 +1244,208 @@ void b2Body_SetMassData(b2BodyId bodyId, b2MassData massData) bodySim->invInertia = bodySim->inertia > 0.0f ? 1.0f / bodySim->inertia : 0.0f; } -b2MassData b2Body_GetMassData(b2BodyId bodyId) +b2MassData b2Body_GetMassData( b2BodyId bodyId ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); - b2BodySim* bodySim = b2GetBodySim(world, body); - b2MassData massData = {bodySim->mass, bodySim->localCenter, bodySim->inertia}; + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); + b2BodySim* bodySim = b2GetBodySim( world, body ); + b2MassData massData = { bodySim->mass, bodySim->localCenter, bodySim->inertia }; return massData; } -void b2Body_ApplyMassFromShapes(b2BodyId bodyId) +void b2Body_ApplyMassFromShapes( b2BodyId bodyId ) { - b2World* world = b2GetWorldLocked(bodyId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( bodyId.world0 ); + if ( world == NULL ) { return; } - b2Body* body = b2GetBodyFullId(world, bodyId); - b2UpdateBodyMassData(world, body); + b2Body* body = b2GetBodyFullId( world, bodyId ); + b2UpdateBodyMassData( world, body ); } -void b2Body_SetAutomaticMass(b2BodyId bodyId, bool automaticMass) +void b2Body_SetAutomaticMass( b2BodyId bodyId, bool automaticMass ) { - b2World* world = b2GetWorldLocked(bodyId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( bodyId.world0 ); + if ( world == NULL ) { return; } - b2Body* body = b2GetBodyFullId(world, bodyId); + b2Body* body = b2GetBodyFullId( world, bodyId ); body->automaticMass = automaticMass; } -bool b2Body_GetAutomaticMass(b2BodyId bodyId) +bool b2Body_GetAutomaticMass( b2BodyId bodyId ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); return body->automaticMass; } -void b2Body_SetLinearDamping(b2BodyId bodyId, float linearDamping) +void b2Body_SetLinearDamping( b2BodyId bodyId, float linearDamping ) { - B2_ASSERT(b2IsValid(linearDamping) && linearDamping >= 0.0f); + B2_ASSERT( b2IsValid( linearDamping ) && linearDamping >= 0.0f ); - b2World* world = b2GetWorldLocked(bodyId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( bodyId.world0 ); + if ( world == NULL ) { return; } - b2Body* body = b2GetBodyFullId(world, bodyId); - b2BodySim* bodySim = b2GetBodySim(world, body); + b2Body* body = b2GetBodyFullId( world, bodyId ); + b2BodySim* bodySim = b2GetBodySim( world, body ); bodySim->linearDamping = linearDamping; } -float b2Body_GetLinearDamping(b2BodyId bodyId) +float b2Body_GetLinearDamping( b2BodyId bodyId ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); - b2BodySim* bodySim = b2GetBodySim(world, body); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); + b2BodySim* bodySim = b2GetBodySim( world, body ); return bodySim->linearDamping; } -void b2Body_SetAngularDamping(b2BodyId bodyId, float angularDamping) +void b2Body_SetAngularDamping( b2BodyId bodyId, float angularDamping ) { - B2_ASSERT(b2IsValid(angularDamping) && angularDamping >= 0.0f); + B2_ASSERT( b2IsValid( angularDamping ) && angularDamping >= 0.0f ); - b2World* world = b2GetWorldLocked(bodyId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( bodyId.world0 ); + if ( world == NULL ) { return; } - b2Body* body = b2GetBodyFullId(world, bodyId); - b2BodySim* bodySim = b2GetBodySim(world, body); + b2Body* body = b2GetBodyFullId( world, bodyId ); + b2BodySim* bodySim = b2GetBodySim( world, body ); bodySim->angularDamping = angularDamping; } -float b2Body_GetAngularDamping(b2BodyId bodyId) +float b2Body_GetAngularDamping( b2BodyId bodyId ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); - b2BodySim* bodySim = b2GetBodySim(world, body); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); + b2BodySim* bodySim = b2GetBodySim( world, body ); return bodySim->angularDamping; } -void b2Body_SetGravityScale(b2BodyId bodyId, float gravityScale) +void b2Body_SetGravityScale( b2BodyId bodyId, float gravityScale ) { - B2_ASSERT(b2Body_IsValid(bodyId)); - B2_ASSERT(b2IsValid(gravityScale)); + B2_ASSERT( b2Body_IsValid( bodyId ) ); + B2_ASSERT( b2IsValid( gravityScale ) ); - b2World* world = b2GetWorldLocked(bodyId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( bodyId.world0 ); + if ( world == NULL ) { return; } - b2Body* body = b2GetBodyFullId(world, bodyId); - b2BodySim* bodySim = b2GetBodySim(world, body); + b2Body* body = b2GetBodyFullId( world, bodyId ); + b2BodySim* bodySim = b2GetBodySim( world, body ); bodySim->gravityScale = gravityScale; } -float b2Body_GetGravityScale(b2BodyId bodyId) +float b2Body_GetGravityScale( b2BodyId bodyId ) { - B2_ASSERT(b2Body_IsValid(bodyId)); - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); - b2BodySim* bodySim = b2GetBodySim(world, body); + B2_ASSERT( b2Body_IsValid( bodyId ) ); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); + b2BodySim* bodySim = b2GetBodySim( world, body ); return bodySim->gravityScale; } -bool b2Body_IsAwake(b2BodyId bodyId) +bool b2Body_IsAwake( b2BodyId bodyId ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); return body->setIndex == b2_awakeSet; } -void b2Body_SetAwake(b2BodyId bodyId, bool awake) +void b2Body_SetAwake( b2BodyId bodyId, bool awake ) { - b2World* world = b2GetWorldLocked(bodyId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( bodyId.world0 ); + if ( world == NULL ) { return; } - b2Body* body = b2GetBodyFullId(world, bodyId); + b2Body* body = b2GetBodyFullId( world, bodyId ); - if (awake && body->setIndex >= b2_firstSleepingSet) + if ( awake && body->setIndex >= b2_firstSleepingSet ) { - b2WakeBody(world, body); + b2WakeBody( world, body ); } - else if (awake == false && body->setIndex == b2_awakeSet) + else if ( awake == false && body->setIndex == b2_awakeSet ) { - b2CheckIndex(world->islandArray, body->islandId); + b2CheckIndex( world->islandArray, body->islandId ); b2Island* island = world->islandArray + body->islandId; - if (island->constraintRemoveCount > 0) + if ( island->constraintRemoveCount > 0 ) { - b2SplitIsland(world, body->islandId); + b2SplitIsland( world, body->islandId ); } - b2TrySleepIsland(world, body->islandId); + b2TrySleepIsland( world, body->islandId ); } } -bool b2Body_IsEnabled(b2BodyId bodyId) +bool b2Body_IsEnabled( b2BodyId bodyId ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); return body->setIndex != b2_disabledSet; } -bool b2Body_IsSleepEnabled(b2BodyId bodyId) +bool b2Body_IsSleepEnabled( b2BodyId bodyId ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); return body->enableSleep; } -void b2Body_SetSleepThreshold(b2BodyId bodyId, float sleepVelocity) +void b2Body_SetSleepThreshold( b2BodyId bodyId, float sleepVelocity ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); body->sleepThreshold = sleepVelocity; } -float b2Body_GetSleepThreshold(b2BodyId bodyId) +float b2Body_GetSleepThreshold( b2BodyId bodyId ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); return body->sleepThreshold; } -void b2Body_EnableSleep(b2BodyId bodyId, bool enableSleep) +void b2Body_EnableSleep( b2BodyId bodyId, bool enableSleep ) { - b2World* world = b2GetWorldLocked(bodyId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( bodyId.world0 ); + if ( world == NULL ) { return; } - b2Body* body = b2GetBodyFullId(world, bodyId); + b2Body* body = b2GetBodyFullId( world, bodyId ); body->enableSleep = enableSleep; - if (enableSleep == false) + if ( enableSleep == false ) { - b2WakeBody(world, body); + b2WakeBody( world, body ); } } // Disabling a body requires a lot of detailed bookkeeping, but it is a valuable feature. // The most challenging aspect that joints may connect to bodies that are not disabled. -void b2Body_Disable(b2BodyId bodyId) +void b2Body_Disable( b2BodyId bodyId ) { - b2World* world = b2GetWorldLocked(bodyId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( bodyId.world0 ); + if ( world == NULL ) { return; } - b2Body* body = b2GetBodyFullId(world, bodyId); - if (body->setIndex == b2_disabledSet) + b2Body* body = b2GetBodyFullId( world, bodyId ); + if ( body->setIndex == b2_disabledSet ) { return; } @@ -1454,31 +1453,31 @@ void b2Body_Disable(b2BodyId bodyId) // Destroy contacts and wake bodies touching this body. This avoid floating bodies. // This is necessary even for static bodies. bool wakeBodies = true; - b2DestroyBodyContacts(world, body, wakeBodies); + b2DestroyBodyContacts( world, body, wakeBodies ); // Disabled bodies are not in an island. - b2RemoveBodyFromIsland(world, body); + b2RemoveBodyFromIsland( world, body ); // Remove shapes from broad-phase int shapeId = body->headShapeId; - while (shapeId != B2_NULL_INDEX) + while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = world->shapeArray + shapeId; shapeId = shape->nextShapeId; - b2DestroyShapeProxy(shape, &world->broadPhase); + b2DestroyShapeProxy( shape, &world->broadPhase ); } // Transfer simulation data to disabled set - b2CheckIndex(world->solverSetArray, body->setIndex); + b2CheckIndex( world->solverSetArray, body->setIndex ); b2SolverSet* set = world->solverSetArray + body->setIndex; b2SolverSet* disabledSet = world->solverSetArray + b2_disabledSet; // Transfer body sim - b2TransferBody(world, disabledSet, set, body); + b2TransferBody( world, disabledSet, set, body ); // Unlink joints and transfer int jointKey = body->headJointKey; - while (jointKey != B2_NULL_INDEX) + while ( jointKey != B2_NULL_INDEX ) { int jointId = jointKey >> 1; int edgeIndex = jointKey & 1; @@ -1487,39 +1486,39 @@ void b2Body_Disable(b2BodyId bodyId) jointKey = joint->edges[edgeIndex].nextKey; // joint may already be disabled by other body - if (joint->setIndex == b2_disabledSet) + if ( joint->setIndex == b2_disabledSet ) { continue; } - B2_ASSERT(joint->setIndex == set->setIndex || set->setIndex == b2_staticSet); + B2_ASSERT( joint->setIndex == set->setIndex || set->setIndex == b2_staticSet ); // Remove joint from island - if (joint->islandId != B2_NULL_INDEX) + if ( joint->islandId != B2_NULL_INDEX ) { - b2UnlinkJoint(world, joint); + b2UnlinkJoint( world, joint ); } // Transfer joint to disabled set - b2CheckIndex(world->solverSetArray, joint->setIndex); + b2CheckIndex( world->solverSetArray, joint->setIndex ); b2SolverSet* jointSet = world->solverSetArray + joint->setIndex; - b2TransferJoint(world, disabledSet, jointSet, joint); + b2TransferJoint( world, disabledSet, jointSet, joint ); } - b2ValidateConnectivity(world); - b2ValidateSolverSets(world); + b2ValidateConnectivity( world ); + b2ValidateSolverSets( world ); } -void b2Body_Enable(b2BodyId bodyId) +void b2Body_Enable( b2BodyId bodyId ) { - b2World* world = b2GetWorldLocked(bodyId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( bodyId.world0 ); + if ( world == NULL ) { return; } - b2Body* body = b2GetBodyFullId(world, bodyId); - if (body->setIndex != b2_disabledSet) + b2Body* body = b2GetBodyFullId( world, bodyId ); + if ( body->setIndex != b2_disabledSet ) { return; } @@ -1528,45 +1527,45 @@ void b2Body_Enable(b2BodyId bodyId) int setId = body->type == b2_staticBody ? b2_staticSet : b2_awakeSet; b2SolverSet* targetSet = world->solverSetArray + setId; - b2TransferBody(world, targetSet, disabledSet, body); + b2TransferBody( world, targetSet, disabledSet, body ); - b2Transform transform = b2GetBodyTransformQuick(world, body); + b2Transform transform = b2GetBodyTransformQuick( world, body ); // Add shapes to broad-phase b2BodyType proxyType = body->type; bool forcePairCreation = true; int shapeId = body->headShapeId; - while (shapeId != B2_NULL_INDEX) + while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = world->shapeArray + shapeId; shapeId = shape->nextShapeId; - b2CreateShapeProxy(shape, &world->broadPhase, proxyType, transform, forcePairCreation); + b2CreateShapeProxy( shape, &world->broadPhase, proxyType, transform, forcePairCreation ); } - if (setId != b2_staticSet) + if ( setId != b2_staticSet ) { - b2CreateIslandForBody(world, setId, body); + b2CreateIslandForBody( world, setId, body ); } // Transfer joints. If the other body is disabled, don't transfer. // If the other body is sleeping, wake it. int jointKey = body->headJointKey; - while (jointKey != B2_NULL_INDEX) + while ( jointKey != B2_NULL_INDEX ) { int jointId = jointKey >> 1; int edgeIndex = jointKey & 1; b2Joint* joint = world->jointArray + jointId; - B2_ASSERT(joint->setIndex == b2_disabledSet); - B2_ASSERT(joint->islandId == B2_NULL_INDEX); + B2_ASSERT( joint->setIndex == b2_disabledSet ); + B2_ASSERT( joint->islandId == B2_NULL_INDEX ); jointKey = joint->edges[edgeIndex].nextKey; b2Body* bodyA = world->bodyArray + joint->edges[0].bodyId; b2Body* bodyB = world->bodyArray + joint->edges[1].bodyId; - if (bodyA->setIndex == b2_disabledSet || bodyB->setIndex == b2_disabledSet) + if ( bodyA->setIndex == b2_disabledSet || bodyB->setIndex == b2_disabledSet ) { // one body is still disabled continue; @@ -1574,11 +1573,11 @@ void b2Body_Enable(b2BodyId bodyId) // Transfer joint first int jointSetId; - if (bodyA->setIndex == b2_staticSet && bodyB->setIndex == b2_staticSet) + if ( bodyA->setIndex == b2_staticSet && bodyB->setIndex == b2_staticSet ) { jointSetId = b2_staticSet; } - else if (bodyA->setIndex == b2_staticSet) + else if ( bodyA->setIndex == b2_staticSet ) { jointSetId = bodyB->setIndex; } @@ -1587,77 +1586,77 @@ void b2Body_Enable(b2BodyId bodyId) jointSetId = bodyA->setIndex; } - b2CheckIndex(world->solverSetArray, jointSetId); + b2CheckIndex( world->solverSetArray, jointSetId ); b2SolverSet* jointSet = world->solverSetArray + jointSetId; - b2TransferJoint(world, jointSet, disabledSet, joint); + b2TransferJoint( world, jointSet, disabledSet, joint ); // Now that the joint is in the correct set, I can link the joint in the island. - if (jointSetId != b2_staticSet) + if ( jointSetId != b2_staticSet ) { - b2LinkJoint(world, joint); + b2LinkJoint( world, joint ); } } - b2ValidateConnectivity(world); - b2ValidateSolverSets(world); + b2ValidateConnectivity( world ); + b2ValidateSolverSets( world ); } -void b2Body_SetFixedRotation(b2BodyId bodyId, bool flag) +void b2Body_SetFixedRotation( b2BodyId bodyId, bool flag ) { - b2World* world = b2GetWorldLocked(bodyId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( bodyId.world0 ); + if ( world == NULL ) { return; } - b2Body* body = b2GetBodyFullId(world, bodyId); - if (body->fixedRotation != flag) + b2Body* body = b2GetBodyFullId( world, bodyId ); + if ( body->fixedRotation != flag ) { body->fixedRotation = flag; - b2BodyState* state = b2GetBodyState(world, body); - if (state != NULL) + b2BodyState* state = b2GetBodyState( world, body ); + if ( state != NULL ) { state->angularVelocity = 0.0f; } - b2UpdateBodyMassData(world, body); + b2UpdateBodyMassData( world, body ); } } -bool b2Body_IsFixedRotation(b2BodyId bodyId) +bool b2Body_IsFixedRotation( b2BodyId bodyId ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); return body->fixedRotation; } -void b2Body_SetBullet(b2BodyId bodyId, bool flag) +void b2Body_SetBullet( b2BodyId bodyId, bool flag ) { - b2World* world = b2GetWorldLocked(bodyId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( bodyId.world0 ); + if ( world == NULL ) { return; } - b2Body* body = b2GetBodyFullId(world, bodyId); - b2BodySim* bodySim = b2GetBodySim(world, body); + b2Body* body = b2GetBodyFullId( world, bodyId ); + b2BodySim* bodySim = b2GetBodySim( world, body ); bodySim->isBullet = flag; } -bool b2Body_IsBullet(b2BodyId bodyId) +bool b2Body_IsBullet( b2BodyId bodyId ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); - b2BodySim* bodySim = b2GetBodySim(world, body); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); + b2BodySim* bodySim = b2GetBodySim( world, body ); return bodySim->isBullet; } -void b2Body_EnableHitEvents(b2BodyId bodyId, bool enableHitEvents) +void b2Body_EnableHitEvents( b2BodyId bodyId, bool enableHitEvents ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); int shapeId = body->headShapeId; - while (shapeId != B2_NULL_INDEX) + while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = world->shapeArray + shapeId; shape->enableHitEvents = enableHitEvents; @@ -1665,73 +1664,73 @@ void b2Body_EnableHitEvents(b2BodyId bodyId, bool enableHitEvents) } } -int b2Body_GetShapeCount(b2BodyId bodyId) +int b2Body_GetShapeCount( b2BodyId bodyId ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); return body->shapeCount; } -int b2Body_GetShapes(b2BodyId bodyId, b2ShapeId* shapeArray, int capacity) +int b2Body_GetShapes( b2BodyId bodyId, b2ShapeId* shapeArray, int capacity ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); int shapeId = body->headShapeId; int shapeCount = 0; - while (shapeId != B2_NULL_INDEX && shapeCount < capacity) + while ( shapeId != B2_NULL_INDEX && shapeCount < capacity ) { b2Shape* shape = world->shapeArray + shapeId; - b2ShapeId id = {shape->id + 1, bodyId.world0, shape->revision}; + b2ShapeId id = { shape->id + 1, bodyId.world0, shape->revision }; shapeArray[shapeCount] = id; shapeCount += 1; - + shapeId = shape->nextShapeId; } return shapeCount; } -int b2Body_GetJointCount(b2BodyId bodyId) +int b2Body_GetJointCount( b2BodyId bodyId ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); return body->jointCount; } -int b2Body_GetJoints(b2BodyId bodyId, b2JointId* jointArray, int capacity) +int b2Body_GetJoints( b2BodyId bodyId, b2JointId* jointArray, int capacity ) { - b2World* world = b2GetWorld(bodyId.world0); - b2Body* body = b2GetBodyFullId(world, bodyId); + b2World* world = b2GetWorld( bodyId.world0 ); + b2Body* body = b2GetBodyFullId( world, bodyId ); int jointKey = body->headJointKey; int jointCount = 0; - while (jointKey != B2_NULL_INDEX && jointCount < capacity) + while ( jointKey != B2_NULL_INDEX && jointCount < capacity ) { int jointId = jointKey >> 1; int edgeIndex = jointKey & 1; - b2Joint* joint = b2GetJoint(world, jointId); + b2Joint* joint = b2GetJoint( world, jointId ); - b2JointId id = {jointId + 1, bodyId.world0, joint->revision}; + b2JointId id = { jointId + 1, bodyId.world0, joint->revision }; jointArray[jointCount] = id; jointCount += 1; - + jointKey = joint->edges[edgeIndex].nextKey; } return jointCount; } -bool b2ShouldBodiesCollide(b2World* world, b2Body* bodyA, b2Body* bodyB) +bool b2ShouldBodiesCollide( b2World* world, b2Body* bodyA, b2Body* bodyB ) { - if (bodyA->type != b2_dynamicBody && bodyB->type != b2_dynamicBody) + if ( bodyA->type != b2_dynamicBody && bodyB->type != b2_dynamicBody ) { return false; } int jointKey; int otherBodyId; - if (bodyA->jointCount < bodyB->jointCount) + if ( bodyA->jointCount < bodyB->jointCount ) { jointKey = bodyA->headJointKey; otherBodyId = bodyB->id; @@ -1742,14 +1741,14 @@ bool b2ShouldBodiesCollide(b2World* world, b2Body* bodyA, b2Body* bodyB) otherBodyId = bodyA->id; } - while (jointKey != B2_NULL_INDEX) + while ( jointKey != B2_NULL_INDEX ) { int jointId = jointKey >> 1; int edgeIndex = jointKey & 1; int otherEdgeIndex = edgeIndex ^ 1; - b2Joint* joint = b2GetJoint(world, jointId); - if (joint->collideConnected == false && joint->edges[otherEdgeIndex].bodyId == otherBodyId) + b2Joint* joint = b2GetJoint( world, jointId ); + if ( joint->collideConnected == false && joint->edges[otherEdgeIndex].bodyId == otherBodyId ) { return false; } diff --git a/src/body.h b/src/body.h index 47163aaf..c80126f0 100644 --- a/src/body.h +++ b/src/body.h @@ -88,7 +88,7 @@ typedef struct b2BodyState } b2BodyState; // Identity body state, notice the deltaRotation is {1, 0} -static const b2BodyState b2_identityBodyState = {{0.0f, 0.0f}, 0.0f, 0, {0.0f, 0.0f}, {1.0f, 0.0f}}; +static const b2BodyState b2_identityBodyState = { { 0.0f, 0.0f }, 0.0f, 0, { 0.0f, 0.0f }, { 1.0f, 0.0f } }; // Body simulation data used for integration of position and velocity // Transform data used for collision and solver preparation. @@ -132,31 +132,31 @@ typedef struct b2BodySim bool enlargeAABB; } b2BodySim; -b2Body* b2GetBodyFullId(b2World* world, b2BodyId bodyId); +b2Body* b2GetBodyFullId( b2World* world, b2BodyId bodyId ); -b2Body* b2GetBody(b2World* world, int bodyId); +b2Body* b2GetBody( b2World* world, int bodyId ); // Get a validated body from a world using an id. -b2Body* b2GetBodyFullId(b2World* world, b2BodyId bodyId); +b2Body* b2GetBodyFullId( b2World* world, b2BodyId bodyId ); -b2Transform b2GetBodyTransformQuick(b2World* world, b2Body* body); -b2Transform b2GetBodyTransform(b2World* world, int bodyId); +b2Transform b2GetBodyTransformQuick( b2World* world, b2Body* body ); +b2Transform b2GetBodyTransform( b2World* world, int bodyId ); // Create a b2BodyId from a raw id. -b2BodyId b2MakeBodyId(b2World* world, int bodyId); +b2BodyId b2MakeBodyId( b2World* world, int bodyId ); -bool b2ShouldBodiesCollide(b2World* world, b2Body* bodyA, b2Body* bodyB); -bool b2IsBodyAwake(b2World* world, b2Body* body); +bool b2ShouldBodiesCollide( b2World* world, b2Body* bodyA, b2Body* bodyB ); +bool b2IsBodyAwake( b2World* world, b2Body* body ); -b2BodySim* b2GetBodySim(b2World* world, b2Body* body); -b2BodyState* b2GetBodyState(b2World* world, b2Body* body); +b2BodySim* b2GetBodySim( b2World* world, b2Body* body ); +b2BodyState* b2GetBodyState( b2World* world, b2Body* body ); // careful calling this because it can invalidate body, state, joint, and contact pointers -bool b2WakeBody(b2World* world, b2Body* body); +bool b2WakeBody( b2World* world, b2Body* body ); -void b2UpdateBodyMassData(b2World* world, b2Body* body); +void b2UpdateBodyMassData( b2World* world, b2Body* body ); -static inline b2Sweep b2MakeSweep(const b2BodySim* bodySim) +static inline b2Sweep b2MakeSweep( const b2BodySim* bodySim ) { b2Sweep s; s.c1 = bodySim->center0; diff --git a/src/broad_phase.c b/src/broad_phase.c index f8f402f2..8e144abe 100644 --- a/src/broad_phase.c +++ b/src/broad_phase.c @@ -7,12 +7,12 @@ #include "aabb.h" #include "allocate.h" -#include "stack_allocator.h" #include "array.h" #include "body.h" #include "contact.h" #include "core.h" #include "shape.h" +#include "stack_allocator.h" #include "world.h" #include @@ -23,9 +23,9 @@ // static FILE* s_file = NULL; -void b2CreateBroadPhase(b2BroadPhase* bp) +void b2CreateBroadPhase( b2BroadPhase* bp ) { - _Static_assert(b2_bodyTypeCount == 3, "must be three body types"); + _Static_assert( b2_bodyTypeCount == 3, "must be three body types" ); // if (s_file == NULL) //{ @@ -34,32 +34,32 @@ void b2CreateBroadPhase(b2BroadPhase* bp) // } bp->proxyCount = 0; - bp->moveSet = b2CreateSet(16); - bp->moveArray = b2CreateArray(sizeof(int), 16); + bp->moveSet = b2CreateSet( 16 ); + bp->moveArray = b2CreateArray( sizeof( int ), 16 ); bp->moveResults = NULL; bp->movePairs = NULL; bp->movePairCapacity = 0; bp->movePairIndex = 0; - bp->pairSet = b2CreateSet(32); + bp->pairSet = b2CreateSet( 32 ); - for (int i = 0; i < b2_bodyTypeCount; ++i) + for ( int i = 0; i < b2_bodyTypeCount; ++i ) { bp->trees[i] = b2DynamicTree_Create(); } } -void b2DestroyBroadPhase(b2BroadPhase* bp) +void b2DestroyBroadPhase( b2BroadPhase* bp ) { - for (int i = 0; i < b2_bodyTypeCount; ++i) + for ( int i = 0; i < b2_bodyTypeCount; ++i ) { - b2DynamicTree_Destroy(bp->trees + i); + b2DynamicTree_Destroy( bp->trees + i ); } - b2DestroySet(&bp->moveSet); - b2DestroyArray(bp->moveArray, sizeof(int)); - b2DestroySet(&bp->pairSet); + b2DestroySet( &bp->moveSet ); + b2DestroyArray( bp->moveArray, sizeof( int ) ); + b2DestroySet( &bp->pairSet ); - memset(bp, 0, sizeof(b2BroadPhase)); + memset( bp, 0, sizeof( b2BroadPhase ) ); // if (s_file != NULL) //{ @@ -68,72 +68,72 @@ void b2DestroyBroadPhase(b2BroadPhase* bp) // } } -static inline void b2UnBufferMove(b2BroadPhase* bp, int proxyKey) +static inline void b2UnBufferMove( b2BroadPhase* bp, int proxyKey ) { - bool found = b2RemoveKey(&bp->moveSet, proxyKey + 1); + bool found = b2RemoveKey( &bp->moveSet, proxyKey + 1 ); - if (found) + if ( found ) { // Purge from move buffer. Linear search. // todo if I can iterate the move set then I don't need the moveArray - int count = b2Array(bp->moveArray).count; - for (int i = 0; i < count; ++i) + int count = b2Array( bp->moveArray ).count; + for ( int i = 0; i < count; ++i ) { - if (bp->moveArray[i] == proxyKey) + if ( bp->moveArray[i] == proxyKey ) { - b2Array_RemoveSwap(bp->moveArray, i); + b2Array_RemoveSwap( bp->moveArray, i ); break; } } } } -int b2BroadPhase_CreateProxy(b2BroadPhase* bp, b2BodyType proxyType, b2AABB aabb, uint32_t categoryBits, int shapeIndex, - bool forcePairCreation) +int b2BroadPhase_CreateProxy( b2BroadPhase* bp, b2BodyType proxyType, b2AABB aabb, uint32_t categoryBits, int shapeIndex, + bool forcePairCreation ) { - B2_ASSERT(0 <= proxyType && proxyType < b2_bodyTypeCount); - int proxyId = b2DynamicTree_CreateProxy(bp->trees + proxyType, aabb, categoryBits, shapeIndex); - int proxyKey = B2_PROXY_KEY(proxyId, proxyType); - if (proxyType != b2_staticBody || forcePairCreation) + B2_ASSERT( 0 <= proxyType && proxyType < b2_bodyTypeCount ); + int proxyId = b2DynamicTree_CreateProxy( bp->trees + proxyType, aabb, categoryBits, shapeIndex ); + int proxyKey = B2_PROXY_KEY( proxyId, proxyType ); + if ( proxyType != b2_staticBody || forcePairCreation ) { - b2BufferMove(bp, proxyKey); + b2BufferMove( bp, proxyKey ); } return proxyKey; } -void b2BroadPhase_DestroyProxy(b2BroadPhase* bp, int proxyKey) +void b2BroadPhase_DestroyProxy( b2BroadPhase* bp, int proxyKey ) { - B2_ASSERT(b2Array(bp->moveArray).count == (int)bp->moveSet.count); - b2UnBufferMove(bp, proxyKey); + B2_ASSERT( b2Array( bp->moveArray ).count == (int)bp->moveSet.count ); + b2UnBufferMove( bp, proxyKey ); --bp->proxyCount; - b2BodyType proxyType = B2_PROXY_TYPE(proxyKey); - int proxyId = B2_PROXY_ID(proxyKey); + b2BodyType proxyType = B2_PROXY_TYPE( proxyKey ); + int proxyId = B2_PROXY_ID( proxyKey ); - B2_ASSERT(0 <= proxyType && proxyType <= b2_bodyTypeCount); - b2DynamicTree_DestroyProxy(bp->trees + proxyType, proxyId); + B2_ASSERT( 0 <= proxyType && proxyType <= b2_bodyTypeCount ); + b2DynamicTree_DestroyProxy( bp->trees + proxyType, proxyId ); } -void b2BroadPhase_MoveProxy(b2BroadPhase* bp, int proxyKey, b2AABB aabb) +void b2BroadPhase_MoveProxy( b2BroadPhase* bp, int proxyKey, b2AABB aabb ) { - b2BodyType proxyType = B2_PROXY_TYPE(proxyKey); - int proxyId = B2_PROXY_ID(proxyKey); + b2BodyType proxyType = B2_PROXY_TYPE( proxyKey ); + int proxyId = B2_PROXY_ID( proxyKey ); - b2DynamicTree_MoveProxy(bp->trees + proxyType, proxyId, aabb); - b2BufferMove(bp, proxyKey); + b2DynamicTree_MoveProxy( bp->trees + proxyType, proxyId, aabb ); + b2BufferMove( bp, proxyKey ); } -void b2BroadPhase_EnlargeProxy(b2BroadPhase* bp, int proxyKey, b2AABB aabb) +void b2BroadPhase_EnlargeProxy( b2BroadPhase* bp, int proxyKey, b2AABB aabb ) { - B2_ASSERT(proxyKey != B2_NULL_INDEX); - int typeIndex = B2_PROXY_TYPE(proxyKey); - int proxyId = B2_PROXY_ID(proxyKey); + B2_ASSERT( proxyKey != B2_NULL_INDEX ); + int typeIndex = B2_PROXY_TYPE( proxyKey ); + int proxyId = B2_PROXY_ID( proxyKey ); - B2_ASSERT(typeIndex != b2_staticBody); + B2_ASSERT( typeIndex != b2_staticBody ); - b2DynamicTree_EnlargeProxy(bp->trees + typeIndex, proxyId, aabb); - b2BufferMove(bp, proxyKey); + b2DynamicTree_EnlargeProxy( bp->trees + typeIndex, proxyId, aabb ); + b2BufferMove( bp, proxyKey ); } typedef struct b2MovePair @@ -159,39 +159,39 @@ typedef struct b2QueryPairContext } b2QueryPairContext; // This is called from b2DynamicTree::Query when we are gathering pairs. -static bool b2PairQueryCallback(int proxyId, int shapeId, void* context) +static bool b2PairQueryCallback( int proxyId, int shapeId, void* context ) { b2QueryPairContext* queryContext = context; b2BroadPhase* bp = &queryContext->world->broadPhase; - int proxyKey = B2_PROXY_KEY(proxyId, queryContext->queryTreeType); + int proxyKey = B2_PROXY_KEY( proxyId, queryContext->queryTreeType ); // A proxy cannot form a pair with itself. - if (proxyKey == queryContext->queryProxyKey) + if ( proxyKey == queryContext->queryProxyKey ) { return true; } // Is this proxy also moving? - if (queryContext->queryTreeType != b2_staticBody) + if ( queryContext->queryTreeType != b2_staticBody ) { - bool moved = b2ContainsKey(&bp->moveSet, proxyKey + 1); - if (moved && proxyKey < queryContext->queryProxyKey) + bool moved = b2ContainsKey( &bp->moveSet, proxyKey + 1 ); + if ( moved && proxyKey < queryContext->queryProxyKey ) { // Both proxies are moving. Avoid duplicate pairs. return true; } } - uint64_t pairKey = B2_SHAPE_PAIR_KEY(shapeId, queryContext->queryShapeIndex); - if (b2ContainsKey(&bp->pairSet, pairKey)) + uint64_t pairKey = B2_SHAPE_PAIR_KEY( shapeId, queryContext->queryShapeIndex ); + if ( b2ContainsKey( &bp->pairSet, pairKey ) ) { // contact exists return true; } int shapeIdA, shapeIdB; - if (proxyKey < queryContext->queryProxyKey) + if ( proxyKey < queryContext->queryProxyKey ) { shapeIdA = shapeId; shapeIdB = queryContext->queryShapeIndex; @@ -204,8 +204,8 @@ static bool b2PairQueryCallback(int proxyId, int shapeId, void* context) b2World* world = queryContext->world; - b2CheckId(world->shapeArray, shapeIdA); - b2CheckId(world->shapeArray, shapeIdB); + b2CheckId( world->shapeArray, shapeIdA ); + b2CheckId( world->shapeArray, shapeIdB ); b2Shape* shapeA = world->shapeArray + shapeIdA; b2Shape* shapeB = world->shapeArray + shapeIdB; @@ -214,55 +214,55 @@ static bool b2PairQueryCallback(int proxyId, int shapeId, void* context) int bodyIdB = shapeB->bodyId; // Are the shapes on the same body? - if (bodyIdA == bodyIdB) + if ( bodyIdA == bodyIdB ) { return true; } - if (b2ShouldShapesCollide(shapeA->filter, shapeB->filter) == false) + if ( b2ShouldShapesCollide( shapeA->filter, shapeB->filter ) == false ) { return true; } // Sensors don't collide with other sensors - if (shapeA->isSensor == true && shapeB->isSensor == true) + if ( shapeA->isSensor == true && shapeB->isSensor == true ) { return true; } // Does a joint override collision? - b2Body* bodyA = b2GetBody(world, bodyIdA); - b2Body* bodyB = b2GetBody(world, bodyIdB); - if (b2ShouldBodiesCollide(world, bodyA, bodyB) == false) + b2Body* bodyA = b2GetBody( world, bodyIdA ); + b2Body* bodyB = b2GetBody( world, bodyIdB ); + if ( b2ShouldBodiesCollide( world, bodyA, bodyB ) == false ) { return true; } // Custom user filter b2CustomFilterFcn* customFilterFcn = queryContext->world->customFilterFcn; - if (customFilterFcn != NULL) + if ( customFilterFcn != NULL ) { - b2ShapeId idA = {shapeIdA + 1, world->worldId, shapeA->revision}; - b2ShapeId idB = {shapeIdB + 1, world->worldId, shapeB->revision}; - bool shouldCollide = customFilterFcn(idA, idB, queryContext->world->customFilterContext); - if (shouldCollide == false) + b2ShapeId idA = { shapeIdA + 1, world->worldId, shapeA->revision }; + b2ShapeId idB = { shapeIdB + 1, world->worldId, shapeB->revision }; + bool shouldCollide = customFilterFcn( idA, idB, queryContext->world->customFilterContext ); + if ( shouldCollide == false ) { return true; } } // #todo per thread to eliminate atomic? - int pairIndex = atomic_fetch_add(&bp->movePairIndex, 1); + int pairIndex = atomic_fetch_add( &bp->movePairIndex, 1 ); b2MovePair* pair; - if (pairIndex < bp->movePairCapacity) + if ( pairIndex < bp->movePairCapacity ) { pair = bp->movePairs + pairIndex; pair->heap = false; } else { - pair = b2Alloc(sizeof(b2MovePair)); + pair = b2Alloc( sizeof( b2MovePair ) ); pair->heap = true; } @@ -275,11 +275,11 @@ static bool b2PairQueryCallback(int proxyId, int shapeId, void* context) return true; } -void b2FindPairsTask(int startIndex, int endIndex, uint32_t threadIndex, void* context) +void b2FindPairsTask( int startIndex, int endIndex, uint32_t threadIndex, void* context ) { - b2TracyCZoneNC(pair_task, "Pair Task", b2_colorAquamarine3, true); + b2TracyCZoneNC( pair_task, "Pair Task", b2_colorAquamarine, true ); - B2_MAYBE_UNUSED(threadIndex); + B2_MAYBE_UNUSED( threadIndex ); b2World* world = context; b2BroadPhase* bp = &world->broadPhase; @@ -287,93 +287,93 @@ void b2FindPairsTask(int startIndex, int endIndex, uint32_t threadIndex, void* c b2QueryPairContext queryContext; queryContext.world = world; - for (int i = startIndex; i < endIndex; ++i) + for ( int i = startIndex; i < endIndex; ++i ) { // Initialize move result for this moved proxy queryContext.moveResult = bp->moveResults + i; queryContext.moveResult->pairList = NULL; int proxyKey = bp->moveArray[i]; - if (proxyKey == B2_NULL_INDEX) + if ( proxyKey == B2_NULL_INDEX ) { // proxy was destroyed after it moved continue; } - b2BodyType proxyType = B2_PROXY_TYPE(proxyKey); + b2BodyType proxyType = B2_PROXY_TYPE( proxyKey ); - int proxyId = B2_PROXY_ID(proxyKey); + int proxyId = B2_PROXY_ID( proxyKey ); queryContext.queryProxyKey = proxyKey; const b2DynamicTree* baseTree = bp->trees + proxyType; // We have to query the tree with the fat AABB so that // we don't fail to create a contact that may touch later. - b2AABB fatAABB = b2DynamicTree_GetAABB(baseTree, proxyId); - queryContext.queryShapeIndex = b2DynamicTree_GetUserData(baseTree, proxyId); + b2AABB fatAABB = b2DynamicTree_GetAABB( baseTree, proxyId ); + queryContext.queryShapeIndex = b2DynamicTree_GetUserData( baseTree, proxyId ); // Query trees. Only dynamic proxies collide with kinematic and static proxies - if (proxyType == b2_dynamicBody) + if ( proxyType == b2_dynamicBody ) { queryContext.queryTreeType = b2_kinematicBody; - b2DynamicTree_Query(bp->trees + b2_kinematicBody, fatAABB, b2_defaultMaskBits, b2PairQueryCallback, &queryContext); + b2DynamicTree_Query( bp->trees + b2_kinematicBody, fatAABB, b2_defaultMaskBits, b2PairQueryCallback, &queryContext ); queryContext.queryTreeType = b2_staticBody; - b2DynamicTree_Query(bp->trees + b2_staticBody, fatAABB, b2_defaultMaskBits, b2PairQueryCallback, &queryContext); + b2DynamicTree_Query( bp->trees + b2_staticBody, fatAABB, b2_defaultMaskBits, b2PairQueryCallback, &queryContext ); } // All proxies collide with dynamic proxies queryContext.queryTreeType = b2_dynamicBody; - b2DynamicTree_Query(bp->trees + b2_dynamicBody, fatAABB, b2_defaultMaskBits, b2PairQueryCallback, &queryContext); + b2DynamicTree_Query( bp->trees + b2_dynamicBody, fatAABB, b2_defaultMaskBits, b2PairQueryCallback, &queryContext ); } - b2TracyCZoneEnd(pair_task); + b2TracyCZoneEnd( pair_task ); } -void b2UpdateBroadPhasePairs(b2World* world) +void b2UpdateBroadPhasePairs( b2World* world ) { b2BroadPhase* bp = &world->broadPhase; - int moveCount = b2Array(bp->moveArray).count; - B2_ASSERT(moveCount == (int)bp->moveSet.count); + int moveCount = b2Array( bp->moveArray ).count; + B2_ASSERT( moveCount == (int)bp->moveSet.count ); - if (moveCount == 0) + if ( moveCount == 0 ) { return; } - b2TracyCZoneNC(update_pairs, "Pairs", b2_colorFuchsia, true); + b2TracyCZoneNC( update_pairs, "Pairs", b2_colorFuchsia, true ); b2StackAllocator* alloc = &world->stackAllocator; // todo these could be in the step context - bp->moveResults = b2AllocateStackItem(alloc, moveCount * sizeof(b2MoveResult), "move results"); + bp->moveResults = b2AllocateStackItem( alloc, moveCount * sizeof( b2MoveResult ), "move results" ); bp->movePairCapacity = 16 * moveCount; - bp->movePairs = b2AllocateStackItem(alloc, bp->movePairCapacity * sizeof(b2MovePair), "move pairs"); + bp->movePairs = b2AllocateStackItem( alloc, bp->movePairCapacity * sizeof( b2MovePair ), "move pairs" ); bp->movePairIndex = 0; - + #ifndef NDEBUG extern _Atomic int g_probeCount; g_probeCount = 0; #endif int minRange = 64; - void* userPairTask = world->enqueueTaskFcn(&b2FindPairsTask, moveCount, minRange, world, world->userTaskContext); - world->finishTaskFcn(userPairTask, world->userTaskContext); + void* userPairTask = world->enqueueTaskFcn( &b2FindPairsTask, moveCount, minRange, world, world->userTaskContext ); + world->finishTaskFcn( userPairTask, world->userTaskContext ); world->taskCount += 1; - b2TracyCZoneNC(create_contacts, "Create Contacts", b2_colorGold, true); + b2TracyCZoneNC( create_contacts, "Create Contacts", b2_colorGold, true ); // Single-threaded work // - Clear move flags // - Create contacts in deterministic order b2Shape* shapes = world->shapeArray; - for (int i = 0; i < moveCount; ++i) + for ( int i = 0; i < moveCount; ++i ) { b2MoveResult* result = bp->moveResults + i; b2MovePair* pair = result->pairList; - while (pair != NULL) + while ( pair != NULL ) { // TODO_ERIN Check user filtering. // if (m_contactFilter && m_contactFilter->ShouldCollide(shapeA, shapeB) == false) @@ -391,16 +391,16 @@ void b2UpdateBroadPhasePairs(b2World* world) //++pairCount; - b2CheckId(shapes, shapeIdA); - b2CheckId(shapes, shapeIdB); + b2CheckId( shapes, shapeIdA ); + b2CheckId( shapes, shapeIdB ); - b2CreateContact(world, shapes + shapeIdA, shapes + shapeIdB); + b2CreateContact( world, shapes + shapeIdA, shapes + shapeIdB ); - if (pair->heap) + if ( pair->heap ) { b2MovePair* temp = pair; pair = pair->next; - b2Free(temp, sizeof(b2MovePair)); + b2Free( temp, sizeof( b2MovePair ) ); } else { @@ -420,80 +420,80 @@ void b2UpdateBroadPhasePairs(b2World* world) // } // Reset move buffer - b2Array_Clear(bp->moveArray); - b2ClearSet(&bp->moveSet); + b2Array_Clear( bp->moveArray ); + b2ClearSet( &bp->moveSet ); - b2FreeStackItem(alloc, bp->movePairs); + b2FreeStackItem( alloc, bp->movePairs ); bp->movePairs = NULL; - b2FreeStackItem(alloc, bp->moveResults); + b2FreeStackItem( alloc, bp->moveResults ); bp->moveResults = NULL; - b2ValidateSolverSets(world); + b2ValidateSolverSets( world ); - b2TracyCZoneEnd(create_contacts); + b2TracyCZoneEnd( create_contacts ); - b2TracyCZoneEnd(update_pairs); + b2TracyCZoneEnd( update_pairs ); } -bool b2BroadPhase_TestOverlap(const b2BroadPhase* bp, int proxyKeyA, int proxyKeyB) +bool b2BroadPhase_TestOverlap( const b2BroadPhase* bp, int proxyKeyA, int proxyKeyB ) { - int typeIndexA = B2_PROXY_TYPE(proxyKeyA); - int proxyIdA = B2_PROXY_ID(proxyKeyA); - int typeIndexB = B2_PROXY_TYPE(proxyKeyB); - int proxyIdB = B2_PROXY_ID(proxyKeyB); - - b2AABB aabbA = b2DynamicTree_GetAABB(bp->trees + typeIndexA, proxyIdA); - b2AABB aabbB = b2DynamicTree_GetAABB(bp->trees + typeIndexB, proxyIdB); - return b2AABB_Overlaps(aabbA, aabbB); + int typeIndexA = B2_PROXY_TYPE( proxyKeyA ); + int proxyIdA = B2_PROXY_ID( proxyKeyA ); + int typeIndexB = B2_PROXY_TYPE( proxyKeyB ); + int proxyIdB = B2_PROXY_ID( proxyKeyB ); + + b2AABB aabbA = b2DynamicTree_GetAABB( bp->trees + typeIndexA, proxyIdA ); + b2AABB aabbB = b2DynamicTree_GetAABB( bp->trees + typeIndexB, proxyIdB ); + return b2AABB_Overlaps( aabbA, aabbB ); } -void b2BroadPhase_RebuildTrees(b2BroadPhase* bp) +void b2BroadPhase_RebuildTrees( b2BroadPhase* bp ) { - b2DynamicTree_Rebuild(bp->trees + b2_dynamicBody, false); - b2DynamicTree_Rebuild(bp->trees + b2_kinematicBody, false); + b2DynamicTree_Rebuild( bp->trees + b2_dynamicBody, false ); + b2DynamicTree_Rebuild( bp->trees + b2_kinematicBody, false ); } -int b2BroadPhase_GetShapeIndex(b2BroadPhase* bp, int proxyKey) +int b2BroadPhase_GetShapeIndex( b2BroadPhase* bp, int proxyKey ) { - int typeIndex = B2_PROXY_TYPE(proxyKey); - int proxyId = B2_PROXY_ID(proxyKey); + int typeIndex = B2_PROXY_TYPE( proxyKey ); + int proxyId = B2_PROXY_ID( proxyKey ); - return b2DynamicTree_GetUserData(bp->trees + typeIndex, proxyId); + return b2DynamicTree_GetUserData( bp->trees + typeIndex, proxyId ); } -void b2ValidateBroadphase(const b2BroadPhase* bp) +void b2ValidateBroadphase( const b2BroadPhase* bp ) { - b2DynamicTree_Validate(bp->trees + b2_dynamicBody); - b2DynamicTree_Validate(bp->trees + b2_kinematicBody); + b2DynamicTree_Validate( bp->trees + b2_dynamicBody ); + b2DynamicTree_Validate( bp->trees + b2_kinematicBody ); // TODO_ERIN validate every shape AABB is contained in tree AABB } -void b2ValidateNoEnlarged(const b2BroadPhase* bp) +void b2ValidateNoEnlarged( const b2BroadPhase* bp ) { #if B2_VALIDATE == 1 - for (int j = 0; j < b2_bodyTypeCount; ++j) + for ( int j = 0; j < b2_bodyTypeCount; ++j ) { const b2DynamicTree* tree = bp->trees + j; int capacity = tree->nodeCapacity; const b2TreeNode* nodes = tree->nodes; - for (int i = 0; i < capacity; ++i) + for ( int i = 0; i < capacity; ++i ) { const b2TreeNode* node = nodes + i; - if (node->height < 0) + if ( node->height < 0 ) { continue; } - if (node->enlarged == true) + if ( node->enlarged == true ) { capacity += 0; } - B2_ASSERT(node->enlarged == false); + B2_ASSERT( node->enlarged == false ); } } #else - B2_MAYBE_UNUSED(bp); + B2_MAYBE_UNUSED( bp ); #endif } diff --git a/src/broad_phase.h b/src/broad_phase.h index 4444458b..b1c8dda2 100644 --- a/src/broad_phase.h +++ b/src/broad_phase.h @@ -16,9 +16,9 @@ typedef struct b2StackAllocator b2StackAllocator; typedef struct b2World b2World; // Store the proxy type in the lower 2 bits of the proxy key. This leaves 30 bits for the id. -#define B2_PROXY_TYPE(KEY) ((b2BodyType)((KEY) & 3)) -#define B2_PROXY_ID(KEY) ((KEY) >> 2) -#define B2_PROXY_KEY(ID, TYPE) (((ID) << 2) | (TYPE)) +#define B2_PROXY_TYPE( KEY ) ( (b2BodyType)( ( KEY ) & 3 ) ) +#define B2_PROXY_ID( KEY ) ( ( KEY ) >> 2 ) +#define B2_PROXY_KEY( ID, TYPE ) ( ( ( ID ) << 2 ) | ( TYPE ) ) /// The broad-phase is used for computing pairs and performing volume queries and ray casts. /// This broad-phase does not persist pairs. Instead, this reports potentially new pairs. @@ -50,33 +50,34 @@ typedef struct b2BroadPhase } b2BroadPhase; -void b2CreateBroadPhase(b2BroadPhase* bp); -void b2DestroyBroadPhase(b2BroadPhase* bp); +void b2CreateBroadPhase( b2BroadPhase* bp ); +void b2DestroyBroadPhase( b2BroadPhase* bp ); -int b2BroadPhase_CreateProxy(b2BroadPhase* bp, b2BodyType proxyType, b2AABB aabb, uint32_t categoryBits, int shapeIndex, bool forcePairCreation); -void b2BroadPhase_DestroyProxy(b2BroadPhase* bp, int proxyKey); +int b2BroadPhase_CreateProxy( b2BroadPhase* bp, b2BodyType proxyType, b2AABB aabb, uint32_t categoryBits, int shapeIndex, + bool forcePairCreation ); +void b2BroadPhase_DestroyProxy( b2BroadPhase* bp, int proxyKey ); -void b2BroadPhase_MoveProxy(b2BroadPhase* bp, int proxyKey, b2AABB aabb); -void b2BroadPhase_EnlargeProxy(b2BroadPhase* bp, int proxyKey, b2AABB aabb); +void b2BroadPhase_MoveProxy( b2BroadPhase* bp, int proxyKey, b2AABB aabb ); +void b2BroadPhase_EnlargeProxy( b2BroadPhase* bp, int proxyKey, b2AABB aabb ); -void b2BroadPhase_RebuildTrees(b2BroadPhase* bp); +void b2BroadPhase_RebuildTrees( b2BroadPhase* bp ); -int b2BroadPhase_GetShapeIndex(b2BroadPhase* bp, int proxyKey); +int b2BroadPhase_GetShapeIndex( b2BroadPhase* bp, int proxyKey ); -void b2UpdateBroadPhasePairs(b2World* world); -bool b2BroadPhase_TestOverlap(const b2BroadPhase* bp, int proxyKeyA, int proxyKeyB); +void b2UpdateBroadPhasePairs( b2World* world ); +bool b2BroadPhase_TestOverlap( const b2BroadPhase* bp, int proxyKeyA, int proxyKeyB ); -void b2ValidateBroadphase(const b2BroadPhase* bp); -void b2ValidateNoEnlarged(const b2BroadPhase* bp); +void b2ValidateBroadphase( const b2BroadPhase* bp ); +void b2ValidateNoEnlarged( const b2BroadPhase* bp ); // This is what triggers new contact pairs to be created // Warning: this must be called in deterministic order -static inline void b2BufferMove(b2BroadPhase* bp, int queryProxy) +static inline void b2BufferMove( b2BroadPhase* bp, int queryProxy ) { // Adding 1 because 0 is the sentinel - bool alreadyAdded = b2AddKey(&bp->moveSet, queryProxy + 1); - if (alreadyAdded == false) + bool alreadyAdded = b2AddKey( &bp->moveSet, queryProxy + 1 ); + if ( alreadyAdded == false ) { - b2Array_Push(bp->moveArray, queryProxy); + b2Array_Push( bp->moveArray, queryProxy ); } } diff --git a/src/constraint_graph.c b/src/constraint_graph.c index ed595081..8f4a9336 100644 --- a/src/constraint_graph.c +++ b/src/constraint_graph.c @@ -25,107 +25,107 @@ // This is used for debugging by making all constraints be assigned to overflow. #define B2_FORCE_OVERFLOW 0 -_Static_assert(b2_graphColorCount == 12, "graph color count assumed to be 12"); +_Static_assert( b2_graphColorCount == 12, "graph color count assumed to be 12" ); -void b2CreateGraph(b2ConstraintGraph* graph, int bodyCapacity) +void b2CreateGraph( b2ConstraintGraph* graph, int bodyCapacity ) { - _Static_assert(b2_graphColorCount >= 2, "must have at least two constraint graph colors"); + _Static_assert( b2_graphColorCount >= 2, "must have at least two constraint graph colors" ); - *graph = (b2ConstraintGraph){0}; + *graph = ( b2ConstraintGraph ){ 0 }; - bodyCapacity = b2MaxInt(bodyCapacity, 8); - for (int i = 0; i < b2_graphColorCount; ++i) + bodyCapacity = b2MaxInt( bodyCapacity, 8 ); + for ( int i = 0; i < b2_graphColorCount; ++i ) { b2GraphColor* color = graph->colors + i; - if (i != b2_overflowIndex) + if ( i != b2_overflowIndex ) { - color->bodySet = b2CreateBitSet(bodyCapacity); - b2SetBitCountAndClear(&color->bodySet, bodyCapacity); + color->bodySet = b2CreateBitSet( bodyCapacity ); + b2SetBitCountAndClear( &color->bodySet, bodyCapacity ); } } } -void b2DestroyGraph(b2ConstraintGraph* graph) +void b2DestroyGraph( b2ConstraintGraph* graph ) { - for (int i = 0; i < b2_graphColorCount; ++i) + for ( int i = 0; i < b2_graphColorCount; ++i ) { b2GraphColor* color = graph->colors + i; - b2DestroyBitSet(&color->bodySet); + b2DestroyBitSet( &color->bodySet ); - b2DestroyContactArray(&color->contacts); - b2DestroyJointArray(&color->joints); + b2DestroyContactArray( &color->contacts ); + b2DestroyJointArray( &color->joints ); } } // Contacts are always created as non-touching. They get cloned into the constraint // graph once they are found to be touching. // todo maybe kinematic bodies should not go into graph -void b2AddContactToGraph(b2World* world, b2ContactSim* contactSim, b2Contact* contact) +void b2AddContactToGraph( b2World* world, b2ContactSim* contactSim, b2Contact* contact ) { - B2_ASSERT(contactSim->manifold.pointCount > 0); - B2_ASSERT(contactSim->simFlags & b2_simTouchingFlag); - B2_ASSERT(contact->flags & b2_contactTouchingFlag); + B2_ASSERT( contactSim->manifold.pointCount > 0 ); + B2_ASSERT( contactSim->simFlags & b2_simTouchingFlag ); + B2_ASSERT( contact->flags & b2_contactTouchingFlag ); b2ConstraintGraph* graph = &world->constraintGraph; int colorIndex = b2_overflowIndex; int bodyIdA = contact->edges[0].bodyId; int bodyIdB = contact->edges[1].bodyId; - b2CheckIndex(world->bodyArray, bodyIdA); - b2CheckIndex(world->bodyArray, bodyIdB); + b2CheckIndex( world->bodyArray, bodyIdA ); + b2CheckIndex( world->bodyArray, bodyIdB ); b2Body* bodyA = world->bodyArray + bodyIdA; b2Body* bodyB = world->bodyArray + bodyIdB; bool staticA = bodyA->setIndex == b2_staticSet; bool staticB = bodyB->setIndex == b2_staticSet; - B2_ASSERT(staticA == false || staticB == false); + B2_ASSERT( staticA == false || staticB == false ); #if B2_FORCE_OVERFLOW == 0 - if (staticA == false && staticB == false) + if ( staticA == false && staticB == false ) { - for (int i = 0; i < b2_overflowIndex; ++i) + for ( int i = 0; i < b2_overflowIndex; ++i ) { b2GraphColor* color = graph->colors + i; - if (b2GetBit(&color->bodySet, bodyIdA) || b2GetBit(&color->bodySet, bodyIdB)) + if ( b2GetBit( &color->bodySet, bodyIdA ) || b2GetBit( &color->bodySet, bodyIdB ) ) { continue; } - b2SetBitGrow(&color->bodySet, bodyIdA); - b2SetBitGrow(&color->bodySet, bodyIdB); + b2SetBitGrow( &color->bodySet, bodyIdA ); + b2SetBitGrow( &color->bodySet, bodyIdB ); colorIndex = i; break; } } - else if (staticA == false) + else if ( staticA == false ) { // No static contacts in color 0 - for (int i = 1; i < b2_overflowIndex; ++i) + for ( int i = 1; i < b2_overflowIndex; ++i ) { b2GraphColor* color = graph->colors + i; - if (b2GetBit(&color->bodySet, bodyIdA)) + if ( b2GetBit( &color->bodySet, bodyIdA ) ) { continue; } - b2SetBitGrow(&color->bodySet, bodyIdA); + b2SetBitGrow( &color->bodySet, bodyIdA ); colorIndex = i; break; } } - else if (staticB == false) + else if ( staticB == false ) { // No static contacts in color 0 - for (int i = 1; i < b2_overflowIndex; ++i) + for ( int i = 1; i < b2_overflowIndex; ++i ) { b2GraphColor* color = graph->colors + i; - if (b2GetBit(&color->bodySet, bodyIdB)) + if ( b2GetBit( &color->bodySet, bodyIdB ) ) { continue; } - b2SetBitGrow(&color->bodySet, bodyIdB); + b2SetBitGrow( &color->bodySet, bodyIdB ); colorIndex = i; break; } @@ -136,12 +136,12 @@ void b2AddContactToGraph(b2World* world, b2ContactSim* contactSim, b2Contact* co contact->colorIndex = colorIndex; contact->localIndex = color->contacts.count; - b2ContactSim* newContact = b2AddContact(&color->contacts); - memcpy(newContact, contactSim, sizeof(b2ContactSim)); + b2ContactSim* newContact = b2AddContact( &color->contacts ); + memcpy( newContact, contactSim, sizeof( b2ContactSim ) ); // todo perhaps skip this if the contact is already awake - - if (staticA) + + if ( staticA ) { newContact->bodySimIndexA = B2_NULL_INDEX; newContact->invMassA = 0.0f; @@ -149,11 +149,11 @@ void b2AddContactToGraph(b2World* world, b2ContactSim* contactSim, b2Contact* co } else { - B2_ASSERT(bodyA->setIndex == b2_awakeSet); + B2_ASSERT( bodyA->setIndex == b2_awakeSet ); b2SolverSet* awakeSet = world->solverSetArray + b2_awakeSet; int localIndex = bodyA->localIndex; - B2_ASSERT(0 <= localIndex && localIndex < awakeSet->sims.count); + B2_ASSERT( 0 <= localIndex && localIndex < awakeSet->sims.count ); newContact->bodySimIndexA = localIndex; b2BodySim* bodySimA = awakeSet->sims.data + localIndex; @@ -161,7 +161,7 @@ void b2AddContactToGraph(b2World* world, b2ContactSim* contactSim, b2Contact* co newContact->invIA = bodySimA->invInertia; } - if (staticB) + if ( staticB ) { newContact->bodySimIndexB = B2_NULL_INDEX; newContact->invMassB = 0.0f; @@ -169,11 +169,11 @@ void b2AddContactToGraph(b2World* world, b2ContactSim* contactSim, b2Contact* co } else { - B2_ASSERT(bodyB->setIndex == b2_awakeSet); + B2_ASSERT( bodyB->setIndex == b2_awakeSet ); b2SolverSet* awakeSet = world->solverSetArray + b2_awakeSet; int localIndex = bodyB->localIndex; - B2_ASSERT(0 <= localIndex && localIndex < awakeSet->sims.count); + B2_ASSERT( 0 <= localIndex && localIndex < awakeSet->sims.count ); newContact->bodySimIndexB = localIndex; b2BodySim* bodySimB = awakeSet->sims.data + localIndex; @@ -182,82 +182,82 @@ void b2AddContactToGraph(b2World* world, b2ContactSim* contactSim, b2Contact* co } } -void b2RemoveContactFromGraph(b2World* world, int bodyIdA, int bodyIdB, int colorIndex, int localIndex) +void b2RemoveContactFromGraph( b2World* world, int bodyIdA, int bodyIdB, int colorIndex, int localIndex ) { b2ConstraintGraph* graph = &world->constraintGraph; - B2_ASSERT(0 <= colorIndex && colorIndex < b2_graphColorCount); + B2_ASSERT( 0 <= colorIndex && colorIndex < b2_graphColorCount ); b2GraphColor* color = graph->colors + colorIndex; - if (colorIndex != b2_overflowIndex) + if ( colorIndex != b2_overflowIndex ) { // might clear a bit for a static body, but this has no effect - b2ClearBit(&color->bodySet, bodyIdA); - b2ClearBit(&color->bodySet, bodyIdB); + b2ClearBit( &color->bodySet, bodyIdA ); + b2ClearBit( &color->bodySet, bodyIdB ); } - int movedIndex = b2RemoveContact(&color->contacts, localIndex); - if (movedIndex != B2_NULL_INDEX) + int movedIndex = b2RemoveContact( &color->contacts, localIndex ); + if ( movedIndex != B2_NULL_INDEX ) { // Fix index on swapped contact b2ContactSim* movedContactSim = color->contacts.data + localIndex; // Fix moved contact int movedId = movedContactSim->contactId; - b2CheckIndex(world->contactArray, movedId); + b2CheckIndex( world->contactArray, movedId ); b2Contact* movedContact = world->contactArray + movedId; - B2_ASSERT(movedContact->setIndex == b2_awakeSet); - B2_ASSERT(movedContact->colorIndex == colorIndex); - B2_ASSERT(movedContact->localIndex == movedIndex); + B2_ASSERT( movedContact->setIndex == b2_awakeSet ); + B2_ASSERT( movedContact->colorIndex == colorIndex ); + B2_ASSERT( movedContact->localIndex == movedIndex ); movedContact->localIndex = localIndex; } } -static int b2AssignJointColor(b2ConstraintGraph* graph, int bodyIdA, int bodyIdB, bool staticA, bool staticB) +static int b2AssignJointColor( b2ConstraintGraph* graph, int bodyIdA, int bodyIdB, bool staticA, bool staticB ) { - B2_ASSERT(staticA == false || staticB == false); + B2_ASSERT( staticA == false || staticB == false ); #if B2_FORCE_OVERFLOW == 0 - if (staticA == false && staticB == false) + if ( staticA == false && staticB == false ) { - for (int i = 0; i < b2_graphColorCount; ++i) + for ( int i = 0; i < b2_graphColorCount; ++i ) { b2GraphColor* color = graph->colors + i; - if (b2GetBit(&color->bodySet, bodyIdA) || b2GetBit(&color->bodySet, bodyIdB)) + if ( b2GetBit( &color->bodySet, bodyIdA ) || b2GetBit( &color->bodySet, bodyIdB ) ) { continue; } - b2SetBitGrow(&color->bodySet, bodyIdA); - b2SetBitGrow(&color->bodySet, bodyIdB); + b2SetBitGrow( &color->bodySet, bodyIdA ); + b2SetBitGrow( &color->bodySet, bodyIdB ); return i; } } - else if (staticA == false) + else if ( staticA == false ) { - for (int i = 0; i < b2_graphColorCount; ++i) + for ( int i = 0; i < b2_graphColorCount; ++i ) { b2GraphColor* color = graph->colors + i; - if (b2GetBit(&color->bodySet, bodyIdA)) + if ( b2GetBit( &color->bodySet, bodyIdA ) ) { continue; } - b2SetBitGrow(&color->bodySet, bodyIdA); + b2SetBitGrow( &color->bodySet, bodyIdA ); return i; } } - else if (staticB == false) + else if ( staticB == false ) { - for (int i = 0; i < b2_graphColorCount; ++i) + for ( int i = 0; i < b2_graphColorCount; ++i ) { b2GraphColor* color = graph->colors + i; - if (b2GetBit(&color->bodySet, bodyIdB)) + if ( b2GetBit( &color->bodySet, bodyIdB ) ) { continue; } - b2SetBitGrow(&color->bodySet, bodyIdB); + b2SetBitGrow( &color->bodySet, bodyIdB ); return i; } } @@ -266,59 +266,59 @@ static int b2AssignJointColor(b2ConstraintGraph* graph, int bodyIdA, int bodyIdB return b2_overflowIndex; } -b2JointSim* b2CreateJointInGraph(b2World* world, b2Joint* joint) +b2JointSim* b2CreateJointInGraph( b2World* world, b2Joint* joint ) { b2ConstraintGraph* graph = &world->constraintGraph; int bodyIdA = joint->edges[0].bodyId; int bodyIdB = joint->edges[1].bodyId; - b2CheckIndex(world->bodyArray, bodyIdA); - b2CheckIndex(world->bodyArray, bodyIdB); + b2CheckIndex( world->bodyArray, bodyIdA ); + b2CheckIndex( world->bodyArray, bodyIdB ); b2Body* bodyA = world->bodyArray + bodyIdA; b2Body* bodyB = world->bodyArray + bodyIdB; bool staticA = bodyA->setIndex == b2_staticSet; bool staticB = bodyB->setIndex == b2_staticSet; - int colorIndex = b2AssignJointColor(graph, bodyIdA, bodyIdB, staticA, staticB); + int colorIndex = b2AssignJointColor( graph, bodyIdA, bodyIdB, staticA, staticB ); - b2JointSim* jointSim = b2AddJoint(&graph->colors[colorIndex].joints); + b2JointSim* jointSim = b2AddJoint( &graph->colors[colorIndex].joints ); joint->colorIndex = colorIndex; joint->localIndex = graph->colors[colorIndex].joints.count - 1; return jointSim; } -void b2AddJointToGraph(b2World* world, b2JointSim* jointSim, b2Joint* joint) +void b2AddJointToGraph( b2World* world, b2JointSim* jointSim, b2Joint* joint ) { - b2JointSim* jointDst = b2CreateJointInGraph(world, joint); - memcpy(jointDst, jointSim, sizeof(b2JointSim)); + b2JointSim* jointDst = b2CreateJointInGraph( world, joint ); + memcpy( jointDst, jointSim, sizeof( b2JointSim ) ); } -void b2RemoveJointFromGraph(b2World* world, int bodyIdA, int bodyIdB, int colorIndex, int localIndex) +void b2RemoveJointFromGraph( b2World* world, int bodyIdA, int bodyIdB, int colorIndex, int localIndex ) { b2ConstraintGraph* graph = &world->constraintGraph; - B2_ASSERT(0 <= colorIndex && colorIndex < b2_graphColorCount); + B2_ASSERT( 0 <= colorIndex && colorIndex < b2_graphColorCount ); b2GraphColor* color = graph->colors + colorIndex; - if (colorIndex != b2_overflowIndex) + if ( colorIndex != b2_overflowIndex ) { // May clear static bodies, no effect - b2ClearBit(&color->bodySet, bodyIdA); - b2ClearBit(&color->bodySet, bodyIdB); + b2ClearBit( &color->bodySet, bodyIdA ); + b2ClearBit( &color->bodySet, bodyIdB ); } - int movedIndex = b2RemoveJoint(&color->joints, localIndex); - if (movedIndex != B2_NULL_INDEX) + int movedIndex = b2RemoveJoint( &color->joints, localIndex ); + if ( movedIndex != B2_NULL_INDEX ) { // Fix moved joint b2JointSim* movedJointSim = color->joints.data + localIndex; int movedId = movedJointSim->jointId; - b2CheckIndex(world->jointArray, movedId); + b2CheckIndex( world->jointArray, movedId ); b2Joint* movedJoint = world->jointArray + movedId; - B2_ASSERT(movedJoint->setIndex == b2_awakeSet); - B2_ASSERT(movedJoint->colorIndex == colorIndex); - B2_ASSERT(movedJoint->localIndex == movedIndex); + B2_ASSERT( movedJoint->setIndex == b2_awakeSet ); + B2_ASSERT( movedJoint->colorIndex == colorIndex ); + B2_ASSERT( movedJoint->localIndex == movedIndex ); movedJoint->localIndex = localIndex; } } diff --git a/src/constraint_graph.h b/src/constraint_graph.h index e02256f5..15866644 100644 --- a/src/constraint_graph.h +++ b/src/constraint_graph.h @@ -44,12 +44,12 @@ typedef struct b2ConstraintGraph b2GraphColor colors[b2_graphColorCount]; } b2ConstraintGraph; -void b2CreateGraph(b2ConstraintGraph* graph, int bodyCapacity); -void b2DestroyGraph(b2ConstraintGraph* graph); +void b2CreateGraph( b2ConstraintGraph* graph, int bodyCapacity ); +void b2DestroyGraph( b2ConstraintGraph* graph ); -void b2AddContactToGraph(b2World* world, b2ContactSim* contactSim, b2Contact* contact); -void b2RemoveContactFromGraph(b2World* world, int bodyIdA, int bodyIdB, int colorIndex, int localIndex); +void b2AddContactToGraph( b2World* world, b2ContactSim* contactSim, b2Contact* contact ); +void b2RemoveContactFromGraph( b2World* world, int bodyIdA, int bodyIdB, int colorIndex, int localIndex ); -b2JointSim* b2CreateJointInGraph(b2World* world, b2Joint* joint); -void b2AddJointToGraph(b2World* world, b2JointSim* jointSim, b2Joint* joint); -void b2RemoveJointFromGraph(b2World* world, int bodyIdA, int bodyIdB, int colorIndex, int localIndex); +b2JointSim* b2CreateJointInGraph( b2World* world, b2Joint* joint ); +void b2AddJointToGraph( b2World* world, b2JointSim* jointSim, b2Joint* joint ); +void b2RemoveJointFromGraph( b2World* world, int bodyIdA, int bodyIdB, int colorIndex, int localIndex ); diff --git a/src/contact.c b/src/contact.c index 2dba9695..f530622b 100644 --- a/src/contact.c +++ b/src/contact.c @@ -39,22 +39,22 @@ // Friction mixing law. The idea is to allow either shape to drive the friction to zero. // For example, anything slides on ice. -static inline float b2MixFriction(float friction1, float friction2) +static inline float b2MixFriction( float friction1, float friction2 ) { - return sqrtf(friction1 * friction2); + return sqrtf( friction1 * friction2 ); } // Restitution mixing law. The idea is allow for anything to bounce off an inelastic surface. // For example, a superball bounces on anything. -static inline float b2MixRestitution(float restitution1, float restitution2) +static inline float b2MixRestitution( float restitution1, float restitution2 ) { return restitution1 > restitution2 ? restitution1 : restitution2; } // todo make relative for all // typedef b2Manifold b2ManifoldFcn(const b2Shape* shapeA, const b2Shape* shapeB, b2Transform xfB, b2DistanceCache* cache); -typedef b2Manifold b2ManifoldFcn(const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, - b2DistanceCache* cache); +typedef b2Manifold b2ManifoldFcn( const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, + b2DistanceCache* cache ); struct b2ContactRegister { @@ -65,152 +65,152 @@ struct b2ContactRegister static struct b2ContactRegister s_registers[b2_shapeTypeCount][b2_shapeTypeCount]; static bool s_initialized = false; -static b2Manifold b2CircleManifold(const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, - b2DistanceCache* cache) +static b2Manifold b2CircleManifold( const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, + b2DistanceCache* cache ) { - B2_MAYBE_UNUSED(cache); - return b2CollideCircles(&shapeA->circle, xfA, &shapeB->circle, xfB); + B2_MAYBE_UNUSED( cache ); + return b2CollideCircles( &shapeA->circle, xfA, &shapeB->circle, xfB ); } -static b2Manifold b2CapsuleAndCircleManifold(const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, - b2DistanceCache* cache) +static b2Manifold b2CapsuleAndCircleManifold( const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, + b2DistanceCache* cache ) { - B2_MAYBE_UNUSED(cache); - return b2CollideCapsuleAndCircle(&shapeA->capsule, xfA, &shapeB->circle, xfB); + B2_MAYBE_UNUSED( cache ); + return b2CollideCapsuleAndCircle( &shapeA->capsule, xfA, &shapeB->circle, xfB ); } -static b2Manifold b2CapsuleManifold(const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, - b2DistanceCache* cache) +static b2Manifold b2CapsuleManifold( const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, + b2DistanceCache* cache ) { - B2_MAYBE_UNUSED(cache); - return b2CollideCapsules(&shapeA->capsule, xfA, &shapeB->capsule, xfB); + B2_MAYBE_UNUSED( cache ); + return b2CollideCapsules( &shapeA->capsule, xfA, &shapeB->capsule, xfB ); } -static b2Manifold b2PolygonAndCircleManifold(const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, - b2DistanceCache* cache) +static b2Manifold b2PolygonAndCircleManifold( const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, + b2DistanceCache* cache ) { - B2_MAYBE_UNUSED(cache); - return b2CollidePolygonAndCircle(&shapeA->polygon, xfA, &shapeB->circle, xfB); + B2_MAYBE_UNUSED( cache ); + return b2CollidePolygonAndCircle( &shapeA->polygon, xfA, &shapeB->circle, xfB ); } -static b2Manifold b2PolygonAndCapsuleManifold(const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, - b2DistanceCache* cache) +static b2Manifold b2PolygonAndCapsuleManifold( const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, + b2DistanceCache* cache ) { - B2_MAYBE_UNUSED(cache); - return b2CollidePolygonAndCapsule(&shapeA->polygon, xfA, &shapeB->capsule, xfB); + B2_MAYBE_UNUSED( cache ); + return b2CollidePolygonAndCapsule( &shapeA->polygon, xfA, &shapeB->capsule, xfB ); } -static b2Manifold b2PolygonManifold(const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, - b2DistanceCache* cache) +static b2Manifold b2PolygonManifold( const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, + b2DistanceCache* cache ) { - B2_MAYBE_UNUSED(cache); - return b2CollidePolygons(&shapeA->polygon, xfA, &shapeB->polygon, xfB); + B2_MAYBE_UNUSED( cache ); + return b2CollidePolygons( &shapeA->polygon, xfA, &shapeB->polygon, xfB ); } -static b2Manifold b2SegmentAndCircleManifold(const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, - b2DistanceCache* cache) +static b2Manifold b2SegmentAndCircleManifold( const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, + b2DistanceCache* cache ) { - B2_MAYBE_UNUSED(cache); - return b2CollideSegmentAndCircle(&shapeA->segment, xfA, &shapeB->circle, xfB); + B2_MAYBE_UNUSED( cache ); + return b2CollideSegmentAndCircle( &shapeA->segment, xfA, &shapeB->circle, xfB ); } -static b2Manifold b2SegmentAndCapsuleManifold(const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, - b2DistanceCache* cache) +static b2Manifold b2SegmentAndCapsuleManifold( const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, + b2DistanceCache* cache ) { - B2_MAYBE_UNUSED(cache); - return b2CollideSegmentAndCapsule(&shapeA->segment, xfA, &shapeB->capsule, xfB); + B2_MAYBE_UNUSED( cache ); + return b2CollideSegmentAndCapsule( &shapeA->segment, xfA, &shapeB->capsule, xfB ); } -static b2Manifold b2SegmentAndPolygonManifold(const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, - b2DistanceCache* cache) +static b2Manifold b2SegmentAndPolygonManifold( const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, + b2DistanceCache* cache ) { - B2_MAYBE_UNUSED(cache); - return b2CollideSegmentAndPolygon(&shapeA->segment, xfA, &shapeB->polygon, xfB); + B2_MAYBE_UNUSED( cache ); + return b2CollideSegmentAndPolygon( &shapeA->segment, xfA, &shapeB->polygon, xfB ); } -static b2Manifold b2SmoothSegmentAndCircleManifold(const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, - b2DistanceCache* cache) +static b2Manifold b2SmoothSegmentAndCircleManifold( const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, + b2Transform xfB, b2DistanceCache* cache ) { - B2_MAYBE_UNUSED(cache); - return b2CollideSmoothSegmentAndCircle(&shapeA->smoothSegment, xfA, &shapeB->circle, xfB); + B2_MAYBE_UNUSED( cache ); + return b2CollideSmoothSegmentAndCircle( &shapeA->smoothSegment, xfA, &shapeB->circle, xfB ); } -static b2Manifold b2SmoothSegmentAndCapsuleManifold(const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, - b2Transform xfB, b2DistanceCache* cache) +static b2Manifold b2SmoothSegmentAndCapsuleManifold( const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, + b2Transform xfB, b2DistanceCache* cache ) { - return b2CollideSmoothSegmentAndCapsule(&shapeA->smoothSegment, xfA, &shapeB->capsule, xfB, cache); + return b2CollideSmoothSegmentAndCapsule( &shapeA->smoothSegment, xfA, &shapeB->capsule, xfB, cache ); } -static b2Manifold b2SmoothSegmentAndPolygonManifold(const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, - b2Transform xfB, b2DistanceCache* cache) +static b2Manifold b2SmoothSegmentAndPolygonManifold( const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, + b2Transform xfB, b2DistanceCache* cache ) { - return b2CollideSmoothSegmentAndPolygon(&shapeA->smoothSegment, xfA, &shapeB->polygon, xfB, cache); + return b2CollideSmoothSegmentAndPolygon( &shapeA->smoothSegment, xfA, &shapeB->polygon, xfB, cache ); } -static void b2AddType(b2ManifoldFcn* fcn, b2ShapeType type1, b2ShapeType type2) +static void b2AddType( b2ManifoldFcn* fcn, b2ShapeType type1, b2ShapeType type2 ) { - B2_ASSERT(0 <= type1 && type1 < b2_shapeTypeCount); - B2_ASSERT(0 <= type2 && type2 < b2_shapeTypeCount); + B2_ASSERT( 0 <= type1 && type1 < b2_shapeTypeCount ); + B2_ASSERT( 0 <= type2 && type2 < b2_shapeTypeCount ); s_registers[type1][type2].fcn = fcn; s_registers[type1][type2].primary = true; - if (type1 != type2) + if ( type1 != type2 ) { s_registers[type2][type1].fcn = fcn; s_registers[type2][type1].primary = false; } } -void b2InitializeContactRegisters(void) +void b2InitializeContactRegisters( void ) { - if (s_initialized == false) + if ( s_initialized == false ) { - b2AddType(b2CircleManifold, b2_circleShape, b2_circleShape); - b2AddType(b2CapsuleAndCircleManifold, b2_capsuleShape, b2_circleShape); - b2AddType(b2CapsuleManifold, b2_capsuleShape, b2_capsuleShape); - b2AddType(b2PolygonAndCircleManifold, b2_polygonShape, b2_circleShape); - b2AddType(b2PolygonAndCapsuleManifold, b2_polygonShape, b2_capsuleShape); - b2AddType(b2PolygonManifold, b2_polygonShape, b2_polygonShape); - b2AddType(b2SegmentAndCircleManifold, b2_segmentShape, b2_circleShape); - b2AddType(b2SegmentAndCapsuleManifold, b2_segmentShape, b2_capsuleShape); - b2AddType(b2SegmentAndPolygonManifold, b2_segmentShape, b2_polygonShape); - b2AddType(b2SmoothSegmentAndCircleManifold, b2_smoothSegmentShape, b2_circleShape); - b2AddType(b2SmoothSegmentAndCapsuleManifold, b2_smoothSegmentShape, b2_capsuleShape); - b2AddType(b2SmoothSegmentAndPolygonManifold, b2_smoothSegmentShape, b2_polygonShape); + b2AddType( b2CircleManifold, b2_circleShape, b2_circleShape ); + b2AddType( b2CapsuleAndCircleManifold, b2_capsuleShape, b2_circleShape ); + b2AddType( b2CapsuleManifold, b2_capsuleShape, b2_capsuleShape ); + b2AddType( b2PolygonAndCircleManifold, b2_polygonShape, b2_circleShape ); + b2AddType( b2PolygonAndCapsuleManifold, b2_polygonShape, b2_capsuleShape ); + b2AddType( b2PolygonManifold, b2_polygonShape, b2_polygonShape ); + b2AddType( b2SegmentAndCircleManifold, b2_segmentShape, b2_circleShape ); + b2AddType( b2SegmentAndCapsuleManifold, b2_segmentShape, b2_capsuleShape ); + b2AddType( b2SegmentAndPolygonManifold, b2_segmentShape, b2_polygonShape ); + b2AddType( b2SmoothSegmentAndCircleManifold, b2_smoothSegmentShape, b2_circleShape ); + b2AddType( b2SmoothSegmentAndCapsuleManifold, b2_smoothSegmentShape, b2_capsuleShape ); + b2AddType( b2SmoothSegmentAndPolygonManifold, b2_smoothSegmentShape, b2_polygonShape ); s_initialized = true; } } -void b2CreateContact(b2World* world, b2Shape* shapeA, b2Shape* shapeB) +void b2CreateContact( b2World* world, b2Shape* shapeA, b2Shape* shapeB ) { b2ShapeType type1 = shapeA->type; b2ShapeType type2 = shapeB->type; - B2_ASSERT(0 <= type1 && type1 < b2_shapeTypeCount); - B2_ASSERT(0 <= type2 && type2 < b2_shapeTypeCount); + B2_ASSERT( 0 <= type1 && type1 < b2_shapeTypeCount ); + B2_ASSERT( 0 <= type2 && type2 < b2_shapeTypeCount ); - if (s_registers[type1][type2].fcn == NULL) + if ( s_registers[type1][type2].fcn == NULL ) { // For example, no segment vs segment collision return; } - if (s_registers[type1][type2].primary == false) + if ( s_registers[type1][type2].primary == false ) { // flip order - b2CreateContact(world, shapeB, shapeA); + b2CreateContact( world, shapeB, shapeA ); return; } - b2Body* bodyA = b2GetBody(world, shapeA->bodyId); - b2Body* bodyB = b2GetBody(world, shapeB->bodyId); + b2Body* bodyA = b2GetBody( world, shapeA->bodyId ); + b2Body* bodyB = b2GetBody( world, shapeB->bodyId ); - B2_ASSERT(bodyA->setIndex != b2_disabledSet && bodyB->setIndex != b2_disabledSet); - B2_ASSERT(bodyA->setIndex != b2_staticSet || bodyB->setIndex != b2_staticSet); + B2_ASSERT( bodyA->setIndex != b2_disabledSet && bodyB->setIndex != b2_disabledSet ); + B2_ASSERT( bodyA->setIndex != b2_staticSet || bodyB->setIndex != b2_staticSet ); int setIndex; - if (bodyA->setIndex == b2_awakeSet || bodyB->setIndex == b2_awakeSet) + if ( bodyA->setIndex == b2_awakeSet || bodyB->setIndex == b2_awakeSet ) { setIndex = b2_awakeSet; } @@ -225,10 +225,10 @@ void b2CreateContact(b2World* world, b2Shape* shapeA, b2Shape* shapeB) b2SolverSet* set = world->solverSetArray + setIndex; // Create contact key and contact - int contactId = b2AllocId(&world->contactIdPool); - if (contactId == b2Array(world->contactArray).count) + int contactId = b2AllocId( &world->contactIdPool ); + if ( contactId == b2Array( world->contactArray ).count ) { - b2Array_Push(world->contactArray, (b2Contact){0}); + b2Array_Push( world->contactArray, ( b2Contact ){ 0 } ); } int shapeIdA = shapeA->id; @@ -247,17 +247,17 @@ void b2CreateContact(b2World* world, b2Shape* shapeA, b2Shape* shapeB) contact->isMarked = false; contact->flags = 0; - if (shapeA->isSensor || shapeB->isSensor) + if ( shapeA->isSensor || shapeB->isSensor ) { contact->flags |= b2_contactSensorFlag; } - if (shapeA->enableSensorEvents || shapeB->enableSensorEvents) + if ( shapeA->enableSensorEvents || shapeB->enableSensorEvents ) { contact->flags |= b2_contactEnableSensorEvents; } - if (shapeA->enableContactEvents || shapeB->enableContactEvents) + if ( shapeA->enableContactEvents || shapeB->enableContactEvents ) { contact->flags |= b2_contactEnableContactEvents; } @@ -268,11 +268,11 @@ void b2CreateContact(b2World* world, b2Shape* shapeA, b2Shape* shapeB) contact->edges[0].prevKey = B2_NULL_INDEX; contact->edges[0].nextKey = bodyA->headContactKey; - int keyA = (contactId << 1) | 0; + int keyA = ( contactId << 1 ) | 0; int headContactKey = bodyA->headContactKey; - if (headContactKey != B2_NULL_INDEX) + if ( headContactKey != B2_NULL_INDEX ) { - b2Contact* headContact = world->contactArray + (headContactKey >> 1); + b2Contact* headContact = world->contactArray + ( headContactKey >> 1 ); headContact->edges[headContactKey & 1].prevKey = keyA; } bodyA->headContactKey = keyA; @@ -285,11 +285,11 @@ void b2CreateContact(b2World* world, b2Shape* shapeA, b2Shape* shapeB) contact->edges[1].prevKey = B2_NULL_INDEX; contact->edges[1].nextKey = bodyB->headContactKey; - int keyB = (contactId << 1) | 1; + int keyB = ( contactId << 1 ) | 1; int headContactKey = bodyB->headContactKey; - if (bodyB->headContactKey != B2_NULL_INDEX) + if ( bodyB->headContactKey != B2_NULL_INDEX ) { - b2Contact* headContact = world->contactArray + (headContactKey >> 1); + b2Contact* headContact = world->contactArray + ( headContactKey >> 1 ); headContact->edges[headContactKey & 1].prevKey = keyB; } bodyB->headContactKey = keyB; @@ -297,12 +297,12 @@ void b2CreateContact(b2World* world, b2Shape* shapeA, b2Shape* shapeB) } // Add to pair set for fast lookup - uint64_t pairKey = B2_SHAPE_PAIR_KEY(shapeIdA, shapeIdB); - b2AddKey(&world->broadPhase.pairSet, pairKey); + uint64_t pairKey = B2_SHAPE_PAIR_KEY( shapeIdA, shapeIdB ); + b2AddKey( &world->broadPhase.pairSet, pairKey ); // Contacts are created as non-touching. Later if they are found to be touching // they will link islands and be moved into the constraint graph. - b2ContactSim* contactSim = b2AddContact(&set->contacts); + b2ContactSim* contactSim = b2AddContact( &set->contacts ); contactSim->contactId = contactId; #if B2_VALIDATE @@ -319,13 +319,13 @@ void b2CreateContact(b2World* world, b2Shape* shapeA, b2Shape* shapeB) contactSim->shapeIdA = shapeIdA; contactSim->shapeIdB = shapeIdB; contactSim->cache = b2_emptyDistanceCache; - contactSim->manifold = (b2Manifold){0}; - contactSim->friction = b2MixFriction(shapeA->friction, shapeB->friction); - contactSim->restitution = b2MixRestitution(shapeA->restitution, shapeB->restitution); + contactSim->manifold = ( b2Manifold ){ 0 }; + contactSim->friction = b2MixFriction( shapeA->friction, shapeB->friction ); + contactSim->restitution = b2MixRestitution( shapeA->restitution, shapeB->restitution ); contactSim->tangentSpeed = 0.0f; contactSim->simFlags = 0; - if (shapeA->enablePreSolveEvents || shapeB->enablePreSolveEvents) + if ( shapeA->enablePreSolveEvents || shapeB->enablePreSolveEvents ) { contactSim->simFlags |= b2_simEnablePreSolveEvents; } @@ -339,19 +339,19 @@ void b2CreateContact(b2World* world, b2Shape* shapeA, b2Shape* shapeB) // - a shape is destroyed // - contact filtering is modified // - a shape becomes a sensor (check this!!!) -void b2DestroyContact(b2World* world, b2Contact* contact, bool wakeBodies) +void b2DestroyContact( b2World* world, b2Contact* contact, bool wakeBodies ) { // Remove pair from set - uint64_t pairKey = B2_SHAPE_PAIR_KEY(contact->shapeIdA, contact->shapeIdB); - b2RemoveKey(&world->broadPhase.pairSet, pairKey); + uint64_t pairKey = B2_SHAPE_PAIR_KEY( contact->shapeIdA, contact->shapeIdB ); + b2RemoveKey( &world->broadPhase.pairSet, pairKey ); b2ContactEdge* edgeA = contact->edges + 0; b2ContactEdge* edgeB = contact->edges + 1; int bodyIdA = edgeA->bodyId; int bodyIdB = edgeB->bodyId; - b2Body* bodyA = b2GetBody(world, bodyIdA); - b2Body* bodyB = b2GetBody(world, bodyIdB); + b2Body* bodyA = b2GetBody( world, bodyIdA ); + b2Body* bodyB = b2GetBody( world, bodyIdB ); // if (contactListener && contact->IsTouching()) //{ @@ -359,24 +359,24 @@ void b2DestroyContact(b2World* world, b2Contact* contact, bool wakeBodies) // } // Remove from body A - if (edgeA->prevKey != B2_NULL_INDEX) + if ( edgeA->prevKey != B2_NULL_INDEX ) { - b2Contact* prevContact = world->contactArray + (edgeA->prevKey >> 1); - b2ContactEdge* prevEdge = prevContact->edges + (edgeA->prevKey & 1); + b2Contact* prevContact = world->contactArray + ( edgeA->prevKey >> 1 ); + b2ContactEdge* prevEdge = prevContact->edges + ( edgeA->prevKey & 1 ); prevEdge->nextKey = edgeA->nextKey; } - if (edgeA->nextKey != B2_NULL_INDEX) + if ( edgeA->nextKey != B2_NULL_INDEX ) { - b2Contact* nextContact = world->contactArray + (edgeA->nextKey >> 1); - b2ContactEdge* nextEdge = nextContact->edges + (edgeA->nextKey & 1); + b2Contact* nextContact = world->contactArray + ( edgeA->nextKey >> 1 ); + b2ContactEdge* nextEdge = nextContact->edges + ( edgeA->nextKey & 1 ); nextEdge->prevKey = edgeA->prevKey; } int contactId = contact->contactId; - int edgeKeyA = (contactId << 1) | 0; - if (bodyA->headContactKey == edgeKeyA) + int edgeKeyA = ( contactId << 1 ) | 0; + if ( bodyA->headContactKey == edgeKeyA ) { bodyA->headContactKey = edgeA->nextKey; } @@ -384,22 +384,22 @@ void b2DestroyContact(b2World* world, b2Contact* contact, bool wakeBodies) bodyA->contactCount -= 1; // Remove from body B - if (edgeB->prevKey != B2_NULL_INDEX) + if ( edgeB->prevKey != B2_NULL_INDEX ) { - b2Contact* prevContact = world->contactArray + (edgeB->prevKey >> 1); - b2ContactEdge* prevEdge = prevContact->edges + (edgeB->prevKey & 1); + b2Contact* prevContact = world->contactArray + ( edgeB->prevKey >> 1 ); + b2ContactEdge* prevEdge = prevContact->edges + ( edgeB->prevKey & 1 ); prevEdge->nextKey = edgeB->nextKey; } - if (edgeB->nextKey != B2_NULL_INDEX) + if ( edgeB->nextKey != B2_NULL_INDEX ) { - b2Contact* nextContact = world->contactArray + (edgeB->nextKey >> 1); - b2ContactEdge* nextEdge = nextContact->edges + (edgeB->nextKey & 1); + b2Contact* nextContact = world->contactArray + ( edgeB->nextKey >> 1 ); + b2ContactEdge* nextEdge = nextContact->edges + ( edgeB->nextKey & 1 ); nextEdge->prevKey = edgeB->prevKey; } - int edgeKeyB = (contactId << 1) | 1; - if (bodyB->headContactKey == edgeKeyB) + int edgeKeyB = ( contactId << 1 ) | 1; + if ( bodyB->headContactKey == edgeKeyB ) { bodyB->headContactKey = edgeB->nextKey; } @@ -407,25 +407,25 @@ void b2DestroyContact(b2World* world, b2Contact* contact, bool wakeBodies) bodyB->contactCount -= 1; // Remove contact from the array that owns it - if (contact->islandId != B2_NULL_INDEX) + if ( contact->islandId != B2_NULL_INDEX ) { - b2UnlinkContact(world, contact); + b2UnlinkContact( world, contact ); } - if (contact->colorIndex != B2_NULL_INDEX) + if ( contact->colorIndex != B2_NULL_INDEX ) { // contact is an active constraint - B2_ASSERT(contact->setIndex == b2_awakeSet); - b2RemoveContactFromGraph(world, bodyIdA, bodyIdB, contact->colorIndex, contact->localIndex); + B2_ASSERT( contact->setIndex == b2_awakeSet ); + b2RemoveContactFromGraph( world, bodyIdA, bodyIdB, contact->colorIndex, contact->localIndex ); } else { // contact is non-touching or is sleeping or is a sensor - B2_ASSERT(contact->setIndex != b2_awakeSet || (contact->flags & b2_contactTouchingFlag) == 0 || - (contact->flags & b2_contactSensorFlag) != 0); + B2_ASSERT( contact->setIndex != b2_awakeSet || ( contact->flags & b2_contactTouchingFlag ) == 0 || + ( contact->flags & b2_contactSensorFlag ) != 0 ); b2SolverSet* set = world->solverSetArray + contact->setIndex; - int movedIndex = b2RemoveContact(&set->contacts, contact->localIndex); - if (movedIndex != B2_NULL_INDEX) + int movedIndex = b2RemoveContact( &set->contacts, contact->localIndex ); + if ( movedIndex != B2_NULL_INDEX ) { b2ContactSim* movedContact = set->contacts.data + contact->localIndex; world->contactArray[movedContact->contactId].localIndex = contact->localIndex; @@ -437,68 +437,69 @@ void b2DestroyContact(b2World* world, b2Contact* contact, bool wakeBodies) contact->colorIndex = B2_NULL_INDEX; contact->localIndex = B2_NULL_INDEX; - b2FreeId(&world->contactIdPool, contactId); + b2FreeId( &world->contactIdPool, contactId ); - if (wakeBodies) + if ( wakeBodies ) { - b2WakeBody(world, bodyA); - b2WakeBody(world, bodyB); + b2WakeBody( world, bodyA ); + b2WakeBody( world, bodyB ); } } -b2ContactSim* b2GetContactSim(b2World* world, b2Contact* contact) +b2ContactSim* b2GetContactSim( b2World* world, b2Contact* contact ) { - if (contact->setIndex == b2_awakeSet && contact->colorIndex != B2_NULL_INDEX) + if ( contact->setIndex == b2_awakeSet && contact->colorIndex != B2_NULL_INDEX ) { // contact lives in constraint graph - B2_ASSERT(0 <= contact->colorIndex && contact->colorIndex < b2_graphColorCount); + B2_ASSERT( 0 <= contact->colorIndex && contact->colorIndex < b2_graphColorCount ); b2GraphColor* color = world->constraintGraph.colors + contact->colorIndex; - B2_ASSERT(0 <= contact->localIndex && contact->localIndex < color->contacts.count); + B2_ASSERT( 0 <= contact->localIndex && contact->localIndex < color->contacts.count ); return color->contacts.data + contact->localIndex; } b2SolverSet* set = world->solverSetArray + contact->setIndex; - B2_ASSERT(0 <= contact->localIndex && contact->localIndex <= set->contacts.count); + B2_ASSERT( 0 <= contact->localIndex && contact->localIndex <= set->contacts.count ); return set->contacts.data + contact->localIndex; } -bool b2ShouldShapesCollide(b2Filter filterA, b2Filter filterB) +bool b2ShouldShapesCollide( b2Filter filterA, b2Filter filterB ) { - if (filterA.groupIndex == filterB.groupIndex && filterA.groupIndex != 0) + if ( filterA.groupIndex == filterB.groupIndex && filterA.groupIndex != 0 ) { return filterA.groupIndex > 0; } - bool collide = (filterA.maskBits & filterB.categoryBits) != 0 && (filterA.categoryBits & filterB.maskBits) != 0; + bool collide = ( filterA.maskBits & filterB.categoryBits ) != 0 && ( filterA.categoryBits & filterB.maskBits ) != 0; return collide; } -static bool b2TestShapeOverlap(const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, b2DistanceCache* cache) +static bool b2TestShapeOverlap( const b2Shape* shapeA, b2Transform xfA, const b2Shape* shapeB, b2Transform xfB, + b2DistanceCache* cache ) { b2DistanceInput input; - input.proxyA = b2MakeShapeDistanceProxy(shapeA); - input.proxyB = b2MakeShapeDistanceProxy(shapeB); + input.proxyA = b2MakeShapeDistanceProxy( shapeA ); + input.proxyB = b2MakeShapeDistanceProxy( shapeB ); input.transformA = xfA; input.transformB = xfB; input.useRadii = true; - b2DistanceOutput output = b2ShapeDistance(cache, &input, NULL, 0); + b2DistanceOutput output = b2ShapeDistance( cache, &input, NULL, 0 ); return output.distance < 10.0f * FLT_EPSILON; } // Update the contact manifold and touching status. Also updates sensor overlap. // Note: do not assume the shape AABBs are overlapping or are valid. -bool b2UpdateContact(b2World* world, b2ContactSim* contactSim, b2Shape* shapeA, b2Transform transformA, b2Vec2 centerOffsetA, - b2Shape* shapeB, b2Transform transformB, b2Vec2 centerOffsetB) +bool b2UpdateContact( b2World* world, b2ContactSim* contactSim, b2Shape* shapeA, b2Transform transformA, b2Vec2 centerOffsetA, + b2Shape* shapeB, b2Transform transformB, b2Vec2 centerOffsetB ) { bool touching; // Is this contact a sensor? - if (shapeA->isSensor || shapeB->isSensor) + if ( shapeA->isSensor || shapeB->isSensor ) { // Sensors don't generate manifolds or hit events - touching = b2TestShapeOverlap(shapeA, transformA, shapeB, transformB, &contactSim->cache); + touching = b2TestShapeOverlap( shapeA, transformA, shapeB, transformB, &contactSim->cache ); } else { @@ -507,26 +508,26 @@ bool b2UpdateContact(b2World* world, b2ContactSim* contactSim, b2Shape* shapeA, // Compute TOI b2ManifoldFcn* fcn = s_registers[shapeA->type][shapeB->type].fcn; - contactSim->manifold = fcn(shapeA, transformA, shapeB, transformB, &contactSim->cache); + contactSim->manifold = fcn( shapeA, transformA, shapeB, transformB, &contactSim->cache ); int pointCount = contactSim->manifold.pointCount; touching = pointCount > 0; - if (touching && world->preSolveFcn && (contactSim->simFlags & b2_simEnablePreSolveEvents) != 0) + if ( touching && world->preSolveFcn && ( contactSim->simFlags & b2_simEnablePreSolveEvents ) != 0 ) { - b2ShapeId shapeIdA = {shapeA->id + 1, world->worldId, shapeA->revision}; - b2ShapeId shapeIdB = {shapeB->id + 1, world->worldId, shapeB->revision}; + b2ShapeId shapeIdA = { shapeA->id + 1, world->worldId, shapeA->revision }; + b2ShapeId shapeIdB = { shapeB->id + 1, world->worldId, shapeB->revision }; // this call assumes thread safety - touching = world->preSolveFcn(shapeIdA, shapeIdB, &contactSim->manifold, world->preSolveContext); - if (touching == false) + touching = world->preSolveFcn( shapeIdA, shapeIdB, &contactSim->manifold, world->preSolveContext ); + if ( touching == false ) { // disable contact contactSim->manifold.pointCount = 0; } } - if (touching && (shapeA->enableHitEvents || shapeB->enableHitEvents)) + if ( touching && ( shapeA->enableHitEvents || shapeB->enableHitEvents ) ) { contactSim->simFlags |= b2_simEnableHitEvent; } @@ -537,13 +538,13 @@ bool b2UpdateContact(b2World* world, b2ContactSim* contactSim, b2Shape* shapeA, // Match old contact ids to new contact ids and copy the // stored impulses to warm start the solver. - for (int i = 0; i < pointCount; ++i) + for ( int i = 0; i < pointCount; ++i ) { b2ManifoldPoint* mp2 = contactSim->manifold.points + i; // shift anchors to be center of mass relative - mp2->anchorA = b2Sub(mp2->anchorA, centerOffsetA); - mp2->anchorB = b2Sub(mp2->anchorB, centerOffsetB); + mp2->anchorA = b2Sub( mp2->anchorA, centerOffsetA ); + mp2->anchorB = b2Sub( mp2->anchorB, centerOffsetB ); mp2->normalImpulse = 0.0f; mp2->tangentImpulse = 0.0f; @@ -553,11 +554,11 @@ bool b2UpdateContact(b2World* world, b2ContactSim* contactSim, b2Shape* shapeA, uint16_t id2 = mp2->id; - for (int j = 0; j < oldManifold.pointCount; ++j) + for ( int j = 0; j < oldManifold.pointCount; ++j ) { b2ManifoldPoint* mp1 = oldManifold.points + j; - if (mp1->id == id2) + if ( mp1->id == id2 ) { mp2->normalImpulse = mp1->normalImpulse; mp2->tangentImpulse = mp1->tangentImpulse; @@ -568,7 +569,7 @@ bool b2UpdateContact(b2World* world, b2ContactSim* contactSim, b2Shape* shapeA, } } - if (touching) + if ( touching ) { contactSim->simFlags |= b2_simTouchingFlag; } diff --git a/src/contact.h b/src/contact.h index bff955d8..4b53d656 100644 --- a/src/contact.h +++ b/src/contact.h @@ -140,14 +140,14 @@ typedef struct b2ContactSim b2DistanceCache cache; } b2ContactSim; -void b2InitializeContactRegisters(void); +void b2InitializeContactRegisters( void ); -void b2CreateContact(b2World* world, b2Shape* shapeA, b2Shape* shapeB); -void b2DestroyContact(b2World* world, b2Contact* contact, bool wakeBodies); +void b2CreateContact( b2World* world, b2Shape* shapeA, b2Shape* shapeB ); +void b2DestroyContact( b2World* world, b2Contact* contact, bool wakeBodies ); -b2ContactSim* b2GetContactSim(b2World* world, b2Contact* contact); +b2ContactSim* b2GetContactSim( b2World* world, b2Contact* contact ); -bool b2ShouldShapesCollide(b2Filter filterA, b2Filter filterB); +bool b2ShouldShapesCollide( b2Filter filterA, b2Filter filterB ); -bool b2UpdateContact(b2World* world, b2ContactSim* contactSim, b2Shape* shapeA, b2Transform transformA, b2Vec2 centerOffsetA, - b2Shape* shapeB, b2Transform transformB, b2Vec2 centerOffsetB); +bool b2UpdateContact( b2World* world, b2ContactSim* contactSim, b2Shape* shapeA, b2Transform transformA, b2Vec2 centerOffsetA, + b2Shape* shapeB, b2Transform transformB, b2Vec2 centerOffsetB ); diff --git a/src/contact_solver.c b/src/contact_solver.c index d4379c4d..b1905011 100644 --- a/src/contact_solver.c +++ b/src/contact_solver.c @@ -18,9 +18,9 @@ // Uses fixed anchors for Jacobians for better behavior on rolling shapes (circles & capsules) -void b2PrepareOverflowContacts(b2StepContext* context) +void b2PrepareOverflowContacts( b2StepContext* context ) { - b2TracyCZoneNC(prepare_overflow_contact, "Prepare Overflow Contact", b2_colorYellow, true); + b2TracyCZoneNC( prepare_overflow_contact, "Prepare Overflow Contact", b2_colorYellow, true ); b2World* world = context->world; b2ConstraintGraph* graph = context->graph; @@ -40,14 +40,14 @@ void b2PrepareOverflowContacts(b2StepContext* context) float warmStartScale = world->enableWarmStarting ? 1.0f : 0.0f; - for (int i = 0; i < contactCount; ++i) + for ( int i = 0; i < contactCount; ++i ) { b2ContactSim* contactSim = contacts + i; const b2Manifold* manifold = &contactSim->manifold; int pointCount = manifold->pointCount; - B2_ASSERT(0 < pointCount && pointCount <= 2); + B2_ASSERT( 0 < pointCount && pointCount <= 2 ); int indexA = contactSim->bodySimIndexA; int indexB = contactSim->bodySimIndexB; @@ -55,11 +55,11 @@ void b2PrepareOverflowContacts(b2StepContext* context) #if B2_VALIDATE b2Body* bodyA = bodies + contactSim->bodyIdA; int validIndexA = bodyA->setIndex == b2_awakeSet ? bodyA->localIndex : B2_NULL_INDEX; - B2_ASSERT(indexA == validIndexA); + B2_ASSERT( indexA == validIndexA ); b2Body* bodyB = bodies + contactSim->bodyIdB; int validIndexB = bodyB->setIndex == b2_awakeSet ? bodyB->localIndex : B2_NULL_INDEX; - B2_ASSERT(indexB == validIndexB); + B2_ASSERT( indexB == validIndexB ); #endif b2ContactConstraint* constraint = constraints + i; @@ -74,7 +74,7 @@ void b2PrepareOverflowContacts(b2StepContext* context) float wA = 0.0f; float mA = contactSim->invMassA; float iA = contactSim->invIA; - if (indexA != B2_NULL_INDEX) + if ( indexA != B2_NULL_INDEX ) { b2BodyState* stateA = awakeStates + indexA; vA = stateA->linearVelocity; @@ -85,14 +85,14 @@ void b2PrepareOverflowContacts(b2StepContext* context) float wB = 0.0f; float mB = contactSim->invMassB; float iB = contactSim->invIB; - if (indexB != B2_NULL_INDEX) + if ( indexB != B2_NULL_INDEX ) { b2BodyState* stateB = awakeStates + indexB; vB = stateB->linearVelocity; wB = stateB->angularVelocity; } - if (indexA == B2_NULL_INDEX || indexB == B2_NULL_INDEX) + if ( indexA == B2_NULL_INDEX || indexB == B2_NULL_INDEX ) { constraint->softness = staticSoftness; } @@ -108,9 +108,9 @@ void b2PrepareOverflowContacts(b2StepContext* context) constraint->invIB = iB; b2Vec2 normal = constraint->normal; - b2Vec2 tangent = b2RightPerp(constraint->normal); + b2Vec2 tangent = b2RightPerp( constraint->normal ); - for (int j = 0; j < pointCount; ++j) + for ( int j = 0; j < pointCount; ++j ) { const b2ManifoldPoint* mp = manifold->points + j; b2ContactConstraintPoint* cp = constraint->points + j; @@ -124,31 +124,31 @@ void b2PrepareOverflowContacts(b2StepContext* context) cp->anchorA = rA; cp->anchorB = rB; - cp->baseSeparation = mp->separation - b2Dot(b2Sub(rB, rA), normal); + cp->baseSeparation = mp->separation - b2Dot( b2Sub( rB, rA ), normal ); - float rnA = b2Cross(rA, normal); - float rnB = b2Cross(rB, normal); + float rnA = b2Cross( rA, normal ); + float rnB = b2Cross( rB, normal ); float kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB; cp->normalMass = kNormal > 0.0f ? 1.0f / kNormal : 0.0f; - float rtA = b2Cross(rA, tangent); - float rtB = b2Cross(rB, tangent); + float rtA = b2Cross( rA, tangent ); + float rtB = b2Cross( rB, tangent ); float kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB; cp->tangentMass = kTangent > 0.0f ? 1.0f / kTangent : 0.0f; // Save relative velocity for restitution - b2Vec2 vrA = b2Add(vA, b2CrossSV(wA, rA)); - b2Vec2 vrB = b2Add(vB, b2CrossSV(wB, rB)); - cp->relativeVelocity = b2Dot(normal, b2Sub(vrB, vrA)); + b2Vec2 vrA = b2Add( vA, b2CrossSV( wA, rA ) ); + b2Vec2 vrB = b2Add( vB, b2CrossSV( wB, rB ) ); + cp->relativeVelocity = b2Dot( normal, b2Sub( vrB, vrA ) ); } } - b2TracyCZoneEnd(prepare_overflow_contact); + b2TracyCZoneEnd( prepare_overflow_contact ); } -void b2WarmStartOverflowContacts(b2StepContext* context) +void b2WarmStartOverflowContacts( b2StepContext* context ) { - b2TracyCZoneNC(warmstart_overflow_contact, "WarmStart Overflow Contact", b2_colorDarkOrange2, true); + b2TracyCZoneNC( warmstart_overflow_contact, "WarmStart Overflow Contact", b2_colorDarkOrange, true ); b2ConstraintGraph* graph = context->graph; b2GraphColor* color = graph->colors + b2_overflowIndex; @@ -160,7 +160,7 @@ void b2WarmStartOverflowContacts(b2StepContext* context) // This is a dummy state to represent a static body because static bodies don't have a solver body. b2BodyState dummyState = b2_identityBodyState; - for (int i = 0; i < contactCount; ++i) + for ( int i = 0; i < contactCount; ++i ) { const b2ContactConstraint* constraint = constraints + i; @@ -182,10 +182,10 @@ void b2WarmStartOverflowContacts(b2StepContext* context) // Stiffer for static contacts to avoid bodies getting pushed through the ground b2Vec2 normal = constraint->normal; - b2Vec2 tangent = b2RightPerp(constraint->normal); + b2Vec2 tangent = b2RightPerp( constraint->normal ); int pointCount = constraint->pointCount; - for (int j = 0; j < pointCount; ++j) + for ( int j = 0; j < pointCount; ++j ) { const b2ContactConstraintPoint* cp = constraint->points + j; @@ -193,11 +193,11 @@ void b2WarmStartOverflowContacts(b2StepContext* context) b2Vec2 rA = cp->anchorA; b2Vec2 rB = cp->anchorB; - b2Vec2 P = b2Add(b2MulSV(cp->normalImpulse, normal), b2MulSV(cp->tangentImpulse, tangent)); - wA -= iA * b2Cross(rA, P); - vA = b2MulAdd(vA, -mA, P); - wB += iB * b2Cross(rB, P); - vB = b2MulAdd(vB, mB, P); + b2Vec2 P = b2Add( b2MulSV( cp->normalImpulse, normal ), b2MulSV( cp->tangentImpulse, tangent ) ); + wA -= iA * b2Cross( rA, P ); + vA = b2MulAdd( vA, -mA, P ); + wB += iB * b2Cross( rB, P ); + vB = b2MulAdd( vB, mB, P ); } stateA->linearVelocity = vA; @@ -206,12 +206,12 @@ void b2WarmStartOverflowContacts(b2StepContext* context) stateB->angularVelocity = wB; } - b2TracyCZoneEnd(warmstart_overflow_contact); + b2TracyCZoneEnd( warmstart_overflow_contact ); } -void b2SolveOverflowContacts(b2StepContext* context, bool useBias) +void b2SolveOverflowContacts( b2StepContext* context, bool useBias ) { - b2TracyCZoneNC(solve_contact, "Solve Contact", b2_colorAliceBlue, true); + b2TracyCZoneNC( solve_contact, "Solve Contact", b2_colorAliceBlue, true ); b2ConstraintGraph* graph = context->graph; b2GraphColor* color = graph->colors + b2_overflowIndex; @@ -226,7 +226,7 @@ void b2SolveOverflowContacts(b2StepContext* context, bool useBias) // This is a dummy body to represent a static body since static bodies don't have a solver body. b2BodyState dummyState = b2_identityBodyState; - for (int i = 0; i < contactCount; ++i) + for ( int i = 0; i < contactCount; ++i ) { b2ContactConstraint* constraint = constraints + i; float mA = constraint->invMassA; @@ -244,36 +244,36 @@ void b2SolveOverflowContacts(b2StepContext* context, bool useBias) float wB = stateB->angularVelocity; b2Rot dqB = stateB->deltaRotation; - b2Vec2 dp = b2Sub(stateB->deltaPosition, stateA->deltaPosition); + b2Vec2 dp = b2Sub( stateB->deltaPosition, stateA->deltaPosition ); b2Vec2 normal = constraint->normal; - b2Vec2 tangent = b2RightPerp(normal); + b2Vec2 tangent = b2RightPerp( normal ); float friction = constraint->friction; b2Softness softness = constraint->softness; int pointCount = constraint->pointCount; - for (int j = 0; j < pointCount; ++j) + for ( int j = 0; j < pointCount; ++j ) { b2ContactConstraintPoint* cp = constraint->points + j; // compute current separation // todo this is subject to round-off error if the anchor is far from the body center of mass // todo for example a large world with a single static body and many offset shapes - b2Vec2 ds = b2Add(dp, b2Sub(b2RotateVector(dqB, cp->anchorB), b2RotateVector(dqA, cp->anchorA))); - float s = b2Dot(ds, normal) + cp->baseSeparation; + b2Vec2 ds = b2Add( dp, b2Sub( b2RotateVector( dqB, cp->anchorB ), b2RotateVector( dqA, cp->anchorA ) ) ); + float s = b2Dot( ds, normal ) + cp->baseSeparation; float velocityBias = 0.0f; float massScale = 1.0f; float impulseScale = 0.0f; - if (s > 0.0f) + if ( s > 0.0f ) { // speculative bias velocityBias = s * inv_h; } - else if (useBias) + else if ( useBias ) { - velocityBias = b2MaxFloat(softness.biasRate * s, -pushout); + velocityBias = b2MaxFloat( softness.biasRate * s, -pushout ); massScale = softness.massScale; impulseScale = softness.impulseScale; } @@ -283,29 +283,29 @@ void b2SolveOverflowContacts(b2StepContext* context, bool useBias) b2Vec2 rB = cp->anchorB; // relative normal velocity at contact - b2Vec2 vrA = b2Add(vA, b2CrossSV(wA, rA)); - b2Vec2 vrB = b2Add(vB, b2CrossSV(wB, rB)); - float vn = b2Dot(b2Sub(vrB, vrA), normal); + b2Vec2 vrA = b2Add( vA, b2CrossSV( wA, rA ) ); + b2Vec2 vrB = b2Add( vB, b2CrossSV( wB, rB ) ); + float vn = b2Dot( b2Sub( vrB, vrA ), normal ); // incremental normal impulse - float impulse = -cp->normalMass * massScale * (vn + velocityBias) - impulseScale * cp->normalImpulse; + float impulse = -cp->normalMass * massScale * ( vn + velocityBias ) - impulseScale * cp->normalImpulse; // clamp the accumulated impulse - float newImpulse = b2MaxFloat(cp->normalImpulse + impulse, 0.0f); + float newImpulse = b2MaxFloat( cp->normalImpulse + impulse, 0.0f ); impulse = newImpulse - cp->normalImpulse; cp->normalImpulse = newImpulse; - cp->maxNormalImpulse = b2MaxFloat(cp->maxNormalImpulse, impulse); + cp->maxNormalImpulse = b2MaxFloat( cp->maxNormalImpulse, impulse ); // apply normal impulse - b2Vec2 P = b2MulSV(impulse, normal); - vA = b2MulSub(vA, mA, P); - wA -= iA * b2Cross(rA, P); + b2Vec2 P = b2MulSV( impulse, normal ); + vA = b2MulSub( vA, mA, P ); + wA -= iA * b2Cross( rA, P ); - vB = b2MulAdd(vB, mB, P); - wB += iB * b2Cross(rB, P); + vB = b2MulAdd( vB, mB, P ); + wB += iB * b2Cross( rB, P ); } - for (int j = 0; j < pointCount; ++j) + for ( int j = 0; j < pointCount; ++j ) { b2ContactConstraintPoint* cp = constraint->points + j; @@ -314,25 +314,25 @@ void b2SolveOverflowContacts(b2StepContext* context, bool useBias) b2Vec2 rB = cp->anchorB; // relative tangent velocity at contact - b2Vec2 vrB = b2Add(vB, b2CrossSV(wB, rB)); - b2Vec2 vrA = b2Add(vA, b2CrossSV(wA, rA)); - float vt = b2Dot(b2Sub(vrB, vrA), tangent); + b2Vec2 vrB = b2Add( vB, b2CrossSV( wB, rB ) ); + b2Vec2 vrA = b2Add( vA, b2CrossSV( wA, rA ) ); + float vt = b2Dot( b2Sub( vrB, vrA ), tangent ); // incremental tangent impulse - float impulse = cp->tangentMass * (-vt); + float impulse = cp->tangentMass * ( -vt ); // clamp the accumulated force float maxFriction = friction * cp->normalImpulse; - float newImpulse = b2ClampFloat(cp->tangentImpulse + impulse, -maxFriction, maxFriction); + float newImpulse = b2ClampFloat( cp->tangentImpulse + impulse, -maxFriction, maxFriction ); impulse = newImpulse - cp->tangentImpulse; cp->tangentImpulse = newImpulse; // apply tangent impulse - b2Vec2 P = b2MulSV(impulse, tangent); - vA = b2MulSub(vA, mA, P); - wA -= iA * b2Cross(rA, P); - vB = b2MulAdd(vB, mB, P); - wB += iB * b2Cross(rB, P); + b2Vec2 P = b2MulSV( impulse, tangent ); + vA = b2MulSub( vA, mA, P ); + wA -= iA * b2Cross( rA, P ); + vB = b2MulAdd( vB, mB, P ); + wB += iB * b2Cross( rB, P ); } stateA->linearVelocity = vA; @@ -341,12 +341,12 @@ void b2SolveOverflowContacts(b2StepContext* context, bool useBias) stateB->angularVelocity = wB; } - b2TracyCZoneEnd(solve_contact); + b2TracyCZoneEnd( solve_contact ); } -void b2ApplyOverflowRestitution(b2StepContext* context) +void b2ApplyOverflowRestitution( b2StepContext* context ) { - b2TracyCZoneNC(overflow_resitution, "Overflow Restitution", b2_colorViolet, true); + b2TracyCZoneNC( overflow_resitution, "Overflow Restitution", b2_colorViolet, true ); b2ConstraintGraph* graph = context->graph; b2GraphColor* color = graph->colors + b2_overflowIndex; @@ -360,12 +360,12 @@ void b2ApplyOverflowRestitution(b2StepContext* context) // dummy state to represent a static body b2BodyState dummyState = b2_identityBodyState; - for (int i = 0; i < contactCount; ++i) + for ( int i = 0; i < contactCount; ++i ) { b2ContactConstraint* constraint = constraints + i; float restitution = constraint->restitution; - if (restitution == 0.0f) + if ( restitution == 0.0f ) { continue; } @@ -390,14 +390,14 @@ void b2ApplyOverflowRestitution(b2StepContext* context) // this only makes a difference if there are two contact points // for (int iter = 0; iter < 10; ++iter) { - for (int j = 0; j < pointCount; ++j) + for ( int j = 0; j < pointCount; ++j ) { b2ContactConstraintPoint* cp = constraint->points + j; // if the normal impulse is zero then there was no collision // this skips speculative contact points that didn't generate an impulse // The max normal impulse is used in case there was a collision that moved away within the sub-step process - if (cp->relativeVelocity > -threshold || cp->maxNormalImpulse == 0.0f) + if ( cp->relativeVelocity > -threshold || cp->maxNormalImpulse == 0.0f ) { continue; } @@ -407,26 +407,26 @@ void b2ApplyOverflowRestitution(b2StepContext* context) b2Vec2 rB = cp->anchorB; // relative normal velocity at contact - b2Vec2 vrB = b2Add(vB, b2CrossSV(wB, rB)); - b2Vec2 vrA = b2Add(vA, b2CrossSV(wA, rA)); - float vn = b2Dot(b2Sub(vrB, vrA), normal); + b2Vec2 vrB = b2Add( vB, b2CrossSV( wB, rB ) ); + b2Vec2 vrA = b2Add( vA, b2CrossSV( wA, rA ) ); + float vn = b2Dot( b2Sub( vrB, vrA ), normal ); // compute normal impulse - float impulse = -cp->normalMass * (vn + restitution * cp->relativeVelocity); + float impulse = -cp->normalMass * ( vn + restitution * cp->relativeVelocity ); // clamp the accumulated impulse // todo should this be stored? - float newImpulse = b2MaxFloat(cp->normalImpulse + impulse, 0.0f); + float newImpulse = b2MaxFloat( cp->normalImpulse + impulse, 0.0f ); impulse = newImpulse - cp->normalImpulse; cp->normalImpulse = newImpulse; - cp->maxNormalImpulse = b2MaxFloat(cp->maxNormalImpulse, impulse); + cp->maxNormalImpulse = b2MaxFloat( cp->maxNormalImpulse, impulse ); // apply contact impulse - b2Vec2 P = b2MulSV(impulse, normal); - vA = b2MulSub(vA, mA, P); - wA -= iA * b2Cross(rA, P); - vB = b2MulAdd(vB, mB, P); - wB += iB * b2Cross(rB, P); + b2Vec2 P = b2MulSV( impulse, normal ); + vA = b2MulSub( vA, mA, P ); + wA -= iA * b2Cross( rA, P ); + vB = b2MulAdd( vB, mB, P ); + wB += iB * b2Cross( rB, P ); } } @@ -436,12 +436,12 @@ void b2ApplyOverflowRestitution(b2StepContext* context) stateB->angularVelocity = wB; } - b2TracyCZoneEnd(overflow_resitution); + b2TracyCZoneEnd( overflow_resitution ); } -void b2StoreOverflowImpulses(b2StepContext* context) +void b2StoreOverflowImpulses( b2StepContext* context ) { - b2TracyCZoneNC(store_impulses, "Store", b2_colorFirebrick, true); + b2TracyCZoneNC( store_impulses, "Store", b2_colorFirebrick, true ); b2ConstraintGraph* graph = context->graph; b2GraphColor* color = graph->colors + b2_overflowIndex; @@ -449,16 +449,16 @@ void b2StoreOverflowImpulses(b2StepContext* context) b2ContactSim* contacts = color->contacts.data; int contactCount = color->contacts.count; - //float hitEventThreshold = context->world->hitEventThreshold; + // float hitEventThreshold = context->world->hitEventThreshold; - for (int i = 0; i < contactCount; ++i) + for ( int i = 0; i < contactCount; ++i ) { const b2ContactConstraint* constraint = constraints + i; b2ContactSim* contact = contacts + i; b2Manifold* manifold = &contact->manifold; int pointCount = manifold->pointCount; - for (int j = 0; j < pointCount; ++j) + for ( int j = 0; j < pointCount; ++j ) { manifold->points[j].normalImpulse = constraint->points[j].normalImpulse; manifold->points[j].tangentImpulse = constraint->points[j].tangentImpulse; @@ -467,34 +467,34 @@ void b2StoreOverflowImpulses(b2StepContext* context) } } - b2TracyCZoneEnd(store_impulses); + b2TracyCZoneEnd( store_impulses ); } // SIMD WIP -#define add(a, b) simde_mm256_add_ps((a), (b)) -#define sub(a, b) simde_mm256_sub_ps((a), (b)) -#define mul(a, b) simde_mm256_mul_ps((a), (b)) +#define add( a, b ) simde_mm256_add_ps( ( a ), ( b ) ) +#define sub( a, b ) simde_mm256_sub_ps( ( a ), ( b ) ) +#define mul( a, b ) simde_mm256_mul_ps( ( a ), ( b ) ) // todo SIMDE implementation of simde_mm256_fnmadd_ps is slow if FMA is not available // #define muladd(a, b, c) simde_mm256_fmadd_ps(b, c, a) // #define mulsub(a, b, c) simde_mm256_fnmadd_ps(b, c, a) -#define muladd(a, b, c) simde_mm256_add_ps((a), simde_mm256_mul_ps((b), (c))) -#define mulsub(a, b, c) simde_mm256_sub_ps((a), simde_mm256_mul_ps((b), (c))) +#define muladd( a, b, c ) simde_mm256_add_ps( ( a ), simde_mm256_mul_ps( ( b ), ( c ) ) ) +#define mulsub( a, b, c ) simde_mm256_sub_ps( ( a ), simde_mm256_mul_ps( ( b ), ( c ) ) ) -static inline b2FloatW b2DotW(b2Vec2W a, b2Vec2W b) +static inline b2FloatW b2DotW( b2Vec2W a, b2Vec2W b ) { - return add(mul(a.X, b.X), mul(a.Y, b.Y)); + return add( mul( a.X, b.X ), mul( a.Y, b.Y ) ); } -static inline b2FloatW b2CrossW(b2Vec2W a, b2Vec2W b) +static inline b2FloatW b2CrossW( b2Vec2W a, b2Vec2W b ) { - return sub(mul(a.X, b.Y), mul(a.Y, b.X)); + return sub( mul( a.X, b.Y ), mul( a.Y, b.X ) ); } -static inline b2Vec2W b2RotateVectorW(b2RotW q, b2Vec2W v) +static inline b2Vec2W b2RotateVectorW( b2RotW q, b2Vec2W v ) { - return (b2Vec2W){sub(mul(q.C, v.X), mul(q.S, v.Y)), add(mul(q.S, v.X), mul(q.C, v.Y))}; + return ( b2Vec2W ){ sub( mul( q.C, v.X ), mul( q.S, v.Y ) ), add( mul( q.S, v.X ), mul( q.C, v.Y ) ) }; } // wide version of b2BodyState @@ -508,95 +508,95 @@ typedef struct b2SimdBody } b2SimdBody; // This is a load and 8x8 transpose -static b2SimdBody b2GatherBodies(const b2BodyState* restrict states, int* restrict indices) +static b2SimdBody b2GatherBodies( const b2BodyState* restrict states, int* restrict indices ) { - _Static_assert(sizeof(b2BodyState) == 32, "b2BodyState not 32 bytes"); - B2_ASSERT(((uintptr_t)states & 0x1F) == 0); + _Static_assert( sizeof( b2BodyState ) == 32, "b2BodyState not 32 bytes" ); + B2_ASSERT( ( (uintptr_t)states & 0x1F ) == 0 ); // static const b2BodyState b2_identityBodyState = {{0.0f, 0.0f}, 0.0f, 0, {0.0f, 0.0f}, {1.0f, 0.0f}}; - b2FloatW identity = simde_mm256_setr_ps(0.0f, 0.0f, 0.0f, 0, 0.0f, 0.0f, 1.0f, 0.0f); - b2FloatW b0 = indices[0] == B2_NULL_INDEX ? identity : simde_mm256_load_ps((float*)(states + indices[0])); - b2FloatW b1 = indices[1] == B2_NULL_INDEX ? identity : simde_mm256_load_ps((float*)(states + indices[1])); - b2FloatW b2 = indices[2] == B2_NULL_INDEX ? identity : simde_mm256_load_ps((float*)(states + indices[2])); - b2FloatW b3 = indices[3] == B2_NULL_INDEX ? identity : simde_mm256_load_ps((float*)(states + indices[3])); - b2FloatW b4 = indices[4] == B2_NULL_INDEX ? identity : simde_mm256_load_ps((float*)(states + indices[4])); - b2FloatW b5 = indices[5] == B2_NULL_INDEX ? identity : simde_mm256_load_ps((float*)(states + indices[5])); - b2FloatW b6 = indices[6] == B2_NULL_INDEX ? identity : simde_mm256_load_ps((float*)(states + indices[6])); - b2FloatW b7 = indices[7] == B2_NULL_INDEX ? identity : simde_mm256_load_ps((float*)(states + indices[7])); - - b2FloatW t0 = simde_mm256_unpacklo_ps(b0, b1); - b2FloatW t1 = simde_mm256_unpackhi_ps(b0, b1); - b2FloatW t2 = simde_mm256_unpacklo_ps(b2, b3); - b2FloatW t3 = simde_mm256_unpackhi_ps(b2, b3); - b2FloatW t4 = simde_mm256_unpacklo_ps(b4, b5); - b2FloatW t5 = simde_mm256_unpackhi_ps(b4, b5); - b2FloatW t6 = simde_mm256_unpacklo_ps(b6, b7); - b2FloatW t7 = simde_mm256_unpackhi_ps(b6, b7); - b2FloatW tt0 = simde_mm256_shuffle_ps(t0, t2, SIMDE_MM_SHUFFLE(1, 0, 1, 0)); - b2FloatW tt1 = simde_mm256_shuffle_ps(t0, t2, SIMDE_MM_SHUFFLE(3, 2, 3, 2)); - b2FloatW tt2 = simde_mm256_shuffle_ps(t1, t3, SIMDE_MM_SHUFFLE(1, 0, 1, 0)); - b2FloatW tt3 = simde_mm256_shuffle_ps(t1, t3, SIMDE_MM_SHUFFLE(3, 2, 3, 2)); - b2FloatW tt4 = simde_mm256_shuffle_ps(t4, t6, SIMDE_MM_SHUFFLE(1, 0, 1, 0)); - b2FloatW tt5 = simde_mm256_shuffle_ps(t4, t6, SIMDE_MM_SHUFFLE(3, 2, 3, 2)); - b2FloatW tt6 = simde_mm256_shuffle_ps(t5, t7, SIMDE_MM_SHUFFLE(1, 0, 1, 0)); - b2FloatW tt7 = simde_mm256_shuffle_ps(t5, t7, SIMDE_MM_SHUFFLE(3, 2, 3, 2)); + b2FloatW identity = simde_mm256_setr_ps( 0.0f, 0.0f, 0.0f, 0, 0.0f, 0.0f, 1.0f, 0.0f ); + b2FloatW b0 = indices[0] == B2_NULL_INDEX ? identity : simde_mm256_load_ps( (float*)( states + indices[0] ) ); + b2FloatW b1 = indices[1] == B2_NULL_INDEX ? identity : simde_mm256_load_ps( (float*)( states + indices[1] ) ); + b2FloatW b2 = indices[2] == B2_NULL_INDEX ? identity : simde_mm256_load_ps( (float*)( states + indices[2] ) ); + b2FloatW b3 = indices[3] == B2_NULL_INDEX ? identity : simde_mm256_load_ps( (float*)( states + indices[3] ) ); + b2FloatW b4 = indices[4] == B2_NULL_INDEX ? identity : simde_mm256_load_ps( (float*)( states + indices[4] ) ); + b2FloatW b5 = indices[5] == B2_NULL_INDEX ? identity : simde_mm256_load_ps( (float*)( states + indices[5] ) ); + b2FloatW b6 = indices[6] == B2_NULL_INDEX ? identity : simde_mm256_load_ps( (float*)( states + indices[6] ) ); + b2FloatW b7 = indices[7] == B2_NULL_INDEX ? identity : simde_mm256_load_ps( (float*)( states + indices[7] ) ); + + b2FloatW t0 = simde_mm256_unpacklo_ps( b0, b1 ); + b2FloatW t1 = simde_mm256_unpackhi_ps( b0, b1 ); + b2FloatW t2 = simde_mm256_unpacklo_ps( b2, b3 ); + b2FloatW t3 = simde_mm256_unpackhi_ps( b2, b3 ); + b2FloatW t4 = simde_mm256_unpacklo_ps( b4, b5 ); + b2FloatW t5 = simde_mm256_unpackhi_ps( b4, b5 ); + b2FloatW t6 = simde_mm256_unpacklo_ps( b6, b7 ); + b2FloatW t7 = simde_mm256_unpackhi_ps( b6, b7 ); + b2FloatW tt0 = simde_mm256_shuffle_ps( t0, t2, SIMDE_MM_SHUFFLE( 1, 0, 1, 0 ) ); + b2FloatW tt1 = simde_mm256_shuffle_ps( t0, t2, SIMDE_MM_SHUFFLE( 3, 2, 3, 2 ) ); + b2FloatW tt2 = simde_mm256_shuffle_ps( t1, t3, SIMDE_MM_SHUFFLE( 1, 0, 1, 0 ) ); + b2FloatW tt3 = simde_mm256_shuffle_ps( t1, t3, SIMDE_MM_SHUFFLE( 3, 2, 3, 2 ) ); + b2FloatW tt4 = simde_mm256_shuffle_ps( t4, t6, SIMDE_MM_SHUFFLE( 1, 0, 1, 0 ) ); + b2FloatW tt5 = simde_mm256_shuffle_ps( t4, t6, SIMDE_MM_SHUFFLE( 3, 2, 3, 2 ) ); + b2FloatW tt6 = simde_mm256_shuffle_ps( t5, t7, SIMDE_MM_SHUFFLE( 1, 0, 1, 0 ) ); + b2FloatW tt7 = simde_mm256_shuffle_ps( t5, t7, SIMDE_MM_SHUFFLE( 3, 2, 3, 2 ) ); b2SimdBody simdBody; - simdBody.v.X = simde_mm256_permute2f128_ps(tt0, tt4, 0x20); - simdBody.v.Y = simde_mm256_permute2f128_ps(tt1, tt5, 0x20); - simdBody.w = simde_mm256_permute2f128_ps(tt2, tt6, 0x20); - simdBody.flags = simde_mm256_permute2f128_ps(tt3, tt7, 0x20); - simdBody.dp.X = simde_mm256_permute2f128_ps(tt0, tt4, 0x31); - simdBody.dp.Y = simde_mm256_permute2f128_ps(tt1, tt5, 0x31); - simdBody.dq.C = simde_mm256_permute2f128_ps(tt2, tt6, 0x31); - simdBody.dq.S = simde_mm256_permute2f128_ps(tt3, tt7, 0x31); + simdBody.v.X = simde_mm256_permute2f128_ps( tt0, tt4, 0x20 ); + simdBody.v.Y = simde_mm256_permute2f128_ps( tt1, tt5, 0x20 ); + simdBody.w = simde_mm256_permute2f128_ps( tt2, tt6, 0x20 ); + simdBody.flags = simde_mm256_permute2f128_ps( tt3, tt7, 0x20 ); + simdBody.dp.X = simde_mm256_permute2f128_ps( tt0, tt4, 0x31 ); + simdBody.dp.Y = simde_mm256_permute2f128_ps( tt1, tt5, 0x31 ); + simdBody.dq.C = simde_mm256_permute2f128_ps( tt2, tt6, 0x31 ); + simdBody.dq.S = simde_mm256_permute2f128_ps( tt3, tt7, 0x31 ); return simdBody; } // This writes everything back to the solver bodies but only the velocities change -static void b2ScatterBodies(b2BodyState* restrict states, int* restrict indices, const b2SimdBody* restrict simdBody) +static void b2ScatterBodies( b2BodyState* restrict states, int* restrict indices, const b2SimdBody* restrict simdBody ) { - _Static_assert(sizeof(b2BodyState) == 32, "b2BodyState not 32 bytes"); - B2_ASSERT(((uintptr_t)states & 0x1F) == 0); - b2FloatW t0 = simde_mm256_unpacklo_ps(simdBody->v.X, simdBody->v.Y); - b2FloatW t1 = simde_mm256_unpackhi_ps(simdBody->v.X, simdBody->v.Y); - b2FloatW t2 = simde_mm256_unpacklo_ps(simdBody->w, simdBody->flags); - b2FloatW t3 = simde_mm256_unpackhi_ps(simdBody->w, simdBody->flags); - b2FloatW t4 = simde_mm256_unpacklo_ps(simdBody->dp.X, simdBody->dp.Y); - b2FloatW t5 = simde_mm256_unpackhi_ps(simdBody->dp.X, simdBody->dp.Y); - b2FloatW t6 = simde_mm256_unpacklo_ps(simdBody->dq.C, simdBody->dq.S); - b2FloatW t7 = simde_mm256_unpackhi_ps(simdBody->dq.C, simdBody->dq.S); - b2FloatW tt0 = simde_mm256_shuffle_ps(t0, t2, SIMDE_MM_SHUFFLE(1, 0, 1, 0)); - b2FloatW tt1 = simde_mm256_shuffle_ps(t0, t2, SIMDE_MM_SHUFFLE(3, 2, 3, 2)); - b2FloatW tt2 = simde_mm256_shuffle_ps(t1, t3, SIMDE_MM_SHUFFLE(1, 0, 1, 0)); - b2FloatW tt3 = simde_mm256_shuffle_ps(t1, t3, SIMDE_MM_SHUFFLE(3, 2, 3, 2)); - b2FloatW tt4 = simde_mm256_shuffle_ps(t4, t6, SIMDE_MM_SHUFFLE(1, 0, 1, 0)); - b2FloatW tt5 = simde_mm256_shuffle_ps(t4, t6, SIMDE_MM_SHUFFLE(3, 2, 3, 2)); - b2FloatW tt6 = simde_mm256_shuffle_ps(t5, t7, SIMDE_MM_SHUFFLE(1, 0, 1, 0)); - b2FloatW tt7 = simde_mm256_shuffle_ps(t5, t7, SIMDE_MM_SHUFFLE(3, 2, 3, 2)); + _Static_assert( sizeof( b2BodyState ) == 32, "b2BodyState not 32 bytes" ); + B2_ASSERT( ( (uintptr_t)states & 0x1F ) == 0 ); + b2FloatW t0 = simde_mm256_unpacklo_ps( simdBody->v.X, simdBody->v.Y ); + b2FloatW t1 = simde_mm256_unpackhi_ps( simdBody->v.X, simdBody->v.Y ); + b2FloatW t2 = simde_mm256_unpacklo_ps( simdBody->w, simdBody->flags ); + b2FloatW t3 = simde_mm256_unpackhi_ps( simdBody->w, simdBody->flags ); + b2FloatW t4 = simde_mm256_unpacklo_ps( simdBody->dp.X, simdBody->dp.Y ); + b2FloatW t5 = simde_mm256_unpackhi_ps( simdBody->dp.X, simdBody->dp.Y ); + b2FloatW t6 = simde_mm256_unpacklo_ps( simdBody->dq.C, simdBody->dq.S ); + b2FloatW t7 = simde_mm256_unpackhi_ps( simdBody->dq.C, simdBody->dq.S ); + b2FloatW tt0 = simde_mm256_shuffle_ps( t0, t2, SIMDE_MM_SHUFFLE( 1, 0, 1, 0 ) ); + b2FloatW tt1 = simde_mm256_shuffle_ps( t0, t2, SIMDE_MM_SHUFFLE( 3, 2, 3, 2 ) ); + b2FloatW tt2 = simde_mm256_shuffle_ps( t1, t3, SIMDE_MM_SHUFFLE( 1, 0, 1, 0 ) ); + b2FloatW tt3 = simde_mm256_shuffle_ps( t1, t3, SIMDE_MM_SHUFFLE( 3, 2, 3, 2 ) ); + b2FloatW tt4 = simde_mm256_shuffle_ps( t4, t6, SIMDE_MM_SHUFFLE( 1, 0, 1, 0 ) ); + b2FloatW tt5 = simde_mm256_shuffle_ps( t4, t6, SIMDE_MM_SHUFFLE( 3, 2, 3, 2 ) ); + b2FloatW tt6 = simde_mm256_shuffle_ps( t5, t7, SIMDE_MM_SHUFFLE( 1, 0, 1, 0 ) ); + b2FloatW tt7 = simde_mm256_shuffle_ps( t5, t7, SIMDE_MM_SHUFFLE( 3, 2, 3, 2 ) ); // I don't use any dummy body in the body array because this will lead to multithreaded sharing and the // associated cache flushing. - if (indices[0] != B2_NULL_INDEX) - simde_mm256_store_ps((float*)(states + indices[0]), simde_mm256_permute2f128_ps(tt0, tt4, 0x20)); - if (indices[1] != B2_NULL_INDEX) - simde_mm256_store_ps((float*)(states + indices[1]), simde_mm256_permute2f128_ps(tt1, tt5, 0x20)); - if (indices[2] != B2_NULL_INDEX) - simde_mm256_store_ps((float*)(states + indices[2]), simde_mm256_permute2f128_ps(tt2, tt6, 0x20)); - if (indices[3] != B2_NULL_INDEX) - simde_mm256_store_ps((float*)(states + indices[3]), simde_mm256_permute2f128_ps(tt3, tt7, 0x20)); - if (indices[4] != B2_NULL_INDEX) - simde_mm256_store_ps((float*)(states + indices[4]), simde_mm256_permute2f128_ps(tt0, tt4, 0x31)); - if (indices[5] != B2_NULL_INDEX) - simde_mm256_store_ps((float*)(states + indices[5]), simde_mm256_permute2f128_ps(tt1, tt5, 0x31)); - if (indices[6] != B2_NULL_INDEX) - simde_mm256_store_ps((float*)(states + indices[6]), simde_mm256_permute2f128_ps(tt2, tt6, 0x31)); - if (indices[7] != B2_NULL_INDEX) - simde_mm256_store_ps((float*)(states + indices[7]), simde_mm256_permute2f128_ps(tt3, tt7, 0x31)); + if ( indices[0] != B2_NULL_INDEX ) + simde_mm256_store_ps( (float*)( states + indices[0] ), simde_mm256_permute2f128_ps( tt0, tt4, 0x20 ) ); + if ( indices[1] != B2_NULL_INDEX ) + simde_mm256_store_ps( (float*)( states + indices[1] ), simde_mm256_permute2f128_ps( tt1, tt5, 0x20 ) ); + if ( indices[2] != B2_NULL_INDEX ) + simde_mm256_store_ps( (float*)( states + indices[2] ), simde_mm256_permute2f128_ps( tt2, tt6, 0x20 ) ); + if ( indices[3] != B2_NULL_INDEX ) + simde_mm256_store_ps( (float*)( states + indices[3] ), simde_mm256_permute2f128_ps( tt3, tt7, 0x20 ) ); + if ( indices[4] != B2_NULL_INDEX ) + simde_mm256_store_ps( (float*)( states + indices[4] ), simde_mm256_permute2f128_ps( tt0, tt4, 0x31 ) ); + if ( indices[5] != B2_NULL_INDEX ) + simde_mm256_store_ps( (float*)( states + indices[5] ), simde_mm256_permute2f128_ps( tt1, tt5, 0x31 ) ); + if ( indices[6] != B2_NULL_INDEX ) + simde_mm256_store_ps( (float*)( states + indices[6] ), simde_mm256_permute2f128_ps( tt2, tt6, 0x31 ) ); + if ( indices[7] != B2_NULL_INDEX ) + simde_mm256_store_ps( (float*)( states + indices[7] ), simde_mm256_permute2f128_ps( tt3, tt7, 0x31 ) ); } -void b2PrepareContactsTask(int startIndex, int endIndex, b2StepContext* context) +void b2PrepareContactsTask( int startIndex, int endIndex, b2StepContext* context ) { - b2TracyCZoneNC(prepare_contact, "Prepare Contact", b2_colorYellow, true); + b2TracyCZoneNC( prepare_contact, "Prepare Contact", b2_colorYellow, true ); b2World* world = context->world; b2ContactSim** contacts = context->contacts; b2ContactConstraintSIMD* constraints = context->simdContactConstraints; @@ -611,15 +611,15 @@ void b2PrepareContactsTask(int startIndex, int endIndex, b2StepContext* context) float warmStartScale = world->enableWarmStarting ? 1.0f : 0.0f; - for (int i = startIndex; i < endIndex; ++i) + for ( int i = startIndex; i < endIndex; ++i ) { b2ContactConstraintSIMD* constraint = constraints + i; - for (int j = 0; j < 8; ++j) + for ( int j = 0; j < 8; ++j ) { b2ContactSim* contactSim = contacts[8 * i + j]; - if (contactSim != NULL) + if ( contactSim != NULL ) { const b2Manifold* manifold = &contactSim->manifold; @@ -632,8 +632,8 @@ void b2PrepareContactsTask(int startIndex, int endIndex, b2StepContext* context) b2Body* bodyB = bodies + contactSim->bodyIdB; int validIndexB = bodyB->setIndex == b2_awakeSet ? bodyB->localIndex : B2_NULL_INDEX; - B2_ASSERT(indexA == validIndexA); - B2_ASSERT(indexB == validIndexB); + B2_ASSERT( indexA == validIndexA ); + B2_ASSERT( indexB == validIndexB ); #endif constraint->indexA[j] = indexA; constraint->indexB[j] = indexB; @@ -642,7 +642,7 @@ void b2PrepareContactsTask(int startIndex, int endIndex, b2StepContext* context) float wA = 0.0f; float mA = contactSim->invMassA; float iA = contactSim->invIA; - if (indexA != B2_NULL_INDEX) + if ( indexA != B2_NULL_INDEX ) { b2BodyState* stateA = awakeStates + indexA; vA = stateA->linearVelocity; @@ -653,31 +653,31 @@ void b2PrepareContactsTask(int startIndex, int endIndex, b2StepContext* context) float wB = 0.0f; float mB = contactSim->invMassB; float iB = contactSim->invIB; - if (indexB != B2_NULL_INDEX) + if ( indexB != B2_NULL_INDEX ) { b2BodyState* stateB = awakeStates + indexB; vB = stateB->linearVelocity; wB = stateB->angularVelocity; } - ((float*)&constraint->invMassA)[j] = mA; - ((float*)&constraint->invMassB)[j] = mB; - ((float*)&constraint->invIA)[j] = iA; - ((float*)&constraint->invIB)[j] = iB; + ( (float*)&constraint->invMassA )[j] = mA; + ( (float*)&constraint->invMassB )[j] = mB; + ( (float*)&constraint->invIA )[j] = iA; + ( (float*)&constraint->invIB )[j] = iB; - b2Softness soft = (indexA == B2_NULL_INDEX || indexB == B2_NULL_INDEX) ? staticSoftness : contactSoftness; + b2Softness soft = ( indexA == B2_NULL_INDEX || indexB == B2_NULL_INDEX ) ? staticSoftness : contactSoftness; b2Vec2 normal = manifold->normal; - ((float*)&constraint->normal.X)[j] = normal.x; - ((float*)&constraint->normal.Y)[j] = normal.y; + ( (float*)&constraint->normal.X )[j] = normal.x; + ( (float*)&constraint->normal.Y )[j] = normal.y; - ((float*)&constraint->friction)[j] = contactSim->friction; - ((float*)&constraint->restitution)[j] = contactSim->restitution; - ((float*)&constraint->biasRate)[j] = soft.biasRate; - ((float*)&constraint->massScale)[j] = soft.massScale; - ((float*)&constraint->impulseScale)[j] = soft.impulseScale; + ( (float*)&constraint->friction )[j] = contactSim->friction; + ( (float*)&constraint->restitution )[j] = contactSim->restitution; + ( (float*)&constraint->biasRate )[j] = soft.biasRate; + ( (float*)&constraint->massScale )[j] = soft.massScale; + ( (float*)&constraint->impulseScale )[j] = soft.impulseScale; - b2Vec2 tangent = b2RightPerp(normal); + b2Vec2 tangent = b2RightPerp( normal ); { const b2ManifoldPoint* mp = manifold->points + 0; @@ -685,83 +685,83 @@ void b2PrepareContactsTask(int startIndex, int endIndex, b2StepContext* context) b2Vec2 rA = mp->anchorA; b2Vec2 rB = mp->anchorB; - ((float*)&constraint->anchorA1.X)[j] = rA.x; - ((float*)&constraint->anchorA1.Y)[j] = rA.y; - ((float*)&constraint->anchorB1.X)[j] = rB.x; - ((float*)&constraint->anchorB1.Y)[j] = rB.y; + ( (float*)&constraint->anchorA1.X )[j] = rA.x; + ( (float*)&constraint->anchorA1.Y )[j] = rA.y; + ( (float*)&constraint->anchorB1.X )[j] = rB.x; + ( (float*)&constraint->anchorB1.Y )[j] = rB.y; - ((float*)&constraint->baseSeparation1)[j] = mp->separation - b2Dot(b2Sub(rB, rA), normal); + ( (float*)&constraint->baseSeparation1 )[j] = mp->separation - b2Dot( b2Sub( rB, rA ), normal ); - ((float*)&constraint->normalImpulse1)[j] = warmStartScale * mp->normalImpulse; - ((float*)&constraint->tangentImpulse1)[j] = warmStartScale * mp->tangentImpulse; - ((float*)&constraint->maxNormalImpulse1)[j] = 0.0f; + ( (float*)&constraint->normalImpulse1 )[j] = warmStartScale * mp->normalImpulse; + ( (float*)&constraint->tangentImpulse1 )[j] = warmStartScale * mp->tangentImpulse; + ( (float*)&constraint->maxNormalImpulse1 )[j] = 0.0f; - float rnA = b2Cross(rA, normal); - float rnB = b2Cross(rB, normal); + float rnA = b2Cross( rA, normal ); + float rnB = b2Cross( rB, normal ); float kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB; - ((float*)&constraint->normalMass1)[j] = kNormal > 0.0f ? 1.0f / kNormal : 0.0f; + ( (float*)&constraint->normalMass1 )[j] = kNormal > 0.0f ? 1.0f / kNormal : 0.0f; - float rtA = b2Cross(rA, tangent); - float rtB = b2Cross(rB, tangent); + float rtA = b2Cross( rA, tangent ); + float rtB = b2Cross( rB, tangent ); float kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB; - ((float*)&constraint->tangentMass1)[j] = kTangent > 0.0f ? 1.0f / kTangent : 0.0f; + ( (float*)&constraint->tangentMass1 )[j] = kTangent > 0.0f ? 1.0f / kTangent : 0.0f; // relative velocity for restitution - b2Vec2 vrA = b2Add(vA, b2CrossSV(wA, rA)); - b2Vec2 vrB = b2Add(vB, b2CrossSV(wB, rB)); - ((float*)&constraint->relativeVelocity1)[j] = b2Dot(normal, b2Sub(vrB, vrA)); + b2Vec2 vrA = b2Add( vA, b2CrossSV( wA, rA ) ); + b2Vec2 vrB = b2Add( vB, b2CrossSV( wB, rB ) ); + ( (float*)&constraint->relativeVelocity1 )[j] = b2Dot( normal, b2Sub( vrB, vrA ) ); } int pointCount = manifold->pointCount; - B2_ASSERT(0 < pointCount && pointCount <= 2); + B2_ASSERT( 0 < pointCount && pointCount <= 2 ); - if (pointCount == 2) + if ( pointCount == 2 ) { const b2ManifoldPoint* mp = manifold->points + 1; b2Vec2 rA = mp->anchorA; b2Vec2 rB = mp->anchorB; - ((float*)&constraint->anchorA2.X)[j] = rA.x; - ((float*)&constraint->anchorA2.Y)[j] = rA.y; - ((float*)&constraint->anchorB2.X)[j] = rB.x; - ((float*)&constraint->anchorB2.Y)[j] = rB.y; + ( (float*)&constraint->anchorA2.X )[j] = rA.x; + ( (float*)&constraint->anchorA2.Y )[j] = rA.y; + ( (float*)&constraint->anchorB2.X )[j] = rB.x; + ( (float*)&constraint->anchorB2.Y )[j] = rB.y; - ((float*)&constraint->baseSeparation2)[j] = mp->separation - b2Dot(b2Sub(rB, rA), normal); + ( (float*)&constraint->baseSeparation2 )[j] = mp->separation - b2Dot( b2Sub( rB, rA ), normal ); - ((float*)&constraint->normalImpulse2)[j] = warmStartScale * mp->normalImpulse; - ((float*)&constraint->tangentImpulse2)[j] = warmStartScale * mp->tangentImpulse; - ((float*)&constraint->maxNormalImpulse2)[j] = 0.0f; + ( (float*)&constraint->normalImpulse2 )[j] = warmStartScale * mp->normalImpulse; + ( (float*)&constraint->tangentImpulse2 )[j] = warmStartScale * mp->tangentImpulse; + ( (float*)&constraint->maxNormalImpulse2 )[j] = 0.0f; - float rnA = b2Cross(rA, normal); - float rnB = b2Cross(rB, normal); + float rnA = b2Cross( rA, normal ); + float rnB = b2Cross( rB, normal ); float kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB; - ((float*)&constraint->normalMass2)[j] = kNormal > 0.0f ? 1.0f / kNormal : 0.0f; + ( (float*)&constraint->normalMass2 )[j] = kNormal > 0.0f ? 1.0f / kNormal : 0.0f; - float rtA = b2Cross(rA, tangent); - float rtB = b2Cross(rB, tangent); + float rtA = b2Cross( rA, tangent ); + float rtB = b2Cross( rB, tangent ); float kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB; - ((float*)&constraint->tangentMass2)[j] = kTangent > 0.0f ? 1.0f / kTangent : 0.0f; + ( (float*)&constraint->tangentMass2 )[j] = kTangent > 0.0f ? 1.0f / kTangent : 0.0f; // relative velocity for restitution - b2Vec2 vrA = b2Add(vA, b2CrossSV(wA, rA)); - b2Vec2 vrB = b2Add(vB, b2CrossSV(wB, rB)); - ((float*)&constraint->relativeVelocity2)[j] = b2Dot(normal, b2Sub(vrB, vrA)); + b2Vec2 vrA = b2Add( vA, b2CrossSV( wA, rA ) ); + b2Vec2 vrB = b2Add( vB, b2CrossSV( wB, rB ) ); + ( (float*)&constraint->relativeVelocity2 )[j] = b2Dot( normal, b2Sub( vrB, vrA ) ); } else { // dummy data that has no effect - ((float*)&constraint->baseSeparation2)[j] = 0.0f; - ((float*)&constraint->normalImpulse2)[j] = 0.0f; - ((float*)&constraint->tangentImpulse2)[j] = 0.0f; - ((float*)&constraint->maxNormalImpulse2)[j] = 0.0f; - ((float*)&constraint->anchorA2.X)[j] = 0.0f; - ((float*)&constraint->anchorA2.Y)[j] = 0.0f; - ((float*)&constraint->anchorB2.X)[j] = 0.0f; - ((float*)&constraint->anchorB2.Y)[j] = 0.0f; - ((float*)&constraint->normalMass2)[j] = 0.0f; - ((float*)&constraint->tangentMass2)[j] = 0.0f; - ((float*)&constraint->relativeVelocity2)[j] = 0.0f; + ( (float*)&constraint->baseSeparation2 )[j] = 0.0f; + ( (float*)&constraint->normalImpulse2 )[j] = 0.0f; + ( (float*)&constraint->tangentImpulse2 )[j] = 0.0f; + ( (float*)&constraint->maxNormalImpulse2 )[j] = 0.0f; + ( (float*)&constraint->anchorA2.X )[j] = 0.0f; + ( (float*)&constraint->anchorA2.Y )[j] = 0.0f; + ( (float*)&constraint->anchorB2.X )[j] = 0.0f; + ( (float*)&constraint->anchorB2.Y )[j] = 0.0f; + ( (float*)&constraint->normalMass2 )[j] = 0.0f; + ( (float*)&constraint->tangentMass2 )[j] = 0.0f; + ( (float*)&constraint->relativeVelocity2 )[j] = 0.0f; } } else @@ -769,59 +769,59 @@ void b2PrepareContactsTask(int startIndex, int endIndex, b2StepContext* context) // SIMD remainder constraint->indexA[j] = B2_NULL_INDEX; constraint->indexB[j] = B2_NULL_INDEX; - ((float*)&constraint->friction)[j] = 0.0f; - ((float*)&constraint->restitution)[j] = 0.0f; - ((float*)&constraint->biasRate)[j] = 0.0f; - ((float*)&constraint->massScale)[j] = 0.0f; - ((float*)&constraint->impulseScale)[j] = 0.0f; - ((float*)&constraint->normal.X)[j] = 0.0f; - ((float*)&constraint->normal.Y)[j] = 0.0f; - - ((float*)&constraint->baseSeparation1)[j] = 0.0f; - ((float*)&constraint->normalImpulse1)[j] = 0.0f; - ((float*)&constraint->tangentImpulse1)[j] = 0.0f; - ((float*)&constraint->maxNormalImpulse1)[j] = 0.0f; - ((float*)&constraint->anchorA1.X)[j] = 0.0f; - ((float*)&constraint->anchorA1.Y)[j] = 0.0f; - ((float*)&constraint->anchorB1.X)[j] = 0.0f; - ((float*)&constraint->anchorB1.Y)[j] = 0.0f; - ((float*)&constraint->normalMass1)[j] = 0.0f; - ((float*)&constraint->tangentMass1)[j] = 0.0f; - ((float*)&constraint->relativeVelocity1)[j] = 0.0f; - - ((float*)&constraint->baseSeparation2)[j] = 0.0f; - ((float*)&constraint->normalImpulse2)[j] = 0.0f; - ((float*)&constraint->tangentImpulse2)[j] = 0.0f; - ((float*)&constraint->maxNormalImpulse2)[j] = 0.0f; - ((float*)&constraint->anchorA2.X)[j] = 0.0f; - ((float*)&constraint->anchorA2.Y)[j] = 0.0f; - ((float*)&constraint->anchorB2.X)[j] = 0.0f; - ((float*)&constraint->anchorB2.Y)[j] = 0.0f; - ((float*)&constraint->normalMass2)[j] = 0.0f; - ((float*)&constraint->tangentMass2)[j] = 0.0f; - ((float*)&constraint->relativeVelocity2)[j] = 0.0f; + ( (float*)&constraint->friction )[j] = 0.0f; + ( (float*)&constraint->restitution )[j] = 0.0f; + ( (float*)&constraint->biasRate )[j] = 0.0f; + ( (float*)&constraint->massScale )[j] = 0.0f; + ( (float*)&constraint->impulseScale )[j] = 0.0f; + ( (float*)&constraint->normal.X )[j] = 0.0f; + ( (float*)&constraint->normal.Y )[j] = 0.0f; + + ( (float*)&constraint->baseSeparation1 )[j] = 0.0f; + ( (float*)&constraint->normalImpulse1 )[j] = 0.0f; + ( (float*)&constraint->tangentImpulse1 )[j] = 0.0f; + ( (float*)&constraint->maxNormalImpulse1 )[j] = 0.0f; + ( (float*)&constraint->anchorA1.X )[j] = 0.0f; + ( (float*)&constraint->anchorA1.Y )[j] = 0.0f; + ( (float*)&constraint->anchorB1.X )[j] = 0.0f; + ( (float*)&constraint->anchorB1.Y )[j] = 0.0f; + ( (float*)&constraint->normalMass1 )[j] = 0.0f; + ( (float*)&constraint->tangentMass1 )[j] = 0.0f; + ( (float*)&constraint->relativeVelocity1 )[j] = 0.0f; + + ( (float*)&constraint->baseSeparation2 )[j] = 0.0f; + ( (float*)&constraint->normalImpulse2 )[j] = 0.0f; + ( (float*)&constraint->tangentImpulse2 )[j] = 0.0f; + ( (float*)&constraint->maxNormalImpulse2 )[j] = 0.0f; + ( (float*)&constraint->anchorA2.X )[j] = 0.0f; + ( (float*)&constraint->anchorA2.Y )[j] = 0.0f; + ( (float*)&constraint->anchorB2.X )[j] = 0.0f; + ( (float*)&constraint->anchorB2.Y )[j] = 0.0f; + ( (float*)&constraint->normalMass2 )[j] = 0.0f; + ( (float*)&constraint->tangentMass2 )[j] = 0.0f; + ( (float*)&constraint->relativeVelocity2 )[j] = 0.0f; } } } - b2TracyCZoneEnd(prepare_contact); + b2TracyCZoneEnd( prepare_contact ); } -void b2WarmStartContactsTask(int startIndex, int endIndex, b2StepContext* context, int colorIndex) +void b2WarmStartContactsTask( int startIndex, int endIndex, b2StepContext* context, int colorIndex ) { - b2TracyCZoneNC(warm_start_contact, "Warm Start", b2_colorGreen1, true); + b2TracyCZoneNC( warm_start_contact, "Warm Start", b2_colorGreen, true ); b2BodyState* states = context->states; b2ContactConstraintSIMD* constraints = context->graph->colors[colorIndex].simdConstraints; - for (int i = startIndex; i < endIndex; ++i) + for ( int i = startIndex; i < endIndex; ++i ) { b2ContactConstraintSIMD* c = constraints + i; - b2SimdBody bA = b2GatherBodies(states, c->indexA); - b2SimdBody bB = b2GatherBodies(states, c->indexB); + b2SimdBody bA = b2GatherBodies( states, c->indexA ); + b2SimdBody bB = b2GatherBodies( states, c->indexB ); b2FloatW tangentX = c->normal.Y; - b2FloatW tangentY = sub(simde_mm256_setzero_ps(), c->normal.X); + b2FloatW tangentY = sub( simde_mm256_setzero_ps(), c->normal.X ); { // fixed anchors @@ -829,14 +829,14 @@ void b2WarmStartContactsTask(int startIndex, int endIndex, b2StepContext* contex b2Vec2W rB = c->anchorB1; b2Vec2W P; - P.X = add(mul(c->normalImpulse1, c->normal.X), mul(c->tangentImpulse1, tangentX)); - P.Y = add(mul(c->normalImpulse1, c->normal.Y), mul(c->tangentImpulse1, tangentY)); - bA.w = mulsub(bA.w, c->invIA, b2CrossW(rA, P)); - bA.v.X = mulsub(bA.v.X, c->invMassA, P.X); - bA.v.Y = mulsub(bA.v.Y, c->invMassA, P.Y); - bB.w = muladd(bB.w, c->invIB, b2CrossW(rB, P)); - bB.v.X = muladd(bB.v.X, c->invMassB, P.X); - bB.v.Y = muladd(bB.v.Y, c->invMassB, P.Y); + P.X = add( mul( c->normalImpulse1, c->normal.X ), mul( c->tangentImpulse1, tangentX ) ); + P.Y = add( mul( c->normalImpulse1, c->normal.Y ), mul( c->tangentImpulse1, tangentY ) ); + bA.w = mulsub( bA.w, c->invIA, b2CrossW( rA, P ) ); + bA.v.X = mulsub( bA.v.X, c->invMassA, P.X ); + bA.v.Y = mulsub( bA.v.Y, c->invMassA, P.Y ); + bB.w = muladd( bB.w, c->invIB, b2CrossW( rB, P ) ); + bB.v.X = muladd( bB.v.X, c->invMassB, P.X ); + bB.v.Y = muladd( bB.v.Y, c->invMassB, P.Y ); } { @@ -845,41 +845,41 @@ void b2WarmStartContactsTask(int startIndex, int endIndex, b2StepContext* contex b2Vec2W rB = c->anchorB2; b2Vec2W P; - P.X = add(mul(c->normalImpulse2, c->normal.X), mul(c->tangentImpulse2, tangentX)); - P.Y = add(mul(c->normalImpulse2, c->normal.Y), mul(c->tangentImpulse2, tangentY)); - bA.w = mulsub(bA.w, c->invIA, b2CrossW(rA, P)); - bA.v.X = mulsub(bA.v.X, c->invMassA, P.X); - bA.v.Y = mulsub(bA.v.Y, c->invMassA, P.Y); - bB.w = muladd(bB.w, c->invIB, b2CrossW(rB, P)); - bB.v.X = muladd(bB.v.X, c->invMassB, P.X); - bB.v.Y = muladd(bB.v.Y, c->invMassB, P.Y); + P.X = add( mul( c->normalImpulse2, c->normal.X ), mul( c->tangentImpulse2, tangentX ) ); + P.Y = add( mul( c->normalImpulse2, c->normal.Y ), mul( c->tangentImpulse2, tangentY ) ); + bA.w = mulsub( bA.w, c->invIA, b2CrossW( rA, P ) ); + bA.v.X = mulsub( bA.v.X, c->invMassA, P.X ); + bA.v.Y = mulsub( bA.v.Y, c->invMassA, P.Y ); + bB.w = muladd( bB.w, c->invIB, b2CrossW( rB, P ) ); + bB.v.X = muladd( bB.v.X, c->invMassB, P.X ); + bB.v.Y = muladd( bB.v.Y, c->invMassB, P.Y ); } - b2ScatterBodies(states, c->indexA, &bA); - b2ScatterBodies(states, c->indexB, &bB); + b2ScatterBodies( states, c->indexA, &bA ); + b2ScatterBodies( states, c->indexB, &bB ); } - b2TracyCZoneEnd(warm_start_contact); + b2TracyCZoneEnd( warm_start_contact ); } -void b2SolveContactsTask(int startIndex, int endIndex, b2StepContext* context, int colorIndex, bool useBias) +void b2SolveContactsTask( int startIndex, int endIndex, b2StepContext* context, int colorIndex, bool useBias ) { - b2TracyCZoneNC(solve_contact, "Solve Contact", b2_colorAliceBlue, true); + b2TracyCZoneNC( solve_contact, "Solve Contact", b2_colorAliceBlue, true ); b2BodyState* states = context->states; b2ContactConstraintSIMD* constraints = context->graph->colors[colorIndex].simdConstraints; - b2FloatW inv_h = simde_mm256_set1_ps(context->inv_h); - b2FloatW minBiasVel = simde_mm256_set1_ps(-context->world->contactPushoutVelocity); + b2FloatW inv_h = simde_mm256_set1_ps( context->inv_h ); + b2FloatW minBiasVel = simde_mm256_set1_ps( -context->world->contactPushoutVelocity ); - for (int i = startIndex; i < endIndex; ++i) + for ( int i = startIndex; i < endIndex; ++i ) { b2ContactConstraintSIMD* c = constraints + i; - b2SimdBody bA = b2GatherBodies(states, c->indexA); - b2SimdBody bB = b2GatherBodies(states, c->indexB); + b2SimdBody bA = b2GatherBodies( states, c->indexA ); + b2SimdBody bB = b2GatherBodies( states, c->indexB ); b2FloatW biasRate, massScale, impulseScale; - if (useBias) + if ( useBias ) { biasRate = c->biasRate; massScale = c->massScale; @@ -888,112 +888,114 @@ void b2SolveContactsTask(int startIndex, int endIndex, b2StepContext* context, i else { biasRate = simde_mm256_setzero_ps(); - massScale = simde_mm256_set1_ps(1.0f); + massScale = simde_mm256_set1_ps( 1.0f ); impulseScale = simde_mm256_setzero_ps(); } - b2Vec2W dp = {sub(bB.dp.X, bA.dp.X), sub(bB.dp.Y, bA.dp.Y)}; + b2Vec2W dp = { sub( bB.dp.X, bA.dp.X ), sub( bB.dp.Y, bA.dp.Y ) }; // point1 non-penetration constraint { // moving anchors for current separation - b2Vec2W rsA = b2RotateVectorW(bA.dq, c->anchorA1); - b2Vec2W rsB = b2RotateVectorW(bB.dq, c->anchorB1); + b2Vec2W rsA = b2RotateVectorW( bA.dq, c->anchorA1 ); + b2Vec2W rsB = b2RotateVectorW( bB.dq, c->anchorB1 ); // compute current separation // todo this is subject to round-off error if the anchor is far from the body center of mass // todo for example a large world with a single static body and many offset shapes - b2Vec2W ds = {add(dp.X, sub(rsB.X, rsA.X)), add(dp.Y, sub(rsB.Y, rsA.Y))}; - b2FloatW s = add(b2DotW(c->normal, ds), c->baseSeparation1); + b2Vec2W ds = { add( dp.X, sub( rsB.X, rsA.X ) ), add( dp.Y, sub( rsB.Y, rsA.Y ) ) }; + b2FloatW s = add( b2DotW( c->normal, ds ), c->baseSeparation1 ); - b2FloatW test = simde_mm256_cmp_ps(s, simde_mm256_setzero_ps(), SIMDE_CMP_GT_OQ); - b2FloatW specBias = mul(s, inv_h); - b2FloatW softBias = simde_mm256_max_ps(mul(biasRate, s), minBiasVel); + b2FloatW test = simde_mm256_cmp_ps( s, simde_mm256_setzero_ps(), SIMDE_CMP_GT_OQ ); + b2FloatW specBias = mul( s, inv_h ); + b2FloatW softBias = simde_mm256_max_ps( mul( biasRate, s ), minBiasVel ); // #todo slow on SSE2 - b2FloatW bias = simde_mm256_blendv_ps(softBias, specBias, test); + b2FloatW bias = simde_mm256_blendv_ps( softBias, specBias, test ); // fixed anchors for Jacobians b2Vec2W rA = c->anchorA1; b2Vec2W rB = c->anchorB1; // Relative velocity at contact - b2FloatW dvx = sub(sub(bB.v.X, mul(bB.w, rB.Y)), sub(bA.v.X, mul(bA.w, rA.Y))); - b2FloatW dvy = sub(add(bB.v.Y, mul(bB.w, rB.X)), add(bA.v.Y, mul(bA.w, rA.X))); - b2FloatW vn = add(mul(dvx, c->normal.X), mul(dvy, c->normal.Y)); + b2FloatW dvx = sub( sub( bB.v.X, mul( bB.w, rB.Y ) ), sub( bA.v.X, mul( bA.w, rA.Y ) ) ); + b2FloatW dvy = sub( add( bB.v.Y, mul( bB.w, rB.X ) ), add( bA.v.Y, mul( bA.w, rA.X ) ) ); + b2FloatW vn = add( mul( dvx, c->normal.X ), mul( dvy, c->normal.Y ) ); // Compute normal impulse - b2FloatW negImpulse = add(mul(c->normalMass1, mul(massScale, add(vn, bias))), mul(impulseScale, c->normalImpulse1)); + b2FloatW negImpulse = + add( mul( c->normalMass1, mul( massScale, add( vn, bias ) ) ), mul( impulseScale, c->normalImpulse1 ) ); // Clamp the accumulated impulse - b2FloatW newImpulse = simde_mm256_max_ps(sub(c->normalImpulse1, negImpulse), simde_mm256_setzero_ps()); - b2FloatW impulse = sub(newImpulse, c->normalImpulse1); + b2FloatW newImpulse = simde_mm256_max_ps( sub( c->normalImpulse1, negImpulse ), simde_mm256_setzero_ps() ); + b2FloatW impulse = sub( newImpulse, c->normalImpulse1 ); c->normalImpulse1 = newImpulse; - c->maxNormalImpulse1 = simde_mm256_max_ps(c->maxNormalImpulse1, newImpulse); + c->maxNormalImpulse1 = simde_mm256_max_ps( c->maxNormalImpulse1, newImpulse ); // Apply contact impulse - b2FloatW Px = mul(impulse, c->normal.X); - b2FloatW Py = mul(impulse, c->normal.Y); + b2FloatW Px = mul( impulse, c->normal.X ); + b2FloatW Py = mul( impulse, c->normal.Y ); - bA.v.X = mulsub(bA.v.X, c->invMassA, Px); - bA.v.Y = mulsub(bA.v.Y, c->invMassA, Py); - bA.w = mulsub(bA.w, c->invIA, sub(mul(rA.X, Py), mul(rA.Y, Px))); + bA.v.X = mulsub( bA.v.X, c->invMassA, Px ); + bA.v.Y = mulsub( bA.v.Y, c->invMassA, Py ); + bA.w = mulsub( bA.w, c->invIA, sub( mul( rA.X, Py ), mul( rA.Y, Px ) ) ); - bB.v.X = muladd(bB.v.X, c->invMassB, Px); - bB.v.Y = muladd(bB.v.Y, c->invMassB, Py); - bB.w = muladd(bB.w, c->invIB, sub(mul(rB.X, Py), mul(rB.Y, Px))); + bB.v.X = muladd( bB.v.X, c->invMassB, Px ); + bB.v.Y = muladd( bB.v.Y, c->invMassB, Py ); + bB.w = muladd( bB.w, c->invIB, sub( mul( rB.X, Py ), mul( rB.Y, Px ) ) ); } // second point non-penetration constraint { // moving anchors for current separation - b2Vec2W rsA = b2RotateVectorW(bA.dq, c->anchorA2); - b2Vec2W rsB = b2RotateVectorW(bB.dq, c->anchorB2); + b2Vec2W rsA = b2RotateVectorW( bA.dq, c->anchorA2 ); + b2Vec2W rsB = b2RotateVectorW( bB.dq, c->anchorB2 ); // compute current separation - b2Vec2W ds = {add(dp.X, sub(rsB.X, rsA.X)), add(dp.Y, sub(rsB.Y, rsA.Y))}; - b2FloatW s = add(b2DotW(c->normal, ds), c->baseSeparation2); + b2Vec2W ds = { add( dp.X, sub( rsB.X, rsA.X ) ), add( dp.Y, sub( rsB.Y, rsA.Y ) ) }; + b2FloatW s = add( b2DotW( c->normal, ds ), c->baseSeparation2 ); - b2FloatW test = simde_mm256_cmp_ps(s, simde_mm256_setzero_ps(), SIMDE_CMP_GT_OQ); - b2FloatW specBias = mul(s, inv_h); - b2FloatW softBias = simde_mm256_max_ps(mul(biasRate, s), minBiasVel); + b2FloatW test = simde_mm256_cmp_ps( s, simde_mm256_setzero_ps(), SIMDE_CMP_GT_OQ ); + b2FloatW specBias = mul( s, inv_h ); + b2FloatW softBias = simde_mm256_max_ps( mul( biasRate, s ), minBiasVel ); // #todo slow on SSE2 - b2FloatW bias = simde_mm256_blendv_ps(softBias, specBias, test); + b2FloatW bias = simde_mm256_blendv_ps( softBias, specBias, test ); // fixed anchors for Jacobians b2Vec2W rA = c->anchorA2; b2Vec2W rB = c->anchorB2; // Relative velocity at contact - b2FloatW dvx = sub(sub(bB.v.X, mul(bB.w, rB.Y)), sub(bA.v.X, mul(bA.w, rA.Y))); - b2FloatW dvy = sub(add(bB.v.Y, mul(bB.w, rB.X)), add(bA.v.Y, mul(bA.w, rA.X))); - b2FloatW vn = add(mul(dvx, c->normal.X), mul(dvy, c->normal.Y)); + b2FloatW dvx = sub( sub( bB.v.X, mul( bB.w, rB.Y ) ), sub( bA.v.X, mul( bA.w, rA.Y ) ) ); + b2FloatW dvy = sub( add( bB.v.Y, mul( bB.w, rB.X ) ), add( bA.v.Y, mul( bA.w, rA.X ) ) ); + b2FloatW vn = add( mul( dvx, c->normal.X ), mul( dvy, c->normal.Y ) ); // Compute normal impulse - b2FloatW negImpulse = add(mul(c->normalMass2, mul(massScale, add(vn, bias))), mul(impulseScale, c->normalImpulse2)); + b2FloatW negImpulse = + add( mul( c->normalMass2, mul( massScale, add( vn, bias ) ) ), mul( impulseScale, c->normalImpulse2 ) ); // Clamp the accumulated impulse - b2FloatW newImpulse = simde_mm256_max_ps(sub(c->normalImpulse2, negImpulse), simde_mm256_setzero_ps()); - b2FloatW impulse = sub(newImpulse, c->normalImpulse2); + b2FloatW newImpulse = simde_mm256_max_ps( sub( c->normalImpulse2, negImpulse ), simde_mm256_setzero_ps() ); + b2FloatW impulse = sub( newImpulse, c->normalImpulse2 ); c->normalImpulse2 = newImpulse; - c->maxNormalImpulse2 = simde_mm256_max_ps(c->maxNormalImpulse2, newImpulse); + c->maxNormalImpulse2 = simde_mm256_max_ps( c->maxNormalImpulse2, newImpulse ); // Apply contact impulse - b2FloatW Px = mul(impulse, c->normal.X); - b2FloatW Py = mul(impulse, c->normal.Y); + b2FloatW Px = mul( impulse, c->normal.X ); + b2FloatW Py = mul( impulse, c->normal.Y ); - bA.v.X = mulsub(bA.v.X, c->invMassA, Px); - bA.v.Y = mulsub(bA.v.Y, c->invMassA, Py); - bA.w = mulsub(bA.w, c->invIA, sub(mul(rA.X, Py), mul(rA.Y, Px))); + bA.v.X = mulsub( bA.v.X, c->invMassA, Px ); + bA.v.Y = mulsub( bA.v.Y, c->invMassA, Py ); + bA.w = mulsub( bA.w, c->invIA, sub( mul( rA.X, Py ), mul( rA.Y, Px ) ) ); - bB.v.X = muladd(bB.v.X, c->invMassB, Px); - bB.v.Y = muladd(bB.v.Y, c->invMassB, Py); - bB.w = muladd(bB.w, c->invIB, sub(mul(rB.X, Py), mul(rB.Y, Px))); + bB.v.X = muladd( bB.v.X, c->invMassB, Px ); + bB.v.Y = muladd( bB.v.Y, c->invMassB, Py ); + bB.w = muladd( bB.w, c->invIB, sub( mul( rB.X, Py ), mul( rB.Y, Px ) ) ); } b2FloatW tangentX = c->normal.Y; - b2FloatW tangentY = sub(simde_mm256_setzero_ps(), c->normal.X); + b2FloatW tangentY = sub( simde_mm256_setzero_ps(), c->normal.X ); // point 1 friction constraint { @@ -1002,32 +1004,32 @@ void b2SolveContactsTask(int startIndex, int endIndex, b2StepContext* context, i b2Vec2W rB = c->anchorB1; // Relative velocity at contact - b2FloatW dvx = sub(sub(bB.v.X, mul(bB.w, rB.Y)), sub(bA.v.X, mul(bA.w, rA.Y))); - b2FloatW dvy = sub(add(bB.v.Y, mul(bB.w, rB.X)), add(bA.v.Y, mul(bA.w, rA.X))); - b2FloatW vt = add(mul(dvx, tangentX), mul(dvy, tangentY)); + b2FloatW dvx = sub( sub( bB.v.X, mul( bB.w, rB.Y ) ), sub( bA.v.X, mul( bA.w, rA.Y ) ) ); + b2FloatW dvy = sub( add( bB.v.Y, mul( bB.w, rB.X ) ), add( bA.v.Y, mul( bA.w, rA.X ) ) ); + b2FloatW vt = add( mul( dvx, tangentX ), mul( dvy, tangentY ) ); // Compute tangent force - b2FloatW negImpulse = mul(c->tangentMass1, vt); + b2FloatW negImpulse = mul( c->tangentMass1, vt ); // Clamp the accumulated force - b2FloatW maxFriction = mul(c->friction, c->normalImpulse1); - b2FloatW newImpulse = sub(c->tangentImpulse1, negImpulse); + b2FloatW maxFriction = mul( c->friction, c->normalImpulse1 ); + b2FloatW newImpulse = sub( c->tangentImpulse1, negImpulse ); newImpulse = - simde_mm256_max_ps(sub(simde_mm256_setzero_ps(), maxFriction), simde_mm256_min_ps(newImpulse, maxFriction)); - b2FloatW impulse = sub(newImpulse, c->tangentImpulse1); + simde_mm256_max_ps( sub( simde_mm256_setzero_ps(), maxFriction ), simde_mm256_min_ps( newImpulse, maxFriction ) ); + b2FloatW impulse = sub( newImpulse, c->tangentImpulse1 ); c->tangentImpulse1 = newImpulse; // Apply contact impulse - b2FloatW Px = mul(impulse, tangentX); - b2FloatW Py = mul(impulse, tangentY); + b2FloatW Px = mul( impulse, tangentX ); + b2FloatW Py = mul( impulse, tangentY ); - bA.v.X = mulsub(bA.v.X, c->invMassA, Px); - bA.v.Y = mulsub(bA.v.Y, c->invMassA, Py); - bA.w = mulsub(bA.w, c->invIA, sub(mul(rA.X, Py), mul(rA.Y, Px))); + bA.v.X = mulsub( bA.v.X, c->invMassA, Px ); + bA.v.Y = mulsub( bA.v.Y, c->invMassA, Py ); + bA.w = mulsub( bA.w, c->invIA, sub( mul( rA.X, Py ), mul( rA.Y, Px ) ) ); - bB.v.X = muladd(bB.v.X, c->invMassB, Px); - bB.v.Y = muladd(bB.v.Y, c->invMassB, Py); - bB.w = muladd(bB.w, c->invIB, sub(mul(rB.X, Py), mul(rB.Y, Px))); + bB.v.X = muladd( bB.v.X, c->invMassB, Px ); + bB.v.Y = muladd( bB.v.Y, c->invMassB, Py ); + bB.w = muladd( bB.w, c->invIB, sub( mul( rB.X, Py ), mul( rB.Y, Px ) ) ); } // second point friction constraint @@ -1037,154 +1039,154 @@ void b2SolveContactsTask(int startIndex, int endIndex, b2StepContext* context, i b2Vec2W rB = c->anchorB2; // Relative velocity at contact - b2FloatW dvx = sub(sub(bB.v.X, mul(bB.w, rB.Y)), sub(bA.v.X, mul(bA.w, rA.Y))); - b2FloatW dvy = sub(add(bB.v.Y, mul(bB.w, rB.X)), add(bA.v.Y, mul(bA.w, rA.X))); - b2FloatW vt = add(mul(dvx, tangentX), mul(dvy, tangentY)); + b2FloatW dvx = sub( sub( bB.v.X, mul( bB.w, rB.Y ) ), sub( bA.v.X, mul( bA.w, rA.Y ) ) ); + b2FloatW dvy = sub( add( bB.v.Y, mul( bB.w, rB.X ) ), add( bA.v.Y, mul( bA.w, rA.X ) ) ); + b2FloatW vt = add( mul( dvx, tangentX ), mul( dvy, tangentY ) ); // Compute tangent force - b2FloatW negImpulse = mul(c->tangentMass2, vt); + b2FloatW negImpulse = mul( c->tangentMass2, vt ); // Clamp the accumulated force - b2FloatW maxFriction = mul(c->friction, c->normalImpulse2); - b2FloatW newImpulse = sub(c->tangentImpulse2, negImpulse); + b2FloatW maxFriction = mul( c->friction, c->normalImpulse2 ); + b2FloatW newImpulse = sub( c->tangentImpulse2, negImpulse ); newImpulse = - simde_mm256_max_ps(sub(simde_mm256_setzero_ps(), maxFriction), simde_mm256_min_ps(newImpulse, maxFriction)); - b2FloatW impulse = sub(newImpulse, c->tangentImpulse2); + simde_mm256_max_ps( sub( simde_mm256_setzero_ps(), maxFriction ), simde_mm256_min_ps( newImpulse, maxFriction ) ); + b2FloatW impulse = sub( newImpulse, c->tangentImpulse2 ); c->tangentImpulse2 = newImpulse; // Apply contact impulse - b2FloatW Px = mul(impulse, tangentX); - b2FloatW Py = mul(impulse, tangentY); + b2FloatW Px = mul( impulse, tangentX ); + b2FloatW Py = mul( impulse, tangentY ); - bA.v.X = mulsub(bA.v.X, c->invMassA, Px); - bA.v.Y = mulsub(bA.v.Y, c->invMassA, Py); - bA.w = mulsub(bA.w, c->invIA, sub(mul(rA.X, Py), mul(rA.Y, Px))); + bA.v.X = mulsub( bA.v.X, c->invMassA, Px ); + bA.v.Y = mulsub( bA.v.Y, c->invMassA, Py ); + bA.w = mulsub( bA.w, c->invIA, sub( mul( rA.X, Py ), mul( rA.Y, Px ) ) ); - bB.v.X = muladd(bB.v.X, c->invMassB, Px); - bB.v.Y = muladd(bB.v.Y, c->invMassB, Py); - bB.w = muladd(bB.w, c->invIB, sub(mul(rB.X, Py), mul(rB.Y, Px))); + bB.v.X = muladd( bB.v.X, c->invMassB, Px ); + bB.v.Y = muladd( bB.v.Y, c->invMassB, Py ); + bB.w = muladd( bB.w, c->invIB, sub( mul( rB.X, Py ), mul( rB.Y, Px ) ) ); } - b2ScatterBodies(states, c->indexA, &bA); - b2ScatterBodies(states, c->indexB, &bB); + b2ScatterBodies( states, c->indexA, &bA ); + b2ScatterBodies( states, c->indexB, &bB ); } - b2TracyCZoneEnd(solve_contact); + b2TracyCZoneEnd( solve_contact ); } -void b2ApplyRestitutionTask(int startIndex, int endIndex, b2StepContext* context, int colorIndex) +void b2ApplyRestitutionTask( int startIndex, int endIndex, b2StepContext* context, int colorIndex ) { - b2TracyCZoneNC(restitution, "Restitution", b2_colorDodgerBlue, true); + b2TracyCZoneNC( restitution, "Restitution", b2_colorDodgerBlue, true ); b2BodyState* states = context->states; b2ContactConstraintSIMD* constraints = context->graph->colors[colorIndex].simdConstraints; - b2FloatW threshold = simde_mm256_set1_ps(context->world->restitutionThreshold); + b2FloatW threshold = simde_mm256_set1_ps( context->world->restitutionThreshold ); b2FloatW zero = simde_mm256_setzero_ps(); - for (int i = startIndex; i < endIndex; ++i) + for ( int i = startIndex; i < endIndex; ++i ) { b2ContactConstraintSIMD* c = constraints + i; - b2SimdBody bA = b2GatherBodies(states, c->indexA); - b2SimdBody bB = b2GatherBodies(states, c->indexB); + b2SimdBody bA = b2GatherBodies( states, c->indexA ); + b2SimdBody bB = b2GatherBodies( states, c->indexB ); // first point non-penetration constraint { // Set effective mass to zero if restitution should not be applied - b2FloatW test1 = simde_mm256_cmp_ps(add(c->relativeVelocity1, threshold), zero, SIMDE_CMP_GT_OQ); - b2FloatW test2 = simde_mm256_cmp_ps(c->maxNormalImpulse1, zero, SIMDE_CMP_EQ_OQ); - b2FloatW test = simde_mm256_or_ps(test1, test2); + b2FloatW test1 = simde_mm256_cmp_ps( add( c->relativeVelocity1, threshold ), zero, SIMDE_CMP_GT_OQ ); + b2FloatW test2 = simde_mm256_cmp_ps( c->maxNormalImpulse1, zero, SIMDE_CMP_EQ_OQ ); + b2FloatW test = simde_mm256_or_ps( test1, test2 ); // todo slow on SSE2 - b2FloatW mass = simde_mm256_blendv_ps(c->normalMass1, zero, test); + b2FloatW mass = simde_mm256_blendv_ps( c->normalMass1, zero, test ); // fixed anchors for Jacobians b2Vec2W rA = c->anchorA1; b2Vec2W rB = c->anchorB1; // Relative velocity at contact - b2FloatW dvx = sub(sub(bB.v.X, mul(bB.w, rB.Y)), sub(bA.v.X, mul(bA.w, rA.Y))); - b2FloatW dvy = sub(add(bB.v.Y, mul(bB.w, rB.X)), add(bA.v.Y, mul(bA.w, rA.X))); - b2FloatW vn = add(mul(dvx, c->normal.X), mul(dvy, c->normal.Y)); + b2FloatW dvx = sub( sub( bB.v.X, mul( bB.w, rB.Y ) ), sub( bA.v.X, mul( bA.w, rA.Y ) ) ); + b2FloatW dvy = sub( add( bB.v.Y, mul( bB.w, rB.X ) ), add( bA.v.Y, mul( bA.w, rA.X ) ) ); + b2FloatW vn = add( mul( dvx, c->normal.X ), mul( dvy, c->normal.Y ) ); // Compute normal impulse - b2FloatW negImpulse = mul(mass, add(vn, mul(c->restitution, c->relativeVelocity1))); + b2FloatW negImpulse = mul( mass, add( vn, mul( c->restitution, c->relativeVelocity1 ) ) ); // Clamp the accumulated impulse - b2FloatW newImpulse = simde_mm256_max_ps(sub(c->normalImpulse1, negImpulse), simde_mm256_setzero_ps()); - b2FloatW impulse = sub(newImpulse, c->normalImpulse1); + b2FloatW newImpulse = simde_mm256_max_ps( sub( c->normalImpulse1, negImpulse ), simde_mm256_setzero_ps() ); + b2FloatW impulse = sub( newImpulse, c->normalImpulse1 ); c->normalImpulse1 = newImpulse; // Apply contact impulse - b2FloatW Px = mul(impulse, c->normal.X); - b2FloatW Py = mul(impulse, c->normal.Y); + b2FloatW Px = mul( impulse, c->normal.X ); + b2FloatW Py = mul( impulse, c->normal.Y ); - bA.v.X = mulsub(bA.v.X, c->invMassA, Px); - bA.v.Y = mulsub(bA.v.Y, c->invMassA, Py); - bA.w = mulsub(bA.w, c->invIA, sub(mul(rA.X, Py), mul(rA.Y, Px))); + bA.v.X = mulsub( bA.v.X, c->invMassA, Px ); + bA.v.Y = mulsub( bA.v.Y, c->invMassA, Py ); + bA.w = mulsub( bA.w, c->invIA, sub( mul( rA.X, Py ), mul( rA.Y, Px ) ) ); - bB.v.X = muladd(bB.v.X, c->invMassB, Px); - bB.v.Y = muladd(bB.v.Y, c->invMassB, Py); - bB.w = muladd(bB.w, c->invIB, sub(mul(rB.X, Py), mul(rB.Y, Px))); + bB.v.X = muladd( bB.v.X, c->invMassB, Px ); + bB.v.Y = muladd( bB.v.Y, c->invMassB, Py ); + bB.w = muladd( bB.w, c->invIB, sub( mul( rB.X, Py ), mul( rB.Y, Px ) ) ); } // second point non-penetration constraint { // Set effective mass to zero if restitution should not be applied - b2FloatW test1 = simde_mm256_cmp_ps(add(c->relativeVelocity2, threshold), zero, SIMDE_CMP_GT_OQ); - b2FloatW test2 = simde_mm256_cmp_ps(c->maxNormalImpulse2, zero, SIMDE_CMP_EQ_OQ); - b2FloatW test = simde_mm256_or_ps(test1, test2); + b2FloatW test1 = simde_mm256_cmp_ps( add( c->relativeVelocity2, threshold ), zero, SIMDE_CMP_GT_OQ ); + b2FloatW test2 = simde_mm256_cmp_ps( c->maxNormalImpulse2, zero, SIMDE_CMP_EQ_OQ ); + b2FloatW test = simde_mm256_or_ps( test1, test2 ); // todo slow on SSE2 - b2FloatW mass = simde_mm256_blendv_ps(c->normalMass2, zero, test); + b2FloatW mass = simde_mm256_blendv_ps( c->normalMass2, zero, test ); // fixed anchors for Jacobians b2Vec2W rA = c->anchorA2; b2Vec2W rB = c->anchorB2; // Relative velocity at contact - b2FloatW dvx = sub(sub(bB.v.X, mul(bB.w, rB.Y)), sub(bA.v.X, mul(bA.w, rA.Y))); - b2FloatW dvy = sub(add(bB.v.Y, mul(bB.w, rB.X)), add(bA.v.Y, mul(bA.w, rA.X))); - b2FloatW vn = add(mul(dvx, c->normal.X), mul(dvy, c->normal.Y)); + b2FloatW dvx = sub( sub( bB.v.X, mul( bB.w, rB.Y ) ), sub( bA.v.X, mul( bA.w, rA.Y ) ) ); + b2FloatW dvy = sub( add( bB.v.Y, mul( bB.w, rB.X ) ), add( bA.v.Y, mul( bA.w, rA.X ) ) ); + b2FloatW vn = add( mul( dvx, c->normal.X ), mul( dvy, c->normal.Y ) ); // Compute normal impulse - b2FloatW negImpulse = mul(mass, add(vn, mul(c->restitution, c->relativeVelocity2))); + b2FloatW negImpulse = mul( mass, add( vn, mul( c->restitution, c->relativeVelocity2 ) ) ); // Clamp the accumulated impulse - b2FloatW newImpulse = simde_mm256_max_ps(sub(c->normalImpulse2, negImpulse), simde_mm256_setzero_ps()); - b2FloatW impulse = sub(newImpulse, c->normalImpulse2); + b2FloatW newImpulse = simde_mm256_max_ps( sub( c->normalImpulse2, negImpulse ), simde_mm256_setzero_ps() ); + b2FloatW impulse = sub( newImpulse, c->normalImpulse2 ); c->normalImpulse2 = newImpulse; // Apply contact impulse - b2FloatW Px = mul(impulse, c->normal.X); - b2FloatW Py = mul(impulse, c->normal.Y); + b2FloatW Px = mul( impulse, c->normal.X ); + b2FloatW Py = mul( impulse, c->normal.Y ); - bA.v.X = mulsub(bA.v.X, c->invMassA, Px); - bA.v.Y = mulsub(bA.v.Y, c->invMassA, Py); - bA.w = mulsub(bA.w, c->invIA, sub(mul(rA.X, Py), mul(rA.Y, Px))); + bA.v.X = mulsub( bA.v.X, c->invMassA, Px ); + bA.v.Y = mulsub( bA.v.Y, c->invMassA, Py ); + bA.w = mulsub( bA.w, c->invIA, sub( mul( rA.X, Py ), mul( rA.Y, Px ) ) ); - bB.v.X = muladd(bB.v.X, c->invMassB, Px); - bB.v.Y = muladd(bB.v.Y, c->invMassB, Py); - bB.w = muladd(bB.w, c->invIB, sub(mul(rB.X, Py), mul(rB.Y, Px))); + bB.v.X = muladd( bB.v.X, c->invMassB, Px ); + bB.v.Y = muladd( bB.v.Y, c->invMassB, Py ); + bB.w = muladd( bB.w, c->invIB, sub( mul( rB.X, Py ), mul( rB.Y, Px ) ) ); } - b2ScatterBodies(states, c->indexA, &bA); - b2ScatterBodies(states, c->indexB, &bB); + b2ScatterBodies( states, c->indexA, &bA ); + b2ScatterBodies( states, c->indexB, &bB ); } - b2TracyCZoneEnd(restitution); + b2TracyCZoneEnd( restitution ); } -void b2StoreImpulsesTask(int startIndex, int endIndex, b2StepContext* context) +void b2StoreImpulsesTask( int startIndex, int endIndex, b2StepContext* context ) { - b2TracyCZoneNC(store_impulses, "Store", b2_colorFirebrick, true); + b2TracyCZoneNC( store_impulses, "Store", b2_colorFirebrick, true ); b2ContactSim** contacts = context->contacts; const b2ContactConstraintSIMD* constraints = context->simdContactConstraints; - b2Manifold dummy = {0}; + b2Manifold dummy = { 0 }; - for (int i = startIndex; i < endIndex; ++i) + for ( int i = startIndex; i < endIndex; ++i ) { const b2ContactConstraintSIMD* c = constraints + i; const float* normalImpulse1 = (float*)&c->normalImpulse1; @@ -1260,7 +1262,7 @@ void b2StoreImpulsesTask(int startIndex, int endIndex, b2StepContext* context) m5->points[0].tangentImpulse = tangentImpulse1[5]; m5->points[0].maxNormalImpulse = maxNormalImpulse1[5]; m5->points[0].normalVelocity = normalVelocity1[5]; - + m5->points[1].normalImpulse = normalImpulse2[5]; m5->points[1].tangentImpulse = tangentImpulse2[5]; m5->points[1].maxNormalImpulse = maxNormalImpulse2[5]; @@ -1280,12 +1282,12 @@ void b2StoreImpulsesTask(int startIndex, int endIndex, b2StepContext* context) m7->points[0].tangentImpulse = tangentImpulse1[7]; m7->points[0].maxNormalImpulse = maxNormalImpulse1[7]; m7->points[0].normalVelocity = normalVelocity1[7]; - + m7->points[1].normalImpulse = normalImpulse2[7]; m7->points[1].tangentImpulse = tangentImpulse2[7]; m7->points[1].maxNormalImpulse = maxNormalImpulse2[7]; m7->points[1].normalVelocity = normalVelocity2[7]; } - b2TracyCZoneEnd(store_impulses); + b2TracyCZoneEnd( store_impulses ); } diff --git a/src/contact_solver.h b/src/contact_solver.h index 2deff3c8..e265e93f 100644 --- a/src/contact_solver.h +++ b/src/contact_solver.h @@ -4,7 +4,6 @@ #pragma once #include "solver.h" - #include "x86/avx.h" typedef struct b2ContactSim b2ContactSim; @@ -79,15 +78,15 @@ typedef struct b2ContactConstraintSIMD } b2ContactConstraintSIMD; // Overflow contacts don't fit into the constraint graph coloring -void b2PrepareOverflowContacts(b2StepContext* context); -void b2WarmStartOverflowContacts(b2StepContext* context); -void b2SolveOverflowContacts(b2StepContext* context, bool useBias); -void b2ApplyOverflowRestitution(b2StepContext* context); -void b2StoreOverflowImpulses(b2StepContext* context); +void b2PrepareOverflowContacts( b2StepContext* context ); +void b2WarmStartOverflowContacts( b2StepContext* context ); +void b2SolveOverflowContacts( b2StepContext* context, bool useBias ); +void b2ApplyOverflowRestitution( b2StepContext* context ); +void b2StoreOverflowImpulses( b2StepContext* context ); // Contacts that live within the constraint graph coloring -void b2PrepareContactsTask(int startIndex, int endIndex, b2StepContext* context); -void b2WarmStartContactsTask(int startIndex, int endIndex, b2StepContext* context, int colorIndex); -void b2SolveContactsTask(int startIndex, int endIndex, b2StepContext* context, int colorIndex, bool useBias); -void b2ApplyRestitutionTask(int startIndex, int endIndex, b2StepContext* context, int colorIndex); -void b2StoreImpulsesTask(int startIndex, int endIndex, b2StepContext* context); +void b2PrepareContactsTask( int startIndex, int endIndex, b2StepContext* context ); +void b2WarmStartContactsTask( int startIndex, int endIndex, b2StepContext* context, int colorIndex ); +void b2SolveContactsTask( int startIndex, int endIndex, b2StepContext* context, int colorIndex, bool useBias ); +void b2ApplyRestitutionTask( int startIndex, int endIndex, b2StepContext* context, int colorIndex ); +void b2StoreImpulsesTask( int startIndex, int endIndex, b2StepContext* context ); diff --git a/src/core.c b/src/core.c index 4d554f33..24fea5b4 100644 --- a/src/core.c +++ b/src/core.c @@ -2,26 +2,27 @@ // SPDX-License-Identifier: MIT #include "core.h" + #include "box2d/math_functions.h" #include float b2_lengthUnitsPerMeter = 1.0f; -void b2SetLengthUnitsPerMeter(float lengthUnits) +void b2SetLengthUnitsPerMeter( float lengthUnits ) { - B2_ASSERT(b2IsValid(lengthUnits) && lengthUnits > 0.0f); + B2_ASSERT( b2IsValid( lengthUnits ) && lengthUnits > 0.0f ); b2_lengthUnitsPerMeter = lengthUnits; } -float b2GetLengthUnitsPerMeter(void) +float b2GetLengthUnitsPerMeter( void ) { return b2_lengthUnitsPerMeter; } -static int b2DefaultAssertFcn(const char* condition, const char* fileName, int lineNumber) +static int b2DefaultAssertFcn( const char* condition, const char* fileName, int lineNumber ) { - printf("BOX2D ASSERTION: %s, %s, line %d\n", condition, fileName, lineNumber); + printf( "BOX2D ASSERTION: %s, %s, line %d\n", condition, fileName, lineNumber ); // return non-zero to break to debugger return 1; @@ -29,13 +30,13 @@ static int b2DefaultAssertFcn(const char* condition, const char* fileName, int l b2AssertFcn* b2AssertHandler = b2DefaultAssertFcn; -void b2SetAssertFcn(b2AssertFcn* assertFcn) +void b2SetAssertFcn( b2AssertFcn* assertFcn ) { - B2_ASSERT(assertFcn != NULL); + B2_ASSERT( assertFcn != NULL ); b2AssertHandler = assertFcn; } -b2Version b2GetVersion(void) +b2Version b2GetVersion( void ) { - return (b2Version){3, 0, 0}; + return ( b2Version ){ 3, 0, 0 }; } diff --git a/src/core.h b/src/core.h index 26477e77..3066635c 100644 --- a/src/core.h +++ b/src/core.h @@ -5,7 +5,7 @@ #include "box2d/base.h" -#define B2_NULL_INDEX (-1) +#define B2_NULL_INDEX ( -1 ) #ifdef NDEBUG #define B2_DEBUG 0 @@ -13,81 +13,81 @@ #define B2_DEBUG 1 #endif -#if defined(BOX2D_VALIDATE) && !defined(NDEBUG) +#if defined( BOX2D_VALIDATE ) && !defined( NDEBUG ) #define B2_VALIDATE 1 #else #define B2_VALIDATE 0 #endif // Define platform -#if defined(_WIN64) +#if defined( _WIN64 ) #define B2_PLATFORM_WINDOWS -#elif defined(__ANDROID__) +#elif defined( __ANDROID__ ) #define B2_PLATFORM_ANDROID -#elif defined(__linux__) +#elif defined( __linux__ ) #define B2_PLATFORM_LINUX -#elif defined(__APPLE__) +#elif defined( __APPLE__ ) #include - #if defined(TARGET_OS_IPHONE) && !TARGET_OS_IPHONE + #if defined( TARGET_OS_IPHONE ) && !TARGET_OS_IPHONE #define B2_PLATFORM_MACOS #else #define B2_PLATFORM_IOS #endif -#elif defined(__EMSCRIPTEN__) +#elif defined( __EMSCRIPTEN__ ) #define B2_PLATFORM_WASM #else #error Unsupported platform #endif // Define CPU -#if defined(__x86_64__) || defined(_M_X64) +#if defined( __x86_64__ ) || defined( _M_X64 ) #define B2_CPU_X64 -#elif defined(__aarch64__) || defined(_M_ARM64) +#elif defined( __aarch64__ ) || defined( _M_ARM64 ) #define B2_CPU_ARM -#elif defined(__EMSCRIPTEN__) +#elif defined( __EMSCRIPTEN__ ) #define B2_CPU_WASM #else #error Unsupported CPU #endif // Define compiler -#if defined(__clang__) +#if defined( __clang__ ) #define B2_COMPILER_CLANG -#elif defined(__GNUC__) +#elif defined( __GNUC__ ) #define B2_COMPILER_GCC -#elif defined(_MSC_VER) +#elif defined( _MSC_VER ) #define B2_COMPILER_MSVC #endif -#if defined(B2_COMPILER_MSVC) +#if defined( B2_COMPILER_MSVC ) #define B2_BREAKPOINT __debugbreak() -#elif defined(B2_COMPILER_GCC) || defined(B2_COMPILER_CLANG) - #if defined(B2_CPU_X64) - #define B2_BREAKPOINT __asm volatile("int $0x3") - #elif defined(B2_CPU_ARM) +#elif defined( B2_COMPILER_GCC ) || defined( B2_COMPILER_CLANG ) + #if defined( B2_CPU_X64 ) + #define B2_BREAKPOINT __asm volatile( "int $0x3" ) + #elif defined( B2_CPU_ARM ) #define B2_BREAKPOINT __builtin_trap() #endif -#elif defined(B2_PLATFORM_WASM) +#elif defined( B2_PLATFORM_WASM ) #define B2_BREAKPOINT \ do \ { \ } \ - while (0) + while ( 0 ) #else #error Unknown platform #endif -#if !defined(NDEBUG) || defined(B2_ENABLE_ASSERT) +#if !defined( NDEBUG ) || defined( B2_ENABLE_ASSERT ) extern b2AssertFcn* b2AssertHandler; - #define B2_ASSERT(condition) \ + #define B2_ASSERT( condition ) \ do \ { \ - if (!(condition) && b2AssertHandler(#condition, __FILE__, (int)__LINE__)) \ + if ( !( condition ) && b2AssertHandler( #condition, __FILE__, (int)__LINE__ ) ) \ B2_BREAKPOINT; \ } \ - while (0) + while ( 0 ) #else - #define B2_ASSERT(...) ((void)0) + #define B2_ASSERT( ... ) ( (void)0 ) #endif /// Tracy profiler instrumentation @@ -95,15 +95,15 @@ extern b2AssertFcn* b2AssertHandler; #ifdef BOX2D_PROFILE #include - #define b2TracyCZoneC(ctx, color, active) TracyCZoneC(ctx, color, active) - #define b2TracyCZoneNC(ctx, name, color, active) TracyCZoneNC(ctx, name, color, active) - #define b2TracyCZoneEnd(ctx) TracyCZoneEnd(ctx) + #define b2TracyCZoneC( ctx, color, active ) TracyCZoneC( ctx, color, active ) + #define b2TracyCZoneNC( ctx, name, color, active ) TracyCZoneNC( ctx, name, color, active ) + #define b2TracyCZoneEnd( ctx ) TracyCZoneEnd( ctx ) #else - #define b2TracyCZoneC(ctx, color, active) - #define b2TracyCZoneNC(ctx, name, color, active) - #define b2TracyCZoneEnd(ctx) + #define b2TracyCZoneC( ctx, color, active ) + #define b2TracyCZoneNC( ctx, name, color, active ) + #define b2TracyCZoneEnd( ctx ) #endif @@ -111,7 +111,7 @@ extern float b2_lengthUnitsPerMeter; // Used to detect bad values. Positions greater than about 16km will have precision // problems, so 100km as a limit should be fine in all cases. -#define b2_huge (100000.0f * b2_lengthUnitsPerMeter) +#define b2_huge ( 100000.0f * b2_lengthUnitsPerMeter ) // Maximum parallel workers. Used to size some static arrays. #define b2_maxWorkers 64 @@ -123,7 +123,7 @@ extern float b2_lengthUnitsPerMeter; // 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 b2_linearSlop (0.005f * b2_lengthUnitsPerMeter) +#define b2_linearSlop ( 0.005f * b2_lengthUnitsPerMeter ) // Maximum number of simultaneous worlds that can be allocated #define b2_maxWorlds 128 @@ -131,32 +131,32 @@ extern float b2_lengthUnitsPerMeter; // The maximum translation 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. Meters. // @warning modifying this can have a significant impact on stability -#define b2_maxTranslation (4.0f * b2_lengthUnitsPerMeter) +#define b2_maxTranslation ( 4.0f * b2_lengthUnitsPerMeter ) // 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 modifying this can have a significant impact on stability -#define b2_maxRotation (0.25f * b2_pi) +#define b2_maxRotation ( 0.25f * b2_pi ) // @warning modifying this can have a significant impact on performance and stability -#define b2_speculativeDistance (4.0f * b2_linearSlop) +#define b2_speculativeDistance ( 4.0f * b2_linearSlop ) // 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 b2_aabbMargin (0.1f * b2_lengthUnitsPerMeter) +#define b2_aabbMargin ( 0.1f * b2_lengthUnitsPerMeter ) // The time that a body must be still before it will go to sleep. In seconds. #define b2_timeToSleep 0.5f // Returns the number of elements of an array -#define B2_ARRAY_COUNT(A) (int)(sizeof(A) / sizeof(A[0])) +#define B2_ARRAY_COUNT( A ) (int)( sizeof( A ) / sizeof( A[0] ) ) // Used to prevent the compiler from warning about unused variables -#define B2_MAYBE_UNUSED(x) ((void)(x)) +#define B2_MAYBE_UNUSED( x ) ( (void)( x ) ) // Use to validate definitions. Do not take my cookie. #define B2_SECRET_COOKIE 1152023 -#define b2CheckDef(DEF) B2_ASSERT(DEF->internalValue == B2_SECRET_COOKIE) +#define b2CheckDef( DEF ) B2_ASSERT( DEF->internalValue == B2_SECRET_COOKIE ) diff --git a/src/ctz.h b/src/ctz.h index 0b756fca..9959527c 100644 --- a/src/ctz.h +++ b/src/ctz.h @@ -6,26 +6,26 @@ #include #include -#if defined(_MSC_VER) && !defined(__clang__) -#include +#if defined( _MSC_VER ) && !defined( __clang__ ) + #include // https://en.wikipedia.org/wiki/Find_first_set -static inline uint32_t b2CTZ32(uint32_t block) +static inline uint32_t b2CTZ32( uint32_t block ) { unsigned long index; - _BitScanForward(&index, block); + _BitScanForward( &index, block ); return index; } // This function doesn't need to be fast, so using the Ivy Bridge fallback. -static inline uint32_t b2CLZ32(uint32_t value) +static inline uint32_t b2CLZ32( uint32_t value ) { #if 1 - + // Use BSR (Bit Scan Reverse) which is available on Ivy Bridge unsigned long index; - if (_BitScanReverse(&index, value)) + if ( _BitScanReverse( &index, value ) ) { // BSR gives the index of the most significant 1-bit // We need to invert this to get the number of leading zeros @@ -40,73 +40,73 @@ static inline uint32_t b2CLZ32(uint32_t value) #else - return __lzcnt(value); + return __lzcnt( value ); #endif } -static inline uint32_t b2CTZ64(uint64_t block) +static inline uint32_t b2CTZ64( uint64_t block ) { unsigned long index; -#ifdef _WIN64 - _BitScanForward64(&index, block); -#else + #ifdef _WIN64 + _BitScanForward64( &index, block ); + #else // 32-bit fall back - if ((uint32_t)block != 0) + if ( (uint32_t)block != 0 ) { - _BitScanForward(&index, (uint32_t)block); + _BitScanForward( &index, (uint32_t)block ); } else { - _BitScanForward(&index, (uint32_t)(block >> 32)); + _BitScanForward( &index, (uint32_t)( block >> 32 ) ); index += 32; } -#endif + #endif return index; } #else -static inline uint32_t b2CTZ32(uint32_t block) +static inline uint32_t b2CTZ32( uint32_t block ) { - return __builtin_ctz(block); + return __builtin_ctz( block ); } -static inline uint32_t b2CLZ32(uint32_t value) +static inline uint32_t b2CLZ32( uint32_t value ) { - return __builtin_clz(value); + return __builtin_clz( value ); } -static inline uint32_t b2CTZ64(uint64_t block) +static inline uint32_t b2CTZ64( uint64_t block ) { - return __builtin_ctzll(block); + return __builtin_ctzll( block ); } #endif -static inline bool b2IsPowerOf2(int x) +static inline bool b2IsPowerOf2( int x ) { - return (x & (x - 1)) == 0; + return ( x & ( x - 1 ) ) == 0; } -static inline int b2BoundingPowerOf2(int x) +static inline int b2BoundingPowerOf2( int x ) { - if (x <= 1) + if ( x <= 1 ) { - return 1; + return 1; } - return 32 - (int)b2CLZ32((uint32_t)x - 1); + return 32 - (int)b2CLZ32( (uint32_t)x - 1 ); } -static inline int b2RoundUpPowerOf2(int x) +static inline int b2RoundUpPowerOf2( int x ) { - if (x <= 1) + if ( x <= 1 ) { return 1; } - - return 1 << (32 - (int)b2CLZ32((uint32_t)x - 1)); + + return 1 << ( 32 - (int)b2CLZ32( (uint32_t)x - 1 ) ); } diff --git a/src/distance.c b/src/distance.c index 7cdd693b..048860c0 100644 --- a/src/distance.c +++ b/src/distance.c @@ -10,53 +10,53 @@ #include #include -b2Transform b2GetSweepTransform(const b2Sweep* sweep, float time) +b2Transform b2GetSweepTransform( const b2Sweep* sweep, float time ) { // https://fgiesen.wordpress.com/2012/08/15/linear-interpolation-past-present-and-future/ b2Transform xf; - xf.p = b2Add(b2MulSV(1.0f - time, sweep->c1), b2MulSV(time, sweep->c2)); + xf.p = b2Add( b2MulSV( 1.0f - time, sweep->c1 ), b2MulSV( time, sweep->c2 ) ); b2Rot q = { - (1.0f - time) * sweep->q1.c + time * sweep->q2.c, - (1.0f - time) * sweep->q1.s + time * sweep->q2.s, + ( 1.0f - time ) * sweep->q1.c + time * sweep->q2.c, + ( 1.0f - time ) * sweep->q1.s + time * sweep->q2.s, }; - xf.q = b2NormalizeRot(q); + xf.q = b2NormalizeRot( q ); // Shift to origin - xf.p = b2Sub(xf.p, b2RotateVector(xf.q, sweep->localCenter)); + xf.p = b2Sub( xf.p, b2RotateVector( xf.q, sweep->localCenter ) ); return xf; } /// Follows Ericson 5.1.9 Closest Points of Two Line Segments -b2SegmentDistanceResult b2SegmentDistance(b2Vec2 p1, b2Vec2 q1, b2Vec2 p2, b2Vec2 q2) +b2SegmentDistanceResult b2SegmentDistance( b2Vec2 p1, b2Vec2 q1, b2Vec2 p2, b2Vec2 q2 ) { - b2SegmentDistanceResult result = {0}; + b2SegmentDistanceResult result = { 0 }; - b2Vec2 d1 = b2Sub(q1, p1); - b2Vec2 d2 = b2Sub(q2, p2); - b2Vec2 r = b2Sub(p1, p2); - float dd1 = b2Dot(d1, d1); - float dd2 = b2Dot(d2, d2); - float rd2 = b2Dot(r, d2); - float rd1 = b2Dot(r, d1); + b2Vec2 d1 = b2Sub( q1, p1 ); + b2Vec2 d2 = b2Sub( q2, p2 ); + b2Vec2 r = b2Sub( p1, p2 ); + float dd1 = b2Dot( d1, d1 ); + float dd2 = b2Dot( d2, d2 ); + float rd2 = b2Dot( r, d2 ); + float rd1 = b2Dot( r, d1 ); const float epsSqr = FLT_EPSILON * FLT_EPSILON; - if (dd1 < epsSqr || dd2 < epsSqr) + if ( dd1 < epsSqr || dd2 < epsSqr ) { // Handle all degeneracies - if (dd1 >= epsSqr) + if ( dd1 >= epsSqr ) { // Segment 2 is degenerate - result.fraction1 = b2ClampFloat(-rd1 / dd1, 0.0f, 1.0f); + result.fraction1 = b2ClampFloat( -rd1 / dd1, 0.0f, 1.0f ); result.fraction2 = 0.0f; } - else if (dd2 >= epsSqr) + else if ( dd2 >= epsSqr ) { // Segment 1 is degenerate result.fraction1 = 0.0f; - result.fraction2 = b2ClampFloat(rd2 / dd2, 0.0f, 1.0f); + result.fraction2 = b2ClampFloat( rd2 / dd2, 0.0f, 1.0f ); } else { @@ -67,50 +67,50 @@ b2SegmentDistanceResult b2SegmentDistance(b2Vec2 p1, b2Vec2 q1, b2Vec2 p2, b2Vec else { // Non-degenerate segments - float d12 = b2Dot(d1, d2); + float d12 = b2Dot( d1, d2 ); float denom = dd1 * dd2 - d12 * d12; // Fraction on segment 1 float f1 = 0.0f; - if (denom != 0.0f) + if ( denom != 0.0f ) { // not parallel - f1 = b2ClampFloat((d12 * rd2 - rd1 * dd2) / denom, 0.0f, 1.0f); + f1 = b2ClampFloat( ( d12 * rd2 - rd1 * dd2 ) / denom, 0.0f, 1.0f ); } // Compute point on segment 2 closest to p1 + f1 * d1 - float f2 = (d12 * f1 + rd2) / dd2; + float f2 = ( d12 * f1 + rd2 ) / dd2; // Clamping of segment 2 requires a do over on segment 1 - if (f2 < 0.0f) + if ( f2 < 0.0f ) { f2 = 0.0f; - f1 = b2ClampFloat(-rd1 / dd1, 0.0f, 1.0f); + f1 = b2ClampFloat( -rd1 / dd1, 0.0f, 1.0f ); } - else if (f2 > 1.0f) + else if ( f2 > 1.0f ) { f2 = 1.0f; - f1 = b2ClampFloat((d12 - rd1) / dd1, 0.0f, 1.0f); + f1 = b2ClampFloat( ( d12 - rd1 ) / dd1, 0.0f, 1.0f ); } result.fraction1 = f1; result.fraction2 = f2; } - result.closest1 = b2MulAdd(p1, result.fraction1, d1); - result.closest2 = b2MulAdd(p2, result.fraction2, d2); - result.distanceSquared = b2DistanceSquared(result.closest1, result.closest2); + result.closest1 = b2MulAdd( p1, result.fraction1, d1 ); + result.closest2 = b2MulAdd( p2, result.fraction2, d2 ); + result.distanceSquared = b2DistanceSquared( result.closest1, result.closest2 ); return result; } // GJK using Voronoi regions (Christer Ericson) and Barycentric coordinates. // todo try not copying -b2DistanceProxy b2MakeProxy(const b2Vec2* vertices, int count, float radius) +b2DistanceProxy b2MakeProxy( const b2Vec2* vertices, int count, float radius ) { - count = b2MinInt(count, b2_maxPolygonVertices); + count = b2MinInt( count, b2_maxPolygonVertices ); b2DistanceProxy proxy; - for (int i = 0; i < count; ++i) + for ( int i = 0; i < count; ++i ) { proxy.points[i] = vertices[i]; } @@ -119,24 +119,24 @@ b2DistanceProxy b2MakeProxy(const b2Vec2* vertices, int count, float radius) return proxy; } -static b2Vec2 b2Weight2(float a1, b2Vec2 w1, float a2, b2Vec2 w2) +static b2Vec2 b2Weight2( float a1, b2Vec2 w1, float a2, b2Vec2 w2 ) { - return (b2Vec2){a1 * w1.x + a2 * w2.x, a1 * w1.y + a2 * w2.y}; + return ( b2Vec2 ){ a1 * w1.x + a2 * w2.x, a1 * w1.y + a2 * w2.y }; } -static b2Vec2 b2Weight3(float a1, b2Vec2 w1, float a2, b2Vec2 w2, float a3, b2Vec2 w3) +static b2Vec2 b2Weight3( float a1, b2Vec2 w1, float a2, b2Vec2 w2, float a3, b2Vec2 w3 ) { - return (b2Vec2){a1 * w1.x + a2 * w2.x + a3 * w3.x, a1 * w1.y + a2 * w2.y + a3 * w3.y}; + return ( b2Vec2 ){ a1 * w1.x + a2 * w2.x + a3 * w3.x, a1 * w1.y + a2 * w2.y + a3 * w3.y }; } -static int b2FindSupport(const b2DistanceProxy* proxy, b2Vec2 direction) +static int b2FindSupport( const b2DistanceProxy* proxy, b2Vec2 direction ) { int bestIndex = 0; - float bestValue = b2Dot(proxy->points[0], direction); - for (int i = 1; i < proxy->count; ++i) + float bestValue = b2Dot( proxy->points[0], direction ); + for ( int i = 1; i < proxy->count; ++i ) { - float value = b2Dot(proxy->points[i], direction); - if (value > bestValue) + float value = b2Dot( proxy->points[i], direction ); + if ( value > bestValue ) { bestIndex = i; bestValue = value; @@ -146,42 +146,42 @@ static int b2FindSupport(const b2DistanceProxy* proxy, b2Vec2 direction) return bestIndex; } -static b2Simplex b2MakeSimplexFromCache(const b2DistanceCache* cache, const b2DistanceProxy* proxyA, b2Transform transformA, - const b2DistanceProxy* proxyB, b2Transform transformB) +static b2Simplex b2MakeSimplexFromCache( const b2DistanceCache* cache, const b2DistanceProxy* proxyA, b2Transform transformA, + const b2DistanceProxy* proxyB, b2Transform transformB ) { - B2_ASSERT(cache->count <= 3); + B2_ASSERT( cache->count <= 3 ); b2Simplex s; // Copy data from cache. s.count = cache->count; - b2SimplexVertex* vertices[] = {&s.v1, &s.v2, &s.v3}; - for (int i = 0; i < s.count; ++i) + b2SimplexVertex* vertices[] = { &s.v1, &s.v2, &s.v3 }; + for ( int i = 0; i < s.count; ++i ) { b2SimplexVertex* v = vertices[i]; v->indexA = cache->indexA[i]; v->indexB = cache->indexB[i]; b2Vec2 wALocal = proxyA->points[v->indexA]; b2Vec2 wBLocal = proxyB->points[v->indexB]; - v->wA = b2TransformPoint(transformA, wALocal); - v->wB = b2TransformPoint(transformB, wBLocal); - v->w = b2Sub(v->wB, v->wA); + v->wA = b2TransformPoint( transformA, wALocal ); + v->wB = b2TransformPoint( transformB, wBLocal ); + v->w = b2Sub( v->wB, v->wA ); // invalid v->a = -1.0f; } // If the cache is empty or invalid ... - if (s.count == 0) + if ( s.count == 0 ) { b2SimplexVertex* v = vertices[0]; v->indexA = 0; v->indexB = 0; b2Vec2 wALocal = proxyA->points[0]; b2Vec2 wBLocal = proxyB->points[0]; - v->wA = b2TransformPoint(transformA, wALocal); - v->wB = b2TransformPoint(transformB, wBLocal); - v->w = b2Sub(v->wB, v->wA); + v->wA = b2TransformPoint( transformA, wALocal ); + v->wB = b2TransformPoint( transformB, wBLocal ); + v->w = b2Sub( v->wB, v->wA ); v->a = 1.0f; s.count = 1; } @@ -189,11 +189,11 @@ static b2Simplex b2MakeSimplexFromCache(const b2DistanceCache* cache, const b2Di return s; } -static void b2MakeSimplexCache(b2DistanceCache* cache, const b2Simplex* simplex) +static void b2MakeSimplexCache( b2DistanceCache* cache, const b2Simplex* simplex ) { cache->count = (uint16_t)simplex->count; - const b2SimplexVertex* vertices[] = {&simplex->v1, &simplex->v2, &simplex->v3}; - for (int i = 0; i < simplex->count; ++i) + const b2SimplexVertex* vertices[] = { &simplex->v1, &simplex->v2, &simplex->v3 }; + for ( int i = 0; i < simplex->count; ++i ) { cache->indexA[i] = (uint8_t)vertices[i]->indexA; cache->indexB[i] = (uint8_t)vertices[i]->indexB; @@ -207,64 +207,64 @@ static void b2MakeSimplexCache(b2DistanceCache* cache, const b2Simplex* simplex) // vector of the simplex. For example, the normal vector of a line segment // can be computed more accurately because it does not involve barycentric // coordinates. -b2Vec2 b2ComputeSimplexSearchDirection(const b2Simplex* simplex) +b2Vec2 b2ComputeSimplexSearchDirection( const b2Simplex* simplex ) { - switch (simplex->count) + switch ( simplex->count ) { case 1: - return b2Neg(simplex->v1.w); + return b2Neg( simplex->v1.w ); case 2: { - b2Vec2 e12 = b2Sub(simplex->v2.w, simplex->v1.w); - float sgn = b2Cross(e12, b2Neg(simplex->v1.w)); - if (sgn > 0.0f) + b2Vec2 e12 = b2Sub( simplex->v2.w, simplex->v1.w ); + float sgn = b2Cross( e12, b2Neg( simplex->v1.w ) ); + if ( sgn > 0.0f ) { // Origin is left of e12. - return b2LeftPerp(e12); + return b2LeftPerp( e12 ); } else { // Origin is right of e12. - return b2RightPerp(e12); + return b2RightPerp( e12 ); } } default: - B2_ASSERT(false); + B2_ASSERT( false ); return b2Vec2_zero; } } -b2Vec2 b2ComputeSimplexClosestPoint(const b2Simplex* s) +b2Vec2 b2ComputeSimplexClosestPoint( const b2Simplex* s ) { - switch (s->count) + switch ( s->count ) { case 0: - B2_ASSERT(false); + B2_ASSERT( false ); return b2Vec2_zero; case 1: return s->v1.w; case 2: - return b2Weight2(s->v1.a, s->v1.w, s->v2.a, s->v2.w); + return b2Weight2( s->v1.a, s->v1.w, s->v2.a, s->v2.w ); case 3: return b2Vec2_zero; default: - B2_ASSERT(false); + B2_ASSERT( false ); return b2Vec2_zero; } } -void b2ComputeSimplexWitnessPoints(b2Vec2* a, b2Vec2* b, const b2Simplex* s) +void b2ComputeSimplexWitnessPoints( b2Vec2* a, b2Vec2* b, const b2Simplex* s ) { - switch (s->count) + switch ( s->count ) { case 0: - B2_ASSERT(false); + B2_ASSERT( false ); break; case 1: @@ -273,19 +273,19 @@ void b2ComputeSimplexWitnessPoints(b2Vec2* a, b2Vec2* b, const b2Simplex* s) break; case 2: - *a = b2Weight2(s->v1.a, s->v1.wA, s->v2.a, s->v2.wA); - *b = b2Weight2(s->v1.a, s->v1.wB, s->v2.a, s->v2.wB); + *a = b2Weight2( s->v1.a, s->v1.wA, s->v2.a, s->v2.wA ); + *b = b2Weight2( s->v1.a, s->v1.wB, s->v2.a, s->v2.wB ); break; case 3: - *a = b2Weight3(s->v1.a, s->v1.wA, s->v2.a, s->v2.wA, s->v3.a, s->v3.wA); + *a = b2Weight3( s->v1.a, s->v1.wA, s->v2.a, s->v2.wA, s->v3.a, s->v3.wA ); // TODO_ERIN why are these not equal? //*b = b2Weight3(s->v1.a, s->v1.wB, s->v2.a, s->v2.wB, s->v3.a, s->v3.wB); *b = *a; break; default: - B2_ASSERT(false); + B2_ASSERT( false ); break; } } @@ -313,15 +313,15 @@ void b2ComputeSimplexWitnessPoints(b2Vec2* a, b2Vec2* b, const b2Simplex* s) // Solution // a1 = d12_1 / d12 // a2 = d12_2 / d12 -void b2SolveSimplex2(b2Simplex* s) +void b2SolveSimplex2( b2Simplex* s ) { b2Vec2 w1 = s->v1.w; b2Vec2 w2 = s->v2.w; - b2Vec2 e12 = b2Sub(w2, w1); + b2Vec2 e12 = b2Sub( w2, w1 ); // w1 region - float d12_2 = -b2Dot(w1, e12); - if (d12_2 <= 0.0f) + float d12_2 = -b2Dot( w1, e12 ); + if ( d12_2 <= 0.0f ) { // a2 <= 0, so we clamp it to 0 s->v1.a = 1.0f; @@ -330,8 +330,8 @@ void b2SolveSimplex2(b2Simplex* s) } // w2 region - float d12_1 = b2Dot(w2, e12); - if (d12_1 <= 0.0f) + float d12_1 = b2Dot( w2, e12 ); + if ( d12_1 <= 0.0f ) { // a1 <= 0, so we clamp it to 0 s->v2.a = 1.0f; @@ -341,13 +341,13 @@ void b2SolveSimplex2(b2Simplex* s) } // Must be in e12 region. - float inv_d12 = 1.0f / (d12_1 + d12_2); + float inv_d12 = 1.0f / ( d12_1 + d12_2 ); s->v1.a = d12_1 * inv_d12; s->v2.a = d12_2 * inv_d12; s->count = 2; } -void b2SolveSimplex3(b2Simplex* s) +void b2SolveSimplex3( b2Simplex* s ) { b2Vec2 w1 = s->v1.w; b2Vec2 w2 = s->v2.w; @@ -357,9 +357,9 @@ void b2SolveSimplex3(b2Simplex* s) // [1 1 ][a1] = [1] // [w1.e12 w2.e12][a2] = [0] // a3 = 0 - b2Vec2 e12 = b2Sub(w2, w1); - float w1e12 = b2Dot(w1, e12); - float w2e12 = b2Dot(w2, e12); + b2Vec2 e12 = b2Sub( w2, w1 ); + float w1e12 = b2Dot( w1, e12 ); + float w2e12 = b2Dot( w2, e12 ); float d12_1 = w2e12; float d12_2 = -w1e12; @@ -367,9 +367,9 @@ void b2SolveSimplex3(b2Simplex* s) // [1 1 ][a1] = [1] // [w1.e13 w3.e13][a3] = [0] // a2 = 0 - b2Vec2 e13 = b2Sub(w3, w1); - float w1e13 = b2Dot(w1, e13); - float w3e13 = b2Dot(w3, e13); + b2Vec2 e13 = b2Sub( w3, w1 ); + float w1e13 = b2Dot( w1, e13 ); + float w3e13 = b2Dot( w3, e13 ); float d13_1 = w3e13; float d13_2 = -w1e13; @@ -377,21 +377,21 @@ void b2SolveSimplex3(b2Simplex* s) // [1 1 ][a2] = [1] // [w2.e23 w3.e23][a3] = [0] // a1 = 0 - b2Vec2 e23 = b2Sub(w3, w2); - float w2e23 = b2Dot(w2, e23); - float w3e23 = b2Dot(w3, e23); + b2Vec2 e23 = b2Sub( w3, w2 ); + float w2e23 = b2Dot( w2, e23 ); + float w3e23 = b2Dot( w3, e23 ); float d23_1 = w3e23; float d23_2 = -w2e23; // Triangle123 - float n123 = b2Cross(e12, e13); + float n123 = b2Cross( e12, e13 ); - float d123_1 = n123 * b2Cross(w2, w3); - float d123_2 = n123 * b2Cross(w3, w1); - float d123_3 = n123 * b2Cross(w1, w2); + float d123_1 = n123 * b2Cross( w2, w3 ); + float d123_2 = n123 * b2Cross( w3, w1 ); + float d123_3 = n123 * b2Cross( w1, w2 ); // w1 region - if (d12_2 <= 0.0f && d13_2 <= 0.0f) + if ( d12_2 <= 0.0f && d13_2 <= 0.0f ) { s->v1.a = 1.0f; s->count = 1; @@ -399,9 +399,9 @@ void b2SolveSimplex3(b2Simplex* s) } // e12 - if (d12_1 > 0.0f && d12_2 > 0.0f && d123_3 <= 0.0f) + if ( d12_1 > 0.0f && d12_2 > 0.0f && d123_3 <= 0.0f ) { - float inv_d12 = 1.0f / (d12_1 + d12_2); + float inv_d12 = 1.0f / ( d12_1 + d12_2 ); s->v1.a = d12_1 * inv_d12; s->v2.a = d12_2 * inv_d12; s->count = 2; @@ -409,9 +409,9 @@ void b2SolveSimplex3(b2Simplex* s) } // e13 - if (d13_1 > 0.0f && d13_2 > 0.0f && d123_2 <= 0.0f) + if ( d13_1 > 0.0f && d13_2 > 0.0f && d123_2 <= 0.0f ) { - float inv_d13 = 1.0f / (d13_1 + d13_2); + float inv_d13 = 1.0f / ( d13_1 + d13_2 ); s->v1.a = d13_1 * inv_d13; s->v3.a = d13_2 * inv_d13; s->count = 2; @@ -420,7 +420,7 @@ void b2SolveSimplex3(b2Simplex* s) } // w2 region - if (d12_1 <= 0.0f && d23_2 <= 0.0f) + if ( d12_1 <= 0.0f && d23_2 <= 0.0f ) { s->v2.a = 1.0f; s->count = 1; @@ -429,7 +429,7 @@ void b2SolveSimplex3(b2Simplex* s) } // w3 region - if (d13_1 <= 0.0f && d23_1 <= 0.0f) + if ( d13_1 <= 0.0f && d23_1 <= 0.0f ) { s->v3.a = 1.0f; s->count = 1; @@ -438,9 +438,9 @@ void b2SolveSimplex3(b2Simplex* s) } // e23 - if (d23_1 > 0.0f && d23_2 > 0.0f && d123_1 <= 0.0f) + if ( d23_1 > 0.0f && d23_2 > 0.0f && d123_1 <= 0.0f ) { - float inv_d23 = 1.0f / (d23_1 + d23_2); + float inv_d23 = 1.0f / ( d23_1 + d23_2 ); s->v2.a = d23_1 * inv_d23; s->v3.a = d23_2 * inv_d23; s->count = 2; @@ -449,16 +449,17 @@ void b2SolveSimplex3(b2Simplex* s) } // Must be in triangle123 - float inv_d123 = 1.0f / (d123_1 + d123_2 + d123_3); + float inv_d123 = 1.0f / ( d123_1 + d123_2 + d123_3 ); s->v1.a = d123_1 * inv_d123; s->v2.a = d123_2 * inv_d123; s->v3.a = d123_3 * inv_d123; s->count = 3; } -b2DistanceOutput b2ShapeDistance(b2DistanceCache* cache, const b2DistanceInput* input, b2Simplex* simplexes, int simplexCapacity) +b2DistanceOutput b2ShapeDistance( b2DistanceCache* cache, const b2DistanceInput* input, b2Simplex* simplexes, + int simplexCapacity ) { - b2DistanceOutput output = {0}; + b2DistanceOutput output = { 0 }; const b2DistanceProxy* proxyA = &input->proxyA; const b2DistanceProxy* proxyB = &input->proxyB; @@ -467,17 +468,17 @@ b2DistanceOutput b2ShapeDistance(b2DistanceCache* cache, const b2DistanceInput* b2Transform transformB = input->transformB; // Initialize the simplex. - b2Simplex simplex = b2MakeSimplexFromCache(cache, proxyA, transformA, proxyB, transformB); + b2Simplex simplex = b2MakeSimplexFromCache( cache, proxyA, transformA, proxyB, transformB ); int simplexIndex = 0; - if (simplexes != NULL && simplexIndex < simplexCapacity) + if ( simplexes != NULL && simplexIndex < simplexCapacity ) { simplexes[simplexIndex] = simplex; simplexIndex += 1; } // Get simplex vertices as an array. - b2SimplexVertex* vertices[] = {&simplex.v1, &simplex.v2, &simplex.v3}; + b2SimplexVertex* vertices[] = { &simplex.v1, &simplex.v2, &simplex.v3 }; const int k_maxIters = 20; // These store the vertices of the last simplex so that we can check for duplicates and prevent cycling. @@ -485,50 +486,50 @@ b2DistanceOutput b2ShapeDistance(b2DistanceCache* cache, const b2DistanceInput* // Main iteration loop. int iter = 0; - while (iter < k_maxIters) + while ( iter < k_maxIters ) { // Copy simplex so we can identify duplicates. int saveCount = simplex.count; - for (int i = 0; i < saveCount; ++i) + for ( int i = 0; i < saveCount; ++i ) { saveA[i] = vertices[i]->indexA; saveB[i] = vertices[i]->indexB; } - switch (simplex.count) + switch ( simplex.count ) { case 1: break; case 2: - b2SolveSimplex2(&simplex); + b2SolveSimplex2( &simplex ); break; case 3: - b2SolveSimplex3(&simplex); + b2SolveSimplex3( &simplex ); break; default: - B2_ASSERT(false); + B2_ASSERT( false ); } // If we have 3 points, then the origin is in the corresponding triangle. - if (simplex.count == 3) + if ( simplex.count == 3 ) { break; } - if (simplexes != NULL && simplexIndex < simplexCapacity) + if ( simplexes != NULL && simplexIndex < simplexCapacity ) { simplexes[simplexIndex] = simplex; simplexIndex += 1; } // Get search direction. - b2Vec2 d = b2ComputeSimplexSearchDirection(&simplex); + b2Vec2 d = b2ComputeSimplexSearchDirection( &simplex ); // Ensure the search direction is numerically fit. - if (b2Dot(d, d) < FLT_EPSILON * FLT_EPSILON) + if ( b2Dot( d, d ) < FLT_EPSILON * FLT_EPSILON ) { // The origin is probably contained by a line segment // or triangle. Thus the shapes are overlapped. @@ -542,20 +543,20 @@ b2DistanceOutput b2ShapeDistance(b2DistanceCache* cache, const b2DistanceInput* // Compute a tentative new simplex vertex using support points. // support = support(b, d) - support(a, -d) b2SimplexVertex* vertex = vertices[simplex.count]; - vertex->indexA = b2FindSupport(proxyA, b2InvRotateVector(transformA.q, b2Neg(d))); - vertex->wA = b2TransformPoint(transformA, proxyA->points[vertex->indexA]); - vertex->indexB = b2FindSupport(proxyB, b2InvRotateVector(transformB.q, d)); - vertex->wB = b2TransformPoint(transformB, proxyB->points[vertex->indexB]); - vertex->w = b2Sub(vertex->wB, vertex->wA); + vertex->indexA = b2FindSupport( proxyA, b2InvRotateVector( transformA.q, b2Neg( d ) ) ); + vertex->wA = b2TransformPoint( transformA, proxyA->points[vertex->indexA] ); + vertex->indexB = b2FindSupport( proxyB, b2InvRotateVector( transformB.q, d ) ); + vertex->wB = b2TransformPoint( transformB, proxyB->points[vertex->indexB] ); + vertex->w = b2Sub( vertex->wB, vertex->wA ); // Iteration count is equated to the number of support point calls. ++iter; // Check for duplicate support points. This is the main termination criteria. bool duplicate = false; - for (int i = 0; i < saveCount; ++i) + for ( int i = 0; i < saveCount; ++i ) { - if (vertex->indexA == saveA[i] && vertex->indexB == saveB[i]) + if ( vertex->indexA == saveA[i] && vertex->indexB == saveB[i] ) { duplicate = true; break; @@ -563,7 +564,7 @@ b2DistanceOutput b2ShapeDistance(b2DistanceCache* cache, const b2DistanceInput* } // If we found a duplicate support point we must exit to avoid cycling. - if (duplicate) + if ( duplicate ) { break; } @@ -572,28 +573,28 @@ b2DistanceOutput b2ShapeDistance(b2DistanceCache* cache, const b2DistanceInput* ++simplex.count; } - if (simplexes != NULL && simplexIndex < simplexCapacity) + if ( simplexes != NULL && simplexIndex < simplexCapacity ) { simplexes[simplexIndex] = simplex; simplexIndex += 1; } // Prepare output - b2ComputeSimplexWitnessPoints(&output.pointA, &output.pointB, &simplex); - output.distance = b2Distance(output.pointA, output.pointB); + b2ComputeSimplexWitnessPoints( &output.pointA, &output.pointB, &simplex ); + output.distance = b2Distance( output.pointA, output.pointB ); output.iterations = iter; output.simplexCount = simplexIndex; // Cache the simplex - b2MakeSimplexCache(cache, &simplex); + b2MakeSimplexCache( cache, &simplex ); // Apply radii if requested - if (input->useRadii) + if ( input->useRadii ) { - if (output.distance < FLT_EPSILON) + if ( output.distance < FLT_EPSILON ) { // Shapes are too close to safely compute normal - b2Vec2 p = (b2Vec2){0.5f * (output.pointA.x + output.pointB.x), 0.5f * (output.pointA.y + output.pointB.y)}; + b2Vec2 p = ( b2Vec2 ){ 0.5f * ( output.pointA.x + output.pointB.x ), 0.5f * ( output.pointA.y + output.pointB.y ) }; output.pointA = p; output.pointB = p; output.distance = 0.0f; @@ -604,12 +605,12 @@ b2DistanceOutput b2ShapeDistance(b2DistanceCache* cache, const b2DistanceInput* // the points move smoothly. float rA = proxyA->radius; float rB = proxyB->radius; - output.distance = b2MaxFloat(0.0f, output.distance - rA - rB); - b2Vec2 normal = b2Normalize(b2Sub(output.pointB, output.pointA)); - b2Vec2 offsetA = (b2Vec2){rA * normal.x, rA * normal.y}; - b2Vec2 offsetB = (b2Vec2){rB * normal.x, rB * normal.y}; - output.pointA = b2Add(output.pointA, offsetA); - output.pointB = b2Sub(output.pointB, offsetB); + output.distance = b2MaxFloat( 0.0f, output.distance - rA - rB ); + b2Vec2 normal = b2Normalize( b2Sub( output.pointB, output.pointA ) ); + b2Vec2 offsetA = ( b2Vec2 ){ rA * normal.x, rA * normal.y }; + b2Vec2 offsetB = ( b2Vec2 ){ rB * normal.x, rB * normal.y }; + output.pointA = b2Add( output.pointA, offsetA ); + output.pointB = b2Sub( output.pointB, offsetB ); } } @@ -621,31 +622,31 @@ b2DistanceOutput b2ShapeDistance(b2DistanceCache* cache, const b2DistanceInput* // "Smooth Mesh Contacts with GJK" in Game Physics Pearls. 2010 // todo this is failing when used to raycast a box // todo this converges slowly with a radius -b2CastOutput b2ShapeCast(const b2ShapeCastPairInput* input) +b2CastOutput b2ShapeCast( const b2ShapeCastPairInput* input ) { - b2CastOutput output = {0}; + b2CastOutput output = { 0 }; output.fraction = input->maxFraction; b2DistanceProxy proxyA = input->proxyA; b2Transform xfA = input->transformA; b2Transform xfB = input->transformB; - b2Transform xf = b2InvMulTransforms(xfA, xfB); + b2Transform xf = b2InvMulTransforms( xfA, xfB ); // Put proxyB in proxyA's frame to reduce round-off error b2DistanceProxy proxyB; proxyB.count = input->proxyB.count; proxyB.radius = input->proxyB.radius; - B2_ASSERT(proxyB.count <= b2_maxPolygonVertices); + B2_ASSERT( proxyB.count <= b2_maxPolygonVertices ); - for (int i = 0; i < proxyB.count; ++i) + for ( int i = 0; i < proxyB.count; ++i ) { - proxyB.points[i] = b2TransformPoint(xf, input->proxyB.points[i]); + proxyB.points[i] = b2TransformPoint( xf, input->proxyB.points[i] ); } float radius = proxyA.radius + proxyB.radius; - b2Vec2 r = b2RotateVector(xf.q, input->translationB); + b2Vec2 r = b2RotateVector( xf.q, input->translationB ); float lambda = 0.0f; float maxFraction = input->maxFraction; @@ -654,51 +655,51 @@ b2CastOutput b2ShapeCast(const b2ShapeCastPairInput* input) simplex.count = 0; // Get simplex vertices as an array. - b2SimplexVertex* vertices[] = {&simplex.v1, &simplex.v2, &simplex.v3}; + b2SimplexVertex* vertices[] = { &simplex.v1, &simplex.v2, &simplex.v3 }; // Get an initial point in A - B - int indexA = b2FindSupport(&proxyA, b2Neg(r)); + int indexA = b2FindSupport( &proxyA, b2Neg( r ) ); b2Vec2 wA = proxyA.points[indexA]; - int indexB = b2FindSupport(&proxyB, r); + int indexB = b2FindSupport( &proxyB, r ); b2Vec2 wB = proxyB.points[indexB]; - b2Vec2 v = b2Sub(wA, wB); + b2Vec2 v = b2Sub( wA, wB ); // Sigma is the target distance between proxies const float linearSlop = b2_linearSlop; - const float sigma = b2MaxFloat(linearSlop, radius - linearSlop); + const float sigma = b2MaxFloat( linearSlop, radius - linearSlop ); // Main iteration loop. const int k_maxIters = 20; int iter = 0; - while (iter < k_maxIters && b2Length(v) > sigma + 0.5f * linearSlop) + while ( iter < k_maxIters && b2Length( v ) > sigma + 0.5f * linearSlop ) { - B2_ASSERT(simplex.count < 3); + B2_ASSERT( simplex.count < 3 ); output.iterations += 1; // Support in direction -v (A - B) - indexA = b2FindSupport(&proxyA, b2Neg(v)); + indexA = b2FindSupport( &proxyA, b2Neg( v ) ); wA = proxyA.points[indexA]; - indexB = b2FindSupport(&proxyB, v); + indexB = b2FindSupport( &proxyB, v ); wB = proxyB.points[indexB]; - b2Vec2 p = b2Sub(wA, wB); + b2Vec2 p = b2Sub( wA, wB ); // -v is a normal at p, normalize to work with sigma - v = b2Normalize(v); + v = b2Normalize( v ); // Intersect ray with plane - float vp = b2Dot(v, p); - float vr = b2Dot(v, r); - if (vp - sigma > lambda * vr) + float vp = b2Dot( v, p ); + float vr = b2Dot( v, r ); + if ( vp - sigma > lambda * vr ) { - if (vr <= 0.0f) + if ( vr <= 0.0f ) { // miss return output; } - lambda = (vp - sigma) / vr; - if (lambda > maxFraction) + lambda = ( vp - sigma ) / vr; + if ( lambda > maxFraction ) { // too far return output; @@ -714,32 +715,32 @@ b2CastOutput b2ShapeCast(const b2ShapeCastPairInput* input) // to be formed in unshifted space. b2SimplexVertex* vertex = vertices[simplex.count]; vertex->indexA = indexB; - vertex->wA = (b2Vec2){wB.x + lambda * r.x, wB.y + lambda * r.y}; + vertex->wA = ( b2Vec2 ){ wB.x + lambda * r.x, wB.y + lambda * r.y }; vertex->indexB = indexA; vertex->wB = wA; - vertex->w = b2Sub(vertex->wB, vertex->wA); + vertex->w = b2Sub( vertex->wB, vertex->wA ); vertex->a = 1.0f; simplex.count += 1; - switch (simplex.count) + switch ( simplex.count ) { case 1: break; case 2: - b2SolveSimplex2(&simplex); + b2SolveSimplex2( &simplex ); break; case 3: - b2SolveSimplex3(&simplex); + b2SolveSimplex3( &simplex ); break; default: - B2_ASSERT(false); + B2_ASSERT( false ); } // If we have 3 points, then the origin is in the corresponding triangle. - if (simplex.count == 3) + if ( simplex.count == 3 ) { // Overlap return output; @@ -747,13 +748,13 @@ b2CastOutput b2ShapeCast(const b2ShapeCastPairInput* input) // Get search direction. // todo use more accurate segment perpendicular - v = b2ComputeSimplexClosestPoint(&simplex); + v = b2ComputeSimplexClosestPoint( &simplex ); // Iteration count is equated to the number of support point calls. ++iter; } - if (iter == 0 || lambda == 0.0f) + if ( iter == 0 || lambda == 0.0f ) { // Initial overlap return output; @@ -761,13 +762,13 @@ b2CastOutput b2ShapeCast(const b2ShapeCastPairInput* input) // Prepare output. b2Vec2 pointA, pointB; - b2ComputeSimplexWitnessPoints(&pointB, &pointA, &simplex); + b2ComputeSimplexWitnessPoints( &pointB, &pointA, &simplex ); - b2Vec2 n = b2Normalize(b2Neg(v)); - b2Vec2 point = {pointA.x + proxyA.radius * n.x, pointA.y + proxyA.radius * n.y}; + b2Vec2 n = b2Normalize( b2Neg( v ) ); + b2Vec2 point = { pointA.x + proxyA.radius * n.x, pointA.y + proxyA.radius * n.y }; - output.point = b2TransformPoint(xfA, point); - output.normal = b2RotateVector(xfA.q, n); + output.point = b2TransformPoint( xfA, point ); + output.normal = b2RotateVector( xfA.q, n ); output.fraction = lambda; output.iterations = iter; output.hit = true; @@ -800,55 +801,55 @@ typedef struct b2SeparationFunction b2SeparationType type; } b2SeparationFunction; -b2SeparationFunction b2MakeSeparationFunction(const b2DistanceCache* cache, const b2DistanceProxy* proxyA, const b2Sweep* sweepA, - const b2DistanceProxy* proxyB, const b2Sweep* sweepB, float t1) +b2SeparationFunction b2MakeSeparationFunction( const b2DistanceCache* cache, const b2DistanceProxy* proxyA, const b2Sweep* sweepA, + const b2DistanceProxy* proxyB, const b2Sweep* sweepB, float t1 ) { b2SeparationFunction f; f.proxyA = proxyA; f.proxyB = proxyB; int count = cache->count; - B2_ASSERT(0 < count && count < 3); + B2_ASSERT( 0 < count && count < 3 ); f.sweepA = *sweepA; f.sweepB = *sweepB; - b2Transform xfA = b2GetSweepTransform(sweepA, t1); - b2Transform xfB = b2GetSweepTransform(sweepB, t1); + b2Transform xfA = b2GetSweepTransform( sweepA, t1 ); + b2Transform xfB = b2GetSweepTransform( sweepB, t1 ); - if (count == 1) + if ( count == 1 ) { f.type = b2_pointsType; b2Vec2 localPointA = proxyA->points[cache->indexA[0]]; b2Vec2 localPointB = proxyB->points[cache->indexB[0]]; - b2Vec2 pointA = b2TransformPoint(xfA, localPointA); - b2Vec2 pointB = b2TransformPoint(xfB, localPointB); - f.axis = b2Normalize(b2Sub(pointB, pointA)); + b2Vec2 pointA = b2TransformPoint( xfA, localPointA ); + b2Vec2 pointB = b2TransformPoint( xfB, localPointB ); + f.axis = b2Normalize( b2Sub( pointB, pointA ) ); f.localPoint = b2Vec2_zero; return f; } - if (cache->indexA[0] == cache->indexA[1]) + if ( cache->indexA[0] == cache->indexA[1] ) { // Two points on B and one on A. f.type = b2_faceBType; b2Vec2 localPointB1 = proxyB->points[cache->indexB[0]]; b2Vec2 localPointB2 = proxyB->points[cache->indexB[1]]; - f.axis = b2CrossVS(b2Sub(localPointB2, localPointB1), 1.0f); - f.axis = b2Normalize(f.axis); - b2Vec2 normal = b2RotateVector(xfB.q, f.axis); + f.axis = b2CrossVS( b2Sub( localPointB2, localPointB1 ), 1.0f ); + f.axis = b2Normalize( f.axis ); + b2Vec2 normal = b2RotateVector( xfB.q, f.axis ); - f.localPoint = (b2Vec2){0.5f * (localPointB1.x + localPointB2.x), 0.5f * (localPointB1.y + localPointB2.y)}; - b2Vec2 pointB = b2TransformPoint(xfB, f.localPoint); + f.localPoint = ( b2Vec2 ){ 0.5f * ( localPointB1.x + localPointB2.x ), 0.5f * ( localPointB1.y + localPointB2.y ) }; + b2Vec2 pointB = b2TransformPoint( xfB, f.localPoint ); b2Vec2 localPointA = proxyA->points[cache->indexA[0]]; - b2Vec2 pointA = b2TransformPoint(xfA, localPointA); + b2Vec2 pointA = b2TransformPoint( xfA, localPointA ); - float s = b2Dot(b2Sub(pointA, pointB), normal); - if (s < 0.0f) + float s = b2Dot( b2Sub( pointA, pointB ), normal ); + if ( s < 0.0f ) { - f.axis = b2Neg(f.axis); + f.axis = b2Neg( f.axis ); } return f; } @@ -858,85 +859,85 @@ b2SeparationFunction b2MakeSeparationFunction(const b2DistanceCache* cache, cons b2Vec2 localPointA1 = proxyA->points[cache->indexA[0]]; b2Vec2 localPointA2 = proxyA->points[cache->indexA[1]]; - f.axis = b2CrossVS(b2Sub(localPointA2, localPointA1), 1.0f); - f.axis = b2Normalize(f.axis); - b2Vec2 normal = b2RotateVector(xfA.q, f.axis); + f.axis = b2CrossVS( b2Sub( localPointA2, localPointA1 ), 1.0f ); + f.axis = b2Normalize( f.axis ); + b2Vec2 normal = b2RotateVector( xfA.q, f.axis ); - f.localPoint = (b2Vec2){0.5f * (localPointA1.x + localPointA2.x), 0.5f * (localPointA1.y + localPointA2.y)}; - b2Vec2 pointA = b2TransformPoint(xfA, f.localPoint); + f.localPoint = ( b2Vec2 ){ 0.5f * ( localPointA1.x + localPointA2.x ), 0.5f * ( localPointA1.y + localPointA2.y ) }; + b2Vec2 pointA = b2TransformPoint( xfA, f.localPoint ); b2Vec2 localPointB = proxyB->points[cache->indexB[0]]; - b2Vec2 pointB = b2TransformPoint(xfB, localPointB); + b2Vec2 pointB = b2TransformPoint( xfB, localPointB ); - float s = b2Dot(b2Sub(pointB, pointA), normal); - if (s < 0.0f) + float s = b2Dot( b2Sub( pointB, pointA ), normal ); + if ( s < 0.0f ) { - f.axis = b2Neg(f.axis); + f.axis = b2Neg( f.axis ); } return f; } -static float b2FindMinSeparation(const b2SeparationFunction* f, int* indexA, int* indexB, float t) +static float b2FindMinSeparation( const b2SeparationFunction* f, int* indexA, int* indexB, float t ) { - b2Transform xfA = b2GetSweepTransform(&f->sweepA, t); - b2Transform xfB = b2GetSweepTransform(&f->sweepB, t); + b2Transform xfA = b2GetSweepTransform( &f->sweepA, t ); + b2Transform xfB = b2GetSweepTransform( &f->sweepB, t ); - switch (f->type) + switch ( f->type ) { case b2_pointsType: { - b2Vec2 axisA = b2InvRotateVector(xfA.q, f->axis); - b2Vec2 axisB = b2InvRotateVector(xfB.q, b2Neg(f->axis)); + b2Vec2 axisA = b2InvRotateVector( xfA.q, f->axis ); + b2Vec2 axisB = b2InvRotateVector( xfB.q, b2Neg( f->axis ) ); - *indexA = b2FindSupport(f->proxyA, axisA); - *indexB = b2FindSupport(f->proxyB, axisB); + *indexA = b2FindSupport( f->proxyA, axisA ); + *indexB = b2FindSupport( f->proxyB, axisB ); b2Vec2 localPointA = f->proxyA->points[*indexA]; b2Vec2 localPointB = f->proxyB->points[*indexB]; - b2Vec2 pointA = b2TransformPoint(xfA, localPointA); - b2Vec2 pointB = b2TransformPoint(xfB, localPointB); + b2Vec2 pointA = b2TransformPoint( xfA, localPointA ); + b2Vec2 pointB = b2TransformPoint( xfB, localPointB ); - float separation = b2Dot(b2Sub(pointB, pointA), f->axis); + float separation = b2Dot( b2Sub( pointB, pointA ), f->axis ); return separation; } case b2_faceAType: { - b2Vec2 normal = b2RotateVector(xfA.q, f->axis); - b2Vec2 pointA = b2TransformPoint(xfA, f->localPoint); + b2Vec2 normal = b2RotateVector( xfA.q, f->axis ); + b2Vec2 pointA = b2TransformPoint( xfA, f->localPoint ); - b2Vec2 axisB = b2InvRotateVector(xfB.q, b2Neg(normal)); + b2Vec2 axisB = b2InvRotateVector( xfB.q, b2Neg( normal ) ); *indexA = -1; - *indexB = b2FindSupport(f->proxyB, axisB); + *indexB = b2FindSupport( f->proxyB, axisB ); b2Vec2 localPointB = f->proxyB->points[*indexB]; - b2Vec2 pointB = b2TransformPoint(xfB, localPointB); + b2Vec2 pointB = b2TransformPoint( xfB, localPointB ); - float separation = b2Dot(b2Sub(pointB, pointA), normal); + float separation = b2Dot( b2Sub( pointB, pointA ), normal ); return separation; } case b2_faceBType: { - b2Vec2 normal = b2RotateVector(xfB.q, f->axis); - b2Vec2 pointB = b2TransformPoint(xfB, f->localPoint); + b2Vec2 normal = b2RotateVector( xfB.q, f->axis ); + b2Vec2 pointB = b2TransformPoint( xfB, f->localPoint ); - b2Vec2 axisA = b2InvRotateVector(xfA.q, b2Neg(normal)); + b2Vec2 axisA = b2InvRotateVector( xfA.q, b2Neg( normal ) ); *indexB = -1; - *indexA = b2FindSupport(f->proxyA, axisA); + *indexA = b2FindSupport( f->proxyA, axisA ); b2Vec2 localPointA = f->proxyA->points[*indexA]; - b2Vec2 pointA = b2TransformPoint(xfA, localPointA); + b2Vec2 pointA = b2TransformPoint( xfA, localPointA ); - float separation = b2Dot(b2Sub(pointA, pointB), normal); + float separation = b2Dot( b2Sub( pointA, pointB ), normal ); return separation; } default: - B2_ASSERT(false); + B2_ASSERT( false ); *indexA = -1; *indexB = -1; return 0.0f; @@ -944,58 +945,58 @@ static float b2FindMinSeparation(const b2SeparationFunction* f, int* indexA, int } // -float b2EvaluateSeparation(const b2SeparationFunction* f, int indexA, int indexB, float t) +float b2EvaluateSeparation( const b2SeparationFunction* f, int indexA, int indexB, float t ) { - b2Transform xfA = b2GetSweepTransform(&f->sweepA, t); - b2Transform xfB = b2GetSweepTransform(&f->sweepB, t); + b2Transform xfA = b2GetSweepTransform( &f->sweepA, t ); + b2Transform xfB = b2GetSweepTransform( &f->sweepB, t ); - switch (f->type) + switch ( f->type ) { case b2_pointsType: { b2Vec2 localPointA = f->proxyA->points[indexA]; b2Vec2 localPointB = f->proxyB->points[indexB]; - b2Vec2 pointA = b2TransformPoint(xfA, localPointA); - b2Vec2 pointB = b2TransformPoint(xfB, localPointB); + b2Vec2 pointA = b2TransformPoint( xfA, localPointA ); + b2Vec2 pointB = b2TransformPoint( xfB, localPointB ); - float separation = b2Dot(b2Sub(pointB, pointA), f->axis); + float separation = b2Dot( b2Sub( pointB, pointA ), f->axis ); return separation; } case b2_faceAType: { - b2Vec2 normal = b2RotateVector(xfA.q, f->axis); - b2Vec2 pointA = b2TransformPoint(xfA, f->localPoint); + b2Vec2 normal = b2RotateVector( xfA.q, f->axis ); + b2Vec2 pointA = b2TransformPoint( xfA, f->localPoint ); b2Vec2 localPointB = f->proxyB->points[indexB]; - b2Vec2 pointB = b2TransformPoint(xfB, localPointB); + b2Vec2 pointB = b2TransformPoint( xfB, localPointB ); - float separation = b2Dot(b2Sub(pointB, pointA), normal); + float separation = b2Dot( b2Sub( pointB, pointA ), normal ); return separation; } case b2_faceBType: { - b2Vec2 normal = b2RotateVector(xfB.q, f->axis); - b2Vec2 pointB = b2TransformPoint(xfB, f->localPoint); + b2Vec2 normal = b2RotateVector( xfB.q, f->axis ); + b2Vec2 pointB = b2TransformPoint( xfB, f->localPoint ); b2Vec2 localPointA = f->proxyA->points[indexA]; - b2Vec2 pointA = b2TransformPoint(xfA, localPointA); + b2Vec2 pointA = b2TransformPoint( xfA, localPointA ); - float separation = b2Dot(b2Sub(pointA, pointB), normal); + float separation = b2Dot( b2Sub( pointA, pointB ), normal ); return separation; } default: - B2_ASSERT(false); + B2_ASSERT( false ); return 0.0f; } } // CCD via the local separating axis method. This seeks progression // by computing the largest time at which separation is maintained. -b2TOIOutput b2TimeOfImpact(const b2TOIInput* input) +b2TOIOutput b2TimeOfImpact( const b2TOIInput* input ) { #if B2_TOI_DEBUG b2Timer timer = b2CreateTimer(); @@ -1011,22 +1012,22 @@ b2TOIOutput b2TimeOfImpact(const b2TOIInput* input) b2Sweep sweepA = input->sweepA; b2Sweep sweepB = input->sweepB; - B2_ASSERT(b2IsNormalized(sweepA.q1) && b2IsNormalized(sweepA.q2)); - B2_ASSERT(b2IsNormalized(sweepB.q1) && b2IsNormalized(sweepB.q2)); + B2_ASSERT( b2IsNormalized( sweepA.q1 ) && b2IsNormalized( sweepA.q2 ) ); + B2_ASSERT( b2IsNormalized( sweepB.q1 ) && b2IsNormalized( sweepB.q2 ) ); float tMax = input->tMax; float totalRadius = proxyA->radius + proxyB->radius; - float target = b2MaxFloat(b2_linearSlop, totalRadius - b2_linearSlop); + float target = b2MaxFloat( b2_linearSlop, totalRadius - b2_linearSlop ); float tolerance = 0.25f * b2_linearSlop; - B2_ASSERT(target > tolerance); + B2_ASSERT( target > tolerance ); float t1 = 0.0f; const int k_maxIterations = 20; int iter = 0; // Prepare input for distance query. - b2DistanceCache cache = {0}; + b2DistanceCache cache = { 0 }; b2DistanceInput distanceInput; distanceInput.proxyA = input->proxyA; distanceInput.proxyB = input->proxyB; @@ -1034,19 +1035,19 @@ b2TOIOutput b2TimeOfImpact(const b2TOIInput* input) // The outer loop progressively attempts to compute new separating axes. // This loop terminates when an axis is repeated (no progress is made). - for (;;) + for ( ;; ) { - b2Transform xfA = b2GetSweepTransform(&sweepA, t1); - b2Transform xfB = b2GetSweepTransform(&sweepB, t1); + b2Transform xfA = b2GetSweepTransform( &sweepA, t1 ); + b2Transform xfB = b2GetSweepTransform( &sweepB, t1 ); // Get the distance between shapes. We can also use the results // to get a separating axis. distanceInput.transformA = xfA; distanceInput.transformB = xfB; - b2DistanceOutput distanceOutput = b2ShapeDistance(&cache, &distanceInput, NULL, 0); + b2DistanceOutput distanceOutput = b2ShapeDistance( &cache, &distanceInput, NULL, 0 ); // If the shapes are overlapped, we give up on continuous collision. - if (distanceOutput.distance <= 0.0f) + if ( distanceOutput.distance <= 0.0f ) { // Failure! output.state = b2_toiStateOverlapped; @@ -1054,7 +1055,7 @@ b2TOIOutput b2TimeOfImpact(const b2TOIInput* input) break; } - if (distanceOutput.distance < target + tolerance) + if ( distanceOutput.distance < target + tolerance ) { // Victory! output.state = b2_toiStateHit; @@ -1063,7 +1064,7 @@ b2TOIOutput b2TimeOfImpact(const b2TOIInput* input) } // Initialize the separating axis. - b2SeparationFunction fcn = b2MakeSeparationFunction(&cache, proxyA, &sweepA, proxyB, &sweepB, t1); + b2SeparationFunction fcn = b2MakeSeparationFunction( &cache, proxyA, &sweepA, proxyB, &sweepB, t1 ); #if 0 // Dump the curve seen by the root finder { @@ -1095,14 +1096,14 @@ b2TOIOutput b2TimeOfImpact(const b2TOIInput* input) bool done = false; float t2 = tMax; int pushBackIter = 0; - for (;;) + for ( ;; ) { // Find the deepest point at t2. Store the witness point indices. int indexA, indexB; - float s2 = b2FindMinSeparation(&fcn, &indexA, &indexB, t2); + float s2 = b2FindMinSeparation( &fcn, &indexA, &indexB, t2 ); // Is the final configuration separated? - if (s2 > target + tolerance) + if ( s2 > target + tolerance ) { // Victory! output.state = b2_toiStateSeparated; @@ -1112,7 +1113,7 @@ b2TOIOutput b2TimeOfImpact(const b2TOIInput* input) } // Has the separation reached tolerance? - if (s2 > target - tolerance) + if ( s2 > target - tolerance ) { // Advance the sweeps t1 = t2; @@ -1120,11 +1121,11 @@ b2TOIOutput b2TimeOfImpact(const b2TOIInput* input) } // Compute the initial separation of the witness points. - float s1 = b2EvaluateSeparation(&fcn, indexA, indexB, t1); + float s1 = b2EvaluateSeparation( &fcn, indexA, indexB, t1 ); // Check for initial overlap. This might happen if the root finder // runs out of iterations. - if (s1 < target - tolerance) + if ( s1 < target - tolerance ) { output.state = b2_toiStateFailed; output.t = t1; @@ -1133,7 +1134,7 @@ b2TOIOutput b2TimeOfImpact(const b2TOIInput* input) } // Check for touching - if (s1 <= target + tolerance) + if ( s1 <= target + tolerance ) { // Victory! t1 should hold the TOI (could be 0.0). output.state = b2_toiStateHit; @@ -1145,19 +1146,19 @@ b2TOIOutput b2TimeOfImpact(const b2TOIInput* input) // Compute 1D root of: f(x) - target = 0 int rootIterCount = 0; float a1 = t1, a2 = t2; - for (;;) + for ( ;; ) { // Use a mix of the secant rule and bisection. float t; - if (rootIterCount & 1) + if ( rootIterCount & 1 ) { // Secant rule to improve convergence. - t = a1 + (target - s1) * (a2 - a1) / (s2 - s1); + t = a1 + ( target - s1 ) * ( a2 - a1 ) / ( s2 - s1 ); } else { // Bisection to guarantee progress. - t = 0.5f * (a1 + a2); + t = 0.5f * ( a1 + a2 ); } ++rootIterCount; @@ -1166,9 +1167,9 @@ b2TOIOutput b2TimeOfImpact(const b2TOIInput* input) ++b2_toiRootIters; #endif - float s = b2EvaluateSeparation(&fcn, indexA, indexB, t); + float s = b2EvaluateSeparation( &fcn, indexA, indexB, t ); - if (b2AbsFloat(s - target) < tolerance) + if ( b2AbsFloat( s - target ) < tolerance ) { // t2 holds a tentative value for t1 t2 = t; @@ -1176,7 +1177,7 @@ b2TOIOutput b2TimeOfImpact(const b2TOIInput* input) } // Ensure we continue to bracket the root. - if (s > target) + if ( s > target ) { a1 = t; s1 = s; @@ -1187,19 +1188,19 @@ b2TOIOutput b2TimeOfImpact(const b2TOIInput* input) s2 = s; } - if (rootIterCount == 50) + if ( rootIterCount == 50 ) { break; } } #if B2_TOI_DEBUG - b2_toiMaxRootIters = b2MaxInt(b2_toiMaxRootIters, rootIterCount); + b2_toiMaxRootIters = b2MaxInt( b2_toiMaxRootIters, rootIterCount ); #endif ++pushBackIter; - if (pushBackIter == b2_maxPolygonVertices) + if ( pushBackIter == b2_maxPolygonVertices ) { break; } @@ -1210,12 +1211,12 @@ b2TOIOutput b2TimeOfImpact(const b2TOIInput* input) ++b2_toiIters; #endif - if (done) + if ( done ) { break; } - if (iter == k_maxIterations) + if ( iter == k_maxIterations ) { // Root finder got stuck. Semi-victory. output.state = b2_toiStateFailed; @@ -1225,10 +1226,10 @@ b2TOIOutput b2TimeOfImpact(const b2TOIInput* input) } #if B2_TOI_DEBUG - b2_toiMaxIters = b2MaxInt(b2_toiMaxIters, iter); + b2_toiMaxIters = b2MaxInt( b2_toiMaxIters, iter ); - float time = b2GetMilliseconds(&timer); - b2_toiMaxTime = b2MaxFloat(b2_toiMaxTime, time); + float time = b2GetMilliseconds( &timer ); + b2_toiMaxTime = b2MaxFloat( b2_toiMaxTime, time ); b2_toiTime += time; #endif diff --git a/src/distance_joint.c b/src/distance_joint.c index 70ac9574..6e86e662 100644 --- a/src/distance_joint.c +++ b/src/distance_joint.c @@ -15,184 +15,184 @@ #include -void b2DistanceJoint_SetLength(b2JointId jointId, float length) +void b2DistanceJoint_SetLength( b2JointId jointId, float length ) { - b2JointSim* base = b2GetJointSimCheckType(jointId, b2_distanceJoint); + b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); b2DistanceJoint* joint = &base->distanceJoint; - joint->length = b2ClampFloat(length, b2_linearSlop, b2_huge); + joint->length = b2ClampFloat( length, b2_linearSlop, b2_huge ); joint->impulse = 0.0f; joint->lowerImpulse = 0.0f; joint->upperImpulse = 0.0f; } -float b2DistanceJoint_GetLength(b2JointId jointId) +float b2DistanceJoint_GetLength( b2JointId jointId ) { - b2JointSim* base = b2GetJointSimCheckType(jointId, b2_distanceJoint); + b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); b2DistanceJoint* joint = &base->distanceJoint; return joint->length; } -void b2DistanceJoint_EnableLimit(b2JointId jointId, bool enableLimit) +void b2DistanceJoint_EnableLimit( b2JointId jointId, bool enableLimit ) { - b2JointSim* base = b2GetJointSimCheckType(jointId, b2_distanceJoint); + b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); b2DistanceJoint* joint = &base->distanceJoint; joint->enableLimit = enableLimit; } -bool b2DistanceJoint_IsLimitEnabled(b2JointId jointId) +bool b2DistanceJoint_IsLimitEnabled( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_distanceJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_distanceJoint ); return joint->distanceJoint.enableLimit; } -void b2DistanceJoint_SetLengthRange(b2JointId jointId, float minLength, float maxLength) +void b2DistanceJoint_SetLengthRange( b2JointId jointId, float minLength, float maxLength ) { - b2JointSim* base = b2GetJointSimCheckType(jointId, b2_distanceJoint); + b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); b2DistanceJoint* joint = &base->distanceJoint; - minLength = b2ClampFloat(minLength, b2_linearSlop, b2_huge); - maxLength = b2ClampFloat(maxLength, b2_linearSlop, b2_huge); - joint->minLength = b2MinFloat(minLength, maxLength); - joint->maxLength = b2MaxFloat(minLength, maxLength); + minLength = b2ClampFloat( minLength, b2_linearSlop, b2_huge ); + maxLength = b2ClampFloat( maxLength, b2_linearSlop, b2_huge ); + joint->minLength = b2MinFloat( minLength, maxLength ); + joint->maxLength = b2MaxFloat( minLength, maxLength ); joint->impulse = 0.0f; joint->lowerImpulse = 0.0f; joint->upperImpulse = 0.0f; } -float b2DistanceJoint_GetMinLength(b2JointId jointId) +float b2DistanceJoint_GetMinLength( b2JointId jointId ) { - b2JointSim* base = b2GetJointSimCheckType(jointId, b2_distanceJoint); + b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); b2DistanceJoint* joint = &base->distanceJoint; return joint->minLength; } -float b2DistanceJoint_GetMaxLength(b2JointId jointId) +float b2DistanceJoint_GetMaxLength( b2JointId jointId ) { - b2JointSim* base = b2GetJointSimCheckType(jointId, b2_distanceJoint); + b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); b2DistanceJoint* joint = &base->distanceJoint; return joint->maxLength; } -float b2DistanceJoint_GetCurrentLength(b2JointId jointId) +float b2DistanceJoint_GetCurrentLength( b2JointId jointId ) { - b2JointSim* base = b2GetJointSimCheckType(jointId, b2_distanceJoint); + b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); - b2World* world = b2GetWorld(jointId.world0); - B2_ASSERT(world->locked == false); - if (world->locked) + b2World* world = b2GetWorld( jointId.world0 ); + B2_ASSERT( world->locked == false ); + if ( world->locked ) { return 0.0f; } - b2Transform transformA = b2GetBodyTransform(world, base->bodyIdA); - b2Transform transformB = b2GetBodyTransform(world, base->bodyIdB); + b2Transform transformA = b2GetBodyTransform( world, base->bodyIdA ); + b2Transform transformB = b2GetBodyTransform( world, base->bodyIdB ); - b2Vec2 pA = b2TransformPoint(transformA, base->localOriginAnchorA); - b2Vec2 pB = b2TransformPoint(transformB, base->localOriginAnchorB); - b2Vec2 d = b2Sub(pB, pA); - float length = b2Length(d); + b2Vec2 pA = b2TransformPoint( transformA, base->localOriginAnchorA ); + b2Vec2 pB = b2TransformPoint( transformB, base->localOriginAnchorB ); + b2Vec2 d = b2Sub( pB, pA ); + float length = b2Length( d ); return length; } -void b2DistanceJoint_EnableSpring(b2JointId jointId, bool enableSpring) +void b2DistanceJoint_EnableSpring( b2JointId jointId, bool enableSpring ) { - b2JointSim* base = b2GetJointSimCheckType(jointId, b2_distanceJoint); + b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); base->distanceJoint.enableSpring = enableSpring; } -bool b2DistanceJoint_IsSpringEnabled(b2JointId jointId) +bool b2DistanceJoint_IsSpringEnabled( b2JointId jointId ) { - b2JointSim* base = b2GetJointSimCheckType(jointId, b2_distanceJoint); + b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); return base->distanceJoint.enableSpring; } -void b2DistanceJoint_SetSpringHertz(b2JointId jointId, float hertz) +void b2DistanceJoint_SetSpringHertz( b2JointId jointId, float hertz ) { - b2JointSim* base = b2GetJointSimCheckType(jointId, b2_distanceJoint); + b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); base->distanceJoint.hertz = hertz; } -void b2DistanceJoint_SetSpringDampingRatio(b2JointId jointId, float dampingRatio) +void b2DistanceJoint_SetSpringDampingRatio( b2JointId jointId, float dampingRatio ) { - b2JointSim* base = b2GetJointSimCheckType(jointId, b2_distanceJoint); + b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); base->distanceJoint.dampingRatio = dampingRatio; } -float b2DistanceJoint_GetHertz(b2JointId jointId) +float b2DistanceJoint_GetHertz( b2JointId jointId ) { - b2JointSim* base = b2GetJointSimCheckType(jointId, b2_distanceJoint); + b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); b2DistanceJoint* joint = &base->distanceJoint; return joint->hertz; } -float b2DistanceJoint_GetDampingRatio(b2JointId jointId) +float b2DistanceJoint_GetDampingRatio( b2JointId jointId ) { - b2JointSim* base = b2GetJointSimCheckType(jointId, b2_distanceJoint); + b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); b2DistanceJoint* joint = &base->distanceJoint; return joint->dampingRatio; } -void b2DistanceJoint_EnableMotor(b2JointId jointId, bool enableMotor) +void b2DistanceJoint_EnableMotor( b2JointId jointId, bool enableMotor ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_distanceJoint); - if (enableMotor != joint->distanceJoint.enableMotor) + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_distanceJoint ); + if ( enableMotor != joint->distanceJoint.enableMotor ) { joint->distanceJoint.enableMotor = enableMotor; joint->distanceJoint.motorImpulse = 0.0f; } } -bool b2DistanceJoint_IsMotorEnabled(b2JointId jointId) +bool b2DistanceJoint_IsMotorEnabled( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_distanceJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_distanceJoint ); return joint->distanceJoint.enableMotor; } -void b2DistanceJoint_SetMotorSpeed(b2JointId jointId, float motorSpeed) +void b2DistanceJoint_SetMotorSpeed( b2JointId jointId, float motorSpeed ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_distanceJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_distanceJoint ); joint->distanceJoint.motorSpeed = motorSpeed; } -float b2DistanceJoint_GetMotorSpeed(b2JointId jointId) +float b2DistanceJoint_GetMotorSpeed( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_distanceJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_distanceJoint ); return joint->distanceJoint.motorSpeed; } -float b2DistanceJoint_GetMotorForce(b2JointId jointId) +float b2DistanceJoint_GetMotorForce( b2JointId jointId ) { - b2World* world = b2GetWorld(jointId.world0); - b2JointSim* base = b2GetJointSimCheckType(jointId, b2_distanceJoint); + b2World* world = b2GetWorld( jointId.world0 ); + b2JointSim* base = b2GetJointSimCheckType( jointId, b2_distanceJoint ); return world->inv_h * base->distanceJoint.motorImpulse; } -void b2DistanceJoint_SetMaxMotorForce(b2JointId jointId, float force) +void b2DistanceJoint_SetMaxMotorForce( b2JointId jointId, float force ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_distanceJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_distanceJoint ); joint->distanceJoint.maxMotorForce = force; } -float b2DistanceJoint_GetMaxMotorForce(b2JointId jointId) +float b2DistanceJoint_GetMaxMotorForce( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_distanceJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_distanceJoint ); return joint->distanceJoint.maxMotorForce; } -b2Vec2 b2GetDistanceJointForce(b2World* world, b2JointSim* base) +b2Vec2 b2GetDistanceJointForce( b2World* world, b2JointSim* base ) { b2DistanceJoint* joint = &base->distanceJoint; - b2Transform transformA = b2GetBodyTransform(world, base->bodyIdA); - b2Transform transformB = b2GetBodyTransform(world, base->bodyIdB); + b2Transform transformA = b2GetBodyTransform( world, base->bodyIdA ); + b2Transform transformB = b2GetBodyTransform( world, base->bodyIdB ); - b2Vec2 pA = b2TransformPoint(transformA, base->localOriginAnchorA); - b2Vec2 pB = b2TransformPoint(transformB, base->localOriginAnchorB); - b2Vec2 d = b2Sub(pB, pA); - b2Vec2 axis = b2Normalize(d); - float force = (joint->impulse + joint->lowerImpulse - joint->upperImpulse + joint->motorImpulse) * world->inv_h; - return b2MulSV(force, axis); + b2Vec2 pA = b2TransformPoint( transformA, base->localOriginAnchorA ); + b2Vec2 pB = b2TransformPoint( transformB, base->localOriginAnchorB ); + b2Vec2 d = b2Sub( pB, pA ); + b2Vec2 axis = b2Normalize( d ); + float force = ( joint->impulse + joint->lowerImpulse - joint->upperImpulse + joint->motorImpulse ) * world->inv_h; + return b2MulSV( force, axis ); } // 1-D constrained system @@ -210,9 +210,9 @@ b2Vec2 b2GetDistanceJointForce(b2World* world, b2JointSim* base) // K = J * invM * JT // = invMass1 + invI1 * cross(r1, u)^2 + invMass2 + invI2 * cross(r2, u)^2 -void b2PrepareDistanceJoint(b2JointSim* base, b2StepContext* context) +void b2PrepareDistanceJoint( b2JointSim* base, b2StepContext* context ) { - B2_ASSERT(base->type == b2_distanceJoint); + B2_ASSERT( base->type == b2_distanceJoint ); // chase body id to the solver set where the body lives int idA = base->bodyIdA; @@ -221,21 +221,21 @@ void b2PrepareDistanceJoint(b2JointSim* base, b2StepContext* context) b2World* world = context->world; b2Body* bodies = world->bodyArray; - b2CheckIndex(bodies, idA); - b2CheckIndex(bodies, idB); + b2CheckIndex( bodies, idA ); + b2CheckIndex( bodies, idB ); b2Body* bodyA = bodies + idA; b2Body* bodyB = bodies + idB; - B2_ASSERT(bodyA->setIndex == b2_awakeSet || bodyB->setIndex == b2_awakeSet); - b2CheckIndex(world->solverSetArray, bodyA->setIndex); - b2CheckIndex(world->solverSetArray, bodyB->setIndex); + B2_ASSERT( bodyA->setIndex == b2_awakeSet || bodyB->setIndex == b2_awakeSet ); + b2CheckIndex( world->solverSetArray, bodyA->setIndex ); + b2CheckIndex( world->solverSetArray, bodyB->setIndex ); b2SolverSet* setA = world->solverSetArray + bodyA->setIndex; b2SolverSet* setB = world->solverSetArray + bodyB->setIndex; - B2_ASSERT(0 <= bodyA->localIndex && bodyA->localIndex <= setA->sims.count); - B2_ASSERT(0 <= bodyB->localIndex && bodyB->localIndex <= setB->sims.count); + B2_ASSERT( 0 <= bodyA->localIndex && bodyA->localIndex <= setA->sims.count ); + B2_ASSERT( 0 <= bodyB->localIndex && bodyB->localIndex <= setB->sims.count ); b2BodySim* bodySimA = setA->sims.data + bodyA->localIndex; b2BodySim* bodySimB = setB->sims.data + bodyB->localIndex; @@ -256,24 +256,24 @@ void b2PrepareDistanceJoint(b2JointSim* base, b2StepContext* context) joint->indexB = bodyB->setIndex == b2_awakeSet ? bodyB->localIndex : B2_NULL_INDEX; // initial anchors in world space - joint->anchorA = b2RotateVector(bodySimA->transform.q, b2Sub(base->localOriginAnchorA, bodySimA->localCenter)); - joint->anchorB = b2RotateVector(bodySimB->transform.q, b2Sub(base->localOriginAnchorB, bodySimB->localCenter)); - joint->deltaCenter = b2Sub(bodySimB->center, bodySimA->center); + joint->anchorA = b2RotateVector( bodySimA->transform.q, b2Sub( base->localOriginAnchorA, bodySimA->localCenter ) ); + joint->anchorB = b2RotateVector( bodySimB->transform.q, b2Sub( base->localOriginAnchorB, bodySimB->localCenter ) ); + joint->deltaCenter = b2Sub( bodySimB->center, bodySimA->center ); b2Vec2 rA = joint->anchorA; b2Vec2 rB = joint->anchorB; - b2Vec2 separation = b2Add(b2Sub(rB, rA), joint->deltaCenter); - b2Vec2 axis = b2Normalize(separation); + b2Vec2 separation = b2Add( b2Sub( rB, rA ), joint->deltaCenter ); + b2Vec2 axis = b2Normalize( separation ); // compute effective mass - float crA = b2Cross(rA, axis); - float crB = b2Cross(rB, axis); + float crA = b2Cross( rA, axis ); + float crB = b2Cross( rB, axis ); float k = mA + mB + iA * crA * crA + iB * crB * crB; joint->axialMass = k > 0.0f ? 1.0f / k : 0.0f; - joint->distanceSoftness = b2MakeSoft(joint->hertz, joint->dampingRatio, context->h); + joint->distanceSoftness = b2MakeSoft( joint->hertz, joint->dampingRatio, context->h ); - if (context->enableWarmStarting == false) + if ( context->enableWarmStarting == false ) { joint->impulse = 0.0f; joint->lowerImpulse = 0.0f; @@ -282,9 +282,9 @@ void b2PrepareDistanceJoint(b2JointSim* base, b2StepContext* context) } } -void b2WarmStartDistanceJoint(b2JointSim* base, b2StepContext* context) +void b2WarmStartDistanceJoint( b2JointSim* base, b2StepContext* context ) { - B2_ASSERT(base->type == b2_distanceJoint); + B2_ASSERT( base->type == b2_distanceJoint ); float mA = base->invMassA; float mB = base->invMassB; @@ -298,25 +298,25 @@ void b2WarmStartDistanceJoint(b2JointSim* base, b2StepContext* context) b2BodyState* stateA = joint->indexA == B2_NULL_INDEX ? &dummyState : context->states + joint->indexA; b2BodyState* stateB = joint->indexB == B2_NULL_INDEX ? &dummyState : context->states + joint->indexB; - b2Vec2 rA = b2RotateVector(stateA->deltaRotation, joint->anchorA); - b2Vec2 rB = b2RotateVector(stateB->deltaRotation, joint->anchorB); + b2Vec2 rA = b2RotateVector( stateA->deltaRotation, joint->anchorA ); + b2Vec2 rB = b2RotateVector( stateB->deltaRotation, joint->anchorB ); - b2Vec2 ds = b2Add(b2Sub(stateB->deltaPosition, stateA->deltaPosition), b2Sub(rB, rA)); - b2Vec2 separation = b2Add(joint->deltaCenter, ds); - b2Vec2 axis = b2Normalize(separation); + b2Vec2 ds = b2Add( b2Sub( stateB->deltaPosition, stateA->deltaPosition ), b2Sub( rB, rA ) ); + b2Vec2 separation = b2Add( joint->deltaCenter, ds ); + b2Vec2 axis = b2Normalize( separation ); float axialImpulse = joint->impulse + joint->lowerImpulse - joint->upperImpulse + joint->motorImpulse; - b2Vec2 P = b2MulSV(axialImpulse, axis); + b2Vec2 P = b2MulSV( axialImpulse, axis ); - stateA->linearVelocity = b2MulSub(stateA->linearVelocity, mA, P); - stateA->angularVelocity -= iA * b2Cross(rA, P); - stateB->linearVelocity = b2MulAdd(stateB->linearVelocity, mB, P); - stateB->angularVelocity += iB * b2Cross(rB, P); + stateA->linearVelocity = b2MulSub( stateA->linearVelocity, mA, P ); + stateA->angularVelocity -= iA * b2Cross( rA, P ); + stateB->linearVelocity = b2MulAdd( stateB->linearVelocity, mB, P ); + stateB->angularVelocity += iB * b2Cross( rB, P ); } -void b2SolveDistanceJoint(b2JointSim* base, b2StepContext* context, bool useBias) +void b2SolveDistanceJoint( b2JointSim* base, b2StepContext* context, bool useBias ) { - B2_ASSERT(base->type == b2_distanceJoint); + B2_ASSERT( base->type == b2_distanceJoint ); float mA = base->invMassA; float mB = base->invMassB; @@ -329,162 +329,162 @@ void b2SolveDistanceJoint(b2JointSim* base, b2StepContext* context, bool useBias b2DistanceJoint* joint = &base->distanceJoint; b2BodyState* stateA = joint->indexA == B2_NULL_INDEX ? &dummyState : context->states + joint->indexA; b2BodyState* stateB = joint->indexB == B2_NULL_INDEX ? &dummyState : context->states + joint->indexB; - + b2Vec2 vA = stateA->linearVelocity; float wA = stateA->angularVelocity; b2Vec2 vB = stateB->linearVelocity; float wB = stateB->angularVelocity; // current anchors - b2Vec2 rA = b2RotateVector(stateA->deltaRotation, joint->anchorA); - b2Vec2 rB = b2RotateVector(stateB->deltaRotation, joint->anchorB); + b2Vec2 rA = b2RotateVector( stateA->deltaRotation, joint->anchorA ); + b2Vec2 rB = b2RotateVector( stateB->deltaRotation, joint->anchorB ); // current separation - b2Vec2 ds = b2Add(b2Sub(stateB->deltaPosition, stateA->deltaPosition), b2Sub(rB, rA)); - b2Vec2 separation = b2Add(joint->deltaCenter, ds); + b2Vec2 ds = b2Add( b2Sub( stateB->deltaPosition, stateA->deltaPosition ), b2Sub( rB, rA ) ); + b2Vec2 separation = b2Add( joint->deltaCenter, ds ); - float length = b2Length(separation); - b2Vec2 axis = b2Normalize(separation); + float length = b2Length( separation ); + b2Vec2 axis = b2Normalize( separation ); // joint is soft if // - spring is enabled // - and (joint limit is disabled or limits are not equal) - if (joint->enableSpring && (joint->minLength < joint->maxLength || joint->enableLimit == false)) + if ( joint->enableSpring && ( joint->minLength < joint->maxLength || joint->enableLimit == false ) ) { // spring - if (joint->hertz > 0.0f) + if ( joint->hertz > 0.0f ) { // Cdot = dot(u, v + cross(w, r)) - b2Vec2 vr = b2Add(b2Sub(vB, vA), b2Sub(b2CrossSV(wB, rB), b2CrossSV(wA, rA))); - float Cdot = b2Dot(axis, vr); + b2Vec2 vr = b2Add( b2Sub( vB, vA ), b2Sub( b2CrossSV( wB, rB ), b2CrossSV( wA, rA ) ) ); + float Cdot = b2Dot( axis, vr ); float C = length - joint->length; float bias = joint->distanceSoftness.biasRate * C; float m = joint->distanceSoftness.massScale * joint->axialMass; - float impulse = -m * (Cdot + bias) - joint->distanceSoftness.impulseScale * joint->impulse; + float impulse = -m * ( Cdot + bias ) - joint->distanceSoftness.impulseScale * joint->impulse; joint->impulse += impulse; - b2Vec2 P = b2MulSV(impulse, axis); - vA = b2MulSub(vA, mA, P); - wA -= iA * b2Cross(rA, P); - vB = b2MulAdd(vB, mB, P); - wB += iB * b2Cross(rB, P); + b2Vec2 P = b2MulSV( impulse, axis ); + vA = b2MulSub( vA, mA, P ); + wA -= iA * b2Cross( rA, P ); + vB = b2MulAdd( vB, mB, P ); + wB += iB * b2Cross( rB, P ); } - if (joint->enableLimit) + if ( joint->enableLimit ) { // lower limit { - b2Vec2 vr = b2Add(b2Sub(vB, vA), b2Sub(b2CrossSV(wB, rB), b2CrossSV(wA, rA))); - float Cdot = b2Dot(axis, vr); + b2Vec2 vr = b2Add( b2Sub( vB, vA ), b2Sub( b2CrossSV( wB, rB ), b2CrossSV( wA, rA ) ) ); + float Cdot = b2Dot( axis, vr ); float C = length - joint->minLength; float bias = 0.0f; float massCoeff = 1.0f; float impulseCoeff = 0.0f; - if (C > 0.0f) + if ( C > 0.0f ) { // speculative bias = C * context->inv_h; } - else if (useBias) + else if ( useBias ) { bias = context->jointSoftness.biasRate * C; massCoeff = context->jointSoftness.massScale; impulseCoeff = context->jointSoftness.impulseScale; } - float impulse = -massCoeff * joint->axialMass * (Cdot + bias) - impulseCoeff * joint->lowerImpulse; - float newImpulse = b2MaxFloat(0.0f, joint->lowerImpulse + impulse); + float impulse = -massCoeff * joint->axialMass * ( Cdot + bias ) - impulseCoeff * joint->lowerImpulse; + float newImpulse = b2MaxFloat( 0.0f, joint->lowerImpulse + impulse ); impulse = newImpulse - joint->lowerImpulse; joint->lowerImpulse = newImpulse; - b2Vec2 P = b2MulSV(impulse, axis); - vA = b2MulSub(vA, mA, P); - wA -= iA * b2Cross(rA, P); - vB = b2MulAdd(vB, mB, P); - wB += iB * b2Cross(rB, P); + b2Vec2 P = b2MulSV( impulse, axis ); + vA = b2MulSub( vA, mA, P ); + wA -= iA * b2Cross( rA, P ); + vB = b2MulAdd( vB, mB, P ); + wB += iB * b2Cross( rB, P ); } // upper { - b2Vec2 vr = b2Add(b2Sub(vA, vB), b2Sub(b2CrossSV(wA, rA), b2CrossSV(wB, rB))); - float Cdot = b2Dot(axis, vr); + b2Vec2 vr = b2Add( b2Sub( vA, vB ), b2Sub( b2CrossSV( wA, rA ), b2CrossSV( wB, rB ) ) ); + float Cdot = b2Dot( axis, vr ); float C = joint->maxLength - length; float bias = 0.0f; float massScale = 1.0f; float impulseScale = 0.0f; - if (C > 0.0f) + if ( C > 0.0f ) { // speculative bias = C * context->inv_h; } - else if (useBias) + else if ( useBias ) { bias = context->jointSoftness.biasRate * C; massScale = context->jointSoftness.massScale; impulseScale = context->jointSoftness.impulseScale; } - float impulse = -massScale * joint->axialMass * (Cdot + bias) - impulseScale * joint->upperImpulse; - float newImpulse = b2MaxFloat(0.0f, joint->upperImpulse + impulse); + float impulse = -massScale * joint->axialMass * ( Cdot + bias ) - impulseScale * joint->upperImpulse; + float newImpulse = b2MaxFloat( 0.0f, joint->upperImpulse + impulse ); impulse = newImpulse - joint->upperImpulse; joint->upperImpulse = newImpulse; - b2Vec2 P = b2MulSV(-impulse, axis); - vA = b2MulSub(vA, mA, P); - wA -= iA * b2Cross(rA, P); - vB = b2MulAdd(vB, mB, P); - wB += iB * b2Cross(rB, P); - } + b2Vec2 P = b2MulSV( -impulse, axis ); + vA = b2MulSub( vA, mA, P ); + wA -= iA * b2Cross( rA, P ); + vB = b2MulAdd( vB, mB, P ); + wB += iB * b2Cross( rB, P ); + } } - if (joint->enableMotor) + if ( joint->enableMotor ) { - b2Vec2 vr = b2Add(b2Sub(vB, vA), b2Sub(b2CrossSV(wB, rB), b2CrossSV(wA, rA))); - float Cdot = b2Dot(axis, vr); - float impulse = joint->axialMass * (joint->motorSpeed - Cdot); + b2Vec2 vr = b2Add( b2Sub( vB, vA ), b2Sub( b2CrossSV( wB, rB ), b2CrossSV( wA, rA ) ) ); + float Cdot = b2Dot( axis, vr ); + float impulse = joint->axialMass * ( joint->motorSpeed - Cdot ); float oldImpulse = joint->motorImpulse; float maxImpulse = context->h * joint->maxMotorForce; - joint->motorImpulse = b2ClampFloat(joint->motorImpulse + impulse, -maxImpulse, maxImpulse); + joint->motorImpulse = b2ClampFloat( joint->motorImpulse + impulse, -maxImpulse, maxImpulse ); impulse = joint->motorImpulse - oldImpulse; - b2Vec2 P = b2MulSV(impulse, axis); - vA = b2MulSub(vA, mA, P); - wA -= iA * b2Cross(rA, P); - vB = b2MulAdd(vB, mB, P); - wB += iB * b2Cross(rB, P); + b2Vec2 P = b2MulSV( impulse, axis ); + vA = b2MulSub( vA, mA, P ); + wA -= iA * b2Cross( rA, P ); + vB = b2MulAdd( vB, mB, P ); + wB += iB * b2Cross( rB, P ); } } else { // rigid constraint - b2Vec2 vr = b2Add(b2Sub(vB, vA), b2Sub(b2CrossSV(wB, rB), b2CrossSV(wA, rA))); - float Cdot = b2Dot(axis, vr); + b2Vec2 vr = b2Add( b2Sub( vB, vA ), b2Sub( b2CrossSV( wB, rB ), b2CrossSV( wA, rA ) ) ); + float Cdot = b2Dot( axis, vr ); float C = length - joint->length; float bias = 0.0f; float massScale = 1.0f; float impulseScale = 0.0f; - if (useBias) + if ( useBias ) { bias = context->jointSoftness.biasRate * C; massScale = context->jointSoftness.massScale; impulseScale = context->jointSoftness.impulseScale; } - float impulse = -massScale * joint->axialMass * (Cdot + bias) - impulseScale * joint->impulse; + float impulse = -massScale * joint->axialMass * ( Cdot + bias ) - impulseScale * joint->impulse; joint->impulse += impulse; - b2Vec2 P = b2MulSV(impulse, axis); - vA = b2MulSub(vA, mA, P); - wA -= iA * b2Cross(rA, P); - vB = b2MulAdd(vB, mB, P); - wB += iB * b2Cross(rB, P); + b2Vec2 P = b2MulSV( impulse, axis ); + vA = b2MulSub( vA, mA, P ); + wA -= iA * b2Cross( rA, P ); + vB = b2MulAdd( vB, mB, P ); + wB += iB * b2Cross( rB, P ); } stateA->linearVelocity = vA; @@ -493,9 +493,6 @@ void b2SolveDistanceJoint(b2JointSim* base, b2StepContext* context, bool useBias stateB->angularVelocity = wB; } - - - #if 0 void b2DistanceJoint::Dump() { @@ -517,48 +514,48 @@ void b2DistanceJoint::Dump() } #endif -void b2DrawDistanceJoint(b2DebugDraw* draw, b2JointSim* base, b2Transform transformA, b2Transform transformB) +void b2DrawDistanceJoint( b2DebugDraw* draw, b2JointSim* base, b2Transform transformA, b2Transform transformB ) { - B2_ASSERT(base->type == b2_distanceJoint); + B2_ASSERT( base->type == b2_distanceJoint ); b2DistanceJoint* joint = &base->distanceJoint; - b2Vec2 pA = b2TransformPoint(transformA, base->localOriginAnchorA); - b2Vec2 pB = b2TransformPoint(transformB, base->localOriginAnchorB); + b2Vec2 pA = b2TransformPoint( transformA, base->localOriginAnchorA ); + b2Vec2 pB = b2TransformPoint( transformB, base->localOriginAnchorB ); - b2Vec2 axis = b2Normalize(b2Sub(pB, pA)); + b2Vec2 axis = b2Normalize( b2Sub( pB, pA ) ); - if (joint->minLength < joint->maxLength && joint->enableLimit) + if ( joint->minLength < joint->maxLength && joint->enableLimit ) { - b2Vec2 pMin = b2MulAdd(pA, joint->minLength, axis); - b2Vec2 pMax = b2MulAdd(pA, joint->maxLength, axis); - b2Vec2 offset = b2MulSV(0.05f * b2_lengthUnitsPerMeter, b2RightPerp(axis)); + b2Vec2 pMin = b2MulAdd( pA, joint->minLength, axis ); + b2Vec2 pMax = b2MulAdd( pA, joint->maxLength, axis ); + b2Vec2 offset = b2MulSV( 0.05f * b2_lengthUnitsPerMeter, b2RightPerp( axis ) ); - if (joint->minLength > b2_linearSlop) + if ( joint->minLength > b2_linearSlop ) { - //draw->DrawPoint(pMin, 4.0f, c2, draw->context); - draw->DrawSegment(b2Sub(pMin, offset), b2Add(pMin, offset), b2_colorLightGreen, draw->context); + // draw->DrawPoint(pMin, 4.0f, c2, draw->context); + draw->DrawSegment( b2Sub( pMin, offset ), b2Add( pMin, offset ), b2_colorLightGreen, draw->context ); } - if (joint->maxLength < b2_huge) + if ( joint->maxLength < b2_huge ) { - //draw->DrawPoint(pMax, 4.0f, c3, draw->context); - draw->DrawSegment(b2Sub(pMax, offset), b2Add(pMax, offset), b2_colorRed, draw->context); + // draw->DrawPoint(pMax, 4.0f, c3, draw->context); + draw->DrawSegment( b2Sub( pMax, offset ), b2Add( pMax, offset ), b2_colorRed, draw->context ); } - if (joint->minLength > b2_linearSlop && joint->maxLength < b2_huge) + if ( joint->minLength > b2_linearSlop && joint->maxLength < b2_huge ) { - draw->DrawSegment(pMin, pMax, b2_colorGray, draw->context); + draw->DrawSegment( pMin, pMax, b2_colorGray, draw->context ); } } - draw->DrawSegment(pA, pB, b2_colorWhite, draw->context); - draw->DrawPoint(pA, 4.0f, b2_colorWhite, draw->context); - draw->DrawPoint(pB, 4.0f, b2_colorWhite, draw->context); + draw->DrawSegment( pA, pB, b2_colorWhite, draw->context ); + draw->DrawPoint( pA, 4.0f, b2_colorWhite, draw->context ); + draw->DrawPoint( pB, 4.0f, b2_colorWhite, draw->context ); - if (joint->hertz > 0.0f && joint->enableSpring) + if ( joint->hertz > 0.0f && joint->enableSpring ) { - b2Vec2 pRest = b2MulAdd(pA, joint->length, axis); - draw->DrawPoint(pRest, 4.0f, b2_colorBlue, draw->context); + b2Vec2 pRest = b2MulAdd( pA, joint->length, axis ); + draw->DrawPoint( pRest, 4.0f, b2_colorBlue, draw->context ); } } diff --git a/src/dynamic_tree.c b/src/dynamic_tree.c index 4c0e6a81..c5b69aa6 100644 --- a/src/dynamic_tree.c +++ b/src/dynamic_tree.c @@ -17,32 +17,33 @@ // - try incrementally sorting internal nodes by height for better cache efficiency during depth first traversal. static b2TreeNode b2_defaultTreeNode = { - {{0.0f, 0.0f}, {0.0f, 0.0f}}, 0, {B2_NULL_INDEX}, B2_NULL_INDEX, B2_NULL_INDEX, -1, -2, false, {0, 0, 0, 0, 0, 0, 0, 0, 0}}; + { { 0.0f, 0.0f }, { 0.0f, 0.0f } }, 0, { B2_NULL_INDEX }, B2_NULL_INDEX, B2_NULL_INDEX, -1, -2, false, + { 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; -static inline bool b2IsLeaf(const b2TreeNode* node) +static inline bool b2IsLeaf( const b2TreeNode* node ) { return node->height == 0; } -static inline int16_t b2MaxInt16(int16_t a, int16_t b) +static inline int16_t b2MaxInt16( int16_t a, int16_t b ) { return a > b ? a : b; } -b2DynamicTree b2DynamicTree_Create(void) +b2DynamicTree b2DynamicTree_Create( void ) { - _Static_assert((sizeof(b2TreeNode) & 0xF) == 0, "tree node size not a multiple of 16"); + _Static_assert( ( sizeof( b2TreeNode ) & 0xF ) == 0, "tree node size not a multiple of 16" ); b2DynamicTree tree; tree.root = B2_NULL_INDEX; tree.nodeCapacity = 16; tree.nodeCount = 0; - tree.nodes = (b2TreeNode*)b2Alloc(tree.nodeCapacity * sizeof(b2TreeNode)); - memset(tree.nodes, 0, tree.nodeCapacity * sizeof(b2TreeNode)); + tree.nodes = (b2TreeNode*)b2Alloc( tree.nodeCapacity * sizeof( b2TreeNode ) ); + memset( tree.nodes, 0, tree.nodeCapacity * sizeof( b2TreeNode ) ); // Build a linked list for the free list. - for (int32_t i = 0; i < tree.nodeCapacity - 1; ++i) + for ( int32_t i = 0; i < tree.nodeCapacity - 1; ++i ) { tree.nodes[i].next = i + 1; tree.nodes[i].height = -1; @@ -62,36 +63,36 @@ b2DynamicTree b2DynamicTree_Create(void) return tree; } -void b2DynamicTree_Destroy(b2DynamicTree* tree) +void b2DynamicTree_Destroy( b2DynamicTree* tree ) { - b2Free(tree->nodes, tree->nodeCapacity * sizeof(b2TreeNode)); - b2Free(tree->leafIndices, tree->rebuildCapacity * sizeof(int32_t)); - b2Free(tree->leafBoxes, tree->rebuildCapacity * sizeof(b2AABB)); - b2Free(tree->leafCenters, tree->rebuildCapacity * sizeof(b2Vec2)); - b2Free(tree->binIndices, tree->rebuildCapacity * sizeof(int32_t)); + b2Free( tree->nodes, tree->nodeCapacity * sizeof( b2TreeNode ) ); + b2Free( tree->leafIndices, tree->rebuildCapacity * sizeof( int32_t ) ); + b2Free( tree->leafBoxes, tree->rebuildCapacity * sizeof( b2AABB ) ); + b2Free( tree->leafCenters, tree->rebuildCapacity * sizeof( b2Vec2 ) ); + b2Free( tree->binIndices, tree->rebuildCapacity * sizeof( int32_t ) ); - memset(tree, 0, sizeof(b2DynamicTree)); + memset( tree, 0, sizeof( b2DynamicTree ) ); } // Allocate a node from the pool. Grow the pool if necessary. -static int32_t b2AllocateNode(b2DynamicTree* tree) +static int32_t b2AllocateNode( b2DynamicTree* tree ) { // Expand the node pool as needed. - if (tree->freeList == B2_NULL_INDEX) + if ( tree->freeList == B2_NULL_INDEX ) { - B2_ASSERT(tree->nodeCount == tree->nodeCapacity); + B2_ASSERT( tree->nodeCount == tree->nodeCapacity ); // The free list is empty. Rebuild a bigger pool. b2TreeNode* oldNodes = tree->nodes; int32_t oldCapcity = tree->nodeCapacity; tree->nodeCapacity += oldCapcity >> 1; - tree->nodes = (b2TreeNode*)b2Alloc(tree->nodeCapacity * sizeof(b2TreeNode)); - memcpy(tree->nodes, oldNodes, tree->nodeCount * sizeof(b2TreeNode)); - b2Free(oldNodes, oldCapcity * sizeof(b2TreeNode)); + tree->nodes = (b2TreeNode*)b2Alloc( tree->nodeCapacity * sizeof( b2TreeNode ) ); + memcpy( tree->nodes, oldNodes, tree->nodeCount * sizeof( b2TreeNode ) ); + b2Free( oldNodes, oldCapcity * sizeof( b2TreeNode ) ); // Build a linked list for the free list. The parent pointer becomes the "next" pointer. // todo avoid building freelist? - for (int32_t i = tree->nodeCount; i < tree->nodeCapacity - 1; ++i) + for ( int32_t i = tree->nodeCount; i < tree->nodeCapacity - 1; ++i ) { tree->nodes[i].next = i + 1; tree->nodes[i].height = -1; @@ -111,10 +112,10 @@ static int32_t b2AllocateNode(b2DynamicTree* tree) } // Return a node to the pool. -static void b2FreeNode(b2DynamicTree* tree, int32_t nodeId) +static void b2FreeNode( b2DynamicTree* tree, int32_t nodeId ) { - B2_ASSERT(0 <= nodeId && nodeId < tree->nodeCapacity); - B2_ASSERT(0 < tree->nodeCount); + B2_ASSERT( 0 <= nodeId && nodeId < tree->nodeCapacity ); + B2_ASSERT( 0 < tree->nodeCount ); tree->nodes[nodeId].next = tree->freeList; tree->nodes[nodeId].height = -1; tree->freeList = nodeId; @@ -138,10 +139,10 @@ static void b2FreeNode(b2DynamicTree* tree, int32_t nodeId) // Suppose B (or C) is an internal node, then the lowest cost would be one of two cases: // case1: D becomes a sibling of B // case2: D becomes a descendant of B along with a new internal node of area(D). -static int32_t b2FindBestSibling(const b2DynamicTree* tree, b2AABB boxD) +static int32_t b2FindBestSibling( const b2DynamicTree* tree, b2AABB boxD ) { - b2Vec2 centerD = b2AABB_Center(boxD); - float areaD = b2Perimeter(boxD); + b2Vec2 centerD = b2AABB_Center( boxD ); + float areaD = b2Perimeter( boxD ); const b2TreeNode* nodes = tree->nodes; int32_t rootIndex = tree->root; @@ -149,10 +150,10 @@ static int32_t b2FindBestSibling(const b2DynamicTree* tree, b2AABB boxD) b2AABB rootBox = nodes[rootIndex].aabb; // Area of current node - float areaBase = b2Perimeter(rootBox); + float areaBase = b2Perimeter( rootBox ); // Area of inflated node - float directCost = b2Perimeter(b2AABB_Union(rootBox, boxD)); + float directCost = b2Perimeter( b2AABB_Union( rootBox, boxD ) ); float inheritedCost = 0.0f; int32_t bestSibling = rootIndex; @@ -160,7 +161,7 @@ static int32_t b2FindBestSibling(const b2DynamicTree* tree, b2AABB boxD) // Descend the tree from root, following a single greedy path. int32_t index = rootIndex; - while (nodes[index].height > 0) + while ( nodes[index].height > 0 ) { int32_t child1 = nodes[index].child1; int32_t child2 = nodes[index].child2; @@ -170,7 +171,7 @@ static int32_t b2FindBestSibling(const b2DynamicTree* tree, b2AABB boxD) // Sometimes there are multiple identical costs within tolerance. // This breaks the ties using the centroid distance. - if (cost < bestCost) + if ( cost < bestCost ) { bestSibling = index; bestCost = cost; @@ -185,16 +186,16 @@ static int32_t b2FindBestSibling(const b2DynamicTree* tree, b2AABB boxD) // Cost of descending into child 1 float lowerCost1 = FLT_MAX; b2AABB box1 = nodes[child1].aabb; - float directCost1 = b2Perimeter(b2AABB_Union(box1, boxD)); + float directCost1 = b2Perimeter( b2AABB_Union( box1, boxD ) ); float area1 = 0.0f; - if (leaf1) + if ( leaf1 ) { // Child 1 is a leaf // Cost of creating new node and increasing area of node P float cost1 = directCost1 + inheritedCost; // Need this here due to while condition above - if (cost1 < bestCost) + if ( cost1 < bestCost ) { bestSibling = child1; bestCost = cost1; @@ -203,25 +204,25 @@ static int32_t b2FindBestSibling(const b2DynamicTree* tree, b2AABB boxD) else { // Child 1 is an internal node - area1 = b2Perimeter(box1); + area1 = b2Perimeter( box1 ); // Lower bound cost of inserting under child 1. - lowerCost1 = inheritedCost + directCost1 + b2MinFloat(areaD - area1, 0.0f); + lowerCost1 = inheritedCost + directCost1 + b2MinFloat( areaD - area1, 0.0f ); } // Cost of descending into child 2 float lowerCost2 = FLT_MAX; b2AABB box2 = nodes[child2].aabb; - float directCost2 = b2Perimeter(b2AABB_Union(box2, boxD)); + float directCost2 = b2Perimeter( b2AABB_Union( box2, boxD ) ); float area2 = 0.0f; - if (leaf2) + if ( leaf2 ) { // Child 2 is a leaf // Cost of creating new node and increasing area of node P float cost2 = directCost2 + inheritedCost; // Need this here due to while condition above - if (cost2 < bestCost) + if ( cost2 < bestCost ) { bestSibling = child2; bestCost = cost2; @@ -230,39 +231,39 @@ static int32_t b2FindBestSibling(const b2DynamicTree* tree, b2AABB boxD) else { // Child 2 is an internal node - area2 = b2Perimeter(box2); + area2 = b2Perimeter( box2 ); // Lower bound cost of inserting under child 2. This is not the cost // of child 2, it is the best we can hope for under child 2. - lowerCost2 = inheritedCost + directCost2 + b2MinFloat(areaD - area2, 0.0f); + lowerCost2 = inheritedCost + directCost2 + b2MinFloat( areaD - area2, 0.0f ); } - if (leaf1 && leaf2) + if ( leaf1 && leaf2 ) { break; } // Can the cost possibly be decreased? - if (bestCost <= lowerCost1 && bestCost <= lowerCost2) + if ( bestCost <= lowerCost1 && bestCost <= lowerCost2 ) { break; } - if (lowerCost1 == lowerCost2 && leaf1 == false) + if ( lowerCost1 == lowerCost2 && leaf1 == false ) { - B2_ASSERT(lowerCost1 < FLT_MAX); - B2_ASSERT(lowerCost2 < FLT_MAX); + B2_ASSERT( lowerCost1 < FLT_MAX ); + B2_ASSERT( lowerCost2 < FLT_MAX ); // No clear choice based on lower bound surface area. This can happen when both // children fully contain D. Fall back to node distance. - b2Vec2 d1 = b2Sub(b2AABB_Center(box1), centerD); - b2Vec2 d2 = b2Sub(b2AABB_Center(box2), centerD); - lowerCost1 = b2LengthSquared(d1); - lowerCost2 = b2LengthSquared(d2); + b2Vec2 d1 = b2Sub( b2AABB_Center( box1 ), centerD ); + b2Vec2 d2 = b2Sub( b2AABB_Center( box2 ), centerD ); + lowerCost1 = b2LengthSquared( d1 ); + lowerCost2 = b2LengthSquared( d2 ); } // Descend - if (lowerCost1 < lowerCost2 && leaf1 == false) + if ( lowerCost1 < lowerCost2 && leaf1 == false ) { index = child1; areaBase = area1; @@ -275,7 +276,7 @@ static int32_t b2FindBestSibling(const b2DynamicTree* tree, b2AABB boxD) directCost = directCost2; } - B2_ASSERT(nodes[index].height > 0); + B2_ASSERT( nodes[index].height > 0 ); } return bestSibling; @@ -292,56 +293,56 @@ enum b2RotateType // Perform a left or right rotation if node A is imbalanced. // Returns the new root index. -static void b2RotateNodes(b2DynamicTree* tree, int32_t iA) +static void b2RotateNodes( b2DynamicTree* tree, int32_t iA ) { - B2_ASSERT(iA != B2_NULL_INDEX); + B2_ASSERT( iA != B2_NULL_INDEX ); b2TreeNode* nodes = tree->nodes; b2TreeNode* A = nodes + iA; - if (A->height < 2) + if ( A->height < 2 ) { return; } int32_t iB = A->child1; int32_t iC = A->child2; - B2_ASSERT(0 <= iB && iB < tree->nodeCapacity); - B2_ASSERT(0 <= iC && iC < tree->nodeCapacity); + B2_ASSERT( 0 <= iB && iB < tree->nodeCapacity ); + B2_ASSERT( 0 <= iC && iC < tree->nodeCapacity ); b2TreeNode* B = nodes + iB; b2TreeNode* C = nodes + iC; - if (B->height == 0) + if ( B->height == 0 ) { // B is a leaf and C is internal - B2_ASSERT(C->height > 0); + B2_ASSERT( C->height > 0 ); int32_t iF = C->child1; int32_t iG = C->child2; b2TreeNode* F = nodes + iF; b2TreeNode* G = nodes + iG; - B2_ASSERT(0 <= iF && iF < tree->nodeCapacity); - B2_ASSERT(0 <= iG && iG < tree->nodeCapacity); + B2_ASSERT( 0 <= iF && iF < tree->nodeCapacity ); + B2_ASSERT( 0 <= iG && iG < tree->nodeCapacity ); // Base cost - float costBase = b2Perimeter(C->aabb); + float costBase = b2Perimeter( C->aabb ); // Cost of swapping B and F - b2AABB aabbBG = b2AABB_Union(B->aabb, G->aabb); - float costBF = b2Perimeter(aabbBG); + b2AABB aabbBG = b2AABB_Union( B->aabb, G->aabb ); + float costBF = b2Perimeter( aabbBG ); // Cost of swapping B and G - b2AABB aabbBF = b2AABB_Union(B->aabb, F->aabb); - float costBG = b2Perimeter(aabbBF); + b2AABB aabbBF = b2AABB_Union( B->aabb, F->aabb ); + float costBG = b2Perimeter( aabbBF ); - if (costBase < costBF && costBase < costBG) + if ( costBase < costBF && costBase < costBG ) { // Rotation does not improve cost return; } - if (costBF < costBG) + if ( costBF < costBG ) { // Swap B and F A->child1 = iF; @@ -352,8 +353,8 @@ static void b2RotateNodes(b2DynamicTree* tree, int32_t iA) C->aabb = aabbBG; - C->height = 1 + b2MaxInt16(B->height, G->height); - A->height = 1 + b2MaxInt16(C->height, F->height); + C->height = 1 + b2MaxInt16( B->height, G->height ); + A->height = 1 + b2MaxInt16( C->height, F->height ); C->categoryBits = B->categoryBits | G->categoryBits; A->categoryBits = C->categoryBits | F->categoryBits; C->enlarged = B->enlarged || G->enlarged; @@ -370,44 +371,44 @@ static void b2RotateNodes(b2DynamicTree* tree, int32_t iA) C->aabb = aabbBF; - C->height = 1 + b2MaxInt16(B->height, F->height); - A->height = 1 + b2MaxInt16(C->height, G->height); + C->height = 1 + b2MaxInt16( B->height, F->height ); + A->height = 1 + b2MaxInt16( C->height, G->height ); C->categoryBits = B->categoryBits | F->categoryBits; A->categoryBits = C->categoryBits | G->categoryBits; C->enlarged = B->enlarged || F->enlarged; A->enlarged = C->enlarged || G->enlarged; } } - else if (C->height == 0) + else if ( C->height == 0 ) { // C is a leaf and B is internal - B2_ASSERT(B->height > 0); + B2_ASSERT( B->height > 0 ); int iD = B->child1; int iE = B->child2; b2TreeNode* D = nodes + iD; b2TreeNode* E = nodes + iE; - B2_ASSERT(0 <= iD && iD < tree->nodeCapacity); - B2_ASSERT(0 <= iE && iE < tree->nodeCapacity); + B2_ASSERT( 0 <= iD && iD < tree->nodeCapacity ); + B2_ASSERT( 0 <= iE && iE < tree->nodeCapacity ); // Base cost - float costBase = b2Perimeter(B->aabb); + float costBase = b2Perimeter( B->aabb ); // Cost of swapping C and D - b2AABB aabbCE = b2AABB_Union(C->aabb, E->aabb); - float costCD = b2Perimeter(aabbCE); + b2AABB aabbCE = b2AABB_Union( C->aabb, E->aabb ); + float costCD = b2Perimeter( aabbCE ); // Cost of swapping C and E - b2AABB aabbCD = b2AABB_Union(C->aabb, D->aabb); - float costCE = b2Perimeter(aabbCD); + b2AABB aabbCD = b2AABB_Union( C->aabb, D->aabb ); + float costCE = b2Perimeter( aabbCD ); - if (costBase < costCD && costBase < costCE) + if ( costBase < costCD && costBase < costCE ) { // Rotation does not improve cost return; } - if (costCD < costCE) + if ( costCD < costCE ) { // Swap C and D A->child2 = iD; @@ -418,8 +419,8 @@ static void b2RotateNodes(b2DynamicTree* tree, int32_t iA) B->aabb = aabbCE; - B->height = 1 + b2MaxInt16(C->height, E->height); - A->height = 1 + b2MaxInt16(B->height, D->height); + B->height = 1 + b2MaxInt16( C->height, E->height ); + A->height = 1 + b2MaxInt16( B->height, D->height ); B->categoryBits = C->categoryBits | E->categoryBits; A->categoryBits = B->categoryBits | D->categoryBits; B->enlarged = C->enlarged || E->enlarged; @@ -435,8 +436,8 @@ static void b2RotateNodes(b2DynamicTree* tree, int32_t iA) E->parent = iA; B->aabb = aabbCD; - B->height = 1 + b2MaxInt16(C->height, D->height); - A->height = 1 + b2MaxInt16(B->height, E->height); + B->height = 1 + b2MaxInt16( C->height, D->height ); + A->height = 1 + b2MaxInt16( B->height, E->height ); B->categoryBits = C->categoryBits | D->categoryBits; A->categoryBits = B->categoryBits | E->categoryBits; B->enlarged = C->enlarged || D->enlarged; @@ -455,55 +456,55 @@ static void b2RotateNodes(b2DynamicTree* tree, int32_t iA) b2TreeNode* F = nodes + iF; b2TreeNode* G = nodes + iG; - B2_ASSERT(0 <= iD && iD < tree->nodeCapacity); - B2_ASSERT(0 <= iE && iE < tree->nodeCapacity); - B2_ASSERT(0 <= iF && iF < tree->nodeCapacity); - B2_ASSERT(0 <= iG && iG < tree->nodeCapacity); + B2_ASSERT( 0 <= iD && iD < tree->nodeCapacity ); + B2_ASSERT( 0 <= iE && iE < tree->nodeCapacity ); + B2_ASSERT( 0 <= iF && iF < tree->nodeCapacity ); + B2_ASSERT( 0 <= iG && iG < tree->nodeCapacity ); // Base cost - float areaB = b2Perimeter(B->aabb); - float areaC = b2Perimeter(C->aabb); + float areaB = b2Perimeter( B->aabb ); + float areaC = b2Perimeter( C->aabb ); float costBase = areaB + areaC; enum b2RotateType bestRotation = b2_rotateNone; float bestCost = costBase; // Cost of swapping B and F - b2AABB aabbBG = b2AABB_Union(B->aabb, G->aabb); - float costBF = areaB + b2Perimeter(aabbBG); - if (costBF < bestCost) + b2AABB aabbBG = b2AABB_Union( B->aabb, G->aabb ); + float costBF = areaB + b2Perimeter( aabbBG ); + if ( costBF < bestCost ) { bestRotation = b2_rotateBF; bestCost = costBF; } // Cost of swapping B and G - b2AABB aabbBF = b2AABB_Union(B->aabb, F->aabb); - float costBG = areaB + b2Perimeter(aabbBF); - if (costBG < bestCost) + b2AABB aabbBF = b2AABB_Union( B->aabb, F->aabb ); + float costBG = areaB + b2Perimeter( aabbBF ); + if ( costBG < bestCost ) { bestRotation = b2_rotateBG; bestCost = costBG; } // Cost of swapping C and D - b2AABB aabbCE = b2AABB_Union(C->aabb, E->aabb); - float costCD = areaC + b2Perimeter(aabbCE); - if (costCD < bestCost) + b2AABB aabbCE = b2AABB_Union( C->aabb, E->aabb ); + float costCD = areaC + b2Perimeter( aabbCE ); + if ( costCD < bestCost ) { bestRotation = b2_rotateCD; bestCost = costCD; } // Cost of swapping C and E - b2AABB aabbCD = b2AABB_Union(C->aabb, D->aabb); - float costCE = areaC + b2Perimeter(aabbCD); - if (costCE < bestCost) + b2AABB aabbCD = b2AABB_Union( C->aabb, D->aabb ); + float costCE = areaC + b2Perimeter( aabbCD ); + if ( costCE < bestCost ) { bestRotation = b2_rotateCE; // bestCost = costCE; } - switch (bestRotation) + switch ( bestRotation ) { case b2_rotateNone: break; @@ -516,8 +517,8 @@ static void b2RotateNodes(b2DynamicTree* tree, int32_t iA) F->parent = iA; C->aabb = aabbBG; - C->height = 1 + b2MaxInt16(B->height, G->height); - A->height = 1 + b2MaxInt16(C->height, F->height); + C->height = 1 + b2MaxInt16( B->height, G->height ); + A->height = 1 + b2MaxInt16( C->height, F->height ); C->categoryBits = B->categoryBits | G->categoryBits; A->categoryBits = C->categoryBits | F->categoryBits; C->enlarged = B->enlarged || G->enlarged; @@ -532,8 +533,8 @@ static void b2RotateNodes(b2DynamicTree* tree, int32_t iA) G->parent = iA; C->aabb = aabbBF; - C->height = 1 + b2MaxInt16(B->height, F->height); - A->height = 1 + b2MaxInt16(C->height, G->height); + C->height = 1 + b2MaxInt16( B->height, F->height ); + A->height = 1 + b2MaxInt16( C->height, G->height ); C->categoryBits = B->categoryBits | F->categoryBits; A->categoryBits = C->categoryBits | G->categoryBits; C->enlarged = B->enlarged || F->enlarged; @@ -548,8 +549,8 @@ static void b2RotateNodes(b2DynamicTree* tree, int32_t iA) D->parent = iA; B->aabb = aabbCE; - B->height = 1 + b2MaxInt16(C->height, E->height); - A->height = 1 + b2MaxInt16(B->height, D->height); + B->height = 1 + b2MaxInt16( C->height, E->height ); + A->height = 1 + b2MaxInt16( B->height, D->height ); B->categoryBits = C->categoryBits | E->categoryBits; A->categoryBits = B->categoryBits | D->categoryBits; B->enlarged = C->enlarged || E->enlarged; @@ -564,8 +565,8 @@ static void b2RotateNodes(b2DynamicTree* tree, int32_t iA) E->parent = iA; B->aabb = aabbCD; - B->height = 1 + b2MaxInt16(C->height, D->height); - A->height = 1 + b2MaxInt16(B->height, E->height); + B->height = 1 + b2MaxInt16( C->height, D->height ); + A->height = 1 + b2MaxInt16( B->height, E->height ); B->categoryBits = C->categoryBits | D->categoryBits; A->categoryBits = B->categoryBits | E->categoryBits; B->enlarged = C->enlarged || D->enlarged; @@ -573,15 +574,15 @@ static void b2RotateNodes(b2DynamicTree* tree, int32_t iA) break; default: - B2_ASSERT(false); + B2_ASSERT( false ); break; } } } -static void b2InsertLeaf(b2DynamicTree* tree, int32_t leaf, bool shouldRotate) +static void b2InsertLeaf( b2DynamicTree* tree, int32_t leaf, bool shouldRotate ) { - if (tree->root == B2_NULL_INDEX) + if ( tree->root == B2_NULL_INDEX ) { tree->root = leaf; tree->nodes[tree->root].parent = B2_NULL_INDEX; @@ -590,24 +591,24 @@ static void b2InsertLeaf(b2DynamicTree* tree, int32_t leaf, bool shouldRotate) // Stage 1: find the best sibling for this node b2AABB leafAABB = tree->nodes[leaf].aabb; - int32_t sibling = b2FindBestSibling(tree, leafAABB); + int32_t sibling = b2FindBestSibling( tree, leafAABB ); // Stage 2: create a new parent for the leaf and sibling int32_t oldParent = tree->nodes[sibling].parent; - int32_t newParent = b2AllocateNode(tree); + int32_t newParent = b2AllocateNode( tree ); // warning: node pointer can change after allocation b2TreeNode* nodes = tree->nodes; nodes[newParent].parent = oldParent; nodes[newParent].userData = -1; - nodes[newParent].aabb = b2AABB_Union(leafAABB, nodes[sibling].aabb); + nodes[newParent].aabb = b2AABB_Union( leafAABB, nodes[sibling].aabb ); nodes[newParent].categoryBits = nodes[leaf].categoryBits | nodes[sibling].categoryBits; nodes[newParent].height = nodes[sibling].height + 1; - if (oldParent != B2_NULL_INDEX) + if ( oldParent != B2_NULL_INDEX ) { // The sibling was not the root. - if (nodes[oldParent].child1 == sibling) + if ( nodes[oldParent].child1 == sibling ) { nodes[oldParent].child1 = newParent; } @@ -633,31 +634,31 @@ static void b2InsertLeaf(b2DynamicTree* tree, int32_t leaf, bool shouldRotate) // Stage 3: walk back up the tree fixing heights and AABBs int32_t index = nodes[leaf].parent; - while (index != B2_NULL_INDEX) + while ( index != B2_NULL_INDEX ) { int32_t child1 = nodes[index].child1; int32_t child2 = nodes[index].child2; - B2_ASSERT(child1 != B2_NULL_INDEX); - B2_ASSERT(child2 != B2_NULL_INDEX); + B2_ASSERT( child1 != B2_NULL_INDEX ); + B2_ASSERT( child2 != B2_NULL_INDEX ); - nodes[index].aabb = b2AABB_Union(nodes[child1].aabb, nodes[child2].aabb); + nodes[index].aabb = b2AABB_Union( nodes[child1].aabb, nodes[child2].aabb ); nodes[index].categoryBits = nodes[child1].categoryBits | nodes[child2].categoryBits; - nodes[index].height = 1 + b2MaxInt16(nodes[child1].height, nodes[child2].height); + nodes[index].height = 1 + b2MaxInt16( nodes[child1].height, nodes[child2].height ); nodes[index].enlarged = nodes[child1].enlarged || nodes[child2].enlarged; - if (shouldRotate) + if ( shouldRotate ) { - b2RotateNodes(tree, index); + b2RotateNodes( tree, index ); } index = nodes[index].parent; } } -static void b2RemoveLeaf(b2DynamicTree* tree, int32_t leaf) +static void b2RemoveLeaf( b2DynamicTree* tree, int32_t leaf ) { - if (leaf == tree->root) + if ( leaf == tree->root ) { tree->root = B2_NULL_INDEX; return; @@ -668,7 +669,7 @@ static void b2RemoveLeaf(b2DynamicTree* tree, int32_t leaf) int32_t parent = nodes[leaf].parent; int32_t grandParent = nodes[parent].parent; int32_t sibling; - if (nodes[parent].child1 == leaf) + if ( nodes[parent].child1 == leaf ) { sibling = nodes[parent].child2; } @@ -677,10 +678,10 @@ static void b2RemoveLeaf(b2DynamicTree* tree, int32_t leaf) sibling = nodes[parent].child1; } - if (grandParent != B2_NULL_INDEX) + if ( grandParent != B2_NULL_INDEX ) { // Destroy parent and connect sibling to grandParent. - if (nodes[grandParent].child1 == parent) + if ( nodes[grandParent].child1 == parent ) { nodes[grandParent].child1 = sibling; } @@ -689,11 +690,11 @@ static void b2RemoveLeaf(b2DynamicTree* tree, int32_t leaf) nodes[grandParent].child2 = sibling; } nodes[sibling].parent = grandParent; - b2FreeNode(tree, parent); + b2FreeNode( tree, parent ); // Adjust ancestor bounds. int32_t index = grandParent; - while (index != B2_NULL_INDEX) + while ( index != B2_NULL_INDEX ) { b2TreeNode* node = nodes + index; b2TreeNode* child1 = nodes + node->child1; @@ -707,9 +708,9 @@ static void b2RemoveLeaf(b2DynamicTree* tree, int32_t leaf) //__m128 aabb = _mm_shuffle_ps(lower, upper, _MM_SHUFFLE(3, 2, 1, 0)); //_mm_store_ps(&node->aabb.lowerBound.x, aabb); - node->aabb = b2AABB_Union(child1->aabb, child2->aabb); + node->aabb = b2AABB_Union( child1->aabb, child2->aabb ); node->categoryBits = child1->categoryBits | child2->categoryBits; - node->height = 1 + b2MaxInt16(child1->height, child2->height); + node->height = 1 + b2MaxInt16( child1->height, child2->height ); index = node->parent; } @@ -718,20 +719,20 @@ static void b2RemoveLeaf(b2DynamicTree* tree, int32_t leaf) { tree->root = sibling; tree->nodes[sibling].parent = B2_NULL_INDEX; - b2FreeNode(tree, parent); + b2FreeNode( tree, parent ); } } // Create a proxy in the tree as a leaf node. We return the index of the node instead of a pointer so that we can grow // the node pool. -int32_t b2DynamicTree_CreateProxy(b2DynamicTree* tree, b2AABB aabb, uint32_t categoryBits, int32_t userData) +int32_t b2DynamicTree_CreateProxy( b2DynamicTree* tree, b2AABB aabb, uint32_t categoryBits, int32_t userData ) { - B2_ASSERT(-b2_huge < aabb.lowerBound.x && aabb.lowerBound.x < b2_huge); - B2_ASSERT(-b2_huge < aabb.lowerBound.y && aabb.lowerBound.y < b2_huge); - B2_ASSERT(-b2_huge < aabb.upperBound.x && aabb.upperBound.x < b2_huge); - B2_ASSERT(-b2_huge < aabb.upperBound.y && aabb.upperBound.y < b2_huge); + B2_ASSERT( -b2_huge < aabb.lowerBound.x && aabb.lowerBound.x < b2_huge ); + B2_ASSERT( -b2_huge < aabb.lowerBound.y && aabb.lowerBound.y < b2_huge ); + B2_ASSERT( -b2_huge < aabb.upperBound.x && aabb.upperBound.x < b2_huge ); + B2_ASSERT( -b2_huge < aabb.upperBound.y && aabb.upperBound.y < b2_huge ); - int32_t proxyId = b2AllocateNode(tree); + int32_t proxyId = b2AllocateNode( tree ); b2TreeNode* node = tree->nodes + proxyId; node->aabb = aabb; @@ -740,77 +741,77 @@ int32_t b2DynamicTree_CreateProxy(b2DynamicTree* tree, b2AABB aabb, uint32_t cat node->height = 0; bool shouldRotate = true; - b2InsertLeaf(tree, proxyId, shouldRotate); + b2InsertLeaf( tree, proxyId, shouldRotate ); tree->proxyCount += 1; return proxyId; } -void b2DynamicTree_DestroyProxy(b2DynamicTree* tree, int32_t proxyId) +void b2DynamicTree_DestroyProxy( b2DynamicTree* tree, int32_t proxyId ) { - B2_ASSERT(0 <= proxyId && proxyId < tree->nodeCapacity); - B2_ASSERT(b2IsLeaf(tree->nodes + proxyId)); + B2_ASSERT( 0 <= proxyId && proxyId < tree->nodeCapacity ); + B2_ASSERT( b2IsLeaf( tree->nodes + proxyId ) ); - b2RemoveLeaf(tree, proxyId); - b2FreeNode(tree, proxyId); + b2RemoveLeaf( tree, proxyId ); + b2FreeNode( tree, proxyId ); - B2_ASSERT(tree->proxyCount > 0); + B2_ASSERT( tree->proxyCount > 0 ); tree->proxyCount -= 1; } -int32_t b2DynamicTree_GetProxyCount(const b2DynamicTree* tree) +int32_t b2DynamicTree_GetProxyCount( const b2DynamicTree* tree ) { return tree->proxyCount; } -void b2DynamicTree_MoveProxy(b2DynamicTree* tree, int32_t proxyId, b2AABB aabb) +void b2DynamicTree_MoveProxy( b2DynamicTree* tree, int32_t proxyId, b2AABB aabb ) { - B2_ASSERT(b2AABB_IsValid(aabb)); - B2_ASSERT(aabb.upperBound.x - aabb.lowerBound.x < b2_huge); - B2_ASSERT(aabb.upperBound.y - aabb.lowerBound.y < b2_huge); - B2_ASSERT(0 <= proxyId && proxyId < tree->nodeCapacity); - B2_ASSERT(b2IsLeaf(tree->nodes + proxyId)); + B2_ASSERT( b2AABB_IsValid( aabb ) ); + B2_ASSERT( aabb.upperBound.x - aabb.lowerBound.x < b2_huge ); + B2_ASSERT( aabb.upperBound.y - aabb.lowerBound.y < b2_huge ); + B2_ASSERT( 0 <= proxyId && proxyId < tree->nodeCapacity ); + B2_ASSERT( b2IsLeaf( tree->nodes + proxyId ) ); - b2RemoveLeaf(tree, proxyId); + b2RemoveLeaf( tree, proxyId ); tree->nodes[proxyId].aabb = aabb; bool shouldRotate = false; - b2InsertLeaf(tree, proxyId, shouldRotate); + b2InsertLeaf( tree, proxyId, shouldRotate ); } -void b2DynamicTree_EnlargeProxy(b2DynamicTree* tree, int32_t proxyId, b2AABB aabb) +void b2DynamicTree_EnlargeProxy( b2DynamicTree* tree, int32_t proxyId, b2AABB aabb ) { b2TreeNode* nodes = tree->nodes; - B2_ASSERT(b2AABB_IsValid(aabb)); - B2_ASSERT(aabb.upperBound.x - aabb.lowerBound.x < b2_huge); - B2_ASSERT(aabb.upperBound.y - aabb.lowerBound.y < b2_huge); - B2_ASSERT(0 <= proxyId && proxyId < tree->nodeCapacity); - B2_ASSERT(b2IsLeaf(tree->nodes + proxyId)); + B2_ASSERT( b2AABB_IsValid( aabb ) ); + B2_ASSERT( aabb.upperBound.x - aabb.lowerBound.x < b2_huge ); + B2_ASSERT( aabb.upperBound.y - aabb.lowerBound.y < b2_huge ); + B2_ASSERT( 0 <= proxyId && proxyId < tree->nodeCapacity ); + B2_ASSERT( b2IsLeaf( tree->nodes + proxyId ) ); // Caller must ensure this - B2_ASSERT(b2AABB_Contains(nodes[proxyId].aabb, aabb) == false); + B2_ASSERT( b2AABB_Contains( nodes[proxyId].aabb, aabb ) == false ); nodes[proxyId].aabb = aabb; int32_t parentIndex = nodes[proxyId].parent; - while (parentIndex != B2_NULL_INDEX) + while ( parentIndex != B2_NULL_INDEX ) { - bool changed = b2EnlargeAABB(&nodes[parentIndex].aabb, aabb); + bool changed = b2EnlargeAABB( &nodes[parentIndex].aabb, aabb ); nodes[parentIndex].enlarged = true; parentIndex = nodes[parentIndex].parent; - if (changed == false) + if ( changed == false ) { break; } } - while (parentIndex != B2_NULL_INDEX) + while ( parentIndex != B2_NULL_INDEX ) { - if (nodes[parentIndex].enlarged == true) + if ( nodes[parentIndex].enlarged == true ) { // early out because this ancestor was previously ascended and marked as enlarged break; @@ -821,9 +822,9 @@ void b2DynamicTree_EnlargeProxy(b2DynamicTree* tree, int32_t proxyId, b2AABB aab } } -int b2DynamicTree_GetHeight(const b2DynamicTree* tree) +int b2DynamicTree_GetHeight( const b2DynamicTree* tree ) { - if (tree->root == B2_NULL_INDEX) + if ( tree->root == B2_NULL_INDEX ) { return 0; } @@ -831,65 +832,65 @@ int b2DynamicTree_GetHeight(const b2DynamicTree* tree) return tree->nodes[tree->root].height; } -float b2DynamicTree_GetAreaRatio(const b2DynamicTree* tree) +float b2DynamicTree_GetAreaRatio( const b2DynamicTree* tree ) { - if (tree->root == B2_NULL_INDEX) + if ( tree->root == B2_NULL_INDEX ) { return 0.0f; } const b2TreeNode* root = tree->nodes + tree->root; - float rootArea = b2Perimeter(root->aabb); + float rootArea = b2Perimeter( root->aabb ); float totalArea = 0.0f; - for (int32_t i = 0; i < tree->nodeCapacity; ++i) + for ( int32_t i = 0; i < tree->nodeCapacity; ++i ) { const b2TreeNode* node = tree->nodes + i; - if (node->height < 0 || b2IsLeaf(node) || i == tree->root) + if ( node->height < 0 || b2IsLeaf( node ) || i == tree->root ) { // Free node in pool continue; } - totalArea += b2Perimeter(node->aabb); + totalArea += b2Perimeter( node->aabb ); } return totalArea / rootArea; } // Compute the height of a sub-tree. -static int b2ComputeHeight(const b2DynamicTree* tree, int32_t nodeId) +static int b2ComputeHeight( const b2DynamicTree* tree, int32_t nodeId ) { - B2_ASSERT(0 <= nodeId && nodeId < tree->nodeCapacity); + B2_ASSERT( 0 <= nodeId && nodeId < tree->nodeCapacity ); b2TreeNode* node = tree->nodes + nodeId; - if (b2IsLeaf(node)) + if ( b2IsLeaf( node ) ) { return 0; } - int32_t height1 = b2ComputeHeight(tree, node->child1); - int32_t height2 = b2ComputeHeight(tree, node->child2); - return 1 + b2MaxInt16(height1, height2); + int32_t height1 = b2ComputeHeight( tree, node->child1 ); + int32_t height2 = b2ComputeHeight( tree, node->child2 ); + return 1 + b2MaxInt16( height1, height2 ); } -int b2DynamicTree_ComputeHeight(const b2DynamicTree* tree) +int b2DynamicTree_ComputeHeight( const b2DynamicTree* tree ) { - int height = b2ComputeHeight(tree, tree->root); + int height = b2ComputeHeight( tree, tree->root ); return height; } #if B2_VALIDATE -static void b2ValidateStructure(const b2DynamicTree* tree, int32_t index) +static void b2ValidateStructure( const b2DynamicTree* tree, int32_t index ) { - if (index == B2_NULL_INDEX) + if ( index == B2_NULL_INDEX ) { return; } - if (index == tree->root) + if ( index == tree->root ) { - B2_ASSERT(tree->nodes[index].parent == B2_NULL_INDEX); + B2_ASSERT( tree->nodes[index].parent == B2_NULL_INDEX ); } const b2TreeNode* node = tree->nodes + index; @@ -897,32 +898,32 @@ static void b2ValidateStructure(const b2DynamicTree* tree, int32_t index) int32_t child1 = node->child1; int32_t child2 = node->child2; - if (b2IsLeaf(node)) + if ( b2IsLeaf( node ) ) { - B2_ASSERT(child1 == B2_NULL_INDEX); - B2_ASSERT(child2 == B2_NULL_INDEX); - B2_ASSERT(node->height == 0); + B2_ASSERT( child1 == B2_NULL_INDEX ); + B2_ASSERT( child2 == B2_NULL_INDEX ); + B2_ASSERT( node->height == 0 ); return; } - B2_ASSERT(0 <= child1 && child1 < tree->nodeCapacity); - B2_ASSERT(0 <= child2 && child2 < tree->nodeCapacity); + B2_ASSERT( 0 <= child1 && child1 < tree->nodeCapacity ); + B2_ASSERT( 0 <= child2 && child2 < tree->nodeCapacity ); - B2_ASSERT(tree->nodes[child1].parent == index); - B2_ASSERT(tree->nodes[child2].parent == index); + B2_ASSERT( tree->nodes[child1].parent == index ); + B2_ASSERT( tree->nodes[child2].parent == index ); - if (tree->nodes[child1].enlarged || tree->nodes[child2].enlarged) + if ( tree->nodes[child1].enlarged || tree->nodes[child2].enlarged ) { - B2_ASSERT(node->enlarged == true); + B2_ASSERT( node->enlarged == true ); } - b2ValidateStructure(tree, child1); - b2ValidateStructure(tree, child2); + b2ValidateStructure( tree, child1 ); + b2ValidateStructure( tree, child2 ); } -static void b2ValidateMetrics(const b2DynamicTree* tree, int32_t index) +static void b2ValidateMetrics( const b2DynamicTree* tree, int32_t index ) { - if (index == B2_NULL_INDEX) + if ( index == B2_NULL_INDEX ) { return; } @@ -932,27 +933,27 @@ static void b2ValidateMetrics(const b2DynamicTree* tree, int32_t index) int32_t child1 = node->child1; int32_t child2 = node->child2; - if (b2IsLeaf(node)) + if ( b2IsLeaf( node ) ) { - B2_ASSERT(child1 == B2_NULL_INDEX); - B2_ASSERT(child2 == B2_NULL_INDEX); - B2_ASSERT(node->height == 0); + B2_ASSERT( child1 == B2_NULL_INDEX ); + B2_ASSERT( child2 == B2_NULL_INDEX ); + B2_ASSERT( node->height == 0 ); return; } - B2_ASSERT(0 <= child1 && child1 < tree->nodeCapacity); - B2_ASSERT(0 <= child2 && child2 < tree->nodeCapacity); + B2_ASSERT( 0 <= child1 && child1 < tree->nodeCapacity ); + B2_ASSERT( 0 <= child2 && child2 < tree->nodeCapacity ); int32_t height1 = tree->nodes[child1].height; int32_t height2 = tree->nodes[child2].height; int32_t height; - height = 1 + b2MaxInt16(height1, height2); - B2_ASSERT(node->height == height); + height = 1 + b2MaxInt16( height1, height2 ); + B2_ASSERT( node->height == height ); // b2AABB aabb = b2AABB_Union(tree->nodes[child1].aabb, tree->nodes[child2].aabb); - B2_ASSERT(b2AABB_Contains(node->aabb, tree->nodes[child1].aabb)); - B2_ASSERT(b2AABB_Contains(node->aabb, tree->nodes[child2].aabb)); + B2_ASSERT( b2AABB_Contains( node->aabb, tree->nodes[child1].aabb ) ); + B2_ASSERT( b2AABB_Contains( node->aabb, tree->nodes[child2].aabb ) ); // B2_ASSERT(aabb.lowerBound.x == node->aabb.lowerBound.x); // B2_ASSERT(aabb.lowerBound.y == node->aabb.lowerBound.y); @@ -960,80 +961,80 @@ static void b2ValidateMetrics(const b2DynamicTree* tree, int32_t index) // B2_ASSERT(aabb.upperBound.y == node->aabb.upperBound.y); uint32_t categoryBits = tree->nodes[child1].categoryBits | tree->nodes[child2].categoryBits; - B2_ASSERT(node->categoryBits == categoryBits); + B2_ASSERT( node->categoryBits == categoryBits ); - b2ValidateMetrics(tree, child1); - b2ValidateMetrics(tree, child2); + b2ValidateMetrics( tree, child1 ); + b2ValidateMetrics( tree, child2 ); } #endif -void b2DynamicTree_Validate(const b2DynamicTree* tree) +void b2DynamicTree_Validate( const b2DynamicTree* tree ) { #if B2_VALIDATE - if (tree->root == B2_NULL_INDEX) + if ( tree->root == B2_NULL_INDEX ) { return; } - b2ValidateStructure(tree, tree->root); - b2ValidateMetrics(tree, tree->root); + b2ValidateStructure( tree, tree->root ); + b2ValidateMetrics( tree, tree->root ); int32_t freeCount = 0; int32_t freeIndex = tree->freeList; - while (freeIndex != B2_NULL_INDEX) + while ( freeIndex != B2_NULL_INDEX ) { - B2_ASSERT(0 <= freeIndex && freeIndex < tree->nodeCapacity); + B2_ASSERT( 0 <= freeIndex && freeIndex < tree->nodeCapacity ); freeIndex = tree->nodes[freeIndex].next; ++freeCount; } - int32_t height = b2DynamicTree_GetHeight(tree); - int32_t computedHeight = b2DynamicTree_ComputeHeight(tree); - B2_ASSERT(height == computedHeight); + int32_t height = b2DynamicTree_GetHeight( tree ); + int32_t computedHeight = b2DynamicTree_ComputeHeight( tree ); + B2_ASSERT( height == computedHeight ); - B2_ASSERT(tree->nodeCount + freeCount == tree->nodeCapacity); + B2_ASSERT( tree->nodeCount + freeCount == tree->nodeCapacity ); #else - B2_MAYBE_UNUSED(tree); + B2_MAYBE_UNUSED( tree ); #endif } -int32_t b2DynamicTree_GetMaxBalance(const b2DynamicTree* tree) +int32_t b2DynamicTree_GetMaxBalance( const b2DynamicTree* tree ) { int32_t maxBalance = 0; - for (int32_t i = 0; i < tree->nodeCapacity; ++i) + for ( int32_t i = 0; i < tree->nodeCapacity; ++i ) { const b2TreeNode* node = tree->nodes + i; - if (node->height <= 1) + if ( node->height <= 1 ) { continue; } - B2_ASSERT(b2IsLeaf(node) == false); + B2_ASSERT( b2IsLeaf( node ) == false ); int32_t child1 = node->child1; int32_t child2 = node->child2; - int32_t balance = b2AbsFloat(tree->nodes[child2].height - tree->nodes[child1].height); - maxBalance = b2MaxInt(maxBalance, balance); + int32_t balance = b2AbsFloat( tree->nodes[child2].height - tree->nodes[child1].height ); + maxBalance = b2MaxInt( maxBalance, balance ); } return maxBalance; } -void b2DynamicTree_RebuildBottomUp(b2DynamicTree* tree) +void b2DynamicTree_RebuildBottomUp( b2DynamicTree* tree ) { - int32_t* nodes = b2Alloc(tree->nodeCount * sizeof(int32_t)); + int32_t* nodes = b2Alloc( tree->nodeCount * sizeof( int32_t ) ); int32_t count = 0; // Build array of leaves. Free the rest. - for (int32_t i = 0; i < tree->nodeCapacity; ++i) + for ( int32_t i = 0; i < tree->nodeCapacity; ++i ) { - if (tree->nodes[i].height < 0) + if ( tree->nodes[i].height < 0 ) { // free node in pool continue; } - if (b2IsLeaf(tree->nodes + i)) + if ( b2IsLeaf( tree->nodes + i ) ) { tree->nodes[i].parent = B2_NULL_INDEX; nodes[count] = i; @@ -1041,24 +1042,24 @@ void b2DynamicTree_RebuildBottomUp(b2DynamicTree* tree) } else { - b2FreeNode(tree, i); + b2FreeNode( tree, i ); } } - while (count > 1) + while ( count > 1 ) { float minCost = FLT_MAX; int32_t iMin = -1, jMin = -1; - for (int32_t i = 0; i < count; ++i) + for ( int32_t i = 0; i < count; ++i ) { b2AABB aabbi = tree->nodes[nodes[i]].aabb; - for (int32_t j = i + 1; j < count; ++j) + for ( int32_t j = i + 1; j < count; ++j ) { b2AABB aabbj = tree->nodes[nodes[j]].aabb; - b2AABB b = b2AABB_Union(aabbi, aabbj); - float cost = b2Perimeter(b); - if (cost < minCost) + b2AABB b = b2AABB_Union( aabbi, aabbj ); + float cost = b2Perimeter( b ); + if ( cost < minCost ) { iMin = i; jMin = j; @@ -1072,13 +1073,13 @@ void b2DynamicTree_RebuildBottomUp(b2DynamicTree* tree) b2TreeNode* child1 = tree->nodes + index1; b2TreeNode* child2 = tree->nodes + index2; - int32_t parentIndex = b2AllocateNode(tree); + int32_t parentIndex = b2AllocateNode( tree ); b2TreeNode* parent = tree->nodes + parentIndex; parent->child1 = index1; parent->child2 = index2; - parent->aabb = b2AABB_Union(child1->aabb, child2->aabb); + parent->aabb = b2AABB_Union( child1->aabb, child2->aabb ); parent->categoryBits = child1->categoryBits | child2->categoryBits; - parent->height = 1 + b2MaxInt16(child1->height, child2->height); + parent->height = 1 + b2MaxInt16( child1->height, child2->height ); parent->parent = B2_NULL_INDEX; child1->parent = parentIndex; @@ -1090,15 +1091,15 @@ void b2DynamicTree_RebuildBottomUp(b2DynamicTree* tree) } tree->root = nodes[0]; - b2Free(nodes, tree->nodeCount * sizeof(b2TreeNode)); + b2Free( nodes, tree->nodeCount * sizeof( b2TreeNode ) ); - b2DynamicTree_Validate(tree); + b2DynamicTree_Validate( tree ); } -void b2DynamicTree_ShiftOrigin(b2DynamicTree* tree, b2Vec2 newOrigin) +void b2DynamicTree_ShiftOrigin( b2DynamicTree* tree, b2Vec2 newOrigin ) { // shift all AABBs - for (int32_t i = 0; i < tree->nodeCapacity; ++i) + for ( int32_t i = 0; i < tree->nodeCapacity; ++i ) { b2TreeNode* n = tree->nodes + i; n->aabb.lowerBound.x -= newOrigin.x; @@ -1108,46 +1109,46 @@ void b2DynamicTree_ShiftOrigin(b2DynamicTree* tree, b2Vec2 newOrigin) } } -int b2DynamicTree_GetByteCount(const b2DynamicTree* tree) +int b2DynamicTree_GetByteCount( const b2DynamicTree* tree ) { - size_t size = sizeof(b2DynamicTree) + sizeof(b2TreeNode) * tree->nodeCapacity + - tree->rebuildCapacity * (sizeof(int32_t) + sizeof(b2AABB) + sizeof(b2Vec2) + sizeof(int32_t)); + size_t size = sizeof( b2DynamicTree ) + sizeof( b2TreeNode ) * tree->nodeCapacity + + tree->rebuildCapacity * ( sizeof( int32_t ) + sizeof( b2AABB ) + sizeof( b2Vec2 ) + sizeof( int32_t ) ); return (int)size; } -void b2DynamicTree_Query(const b2DynamicTree* tree, b2AABB aabb, uint32_t maskBits, b2TreeQueryCallbackFcn* callback, - void* context) +void b2DynamicTree_Query( const b2DynamicTree* tree, b2AABB aabb, uint32_t maskBits, b2TreeQueryCallbackFcn* callback, + void* context ) { int32_t stack[b2_treeStackSize]; int32_t stackCount = 0; stack[stackCount++] = tree->root; - while (stackCount > 0) + while ( stackCount > 0 ) { int32_t nodeId = stack[--stackCount]; - if (nodeId == B2_NULL_INDEX) + if ( nodeId == B2_NULL_INDEX ) { continue; } const b2TreeNode* node = tree->nodes + nodeId; - if (b2AABB_Overlaps(node->aabb, aabb) && (node->categoryBits & maskBits) != 0) + if ( b2AABB_Overlaps( node->aabb, aabb ) && ( node->categoryBits & maskBits ) != 0 ) { - if (b2IsLeaf(node)) + if ( b2IsLeaf( node ) ) { // callback to user code with proxy id - bool proceed = callback(nodeId, node->userData, context); - if (proceed == false) + bool proceed = callback( nodeId, node->userData, context ); + if ( proceed == false ) { return; } } else { - B2_ASSERT(stackCount < b2_treeStackSize - 1); - if (stackCount < b2_treeStackSize - 1) + B2_ASSERT( stackCount < b2_treeStackSize - 1 ); + if ( stackCount < b2_treeStackSize - 1 ) { stack[stackCount++] = node->child1; stack[stackCount++] = node->child2; @@ -1157,27 +1158,27 @@ void b2DynamicTree_Query(const b2DynamicTree* tree, b2AABB aabb, uint32_t maskBi } } -void b2DynamicTree_RayCast(const b2DynamicTree* tree, const b2RayCastInput* input, uint32_t maskBits, - b2TreeRayCastCallbackFcn* callback, void* context) +void b2DynamicTree_RayCast( const b2DynamicTree* tree, const b2RayCastInput* input, uint32_t maskBits, + b2TreeRayCastCallbackFcn* callback, void* context ) { b2Vec2 p1 = input->origin; b2Vec2 d = input->translation; - b2Vec2 r = b2Normalize(d); + b2Vec2 r = b2Normalize( d ); // v is perpendicular to the segment. - b2Vec2 v = b2CrossSV(1.0f, r); - b2Vec2 abs_v = b2Abs(v); + b2Vec2 v = b2CrossSV( 1.0f, r ); + b2Vec2 abs_v = b2Abs( v ); // Separating axis for segment (Gino, p80). // |dot(v, p1 - c)| > dot(|v|, h) float maxFraction = input->maxFraction; - b2Vec2 p2 = b2MulAdd(p1, maxFraction, d); + b2Vec2 p2 = b2MulAdd( p1, maxFraction, d ); // Build a bounding box for the segment. - b2AABB segmentAABB = {b2Min(p1, p2), b2Max(p1, p2)}; + b2AABB segmentAABB = { b2Min( p1, p2 ), b2Max( p1, p2 ) }; int32_t stack[b2_treeStackSize]; int32_t stackCount = 0; @@ -1185,16 +1186,16 @@ void b2DynamicTree_RayCast(const b2DynamicTree* tree, const b2RayCastInput* inpu b2RayCastInput subInput = *input; - while (stackCount > 0) + while ( stackCount > 0 ) { int32_t nodeId = stack[--stackCount]; - if (nodeId == B2_NULL_INDEX) + if ( nodeId == B2_NULL_INDEX ) { continue; } const b2TreeNode* node = tree->nodes + nodeId; - if (b2AABB_Overlaps(node->aabb, segmentAABB) == false || (node->categoryBits & maskBits) == 0) + if ( b2AABB_Overlaps( node->aabb, segmentAABB ) == false || ( node->categoryBits & maskBits ) == 0 ) { continue; } @@ -1202,40 +1203,40 @@ void b2DynamicTree_RayCast(const b2DynamicTree* tree, const b2RayCastInput* inpu // Separating axis for segment (Gino, p80). // |dot(v, p1 - c)| > dot(|v|, h) // radius extension is added to the node in this case - b2Vec2 c = b2AABB_Center(node->aabb); - b2Vec2 h = b2AABB_Extents(node->aabb); - float term1 = b2AbsFloat(b2Dot(v, b2Sub(p1, c))); - float term2 = b2Dot(abs_v, h); - if (term2 < term1) + b2Vec2 c = b2AABB_Center( node->aabb ); + b2Vec2 h = b2AABB_Extents( node->aabb ); + float term1 = b2AbsFloat( b2Dot( v, b2Sub( p1, c ) ) ); + float term2 = b2Dot( abs_v, h ); + if ( term2 < term1 ) { continue; } - if (b2IsLeaf(node)) + if ( b2IsLeaf( node ) ) { subInput.maxFraction = maxFraction; - float value = callback(&subInput, nodeId, node->userData, context); + float value = callback( &subInput, nodeId, node->userData, context ); - if (value == 0.0f) + if ( value == 0.0f ) { // The client has terminated the ray cast. return; } - if (0.0f < value && value < maxFraction) + if ( 0.0f < value && value < maxFraction ) { // Update segment bounding box. maxFraction = value; - p2 = b2MulAdd(p1, maxFraction, d); - segmentAABB.lowerBound = b2Min(p1, p2); - segmentAABB.upperBound = b2Max(p1, p2); + p2 = b2MulAdd( p1, maxFraction, d ); + segmentAABB.lowerBound = b2Min( p1, p2 ); + segmentAABB.upperBound = b2Max( p1, p2 ); } } else { - B2_ASSERT(stackCount < b2_treeStackSize - 1); - if (stackCount < b2_treeStackSize - 1) + B2_ASSERT( stackCount < b2_treeStackSize - 1 ); + if ( stackCount < b2_treeStackSize - 1 ) { // TODO_ERIN just put one node on the stack, continue on a child node // TODO_ERIN test ordering children by nearest to ray origin @@ -1246,33 +1247,33 @@ void b2DynamicTree_RayCast(const b2DynamicTree* tree, const b2RayCastInput* inpu } } -void b2DynamicTree_ShapeCast(const b2DynamicTree* tree, const b2ShapeCastInput* input, uint32_t maskBits, - b2TreeShapeCastCallbackFcn* callback, void* context) +void b2DynamicTree_ShapeCast( const b2DynamicTree* tree, const b2ShapeCastInput* input, uint32_t maskBits, + b2TreeShapeCastCallbackFcn* callback, void* context ) { - if (input->count == 0) + if ( input->count == 0 ) { return; } - b2AABB originAABB = {input->points[0], input->points[0]}; - for (int i = 1; i < input->count; ++i) + b2AABB originAABB = { input->points[0], input->points[0] }; + for ( int i = 1; i < input->count; ++i ) { - originAABB.lowerBound = b2Min(originAABB.lowerBound, input->points[i]); - originAABB.upperBound = b2Max(originAABB.upperBound, input->points[i]); + originAABB.lowerBound = b2Min( originAABB.lowerBound, input->points[i] ); + originAABB.upperBound = b2Max( originAABB.upperBound, input->points[i] ); } - b2Vec2 radius = {input->radius, input->radius}; + b2Vec2 radius = { input->radius, input->radius }; - originAABB.lowerBound = b2Sub(originAABB.lowerBound, radius); - originAABB.upperBound = b2Add(originAABB.upperBound, radius); + originAABB.lowerBound = b2Sub( originAABB.lowerBound, radius ); + originAABB.upperBound = b2Add( originAABB.upperBound, radius ); - b2Vec2 p1 = b2AABB_Center(originAABB); - b2Vec2 extension = b2AABB_Extents(originAABB); + b2Vec2 p1 = b2AABB_Center( originAABB ); + b2Vec2 extension = b2AABB_Extents( originAABB ); // v is perpendicular to the segment. b2Vec2 r = input->translation; - b2Vec2 v = b2CrossSV(1.0f, r); - b2Vec2 abs_v = b2Abs(v); + b2Vec2 v = b2CrossSV( 1.0f, r ); + b2Vec2 abs_v = b2Abs( v ); // Separating axis for segment (Gino, p80). // |dot(v, p1 - c)| > dot(|v|, h) @@ -1280,10 +1281,10 @@ void b2DynamicTree_ShapeCast(const b2DynamicTree* tree, const b2ShapeCastInput* float maxFraction = input->maxFraction; // Build total box for the shape cast - b2Vec2 t = b2MulSV(maxFraction, input->translation); + b2Vec2 t = b2MulSV( maxFraction, input->translation ); b2AABB totalAABB = { - b2Min(originAABB.lowerBound, b2Add(originAABB.lowerBound, t)), - b2Max(originAABB.upperBound, b2Add(originAABB.upperBound, t)), + b2Min( originAABB.lowerBound, b2Add( originAABB.lowerBound, t ) ), + b2Max( originAABB.upperBound, b2Add( originAABB.upperBound, t ) ), }; b2ShapeCastInput subInput = *input; @@ -1292,16 +1293,16 @@ void b2DynamicTree_ShapeCast(const b2DynamicTree* tree, const b2ShapeCastInput* int32_t stackCount = 0; stack[stackCount++] = tree->root; - while (stackCount > 0) + while ( stackCount > 0 ) { int32_t nodeId = stack[--stackCount]; - if (nodeId == B2_NULL_INDEX) + if ( nodeId == B2_NULL_INDEX ) { continue; } const b2TreeNode* node = tree->nodes + nodeId; - if (b2AABB_Overlaps(node->aabb, totalAABB) == false || (node->categoryBits & maskBits) == 0) + if ( b2AABB_Overlaps( node->aabb, totalAABB ) == false || ( node->categoryBits & maskBits ) == 0 ) { continue; } @@ -1309,40 +1310,40 @@ void b2DynamicTree_ShapeCast(const b2DynamicTree* tree, const b2ShapeCastInput* // Separating axis for segment (Gino, p80). // |dot(v, p1 - c)| > dot(|v|, h) // radius extension is added to the node in this case - b2Vec2 c = b2AABB_Center(node->aabb); - b2Vec2 h = b2Add(b2AABB_Extents(node->aabb), extension); - float term1 = b2AbsFloat(b2Dot(v, b2Sub(p1, c))); - float term2 = b2Dot(abs_v, h); - if (term2 < term1) + b2Vec2 c = b2AABB_Center( node->aabb ); + b2Vec2 h = b2Add( b2AABB_Extents( node->aabb ), extension ); + float term1 = b2AbsFloat( b2Dot( v, b2Sub( p1, c ) ) ); + float term2 = b2Dot( abs_v, h ); + if ( term2 < term1 ) { continue; } - if (b2IsLeaf(node)) + if ( b2IsLeaf( node ) ) { subInput.maxFraction = maxFraction; - float value = callback(&subInput, nodeId, node->userData, context); + float value = callback( &subInput, nodeId, node->userData, context ); - if (value == 0.0f) + if ( value == 0.0f ) { // The client has terminated the ray cast. return; } - if (0.0f < value && value < maxFraction) + if ( 0.0f < value && value < maxFraction ) { // Update segment bounding box. maxFraction = value; - t = b2MulSV(maxFraction, input->translation); - totalAABB.lowerBound = b2Min(originAABB.lowerBound, b2Add(originAABB.lowerBound, t)); - totalAABB.upperBound = b2Max(originAABB.upperBound, b2Add(originAABB.upperBound, t)); + t = b2MulSV( maxFraction, input->translation ); + totalAABB.lowerBound = b2Min( originAABB.lowerBound, b2Add( originAABB.lowerBound, t ) ); + totalAABB.upperBound = b2Max( originAABB.upperBound, b2Add( originAABB.upperBound, t ) ); } } else { - B2_ASSERT(stackCount < b2_treeStackSize - 1); - if (stackCount < b2_treeStackSize - 1) + B2_ASSERT( stackCount < b2_treeStackSize - 1 ); + if ( stackCount < b2_treeStackSize - 1 ) { // TODO_ERIN just put one node on the stack, continue on a child node // TODO_ERIN test ordering children by nearest to ray origin @@ -1359,10 +1360,10 @@ void b2DynamicTree_ShapeCast(const b2DynamicTree* tree, const b2ShapeCastInput* #if B2_TREE_HEURISTIC == 0 // Median split heuristic -static int32_t b2PartitionMid(int32_t* indices, b2Vec2* centers, int32_t count) +static int32_t b2PartitionMid( int32_t* indices, b2Vec2* centers, int32_t count ) { // Handle trivial case - if (count <= 2) + if ( count <= 2 ) { return count / 2; } @@ -1371,36 +1372,36 @@ static int32_t b2PartitionMid(int32_t* indices, b2Vec2* centers, int32_t count) b2Vec2 lowerBound = centers[0]; b2Vec2 upperBound = centers[0]; - for (int32_t i = 1; i < count; ++i) + for ( int32_t i = 1; i < count; ++i ) { - lowerBound = b2Min(lowerBound, centers[i]); - upperBound = b2Max(upperBound, centers[i]); + lowerBound = b2Min( lowerBound, centers[i] ); + upperBound = b2Max( upperBound, centers[i] ); } - b2Vec2 d = b2Sub(upperBound, lowerBound); - b2Vec2 c = {0.5f * (lowerBound.x + upperBound.x), 0.5f * (lowerBound.y + upperBound.y)}; + b2Vec2 d = b2Sub( upperBound, lowerBound ); + b2Vec2 c = { 0.5f * ( lowerBound.x + upperBound.x ), 0.5f * ( lowerBound.y + upperBound.y ) }; // Partition longest axis using the Hoare partition scheme // https://en.wikipedia.org/wiki/Quicksort // https://nicholasvadivelu.com/2021/01/11/array-partition/ int32_t i1 = 0, i2 = count; - if (d.x > d.y) + if ( d.x > d.y ) { float pivot = c.x; - while (i1 < i2) + while ( i1 < i2 ) { - while (i1 < i2 && centers[i1].x < pivot) + while ( i1 < i2 && centers[i1].x < pivot ) { i1 += 1; }; - while (i1 < i2 && centers[i2 - 1].x >= pivot) + while ( i1 < i2 && centers[i2 - 1].x >= pivot ) { i2 -= 1; }; - if (i1 < i2) + if ( i1 < i2 ) { // Swap indices { @@ -1425,19 +1426,19 @@ static int32_t b2PartitionMid(int32_t* indices, b2Vec2* centers, int32_t count) { float pivot = c.y; - while (i1 < i2) + while ( i1 < i2 ) { - while (i1 < i2 && centers[i1].y < pivot) + while ( i1 < i2 && centers[i1].y < pivot ) { i1 += 1; }; - while (i1 < i2 && centers[i2 - 1].y >= pivot) + while ( i1 < i2 && centers[i2 - 1].y >= pivot ) { i2 -= 1; }; - if (i1 < i2) + if ( i1 < i2 ) { // Swap indices { @@ -1458,9 +1459,9 @@ static int32_t b2PartitionMid(int32_t* indices, b2Vec2* centers, int32_t count) } } } - B2_ASSERT(i1 == i2); + B2_ASSERT( i1 == i2 ); - if (i1 > 0 && i1 < count) + if ( i1 > 0 && i1 < count ) { return i1; } @@ -1490,31 +1491,31 @@ typedef struct b2TreePlane // "On Fast Construction of SAH-based Bounding Volume Hierarchies" by Ingo Wald // Returns the left child count -static int32_t b2PartitionSAH(int32_t* indices, int32_t* binIndices, b2AABB* boxes, int32_t count) +static int32_t b2PartitionSAH( int32_t* indices, int32_t* binIndices, b2AABB* boxes, int32_t count ) { - B2_ASSERT(count > 0); + B2_ASSERT( count > 0 ); b2TreeBin bins[B2_BIN_COUNT]; b2TreePlane planes[B2_BIN_COUNT - 1]; - b2Vec2 center = b2AABB_Center(boxes[0]); + b2Vec2 center = b2AABB_Center( boxes[0] ); b2AABB centroidAABB; centroidAABB.lowerBound = center; centroidAABB.upperBound = center; - for (int32_t i = 1; i < count; ++i) + for ( int32_t i = 1; i < count; ++i ) { - center = b2AABB_Center(boxes[i]); - centroidAABB.lowerBound = b2Min(centroidAABB.lowerBound, center); - centroidAABB.upperBound = b2Max(centroidAABB.upperBound, center); + center = b2AABB_Center( boxes[i] ); + centroidAABB.lowerBound = b2Min( centroidAABB.lowerBound, center ); + centroidAABB.upperBound = b2Max( centroidAABB.upperBound, center ); } - b2Vec2 d = b2Sub(centroidAABB.upperBound, centroidAABB.lowerBound); + b2Vec2 d = b2Sub( centroidAABB.upperBound, centroidAABB.lowerBound ); // Find longest axis int32_t axisIndex; float invD; - if (d.x > d.y) + if ( d.x > d.y ) { axisIndex = 0; invD = d.x; @@ -1528,27 +1529,27 @@ static int32_t b2PartitionSAH(int32_t* indices, int32_t* binIndices, b2AABB* box invD = invD > 0.0f ? 1.0f / invD : 0.0f; // Initialize bin bounds and count - for (int32_t i = 0; i < B2_BIN_COUNT; ++i) + for ( int32_t i = 0; i < B2_BIN_COUNT; ++i ) { - bins[i].aabb.lowerBound = (b2Vec2){FLT_MAX, FLT_MAX}; - bins[i].aabb.upperBound = (b2Vec2){-FLT_MAX, -FLT_MAX}; + bins[i].aabb.lowerBound = ( b2Vec2 ){ FLT_MAX, FLT_MAX }; + bins[i].aabb.upperBound = ( b2Vec2 ){ -FLT_MAX, -FLT_MAX }; bins[i].count = 0; } // Assign boxes to bins and compute bin boxes // TODO_ERIN optimize float binCount = B2_BIN_COUNT; - float lowerBoundArray[2] = {centroidAABB.lowerBound.x, centroidAABB.lowerBound.y}; + float lowerBoundArray[2] = { centroidAABB.lowerBound.x, centroidAABB.lowerBound.y }; float minC = lowerBoundArray[axisIndex]; - for (int32_t i = 0; i < count; ++i) + for ( int32_t i = 0; i < count; ++i ) { - b2Vec2 c = b2AABB_Center(boxes[i]); - float cArray[2] = {c.x, c.y}; - int32_t binIndex = (int32_t)(binCount * (cArray[axisIndex] - minC) * invD); - binIndex = b2ClampInt(binIndex, 0, B2_BIN_COUNT - 1); + b2Vec2 c = b2AABB_Center( boxes[i] ); + float cArray[2] = { c.x, c.y }; + int32_t binIndex = (int32_t)( binCount * ( cArray[axisIndex] - minC ) * invD ); + binIndex = b2ClampInt( binIndex, 0, B2_BIN_COUNT - 1 ); binIndices[i] = binIndex; bins[binIndex].count += 1; - bins[binIndex].aabb = b2AABB_Union(bins[binIndex].aabb, boxes[i]); + bins[binIndex].aabb = b2AABB_Union( bins[binIndex].aabb, boxes[i] ); } int32_t planeCount = B2_BIN_COUNT - 1; @@ -1556,33 +1557,33 @@ static int32_t b2PartitionSAH(int32_t* indices, int32_t* binIndices, b2AABB* box // Prepare all the left planes, candidates for left child planes[0].leftCount = bins[0].count; planes[0].leftAABB = bins[0].aabb; - for (int32_t i = 1; i < planeCount; ++i) + for ( int32_t i = 1; i < planeCount; ++i ) { planes[i].leftCount = planes[i - 1].leftCount + bins[i].count; - planes[i].leftAABB = b2AABB_Union(planes[i - 1].leftAABB, bins[i].aabb); + planes[i].leftAABB = b2AABB_Union( planes[i - 1].leftAABB, bins[i].aabb ); } // Prepare all the right planes, candidates for right child planes[planeCount - 1].rightCount = bins[planeCount].count; planes[planeCount - 1].rightAABB = bins[planeCount].aabb; - for (int32_t i = planeCount - 2; i >= 0; --i) + for ( int32_t i = planeCount - 2; i >= 0; --i ) { planes[i].rightCount = planes[i + 1].rightCount + bins[i + 1].count; - planes[i].rightAABB = b2AABB_Union(planes[i + 1].rightAABB, bins[i + 1].aabb); + planes[i].rightAABB = b2AABB_Union( planes[i + 1].rightAABB, bins[i + 1].aabb ); } // Find best split to minimize SAH float minCost = FLT_MAX; int32_t bestPlane = 0; - for (int32_t i = 0; i < planeCount; ++i) + for ( int32_t i = 0; i < planeCount; ++i ) { - float leftArea = b2Perimeter(planes[i].leftAABB); - float rightArea = b2Perimeter(planes[i].rightAABB); + float leftArea = b2Perimeter( planes[i].leftAABB ); + float rightArea = b2Perimeter( planes[i].rightAABB ); int32_t leftCount = planes[i].leftCount; int32_t rightCount = planes[i].rightCount; float cost = leftCount * leftArea + rightCount * rightArea; - if (cost < minCost) + if ( cost < minCost ) { bestPlane = i; minCost = cost; @@ -1593,19 +1594,19 @@ static int32_t b2PartitionSAH(int32_t* indices, int32_t* binIndices, b2AABB* box // https://en.wikipedia.org/wiki/Quicksort // https://nicholasvadivelu.com/2021/01/11/array-partition/ int32_t i1 = 0, i2 = count; - while (i1 < i2) + while ( i1 < i2 ) { - while (i1 < i2 && binIndices[i1] < bestPlane) + while ( i1 < i2 && binIndices[i1] < bestPlane ) { i1 += 1; }; - while (i1 < i2 && binIndices[i2 - 1] >= bestPlane) + while ( i1 < i2 && binIndices[i2 - 1] >= bestPlane ) { i2 -= 1; }; - if (i1 < i2) + if ( i1 < i2 ) { // Swap indices { @@ -1625,9 +1626,9 @@ static int32_t b2PartitionSAH(int32_t* indices, int32_t* binIndices, b2AABB* box i2 -= 1; } } - B2_ASSERT(i1 == i2); + B2_ASSERT( i1 == i2 ); - if (i1 > 0 && i1 < count) + if ( i1 > 0 && i1 < count ) { return i1; } @@ -1652,12 +1653,12 @@ struct b2RebuildItem }; // Returns root node index -static int32_t b2BuildTree(b2DynamicTree* tree, int32_t leafCount) +static int32_t b2BuildTree( b2DynamicTree* tree, int32_t leafCount ) { b2TreeNode* nodes = tree->nodes; int32_t* leafIndices = tree->leafIndices; - if (leafCount == 1) + if ( leafCount == 1 ) { nodes[leafIndices[0]].parent = B2_NULL_INDEX; return leafIndices[0]; @@ -1673,59 +1674,59 @@ static int32_t b2BuildTree(b2DynamicTree* tree, int32_t leafCount) struct b2RebuildItem stack[b2_treeStackSize]; int32_t top = 0; - stack[0].nodeIndex = b2AllocateNode(tree); + stack[0].nodeIndex = b2AllocateNode( tree ); stack[0].childCount = -1; stack[0].startIndex = 0; stack[0].endIndex = leafCount; #if B2_TREE_HEURISTIC == 0 - stack[0].splitIndex = b2PartitionMid(leafIndices, leafCenters, leafCount); + stack[0].splitIndex = b2PartitionMid( leafIndices, leafCenters, leafCount ); #else - stack[0].splitIndex = b2PartitionSAH(leafIndices, binIndices, leafBoxes, leafCount); + stack[0].splitIndex = b2PartitionSAH( leafIndices, binIndices, leafBoxes, leafCount ); #endif - while (true) + while ( true ) { struct b2RebuildItem* item = stack + top; item->childCount += 1; - if (item->childCount == 2) + if ( item->childCount == 2 ) { // This internal node has both children established - if (top == 0) + if ( top == 0 ) { // all done break; } - struct b2RebuildItem* parentItem = stack + (top - 1); + struct b2RebuildItem* parentItem = stack + ( top - 1 ); b2TreeNode* parentNode = nodes + parentItem->nodeIndex; - if (parentItem->childCount == 0) + if ( parentItem->childCount == 0 ) { - B2_ASSERT(parentNode->child1 == B2_NULL_INDEX); + B2_ASSERT( parentNode->child1 == B2_NULL_INDEX ); parentNode->child1 = item->nodeIndex; } else { - B2_ASSERT(parentItem->childCount == 1); - B2_ASSERT(parentNode->child2 == B2_NULL_INDEX); + B2_ASSERT( parentItem->childCount == 1 ); + B2_ASSERT( parentNode->child2 == B2_NULL_INDEX ); parentNode->child2 = item->nodeIndex; } b2TreeNode* node = nodes + item->nodeIndex; - B2_ASSERT(node->parent == B2_NULL_INDEX); + B2_ASSERT( node->parent == B2_NULL_INDEX ); node->parent = parentItem->nodeIndex; - B2_ASSERT(node->child1 != B2_NULL_INDEX); - B2_ASSERT(node->child2 != B2_NULL_INDEX); + B2_ASSERT( node->child1 != B2_NULL_INDEX ); + B2_ASSERT( node->child2 != B2_NULL_INDEX ); b2TreeNode* child1 = nodes + node->child1; b2TreeNode* child2 = nodes + node->child2; - node->aabb = b2AABB_Union(child1->aabb, child2->aabb); - node->height = 1 + b2MaxInt16(child1->height, child2->height); + node->aabb = b2AABB_Union( child1->aabb, child2->aabb ); + node->height = 1 + b2MaxInt16( child1->height, child2->height ); node->categoryBits = child1->categoryBits | child2->categoryBits; // Pop stack @@ -1734,57 +1735,57 @@ static int32_t b2BuildTree(b2DynamicTree* tree, int32_t leafCount) else { int32_t startIndex, endIndex; - if (item->childCount == 0) + if ( item->childCount == 0 ) { startIndex = item->startIndex; endIndex = item->splitIndex; } else { - B2_ASSERT(item->childCount == 1); + B2_ASSERT( item->childCount == 1 ); startIndex = item->splitIndex; endIndex = item->endIndex; } int32_t count = endIndex - startIndex; - if (count == 1) + if ( count == 1 ) { int32_t childIndex = leafIndices[startIndex]; b2TreeNode* node = nodes + item->nodeIndex; - if (item->childCount == 0) + if ( item->childCount == 0 ) { - B2_ASSERT(node->child1 == B2_NULL_INDEX); + B2_ASSERT( node->child1 == B2_NULL_INDEX ); node->child1 = childIndex; } else { - B2_ASSERT(item->childCount == 1); - B2_ASSERT(node->child2 == B2_NULL_INDEX); + B2_ASSERT( item->childCount == 1 ); + B2_ASSERT( node->child2 == B2_NULL_INDEX ); node->child2 = childIndex; } b2TreeNode* childNode = nodes + childIndex; - B2_ASSERT(childNode->parent == B2_NULL_INDEX); + B2_ASSERT( childNode->parent == B2_NULL_INDEX ); childNode->parent = item->nodeIndex; } else { - B2_ASSERT(count > 0); - B2_ASSERT(top < b2_treeStackSize); + B2_ASSERT( count > 0 ); + B2_ASSERT( top < b2_treeStackSize ); top += 1; struct b2RebuildItem* newItem = stack + top; - newItem->nodeIndex = b2AllocateNode(tree); + newItem->nodeIndex = b2AllocateNode( tree ); newItem->childCount = -1; newItem->startIndex = startIndex; newItem->endIndex = endIndex; #if B2_TREE_HEURISTIC == 0 - newItem->splitIndex = b2PartitionMid(leafIndices + startIndex, leafCenters + startIndex, count); + newItem->splitIndex = b2PartitionMid( leafIndices + startIndex, leafCenters + startIndex, count ); #else newItem->splitIndex = - b2PartitionSAH(leafIndices + startIndex, binIndices + startIndex, leafBoxes + startIndex, count); + b2PartitionSAH( leafIndices + startIndex, binIndices + startIndex, leafBoxes + startIndex, count ); #endif newItem->splitIndex += startIndex; } @@ -1792,45 +1793,45 @@ static int32_t b2BuildTree(b2DynamicTree* tree, int32_t leafCount) } b2TreeNode* rootNode = nodes + stack[0].nodeIndex; - B2_ASSERT(rootNode->parent == B2_NULL_INDEX); - B2_ASSERT(rootNode->child1 != B2_NULL_INDEX); - B2_ASSERT(rootNode->child2 != B2_NULL_INDEX); + B2_ASSERT( rootNode->parent == B2_NULL_INDEX ); + B2_ASSERT( rootNode->child1 != B2_NULL_INDEX ); + B2_ASSERT( rootNode->child2 != B2_NULL_INDEX ); b2TreeNode* child1 = nodes + rootNode->child1; b2TreeNode* child2 = nodes + rootNode->child2; - rootNode->aabb = b2AABB_Union(child1->aabb, child2->aabb); - rootNode->height = 1 + b2MaxInt16(child1->height, child2->height); + rootNode->aabb = b2AABB_Union( child1->aabb, child2->aabb ); + rootNode->height = 1 + b2MaxInt16( child1->height, child2->height ); rootNode->categoryBits = child1->categoryBits | child2->categoryBits; return stack[0].nodeIndex; } // Not safe to access tree during this operation because it may grow -int32_t b2DynamicTree_Rebuild(b2DynamicTree* tree, bool fullBuild) +int32_t b2DynamicTree_Rebuild( b2DynamicTree* tree, bool fullBuild ) { int32_t proxyCount = tree->proxyCount; - if (proxyCount == 0) + if ( proxyCount == 0 ) { return 0; } // Ensure capacity for rebuild space - if (proxyCount > tree->rebuildCapacity) + if ( proxyCount > tree->rebuildCapacity ) { int32_t newCapacity = proxyCount + proxyCount / 2; - b2Free(tree->leafIndices, tree->rebuildCapacity * sizeof(int32_t)); - tree->leafIndices = b2Alloc(newCapacity * sizeof(int32_t)); + b2Free( tree->leafIndices, tree->rebuildCapacity * sizeof( int32_t ) ); + tree->leafIndices = b2Alloc( newCapacity * sizeof( int32_t ) ); #if B2_TREE_HEURISTIC == 0 - b2Free(tree->leafCenters, tree->rebuildCapacity * sizeof(b2Vec2)); - tree->leafCenters = b2Alloc(newCapacity * sizeof(b2Vec2)); + b2Free( tree->leafCenters, tree->rebuildCapacity * sizeof( b2Vec2 ) ); + tree->leafCenters = b2Alloc( newCapacity * sizeof( b2Vec2 ) ); #else - b2Free(tree->leafBoxes, tree->rebuildCapacity * sizeof(b2AABB)); - tree->leafBoxes = b2Alloc(newCapacity * sizeof(b2AABB)); - b2Free(tree->binIndices, tree->rebuildCapacity * sizeof(int32_t)); - tree->binIndices = b2Alloc(newCapacity * sizeof(int32_t)); + b2Free( tree->leafBoxes, tree->rebuildCapacity * sizeof( b2AABB ) ); + tree->leafBoxes = b2Alloc( newCapacity * sizeof( b2AABB ) ); + b2Free( tree->binIndices, tree->rebuildCapacity * sizeof( int32_t ) ); + tree->binIndices = b2Alloc( newCapacity * sizeof( int32_t ) ); #endif tree->rebuildCapacity = newCapacity; } @@ -1858,13 +1859,13 @@ int32_t b2DynamicTree_Rebuild(b2DynamicTree* tree, bool fullBuild) // Free all internal nodes that have grown. // todo use a node growth metric instead of simply enlarged to reduce rebuild size and frequency // this should be weighed against b2_aabbMargin - while (true) + while ( true ) { - if (node->height == 0 || (node->enlarged == false && fullBuild == false)) + if ( node->height == 0 || ( node->enlarged == false && fullBuild == false ) ) { leafIndices[leafCount] = nodeIndex; #if B2_TREE_HEURISTIC == 0 - leafCenters[leafCount] = b2AABB_Center(node->aabb); + leafCenters[leafCount] = b2AABB_Center( node->aabb ); #else leafBoxes[leafCount] = node->aabb; #endif @@ -1880,8 +1881,8 @@ int32_t b2DynamicTree_Rebuild(b2DynamicTree* tree, bool fullBuild) // Handle children nodeIndex = node->child1; - B2_ASSERT(stackCount < b2_treeStackSize); - if (stackCount < b2_treeStackSize) + B2_ASSERT( stackCount < b2_treeStackSize ); + if ( stackCount < b2_treeStackSize ) { stack[stackCount++] = node->child2; } @@ -1889,12 +1890,12 @@ int32_t b2DynamicTree_Rebuild(b2DynamicTree* tree, bool fullBuild) node = nodes + nodeIndex; // Remove doomed node - b2FreeNode(tree, doomedNodeIndex); + b2FreeNode( tree, doomedNodeIndex ); continue; } - if (stackCount == 0) + if ( stackCount == 0 ) { break; } @@ -1905,20 +1906,20 @@ int32_t b2DynamicTree_Rebuild(b2DynamicTree* tree, bool fullBuild) #if B2_VALIDATE == 1 int32_t capacity = tree->nodeCapacity; - for (int32_t i = 0; i < capacity; ++i) + for ( int32_t i = 0; i < capacity; ++i ) { - if (nodes[i].height >= 0) + if ( nodes[i].height >= 0 ) { - B2_ASSERT(nodes[i].enlarged == false); + B2_ASSERT( nodes[i].enlarged == false ); } } #endif - B2_ASSERT(leafCount <= proxyCount); + B2_ASSERT( leafCount <= proxyCount ); - tree->root = b2BuildTree(tree, leafCount); + tree->root = b2BuildTree( tree, leafCount ); - b2DynamicTree_Validate(tree); + b2DynamicTree_Validate( tree ); return leafCount; } diff --git a/src/geometry.c b/src/geometry.c index 173e6776..03b05473 100644 --- a/src/geometry.c +++ b/src/geometry.c @@ -11,18 +11,18 @@ #include #include -_Static_assert(b2_maxPolygonVertices > 2, "must be 3 or more"); +_Static_assert( b2_maxPolygonVertices > 2, "must be 3 or more" ); -bool b2IsValidRay(const b2RayCastInput* input) +bool b2IsValidRay( const b2RayCastInput* input ) { - bool isValid = b2Vec2_IsValid(input->origin) && b2Vec2_IsValid(input->translation) && b2IsValid(input->maxFraction) && + bool isValid = b2Vec2_IsValid( input->origin ) && b2Vec2_IsValid( input->translation ) && b2IsValid( input->maxFraction ) && 0.0f <= input->maxFraction && input->maxFraction < b2_huge; return isValid; } -static b2Vec2 b2ComputePolygonCentroid(const b2Vec2* vertices, int32_t count) +static b2Vec2 b2ComputePolygonCentroid( const b2Vec2* vertices, int32_t count ) { - b2Vec2 center = {0.0f, 0.0f}; + b2Vec2 center = { 0.0f, 0.0f }; float area = 0.0f; // Get a reference point for forming triangles. @@ -31,168 +31,168 @@ static b2Vec2 b2ComputePolygonCentroid(const b2Vec2* vertices, int32_t count) const float inv3 = 1.0f / 3.0f; - for (int32_t i = 1; i < count - 1; ++i) + for ( int32_t i = 1; i < count - 1; ++i ) { // Triangle edges - b2Vec2 e1 = b2Sub(vertices[i], origin); - b2Vec2 e2 = b2Sub(vertices[i + 1], origin); - float a = 0.5f * b2Cross(e1, e2); + b2Vec2 e1 = b2Sub( vertices[i], origin ); + b2Vec2 e2 = b2Sub( vertices[i + 1], origin ); + float a = 0.5f * b2Cross( e1, e2 ); // Area weighted centroid - center = b2MulAdd(center, a * inv3, b2Add(e1, e2)); + center = b2MulAdd( center, a * inv3, b2Add( e1, e2 ) ); area += a; } - B2_ASSERT(area > FLT_EPSILON); + B2_ASSERT( area > FLT_EPSILON ); float invArea = 1.0f / area; center.x *= invArea; center.y *= invArea; // Restore offset - center = b2Add(origin, center); + center = b2Add( origin, center ); return center; } -b2Polygon b2MakePolygon(const b2Hull* hull, float radius) +b2Polygon b2MakePolygon( const b2Hull* hull, float radius ) { - B2_ASSERT(b2ValidateHull(hull)); + B2_ASSERT( b2ValidateHull( hull ) ); - if (hull->count < 3) + if ( hull->count < 3 ) { // Handle a bad hull when assertions are disabled - return b2MakeSquare(0.5f); + return b2MakeSquare( 0.5f ); } - b2Polygon shape = {0}; + b2Polygon shape = { 0 }; shape.count = hull->count; shape.radius = radius; // Copy vertices - for (int32_t i = 0; i < shape.count; ++i) + for ( int32_t i = 0; i < shape.count; ++i ) { shape.vertices[i] = hull->points[i]; } // Compute normals. Ensure the edges have non-zero length. - for (int32_t i = 0; i < shape.count; ++i) + for ( int32_t i = 0; i < shape.count; ++i ) { int32_t i1 = i; int32_t i2 = i + 1 < shape.count ? i + 1 : 0; - b2Vec2 edge = b2Sub(shape.vertices[i2], shape.vertices[i1]); - B2_ASSERT(b2Dot(edge, edge) > FLT_EPSILON * FLT_EPSILON); - shape.normals[i] = b2Normalize(b2CrossVS(edge, 1.0f)); + b2Vec2 edge = b2Sub( shape.vertices[i2], shape.vertices[i1] ); + B2_ASSERT( b2Dot( edge, edge ) > FLT_EPSILON * FLT_EPSILON ); + shape.normals[i] = b2Normalize( b2CrossVS( edge, 1.0f ) ); } - shape.centroid = b2ComputePolygonCentroid(shape.vertices, shape.count); + shape.centroid = b2ComputePolygonCentroid( shape.vertices, shape.count ); return shape; } -b2Polygon b2MakeOffsetPolygon(const b2Hull* hull, float radius, b2Transform transform) +b2Polygon b2MakeOffsetPolygon( const b2Hull* hull, float radius, b2Transform transform ) { - B2_ASSERT(b2ValidateHull(hull)); + B2_ASSERT( b2ValidateHull( hull ) ); - if (hull->count < 3) + if ( hull->count < 3 ) { // Handle a bad hull when assertions are disabled - return b2MakeSquare(0.5f); + return b2MakeSquare( 0.5f ); } - b2Polygon shape = {0}; + b2Polygon shape = { 0 }; shape.count = hull->count; shape.radius = radius; // Copy vertices - for (int32_t i = 0; i < shape.count; ++i) + for ( int32_t i = 0; i < shape.count; ++i ) { - shape.vertices[i] = b2TransformPoint(transform, hull->points[i]); + shape.vertices[i] = b2TransformPoint( transform, hull->points[i] ); } // Compute normals. Ensure the edges have non-zero length. - for (int32_t i = 0; i < shape.count; ++i) + for ( int32_t i = 0; i < shape.count; ++i ) { int32_t i1 = i; int32_t i2 = i + 1 < shape.count ? i + 1 : 0; - b2Vec2 edge = b2Sub(shape.vertices[i2], shape.vertices[i1]); - B2_ASSERT(b2Dot(edge, edge) > FLT_EPSILON * FLT_EPSILON); - shape.normals[i] = b2Normalize(b2CrossVS(edge, 1.0f)); + b2Vec2 edge = b2Sub( shape.vertices[i2], shape.vertices[i1] ); + B2_ASSERT( b2Dot( edge, edge ) > FLT_EPSILON * FLT_EPSILON ); + shape.normals[i] = b2Normalize( b2CrossVS( edge, 1.0f ) ); } - shape.centroid = b2ComputePolygonCentroid(shape.vertices, shape.count); + shape.centroid = b2ComputePolygonCentroid( shape.vertices, shape.count ); return shape; } -b2Polygon b2MakeSquare(float h) +b2Polygon b2MakeSquare( float h ) { - return b2MakeBox(h, h); + return b2MakeBox( h, h ); } -b2Polygon b2MakeBox(float hx, float hy) +b2Polygon b2MakeBox( float hx, float hy ) { - B2_ASSERT(b2IsValid(hx) && hx > 0.0f); - B2_ASSERT(b2IsValid(hy) && hy > 0.0f); + B2_ASSERT( b2IsValid( hx ) && hx > 0.0f ); + B2_ASSERT( b2IsValid( hy ) && hy > 0.0f ); - b2Polygon shape = {0}; + b2Polygon shape = { 0 }; shape.count = 4; - shape.vertices[0] = (b2Vec2){-hx, -hy}; - shape.vertices[1] = (b2Vec2){hx, -hy}; - shape.vertices[2] = (b2Vec2){hx, hy}; - shape.vertices[3] = (b2Vec2){-hx, hy}; - shape.normals[0] = (b2Vec2){0.0f, -1.0f}; - shape.normals[1] = (b2Vec2){1.0f, 0.0f}; - shape.normals[2] = (b2Vec2){0.0f, 1.0f}; - shape.normals[3] = (b2Vec2){-1.0f, 0.0f}; + shape.vertices[0] = ( b2Vec2 ){ -hx, -hy }; + shape.vertices[1] = ( b2Vec2 ){ hx, -hy }; + shape.vertices[2] = ( b2Vec2 ){ hx, hy }; + shape.vertices[3] = ( b2Vec2 ){ -hx, hy }; + shape.normals[0] = ( b2Vec2 ){ 0.0f, -1.0f }; + shape.normals[1] = ( b2Vec2 ){ 1.0f, 0.0f }; + shape.normals[2] = ( b2Vec2 ){ 0.0f, 1.0f }; + shape.normals[3] = ( b2Vec2 ){ -1.0f, 0.0f }; shape.radius = 0.0f; shape.centroid = b2Vec2_zero; return shape; } -b2Polygon b2MakeRoundedBox(float hx, float hy, float radius) +b2Polygon b2MakeRoundedBox( float hx, float hy, float radius ) { - b2Polygon shape = b2MakeBox(hx, hy); + b2Polygon shape = b2MakeBox( hx, hy ); shape.radius = radius; return shape; } -b2Polygon b2MakeOffsetBox(float hx, float hy, b2Vec2 center, float angle) +b2Polygon b2MakeOffsetBox( float hx, float hy, b2Vec2 center, float angle ) { b2Transform xf; xf.p = center; - xf.q = b2MakeRot(angle); + xf.q = b2MakeRot( angle ); - b2Polygon shape = {0}; + b2Polygon shape = { 0 }; shape.count = 4; - shape.vertices[0] = b2TransformPoint(xf, (b2Vec2){-hx, -hy}); - shape.vertices[1] = b2TransformPoint(xf, (b2Vec2){hx, -hy}); - shape.vertices[2] = b2TransformPoint(xf, (b2Vec2){hx, hy}); - shape.vertices[3] = b2TransformPoint(xf, (b2Vec2){-hx, hy}); - shape.normals[0] = b2RotateVector(xf.q, (b2Vec2){0.0f, -1.0f}); - shape.normals[1] = b2RotateVector(xf.q, (b2Vec2){1.0f, 0.0f}); - shape.normals[2] = b2RotateVector(xf.q, (b2Vec2){0.0f, 1.0f}); - shape.normals[3] = b2RotateVector(xf.q, (b2Vec2){-1.0f, 0.0f}); + shape.vertices[0] = b2TransformPoint( xf, ( b2Vec2 ){ -hx, -hy } ); + shape.vertices[1] = b2TransformPoint( xf, ( b2Vec2 ){ hx, -hy } ); + shape.vertices[2] = b2TransformPoint( xf, ( b2Vec2 ){ hx, hy } ); + shape.vertices[3] = b2TransformPoint( xf, ( b2Vec2 ){ -hx, hy } ); + shape.normals[0] = b2RotateVector( xf.q, ( b2Vec2 ){ 0.0f, -1.0f } ); + shape.normals[1] = b2RotateVector( xf.q, ( b2Vec2 ){ 1.0f, 0.0f } ); + shape.normals[2] = b2RotateVector( xf.q, ( b2Vec2 ){ 0.0f, 1.0f } ); + shape.normals[3] = b2RotateVector( xf.q, ( b2Vec2 ){ -1.0f, 0.0f } ); shape.radius = 0.0f; shape.centroid = center; return shape; } -b2Polygon b2TransformPolygon(b2Transform transform, const b2Polygon* polygon) +b2Polygon b2TransformPolygon( b2Transform transform, const b2Polygon* polygon ) { b2Polygon p = *polygon; - for (int i = 0; i < p.count; ++i) + for ( int i = 0; i < p.count; ++i ) { - p.vertices[i] = b2TransformPoint(transform, p.vertices[i]); - p.normals[i] = b2RotateVector(transform.q, p.normals[i]); + p.vertices[i] = b2TransformPoint( transform, p.vertices[i] ); + p.normals[i] = b2RotateVector( transform.q, p.normals[i] ); } - p.centroid = b2TransformPoint(transform, p.centroid); + p.centroid = b2TransformPoint( transform, p.centroid ); return p; } -b2MassData b2ComputeCircleMass(const b2Circle* shape, float density) +b2MassData b2ComputeCircleMass( const b2Circle* shape, float density ) { float rr = shape->radius * shape->radius; @@ -201,27 +201,27 @@ b2MassData b2ComputeCircleMass(const b2Circle* shape, float density) massData.center = shape->center; // inertia about the local origin - massData.rotationalInertia = massData.mass * (0.5f * rr + b2Dot(shape->center, shape->center)); + massData.rotationalInertia = massData.mass * ( 0.5f * rr + b2Dot( shape->center, shape->center ) ); return massData; } -b2MassData b2ComputeCapsuleMass(const b2Capsule* shape, float density) +b2MassData b2ComputeCapsuleMass( const b2Capsule* shape, float density ) { float radius = shape->radius; float rr = radius * radius; b2Vec2 p1 = shape->center1; b2Vec2 p2 = shape->center2; - float length = b2Length(b2Sub(p2, p1)); + float length = b2Length( b2Sub( p2, p1 ) ); float ll = length * length; - float circleMass = density * (b2_pi * radius * radius); - float boxMass = density * (2.0f * radius * length); + float circleMass = density * ( b2_pi * radius * radius ); + float boxMass = density * ( 2.0f * radius * length ); b2MassData massData; massData.mass = circleMass + boxMass; - massData.center.x = 0.5f * (p1.x + p2.x); - massData.center.y = 0.5f * (p1.y + p2.y); + massData.center.x = 0.5f * ( p1.x + p2.x ); + massData.center.y = 0.5f * ( p1.y + p2.y ); // two offset half circles, both halves add up to full circle and each half is offset by half length // semi-circle centroid = 4 r / 3 pi @@ -233,22 +233,22 @@ b2MassData b2ComputeCapsuleMass(const b2Capsule* shape, float density) // I verified this formula by computing the convex hull of a 128 vertex capsule // half circle centroid - float lc = 4.0f * radius / (3.0f * b2_pi); + float lc = 4.0f * radius / ( 3.0f * b2_pi ); // half length of rectangular portion of capsule float h = 0.5f * length; - float circleInertia = circleMass * (0.5f * rr + h * h + 2.0f * h * lc); - float boxInertia = boxMass * (4.0f * rr + ll) / 12.0f; + float circleInertia = circleMass * ( 0.5f * rr + h * h + 2.0f * h * lc ); + float boxInertia = boxMass * ( 4.0f * rr + ll ) / 12.0f; massData.rotationalInertia = circleInertia + boxInertia; // inertia about the local origin - massData.rotationalInertia += massData.mass * b2Dot(massData.center, massData.center); + massData.rotationalInertia += massData.mass * b2Dot( massData.center, massData.center ); return massData; } -b2MassData b2ComputePolygonMass(const b2Polygon* shape, float density) +b2MassData b2ComputePolygonMass( const b2Polygon* shape, float density ) { // Polygon mass, centroid, and inertia. // Let rho be the polygon density in mass per unit area. @@ -274,52 +274,52 @@ b2MassData b2ComputePolygonMass(const b2Polygon* shape, float density) // // The rest of the derivation is handled by computer algebra. - B2_ASSERT(shape->count > 0); + B2_ASSERT( shape->count > 0 ); - if (shape->count == 1) + if ( shape->count == 1 ) { b2Circle circle; circle.center = shape->vertices[0]; circle.radius = shape->radius; - return b2ComputeCircleMass(&circle, density); + return b2ComputeCircleMass( &circle, density ); } - if (shape->count == 2) + if ( shape->count == 2 ) { b2Capsule capsule; capsule.center1 = shape->vertices[0]; capsule.center2 = shape->vertices[1]; capsule.radius = shape->radius; - return b2ComputeCapsuleMass(&capsule, density); + return b2ComputeCapsuleMass( &capsule, density ); } - b2Vec2 vertices[b2_maxPolygonVertices] = {0}; + b2Vec2 vertices[b2_maxPolygonVertices] = { 0 }; int32_t count = shape->count; float radius = shape->radius; - if (radius > 0.0f) + if ( radius > 0.0f ) { // Approximate mass of rounded polygons by pushing out the vertices. float sqrt2 = 1.412f; - for (int32_t i = 0; i < count; ++i) + for ( int32_t i = 0; i < count; ++i ) { int32_t j = i == 0 ? count - 1 : i - 1; b2Vec2 n1 = shape->normals[j]; b2Vec2 n2 = shape->normals[i]; - b2Vec2 mid = b2Normalize(b2Add(n1, n2)); - vertices[i] = b2MulAdd(shape->vertices[i], sqrt2 * radius, mid); + b2Vec2 mid = b2Normalize( b2Add( n1, n2 ) ); + vertices[i] = b2MulAdd( shape->vertices[i], sqrt2 * radius, mid ); } } else { - for (int32_t i = 0; i < count; ++i) + for ( int32_t i = 0; i < count; ++i ) { vertices[i] = shape->vertices[i]; } } - b2Vec2 center = {0.0f, 0.0f}; + b2Vec2 center = { 0.0f, 0.0f }; float area = 0.0f; float rotationalInertia = 0.0f; @@ -329,19 +329,19 @@ b2MassData b2ComputePolygonMass(const b2Polygon* shape, float density) const float inv3 = 1.0f / 3.0f; - for (int32_t i = 1; i < count - 1; ++i) + for ( int32_t i = 1; i < count - 1; ++i ) { // Triangle edges - b2Vec2 e1 = b2Sub(vertices[i], r); - b2Vec2 e2 = b2Sub(vertices[i + 1], r); + b2Vec2 e1 = b2Sub( vertices[i], r ); + b2Vec2 e2 = b2Sub( vertices[i + 1], r ); - float D = b2Cross(e1, e2); + float D = b2Cross( e1, e2 ); float triangleArea = 0.5f * D; area += triangleArea; // Area weighted centroid, r at origin - center = b2MulAdd(center, triangleArea * inv3, b2Add(e1, e2)); + center = b2MulAdd( center, triangleArea * inv3, b2Add( e1, e2 ) ); float ex1 = e1.x, ey1 = e1.y; float ex2 = e2.x, ey2 = e2.y; @@ -349,7 +349,7 @@ b2MassData b2ComputePolygonMass(const b2Polygon* shape, float density) float intx2 = ex1 * ex1 + ex2 * ex1 + ex2 * ex2; float inty2 = ey1 * ey1 + ey2 * ey1 + ey2 * ey2; - rotationalInertia += (0.25f * inv3 * D) * (intx2 + inty2); + rotationalInertia += ( 0.25f * inv3 * D ) * ( intx2 + inty2 ); } b2MassData massData; @@ -358,94 +358,94 @@ b2MassData b2ComputePolygonMass(const b2Polygon* shape, float density) massData.mass = density * area; // Center of mass, shift back from origin at r - B2_ASSERT(area > FLT_EPSILON); + B2_ASSERT( area > FLT_EPSILON ); float invArea = 1.0f / area; center.x *= invArea; center.y *= invArea; - massData.center = b2Add(r, center); + massData.center = b2Add( r, center ); // Inertia tensor relative to the local origin (point s). massData.rotationalInertia = density * rotationalInertia; // Shift to center of mass then to original body origin. - massData.rotationalInertia += massData.mass * (b2Dot(massData.center, massData.center) - b2Dot(center, center)); + massData.rotationalInertia += massData.mass * ( b2Dot( massData.center, massData.center ) - b2Dot( center, center ) ); return massData; } -b2AABB b2ComputeCircleAABB(const b2Circle* shape, b2Transform xf) +b2AABB b2ComputeCircleAABB( const b2Circle* shape, b2Transform xf ) { - b2Vec2 p = b2TransformPoint(xf, shape->center); + b2Vec2 p = b2TransformPoint( xf, shape->center ); float r = shape->radius; - b2AABB aabb = {{p.x - r, p.y - r}, {p.x + r, p.y + r}}; + b2AABB aabb = { { p.x - r, p.y - r }, { p.x + r, p.y + r } }; return aabb; } -b2AABB b2ComputeCapsuleAABB(const b2Capsule* shape, b2Transform xf) +b2AABB b2ComputeCapsuleAABB( const b2Capsule* shape, b2Transform xf ) { - b2Vec2 v1 = b2TransformPoint(xf, shape->center1); - b2Vec2 v2 = b2TransformPoint(xf, shape->center2); + b2Vec2 v1 = b2TransformPoint( xf, shape->center1 ); + b2Vec2 v2 = b2TransformPoint( xf, shape->center2 ); - b2Vec2 r = {shape->radius, shape->radius}; - b2Vec2 lower = b2Sub(b2Min(v1, v2), r); - b2Vec2 upper = b2Add(b2Max(v1, v2), r); + b2Vec2 r = { shape->radius, shape->radius }; + b2Vec2 lower = b2Sub( b2Min( v1, v2 ), r ); + b2Vec2 upper = b2Add( b2Max( v1, v2 ), r ); - b2AABB aabb = {lower, upper}; + b2AABB aabb = { lower, upper }; return aabb; } -b2AABB b2ComputePolygonAABB(const b2Polygon* shape, b2Transform xf) +b2AABB b2ComputePolygonAABB( const b2Polygon* shape, b2Transform xf ) { - B2_ASSERT(shape->count > 0); - b2Vec2 lower = b2TransformPoint(xf, shape->vertices[0]); + B2_ASSERT( shape->count > 0 ); + b2Vec2 lower = b2TransformPoint( xf, shape->vertices[0] ); b2Vec2 upper = lower; - for (int32_t i = 1; i < shape->count; ++i) + for ( int32_t i = 1; i < shape->count; ++i ) { - b2Vec2 v = b2TransformPoint(xf, shape->vertices[i]); - lower = b2Min(lower, v); - upper = b2Max(upper, v); + b2Vec2 v = b2TransformPoint( xf, shape->vertices[i] ); + lower = b2Min( lower, v ); + upper = b2Max( upper, v ); } - b2Vec2 r = {shape->radius, shape->radius}; - lower = b2Sub(lower, r); - upper = b2Add(upper, r); + b2Vec2 r = { shape->radius, shape->radius }; + lower = b2Sub( lower, r ); + upper = b2Add( upper, r ); - b2AABB aabb = {lower, upper}; + b2AABB aabb = { lower, upper }; return aabb; } -b2AABB b2ComputeSegmentAABB(const b2Segment* shape, b2Transform xf) +b2AABB b2ComputeSegmentAABB( const b2Segment* shape, b2Transform xf ) { - b2Vec2 v1 = b2TransformPoint(xf, shape->point1); - b2Vec2 v2 = b2TransformPoint(xf, shape->point2); + b2Vec2 v1 = b2TransformPoint( xf, shape->point1 ); + b2Vec2 v2 = b2TransformPoint( xf, shape->point2 ); - b2Vec2 lower = b2Min(v1, v2); - b2Vec2 upper = b2Max(v1, v2); + b2Vec2 lower = b2Min( v1, v2 ); + b2Vec2 upper = b2Max( v1, v2 ); - b2AABB aabb = {lower, upper}; + b2AABB aabb = { lower, upper }; return aabb; } -bool b2PointInCircle(b2Vec2 point, const b2Circle* shape) +bool b2PointInCircle( b2Vec2 point, const b2Circle* shape ) { b2Vec2 center = shape->center; - return b2DistanceSquared(point, center) <= shape->radius * shape->radius; + return b2DistanceSquared( point, center ) <= shape->radius * shape->radius; } -bool b2PointInCapsule(b2Vec2 point, const b2Capsule* shape) +bool b2PointInCapsule( b2Vec2 point, const b2Capsule* shape ) { float rr = shape->radius * shape->radius; b2Vec2 p1 = shape->center1; b2Vec2 p2 = shape->center2; - b2Vec2 d = b2Sub(p2, p1); - float dd = b2Dot(d, d); - if (dd == 0.0f) + b2Vec2 d = b2Sub( p2, p1 ); + float dd = b2Dot( d, d ); + if ( dd == 0.0f ) { // Capsule is really a circle - return b2DistanceSquared(point, p1) <= rr; + return b2DistanceSquared( point, p1 ) <= rr; } // Get closest point on capsule segment @@ -453,44 +453,44 @@ bool b2PointInCapsule(b2Vec2 point, const b2Capsule* shape) // dot(point - c, d) = 0 // dot(point - p1 - t * d, d) = 0 // t = dot(point - p1, d) / dot(d, d) - float t = b2Dot(b2Sub(point, p1), d) / dd; - t = b2ClampFloat(t, 0.0f, 1.0f); - b2Vec2 c = b2MulAdd(p1, t, d); + float t = b2Dot( b2Sub( point, p1 ), d ) / dd; + t = b2ClampFloat( t, 0.0f, 1.0f ); + b2Vec2 c = b2MulAdd( p1, t, d ); // Is query point within radius around closest point? - return b2DistanceSquared(point, c) <= rr; + return b2DistanceSquared( point, c ) <= rr; } -bool b2PointInPolygon(b2Vec2 point, const b2Polygon* shape) +bool b2PointInPolygon( b2Vec2 point, const b2Polygon* shape ) { - b2DistanceInput input = {0}; - input.proxyA = b2MakeProxy(shape->vertices, shape->count, 0.0f); - input.proxyB = b2MakeProxy(&point, 1, 0.0f); + b2DistanceInput input = { 0 }; + input.proxyA = b2MakeProxy( shape->vertices, shape->count, 0.0f ); + input.proxyB = b2MakeProxy( &point, 1, 0.0f ); input.transformA = b2Transform_identity; input.transformB = b2Transform_identity; input.useRadii = false; - b2DistanceCache cache = {0}; - b2DistanceOutput output = b2ShapeDistance(&cache, &input, NULL, 0); + b2DistanceCache cache = { 0 }; + b2DistanceOutput output = b2ShapeDistance( &cache, &input, NULL, 0 ); return output.distance <= shape->radius; } // Precision Improvements for Ray / Sphere Intersection - Ray Tracing Gems 2019 // http://www.codercorner.com/blog/?p=321 -b2CastOutput b2RayCastCircle(const b2RayCastInput* input, const b2Circle* shape) +b2CastOutput b2RayCastCircle( const b2RayCastInput* input, const b2Circle* shape ) { - B2_ASSERT(b2IsValidRay(input)); + B2_ASSERT( b2IsValidRay( input ) ); b2Vec2 p = shape->center; - b2CastOutput output = {0}; + b2CastOutput output = { 0 }; // Shift ray so circle center is the origin - b2Vec2 s = b2Sub(input->origin, p); + b2Vec2 s = b2Sub( input->origin, p ); float length; - b2Vec2 d = b2GetLengthAndNormalize(&length, input->translation); - if (length == 0.0f) + b2Vec2 d = b2GetLengthAndNormalize( &length, input->translation ); + if ( length == 0.0f ) { // zero length ray return output; @@ -499,90 +499,90 @@ b2CastOutput b2RayCastCircle(const b2RayCastInput* input, const b2Circle* shape) // Find closest point on ray to origin // solve: dot(s + t * d, d) = 0 - float t = -b2Dot(s, d); + float t = -b2Dot( s, d ); // c is the closest point on the line to the origin - b2Vec2 c = b2MulAdd(s, t, d); + b2Vec2 c = b2MulAdd( s, t, d ); - float cc = b2Dot(c, c); + float cc = b2Dot( c, c ); float r = shape->radius; float rr = r * r; - if (cc > rr) + if ( cc > rr ) { // closest point is outside the circle return output; } // Pythagorus - float h = sqrtf(rr - cc); + float h = sqrtf( rr - cc ); float fraction = t - h; - if (fraction < 0.0f || input->maxFraction * length < fraction) + if ( fraction < 0.0f || input->maxFraction * length < fraction ) { // outside the range of the ray segment return output; } - b2Vec2 hitPoint = b2MulAdd(s, fraction, d); + b2Vec2 hitPoint = b2MulAdd( s, fraction, d ); output.fraction = fraction / length; - output.normal = b2Normalize(hitPoint); - output.point = b2MulAdd(p, shape->radius, output.normal); + output.normal = b2Normalize( hitPoint ); + output.point = b2MulAdd( p, shape->radius, output.normal ); output.hit = true; return output; } -b2CastOutput b2RayCastCapsule(const b2RayCastInput* input, const b2Capsule* shape) +b2CastOutput b2RayCastCapsule( const b2RayCastInput* input, const b2Capsule* shape ) { - B2_ASSERT(b2IsValidRay(input)); + B2_ASSERT( b2IsValidRay( input ) ); - b2CastOutput output = {0}; + b2CastOutput output = { 0 }; b2Vec2 v1 = shape->center1; b2Vec2 v2 = shape->center2; - b2Vec2 e = b2Sub(v2, v1); + b2Vec2 e = b2Sub( v2, v1 ); float capsuleLength; - b2Vec2 a = b2GetLengthAndNormalize(&capsuleLength, e); + b2Vec2 a = b2GetLengthAndNormalize( &capsuleLength, e ); - if (capsuleLength < FLT_EPSILON) + if ( capsuleLength < FLT_EPSILON ) { // Capsule is really a circle - b2Circle circle = {v1, shape->radius}; - return b2RayCastCircle(input, &circle); + b2Circle circle = { v1, shape->radius }; + return b2RayCastCircle( input, &circle ); } b2Vec2 p1 = input->origin; b2Vec2 d = input->translation; // Ray from capsule start to ray start - b2Vec2 q = b2Sub(p1, v1); - float qa = b2Dot(q, a); + b2Vec2 q = b2Sub( p1, v1 ); + float qa = b2Dot( q, a ); // Vector to ray start that is perpendicular to capsule axis - b2Vec2 qp = b2MulAdd(q, -qa, a); + b2Vec2 qp = b2MulAdd( q, -qa, a ); float radius = shape->radius; // Does the ray start within the infinite length capsule? - if (b2Dot(qp, qp) < radius * radius) + if ( b2Dot( qp, qp ) < radius * radius ) { - if (qa < 0.0f) + if ( qa < 0.0f ) { // start point behind capsule segment - b2Circle circle = {v1, shape->radius}; - return b2RayCastCircle(input, &circle); + b2Circle circle = { v1, shape->radius }; + return b2RayCastCircle( input, &circle ); } - if (qa > 1.0f) + if ( qa > 1.0f ) { // start point ahead of capsule segment - b2Circle circle = {v2, shape->radius}; - return b2RayCastCircle(input, &circle); + b2Circle circle = { v2, shape->radius }; + return b2RayCastCircle( input, &circle ); } // ray starts inside capsule -> no hit @@ -590,10 +590,10 @@ b2CastOutput b2RayCastCapsule(const b2RayCastInput* input, const b2Capsule* shap } // Perpendicular to capsule axis, pointing right - b2Vec2 n = {a.y, -a.x}; + b2Vec2 n = { a.y, -a.x }; float rayLength; - b2Vec2 u = b2GetLengthAndNormalize(&rayLength, d); + b2Vec2 u = b2GetLengthAndNormalize( &rayLength, d ); // Intersect ray with infinite length capsule // v1 + radius * n + s1 * a = p1 + s2 * u @@ -606,26 +606,26 @@ b2CastOutput b2RayCastCapsule(const b2RayCastInput* input, const b2Capsule* shap // Cramer's rule [a -u] float den = -a.x * u.y + u.x * a.y; - if (-FLT_EPSILON < den && den < FLT_EPSILON) + if ( -FLT_EPSILON < den && den < FLT_EPSILON ) { // Ray is parallel to capsule and outside infinite length capsule return output; } - b2Vec2 b1 = b2MulSub(q, radius, n); - b2Vec2 b2 = b2MulAdd(q, radius, n); + b2Vec2 b1 = b2MulSub( q, radius, n ); + b2Vec2 b2 = b2MulAdd( q, radius, n ); float invDen = 1.0f / den; // Cramer's rule [a b1] - float s21 = (a.x * b1.y - b1.x * a.y) * invDen; + float s21 = ( a.x * b1.y - b1.x * a.y ) * invDen; // Cramer's rule [a b2] - float s22 = (a.x * b2.y - b2.x * a.y) * invDen; + float s22 = ( a.x * b2.y - b2.x * a.y ) * invDen; float s2; b2Vec2 b; - if (s21 < s22) + if ( s21 < s22 ) { s2 = s21; b = b1; @@ -634,34 +634,34 @@ b2CastOutput b2RayCastCapsule(const b2RayCastInput* input, const b2Capsule* shap { s2 = s22; b = b2; - n = b2Neg(n); + n = b2Neg( n ); } - if (s2 < 0.0f || input->maxFraction * rayLength < s2) + if ( s2 < 0.0f || input->maxFraction * rayLength < s2 ) { return output; } // Cramer's rule [b -u] - float s1 = (-b.x * u.y + u.x * b.y) * invDen; + float s1 = ( -b.x * u.y + u.x * b.y ) * invDen; - if (s1 < 0.0f) + if ( s1 < 0.0f ) { // ray passes behind capsule segment - b2Circle circle = {v1, shape->radius}; - return b2RayCastCircle(input, &circle); + b2Circle circle = { v1, shape->radius }; + return b2RayCastCircle( input, &circle ); } - else if (capsuleLength < s1) + else if ( capsuleLength < s1 ) { // ray passes ahead of capsule segment - b2Circle circle = {v2, shape->radius}; - return b2RayCastCircle(input, &circle); + b2Circle circle = { v2, shape->radius }; + return b2RayCastCircle( input, &circle ); } else { // ray hits capsule side output.fraction = s2 / rayLength; - output.point = b2Add(b2Lerp(v1, v2, s1 / capsuleLength), b2MulSV(shape->radius, n)); + output.point = b2Add( b2Lerp( v1, v2, s1 / capsuleLength ), b2MulSV( shape->radius, n ) ); output.normal = n; output.hit = true; return output; @@ -669,15 +669,15 @@ b2CastOutput b2RayCastCapsule(const b2RayCastInput* input, const b2Capsule* shap } // Ray vs line segment -b2CastOutput b2RayCastSegment(const b2RayCastInput* input, const b2Segment* shape, bool oneSided) +b2CastOutput b2RayCastSegment( const b2RayCastInput* input, const b2Segment* shape, bool oneSided ) { - if (oneSided) + if ( oneSided ) { // Skip left-side collision - float offset = b2Cross(b2Sub(input->origin, shape->point1), b2Sub(shape->point2, shape->point1)); - if (offset < 0.0f) + float offset = b2Cross( b2Sub( input->origin, shape->point1 ), b2Sub( shape->point2, shape->point1 ) ); + if ( offset < 0.0f ) { - b2CastOutput output = {0}; + b2CastOutput output = { 0 }; return output; } } @@ -688,73 +688,73 @@ b2CastOutput b2RayCastSegment(const b2RayCastInput* input, const b2Segment* shap b2Vec2 v1 = shape->point1; b2Vec2 v2 = shape->point2; - b2Vec2 e = b2Sub(v2, v1); + b2Vec2 e = b2Sub( v2, v1 ); - b2CastOutput output = {0}; + b2CastOutput output = { 0 }; float length; - b2Vec2 eUnit = b2GetLengthAndNormalize(&length, e); - if (length == 0.0f) + b2Vec2 eUnit = b2GetLengthAndNormalize( &length, e ); + if ( length == 0.0f ) { return output; } // Normal points to the right, looking from v1 towards v2 - b2Vec2 normal = b2RightPerp(eUnit); + b2Vec2 normal = b2RightPerp( eUnit ); // Intersect ray with infinite segment using normal // Similar to intersecting a ray with an infinite plane // p = p1 + t * d // dot(normal, p - v1) = 0 // dot(normal, p1 - v1) + t * dot(normal, d) = 0 - float numerator = b2Dot(normal, b2Sub(v1, p1)); - float denominator = b2Dot(normal, d); + float numerator = b2Dot( normal, b2Sub( v1, p1 ) ); + float denominator = b2Dot( normal, d ); - if (denominator == 0.0f) + if ( denominator == 0.0f ) { // parallel return output; } float t = numerator / denominator; - if (t < 0.0f || input->maxFraction < t) + if ( t < 0.0f || input->maxFraction < t ) { // out of ray range return output; } // Intersection point on infinite segment - b2Vec2 p = b2MulAdd(p1, t, d); + b2Vec2 p = b2MulAdd( p1, t, d ); // Compute position of p along segment // p = v1 + s * e // s = dot(p - v1, e) / dot(e, e) - float s = b2Dot(b2Sub(p, v1), eUnit); - if (s < 0.0f || length < s) + float s = b2Dot( b2Sub( p, v1 ), eUnit ); + if ( s < 0.0f || length < s ) { // out of segment range return output; } - if (numerator > 0.0f) + if ( numerator > 0.0f ) { - normal = b2Neg(normal); + normal = b2Neg( normal ); } output.fraction = t; - output.point = b2MulAdd(p1, t, d); + output.point = b2MulAdd( p1, t, d ); output.normal = normal; output.hit = true; return output; } -b2CastOutput b2RayCastPolygon(const b2RayCastInput* input, const b2Polygon* shape) +b2CastOutput b2RayCastPolygon( const b2RayCastInput* input, const b2Polygon* shape ) { - B2_ASSERT(b2IsValidRay(input)); + B2_ASSERT( b2IsValidRay( input ) ); - if (shape->radius == 0.0f) + if ( shape->radius == 0.0f ) { // Put the ray into the polygon's frame of reference. b2Vec2 p1 = input->origin; @@ -764,19 +764,19 @@ b2CastOutput b2RayCastPolygon(const b2RayCastInput* input, const b2Polygon* shap int32_t index = -1; - b2CastOutput output = {0}; + b2CastOutput output = { 0 }; - for (int32_t i = 0; i < shape->count; ++i) + for ( int32_t i = 0; i < shape->count; ++i ) { // p = p1 + a * d // dot(normal, p - v) = 0 // dot(normal, p1 - v) + a * dot(normal, d) = 0 - float numerator = b2Dot(shape->normals[i], b2Sub(shape->vertices[i], p1)); - float denominator = b2Dot(shape->normals[i], d); + float numerator = b2Dot( shape->normals[i], b2Sub( shape->vertices[i], p1 ) ); + float denominator = b2Dot( shape->normals[i], d ); - if (denominator == 0.0f) + if ( denominator == 0.0f ) { - if (numerator < 0.0f) + if ( numerator < 0.0f ) { return output; } @@ -787,14 +787,14 @@ b2CastOutput b2RayCastPolygon(const b2RayCastInput* input, const b2Polygon* shap // lower < numerator / denominator, where denominator < 0 // Since denominator < 0, we have to flip the inequality: // lower < numerator / denominator <==> denominator * lower > numerator. - if (denominator < 0.0f && numerator < lower * denominator) + if ( denominator < 0.0f && numerator < lower * denominator ) { // Increase lower. // The segment enters this half-space. lower = numerator / denominator; index = i; } - else if (denominator > 0.0f && numerator < upper * denominator) + else if ( denominator > 0.0f && numerator < upper * denominator ) { // Decrease upper. // The segment exits this half-space. @@ -806,19 +806,19 @@ b2CastOutput b2RayCastPolygon(const b2RayCastInput* input, const b2Polygon* shap // in some cases. Apparently the use of epsilon was to make edge // shapes work, but now those are handled separately. // if (upper < lower - b2_epsilon) - if (upper < lower) + if ( upper < lower ) { return output; } } - B2_ASSERT(0.0f <= lower && lower <= input->maxFraction); + B2_ASSERT( 0.0f <= lower && lower <= input->maxFraction ); - if (index >= 0) + if ( index >= 0 ) { output.fraction = lower; output.normal = shape->normals[index]; - output.point = b2MulAdd(p1, lower, d); + output.point = b2MulAdd( p1, lower, d ); output.hit = true; } @@ -827,67 +827,67 @@ b2CastOutput b2RayCastPolygon(const b2RayCastInput* input, const b2Polygon* shap // TODO_ERIN this is not working for ray vs box (zero radii) b2ShapeCastPairInput castInput; - castInput.proxyA = b2MakeProxy(shape->vertices, shape->count, shape->radius); - castInput.proxyB = b2MakeProxy(&input->origin, 1, 0.0f); + castInput.proxyA = b2MakeProxy( shape->vertices, shape->count, shape->radius ); + castInput.proxyB = b2MakeProxy( &input->origin, 1, 0.0f ); castInput.transformA = b2Transform_identity; castInput.transformB = b2Transform_identity; castInput.translationB = input->translation; castInput.maxFraction = input->maxFraction; - return b2ShapeCast(&castInput); + return b2ShapeCast( &castInput ); } -b2CastOutput b2ShapeCastCircle(const b2ShapeCastInput* input, const b2Circle* shape) +b2CastOutput b2ShapeCastCircle( const b2ShapeCastInput* input, const b2Circle* shape ) { b2ShapeCastPairInput pairInput; - pairInput.proxyA = b2MakeProxy(&shape->center, 1, shape->radius); - pairInput.proxyB = b2MakeProxy(input->points, input->count, input->radius); + pairInput.proxyA = b2MakeProxy( &shape->center, 1, shape->radius ); + pairInput.proxyB = b2MakeProxy( input->points, input->count, input->radius ); pairInput.transformA = b2Transform_identity; pairInput.transformB = b2Transform_identity; pairInput.translationB = input->translation; pairInput.maxFraction = input->maxFraction; - b2CastOutput output = b2ShapeCast(&pairInput); + b2CastOutput output = b2ShapeCast( &pairInput ); return output; } -b2CastOutput b2ShapeCastCapsule(const b2ShapeCastInput* input, const b2Capsule* shape) +b2CastOutput b2ShapeCastCapsule( const b2ShapeCastInput* input, const b2Capsule* shape ) { b2ShapeCastPairInput pairInput; - pairInput.proxyA = b2MakeProxy(&shape->center1, 2, shape->radius); - pairInput.proxyB = b2MakeProxy(input->points, input->count, input->radius); + pairInput.proxyA = b2MakeProxy( &shape->center1, 2, shape->radius ); + pairInput.proxyB = b2MakeProxy( input->points, input->count, input->radius ); pairInput.transformA = b2Transform_identity; pairInput.transformB = b2Transform_identity; pairInput.translationB = input->translation; pairInput.maxFraction = input->maxFraction; - b2CastOutput output = b2ShapeCast(&pairInput); + b2CastOutput output = b2ShapeCast( &pairInput ); return output; } -b2CastOutput b2ShapeCastSegment(const b2ShapeCastInput* input, const b2Segment* shape) +b2CastOutput b2ShapeCastSegment( const b2ShapeCastInput* input, const b2Segment* shape ) { b2ShapeCastPairInput pairInput; - pairInput.proxyA = b2MakeProxy(&shape->point1, 2, 0.0f); - pairInput.proxyB = b2MakeProxy(input->points, input->count, input->radius); + pairInput.proxyA = b2MakeProxy( &shape->point1, 2, 0.0f ); + pairInput.proxyB = b2MakeProxy( input->points, input->count, input->radius ); pairInput.transformA = b2Transform_identity; pairInput.transformB = b2Transform_identity; pairInput.translationB = input->translation; pairInput.maxFraction = input->maxFraction; - b2CastOutput output = b2ShapeCast(&pairInput); + b2CastOutput output = b2ShapeCast( &pairInput ); return output; } -b2CastOutput b2ShapeCastPolygon(const b2ShapeCastInput* input, const b2Polygon* shape) +b2CastOutput b2ShapeCastPolygon( const b2ShapeCastInput* input, const b2Polygon* shape ) { b2ShapeCastPairInput pairInput; - pairInput.proxyA = b2MakeProxy(shape->vertices, shape->count, shape->radius); - pairInput.proxyB = b2MakeProxy(input->points, input->count, input->radius); + pairInput.proxyA = b2MakeProxy( shape->vertices, shape->count, shape->radius ); + pairInput.proxyB = b2MakeProxy( input->points, input->count, input->radius ); pairInput.transformA = b2Transform_identity; pairInput.transformB = b2Transform_identity; pairInput.translationB = input->translation; pairInput.maxFraction = input->maxFraction; - b2CastOutput output = b2ShapeCast(&pairInput); + b2CastOutput output = b2ShapeCast( &pairInput ); return output; } diff --git a/src/hull.c b/src/hull.c index 8eb80493..41fd76de 100644 --- a/src/hull.c +++ b/src/hull.c @@ -9,46 +9,46 @@ #include // quickhull recursion -static b2Hull b2RecurseHull(b2Vec2 p1, b2Vec2 p2, b2Vec2* ps, int count) +static b2Hull b2RecurseHull( b2Vec2 p1, b2Vec2 p2, b2Vec2* ps, int count ) { b2Hull hull; hull.count = 0; - if (count == 0) + if ( count == 0 ) { return hull; } // create an edge vector pointing from p1 to p2 - b2Vec2 e = b2Normalize(b2Sub(p2, p1)); + b2Vec2 e = b2Normalize( b2Sub( p2, p1 ) ); // discard points left of e and find point furthest to the right of e b2Vec2 rightPoints[b2_maxPolygonVertices]; int rightCount = 0; int bestIndex = 0; - float bestDistance = b2Cross(b2Sub(ps[bestIndex], p1), e); - if (bestDistance > 0.0f) + float bestDistance = b2Cross( b2Sub( ps[bestIndex], p1 ), e ); + if ( bestDistance > 0.0f ) { rightPoints[rightCount++] = ps[bestIndex]; } - for (int i = 1; i < count; ++i) + for ( int i = 1; i < count; ++i ) { - float distance = b2Cross(b2Sub(ps[i], p1), e); - if (distance > bestDistance) + float distance = b2Cross( b2Sub( ps[i], p1 ), e ); + if ( distance > bestDistance ) { bestIndex = i; bestDistance = distance; } - if (distance > 0.0f) + if ( distance > 0.0f ) { rightPoints[rightCount++] = ps[i]; } } - if (bestDistance < 2.0f * b2_linearSlop) + if ( bestDistance < 2.0f * b2_linearSlop ) { return hull; } @@ -56,25 +56,25 @@ static b2Hull b2RecurseHull(b2Vec2 p1, b2Vec2 p2, b2Vec2* ps, int count) b2Vec2 bestPoint = ps[bestIndex]; // compute hull to the right of p1-bestPoint - b2Hull hull1 = b2RecurseHull(p1, bestPoint, rightPoints, rightCount); + b2Hull hull1 = b2RecurseHull( p1, bestPoint, rightPoints, rightCount ); // compute hull to the right of bestPoint-p2 - b2Hull hull2 = b2RecurseHull(bestPoint, p2, rightPoints, rightCount); + b2Hull hull2 = b2RecurseHull( bestPoint, p2, rightPoints, rightCount ); // stitch together hulls - for (int i = 0; i < hull1.count; ++i) + for ( int i = 0; i < hull1.count; ++i ) { hull.points[hull.count++] = hull1.points[i]; } hull.points[hull.count++] = bestPoint; - for (int i = 0; i < hull2.count; ++i) + for ( int i = 0; i < hull2.count; ++i ) { hull.points[hull.count++] = hull2.points[i]; } - B2_ASSERT(hull.count < b2_maxPolygonVertices); + B2_ASSERT( hull.count < b2_maxPolygonVertices ); return hull; } @@ -83,20 +83,20 @@ static b2Hull b2RecurseHull(b2Vec2 p1, b2Vec2 p2, b2Vec2* ps, int count) // - merges vertices based on b2_linearSlop // - removes collinear points using b2_linearSlop // - returns an empty hull if it fails -b2Hull b2ComputeHull(const b2Vec2* points, int count) +b2Hull b2ComputeHull( const b2Vec2* points, int count ) { b2Hull hull; hull.count = 0; - if (count < 3 || count > b2_maxPolygonVertices) + if ( count < 3 || count > b2_maxPolygonVertices ) { // check your data return hull; } - count = b2MinFloat(count, b2_maxPolygonVertices); + count = b2MinFloat( count, b2_maxPolygonVertices ); - b2AABB aabb = {{FLT_MAX, FLT_MAX}, {-FLT_MAX, -FLT_MAX}}; + b2AABB aabb = { { FLT_MAX, FLT_MAX }, { -FLT_MAX, -FLT_MAX } }; // Perform aggressive point welding. First point always remains. // Also compute the bounding box for later. @@ -104,46 +104,46 @@ b2Hull b2ComputeHull(const b2Vec2* points, int count) int n = 0; const float linearSlop = b2_linearSlop; const float tolSqr = 16.0f * linearSlop * linearSlop; - for (int i = 0; i < count; ++i) + for ( int i = 0; i < count; ++i ) { - aabb.lowerBound = b2Min(aabb.lowerBound, points[i]); - aabb.upperBound = b2Max(aabb.upperBound, points[i]); + aabb.lowerBound = b2Min( aabb.lowerBound, points[i] ); + aabb.upperBound = b2Max( aabb.upperBound, points[i] ); b2Vec2 vi = points[i]; bool unique = true; - for (int j = 0; j < i; ++j) + for ( int j = 0; j < i; ++j ) { b2Vec2 vj = points[j]; - float distSqr = b2DistanceSquared(vi, vj); - if (distSqr < tolSqr) + float distSqr = b2DistanceSquared( vi, vj ); + if ( distSqr < tolSqr ) { unique = false; break; } } - if (unique) + if ( unique ) { ps[n++] = vi; } } - if (n < 3) + if ( n < 3 ) { // all points very close together, check your data and check your scale return hull; } // Find an extreme point as the first point on the hull - b2Vec2 c = b2AABB_Center(aabb); + b2Vec2 c = b2AABB_Center( aabb ); int f1 = 0; - float dsq1 = b2DistanceSquared(c, ps[f1]); - for (int i = 1; i < n; ++i) + float dsq1 = b2DistanceSquared( c, ps[f1] ); + for ( int i = 1; i < n; ++i ) { - float dsq = b2DistanceSquared(c, ps[i]); - if (dsq > dsq1) + float dsq = b2DistanceSquared( c, ps[i] ); + if ( dsq > dsq1 ) { f1 = i; dsq1 = dsq; @@ -156,11 +156,11 @@ b2Hull b2ComputeHull(const b2Vec2* points, int count) n = n - 1; int f2 = 0; - float dsq2 = b2DistanceSquared(p1, ps[f2]); - for (int i = 1; i < n; ++i) + float dsq2 = b2DistanceSquared( p1, ps[f2] ); + for ( int i = 1; i < n; ++i ) { - float dsq = b2DistanceSquared(p1, ps[i]); - if (dsq > dsq2) + float dsq = b2DistanceSquared( p1, ps[i] ); + if ( dsq > dsq2 ) { f2 = i; dsq2 = dsq; @@ -179,28 +179,28 @@ b2Hull b2ComputeHull(const b2Vec2* points, int count) b2Vec2 leftPoints[b2_maxPolygonVertices - 2]; int leftCount = 0; - b2Vec2 e = b2Normalize(b2Sub(p2, p1)); + b2Vec2 e = b2Normalize( b2Sub( p2, p1 ) ); - for (int i = 0; i < n; ++i) + for ( int i = 0; i < n; ++i ) { - float d = b2Cross(b2Sub(ps[i], p1), e); + float d = b2Cross( b2Sub( ps[i], p1 ), e ); // slop used here to skip points that are very close to the line p1-p2 - if (d >= 2.0f * linearSlop) + if ( d >= 2.0f * linearSlop ) { rightPoints[rightCount++] = ps[i]; } - else if (d <= -2.0f * linearSlop) + else if ( d <= -2.0f * linearSlop ) { leftPoints[leftCount++] = ps[i]; } } // compute hulls on right and left - b2Hull hull1 = b2RecurseHull(p1, p2, rightPoints, rightCount); - b2Hull hull2 = b2RecurseHull(p2, p1, leftPoints, leftCount); + b2Hull hull1 = b2RecurseHull( p1, p2, rightPoints, rightCount ); + b2Hull hull2 = b2RecurseHull( p2, p1, leftPoints, leftCount ); - if (hull1.count == 0 && hull2.count == 0) + if ( hull1.count == 0 && hull2.count == 0 ) { // all points collinear return hull; @@ -209,44 +209,44 @@ b2Hull b2ComputeHull(const b2Vec2* points, int count) // stitch hulls together, preserving CCW winding order hull.points[hull.count++] = p1; - for (int i = 0; i < hull1.count; ++i) + for ( int i = 0; i < hull1.count; ++i ) { hull.points[hull.count++] = hull1.points[i]; } hull.points[hull.count++] = p2; - for (int i = 0; i < hull2.count; ++i) + for ( int i = 0; i < hull2.count; ++i ) { hull.points[hull.count++] = hull2.points[i]; } - B2_ASSERT(hull.count <= b2_maxPolygonVertices); + B2_ASSERT( hull.count <= b2_maxPolygonVertices ); // merge collinear bool searching = true; - while (searching && hull.count > 2) + while ( searching && hull.count > 2 ) { searching = false; - for (int i = 0; i < hull.count; ++i) + for ( int i = 0; i < hull.count; ++i ) { int i1 = i; - int i2 = (i + 1) % hull.count; - int i3 = (i + 2) % hull.count; + int i2 = ( i + 1 ) % hull.count; + int i3 = ( i + 2 ) % hull.count; b2Vec2 s1 = hull.points[i1]; b2Vec2 s2 = hull.points[i2]; b2Vec2 s3 = hull.points[i3]; // unit edge vector for s1-s3 - b2Vec2 r = b2Normalize(b2Sub(s3, s1)); + b2Vec2 r = b2Normalize( b2Sub( s3, s1 ) ); - float distance = b2Cross(b2Sub(s2, s1), r); - if (distance <= 2.0f * linearSlop) + float distance = b2Cross( b2Sub( s2, s1 ), r ); + if ( distance <= 2.0f * linearSlop ) { // remove midpoint from hull - for (int j = i2; j < hull.count - 1; ++j) + for ( int j = i2; j < hull.count - 1; ++j ) { hull.points[j] = hull.points[j + 1]; } @@ -260,7 +260,7 @@ b2Hull b2ComputeHull(const b2Vec2* points, int count) } } - if (hull.count < 3) + if ( hull.count < 3 ) { // all points collinear, shouldn't be reached since this was validated above hull.count = 0; @@ -269,32 +269,32 @@ b2Hull b2ComputeHull(const b2Vec2* points, int count) return hull; } -bool b2ValidateHull(const b2Hull* hull) +bool b2ValidateHull( const b2Hull* hull ) { - if (hull->count < 3 || b2_maxPolygonVertices < hull->count) + if ( hull->count < 3 || b2_maxPolygonVertices < hull->count ) { return false; } // test that every point is behind every edge - for (int i = 0; i < hull->count; ++i) + for ( int i = 0; i < hull->count; ++i ) { // create an edge vector int i1 = i; int i2 = i < hull->count - 1 ? i1 + 1 : 0; b2Vec2 p = hull->points[i1]; - b2Vec2 e = b2Normalize(b2Sub(hull->points[i2], p)); + b2Vec2 e = b2Normalize( b2Sub( hull->points[i2], p ) ); - for (int j = 0; j < hull->count; ++j) + for ( int j = 0; j < hull->count; ++j ) { // skip points that subtend the current edge - if (j == i1 || j == i2) + if ( j == i1 || j == i2 ) { continue; } - float distance = b2Cross(b2Sub(hull->points[j], p), e); - if (distance >= 0.0f) + float distance = b2Cross( b2Sub( hull->points[j], p ), e ); + if ( distance >= 0.0f ) { return false; } @@ -303,20 +303,20 @@ bool b2ValidateHull(const b2Hull* hull) // test for collinear points const float linearSlop = b2_linearSlop; - for (int i = 0; i < hull->count; ++i) + for ( int i = 0; i < hull->count; ++i ) { int i1 = i; - int i2 = (i + 1) % hull->count; - int i3 = (i + 2) % hull->count; + int i2 = ( i + 1 ) % hull->count; + int i3 = ( i + 2 ) % hull->count; b2Vec2 p1 = hull->points[i1]; b2Vec2 p2 = hull->points[i2]; b2Vec2 p3 = hull->points[i3]; - b2Vec2 e = b2Normalize(b2Sub(p3, p1)); + b2Vec2 e = b2Normalize( b2Sub( p3, p1 ) ); - float distance = b2Cross(b2Sub(p2, p1), e); - if (distance <= linearSlop) + float distance = b2Cross( b2Sub( p2, p1 ), e ); + if ( distance <= linearSlop ) { // p1-p2-p3 are collinear return false; diff --git a/src/id_pool.c b/src/id_pool.c index 4c95afcf..eb793ec9 100644 --- a/src/id_pool.c +++ b/src/id_pool.c @@ -7,23 +7,23 @@ b2IdPool b2CreateIdPool() { - b2IdPool pool = {0}; - pool.freeArray = b2CreateArray(sizeof(int), 32); + b2IdPool pool = { 0 }; + pool.freeArray = b2CreateArray( sizeof( int ), 32 ); return pool; } -void b2DestroyIdPool(b2IdPool* pool) +void b2DestroyIdPool( b2IdPool* pool ) { - b2DestroyArray(pool->freeArray, sizeof(int)); - *pool = (b2IdPool){0}; + b2DestroyArray( pool->freeArray, sizeof( int ) ); + *pool = ( b2IdPool ){ 0 }; } -int b2AllocId(b2IdPool* pool) +int b2AllocId( b2IdPool* pool ) { - if (b2Array(pool->freeArray).count > 0) + if ( b2Array( pool->freeArray ).count > 0 ) { - int id = b2Array_Last(pool->freeArray); - b2Array_Pop(pool->freeArray); + int id = b2Array_Last( pool->freeArray ); + b2Array_Pop( pool->freeArray ); return id; } @@ -32,42 +32,42 @@ int b2AllocId(b2IdPool* pool) return id; } -void b2FreeId(b2IdPool* pool, int id) +void b2FreeId( b2IdPool* pool, int id ) { - B2_ASSERT(pool->nextIndex > 0); - B2_ASSERT(0 <= id && id < pool->nextIndex); + B2_ASSERT( pool->nextIndex > 0 ); + B2_ASSERT( 0 <= id && id < pool->nextIndex ); - if (id == pool->nextIndex) + if ( id == pool->nextIndex ) { pool->nextIndex -= 1; return; } - b2Array_Push(pool->freeArray, id); + b2Array_Push( pool->freeArray, id ); } #if B2_VALIDATE -void b2ValidateFreeId(b2IdPool* pool, int id) +void b2ValidateFreeId( b2IdPool* pool, int id ) { - int freeCount = b2Array(pool->freeArray).count; - for (int i = 0; i < freeCount; ++i) + int freeCount = b2Array( pool->freeArray ).count; + for ( int i = 0; i < freeCount; ++i ) { - if (pool->freeArray[i] == id) + if ( pool->freeArray[i] == id ) { return; } } - B2_ASSERT(0); + B2_ASSERT( 0 ); } #else -void b2ValidateFreeId(b2IdPool* pool, int id) +void b2ValidateFreeId( b2IdPool* pool, int id ) { - B2_MAYBE_UNUSED(pool); - B2_MAYBE_UNUSED(id); + B2_MAYBE_UNUSED( pool ); + B2_MAYBE_UNUSED( id ); } #endif diff --git a/src/id_pool.h b/src/id_pool.h index 10c35ddf..a47a4e3d 100644 --- a/src/id_pool.h +++ b/src/id_pool.h @@ -12,23 +12,23 @@ typedef struct b2IdPool } b2IdPool; b2IdPool b2CreateIdPool(); -void b2DestroyIdPool(b2IdPool* pool); +void b2DestroyIdPool( b2IdPool* pool ); -int b2AllocId(b2IdPool* pool); -void b2FreeId(b2IdPool* pool, int id); -void b2ValidateFreeId(b2IdPool* pool, int id); +int b2AllocId( b2IdPool* pool ); +void b2FreeId( b2IdPool* pool, int id ); +void b2ValidateFreeId( b2IdPool* pool, int id ); -static inline int b2GetIdCount(b2IdPool* pool) +static inline int b2GetIdCount( b2IdPool* pool ) { - return pool->nextIndex - b2Array(pool->freeArray).count; + return pool->nextIndex - b2Array( pool->freeArray ).count; } -static inline int b2GetIdCapacity(b2IdPool* pool) +static inline int b2GetIdCapacity( b2IdPool* pool ) { return pool->nextIndex; } -static inline int b2GetIdBytes(b2IdPool* pool) +static inline int b2GetIdBytes( b2IdPool* pool ) { - return b2GetArrayBytes(pool->freeArray, sizeof(int)); + return b2GetArrayBytes( pool->freeArray, sizeof( int ) ); } diff --git a/src/island.c b/src/island.c index f20630cc..d8409880 100644 --- a/src/island.c +++ b/src/island.c @@ -13,22 +13,23 @@ #include -b2Island* b2CreateIsland(b2World* world, int setIndex) +b2Island* b2CreateIsland( b2World* world, int setIndex ) { - B2_ASSERT(setIndex == b2_awakeSet || setIndex >= b2_firstSleepingSet); + B2_ASSERT( setIndex == b2_awakeSet || setIndex >= b2_firstSleepingSet ); - int islandId = b2AllocId(&world->islandIdPool); + int islandId = b2AllocId( &world->islandIdPool ); - if (islandId == b2Array(world->islandArray).count) + if ( islandId == b2Array( world->islandArray ).count ) { - b2Array_Push(world->islandArray, (b2Island){0}); + b2Island emptyIsland = { 0 }; + b2Array_Push( world->islandArray, emptyIsland ); } else { - B2_ASSERT(world->islandArray[islandId].setIndex == B2_NULL_INDEX); + B2_ASSERT( world->islandArray[islandId].setIndex == B2_NULL_INDEX ); } - b2CheckIndex(world->solverSetArray, setIndex); + b2CheckIndex( world->solverSetArray, setIndex ); b2SolverSet* set = world->solverSetArray + setIndex; b2Island* island = world->islandArray + islandId; @@ -47,27 +48,27 @@ b2Island* b2CreateIsland(b2World* world, int setIndex) island->parentIsland = B2_NULL_INDEX; island->constraintRemoveCount = 0; - b2IslandSim* islandSim = b2AddIsland(&set->islands); + b2IslandSim* islandSim = b2AddIsland( &set->islands ); islandSim->islandId = islandId; return island; } -void b2DestroyIsland(b2World* world, int islandId) +void b2DestroyIsland( b2World* world, int islandId ) { // assume island is empty - b2CheckIndex(world->islandArray, islandId); + b2CheckIndex( world->islandArray, islandId ); b2Island* island = world->islandArray + islandId; - b2CheckIndex(world->solverSetArray, island->setIndex); + b2CheckIndex( world->solverSetArray, island->setIndex ); b2SolverSet* set = world->solverSetArray + island->setIndex; - int movedIndex = b2RemoveIsland(&set->islands, island->localIndex); - if (movedIndex != B2_NULL_INDEX) + int movedIndex = b2RemoveIsland( &set->islands, island->localIndex ); + if ( movedIndex != B2_NULL_INDEX ) { // Fix index on moved element b2IslandSim* movedElement = set->islands.data + island->localIndex; int movedId = movedElement->islandId; b2Island* movedIsland = world->islandArray + movedId; - B2_ASSERT(movedIsland->localIndex == movedIndex); + B2_ASSERT( movedIsland->localIndex == movedIndex ); movedIsland->localIndex = island->localIndex; } @@ -75,34 +76,34 @@ void b2DestroyIsland(b2World* world, int islandId) island->islandId = B2_NULL_INDEX; island->setIndex = B2_NULL_INDEX; island->localIndex = B2_NULL_INDEX; - b2FreeId(&world->islandIdPool, islandId); + b2FreeId( &world->islandIdPool, islandId ); } -b2Island* b2GetIsland(b2World* world, int islandId) +b2Island* b2GetIsland( b2World* world, int islandId ) { - b2CheckIndex(world->islandArray, islandId); + b2CheckIndex( world->islandArray, islandId ); return world->islandArray + islandId; } -static void b2AddContactToIsland(b2World* world, int islandId, b2Contact* contact) +static void b2AddContactToIsland( b2World* world, int islandId, b2Contact* contact ) { - B2_ASSERT(contact->islandId == B2_NULL_INDEX); - B2_ASSERT(contact->islandPrev == B2_NULL_INDEX); - B2_ASSERT(contact->islandNext == B2_NULL_INDEX); + B2_ASSERT( contact->islandId == B2_NULL_INDEX ); + B2_ASSERT( contact->islandPrev == B2_NULL_INDEX ); + B2_ASSERT( contact->islandNext == B2_NULL_INDEX ); - b2CheckIndex(world->islandArray, islandId); - b2Island* island = world->islandArray + islandId; + b2CheckIndex( world->islandArray, islandId ); + b2Island* island = world->islandArray + islandId; - if (island->headContact != B2_NULL_INDEX) + if ( island->headContact != B2_NULL_INDEX ) { contact->islandNext = island->headContact; - b2CheckIndex(world->contactArray, island->headContact); + b2CheckIndex( world->contactArray, island->headContact ); b2Contact* headContact = world->contactArray + island->headContact; headContact->islandPrev = contact->contactId; } island->headContact = contact->contactId; - if (island->tailContact == B2_NULL_INDEX) + if ( island->tailContact == B2_NULL_INDEX ) { island->tailContact = island->headContact; } @@ -110,62 +111,62 @@ static void b2AddContactToIsland(b2World* world, int islandId, b2Contact* contac island->contactCount += 1; contact->islandId = islandId; - b2ValidateIsland(world, islandId); + b2ValidateIsland( world, islandId ); } // Link a contact into an island. // This performs union-find and path compression to join islands. // https://en.wikipedia.org/wiki/Disjoint-set_data_structure -void b2LinkContact(b2World* world, b2Contact* contact) +void b2LinkContact( b2World* world, b2Contact* contact ) { - B2_ASSERT((contact->flags & b2_contactTouchingFlag) != 0 && (contact->flags & b2_contactSensorFlag) == 0); + B2_ASSERT( ( contact->flags & b2_contactTouchingFlag ) != 0 && ( contact->flags & b2_contactSensorFlag ) == 0 ); int bodyIdA = contact->edges[0].bodyId; int bodyIdB = contact->edges[1].bodyId; - b2Body* bodyA = b2GetBody(world, bodyIdA); - b2Body* bodyB = b2GetBody(world, bodyIdB); + b2Body* bodyA = b2GetBody( world, bodyIdA ); + b2Body* bodyB = b2GetBody( world, bodyIdB ); - B2_ASSERT(bodyA->setIndex != b2_disabledSet && bodyB->setIndex != b2_disabledSet); - B2_ASSERT(bodyA->setIndex != b2_staticSet || bodyB->setIndex != b2_staticSet); + B2_ASSERT( bodyA->setIndex != b2_disabledSet && bodyB->setIndex != b2_disabledSet ); + B2_ASSERT( bodyA->setIndex != b2_staticSet || bodyB->setIndex != b2_staticSet ); // Wake bodyB if bodyA is awake and bodyB is sleeping - if (bodyA->setIndex == b2_awakeSet && bodyB->setIndex >= b2_firstSleepingSet) + if ( bodyA->setIndex == b2_awakeSet && bodyB->setIndex >= b2_firstSleepingSet ) { - b2WakeSolverSet(world, bodyB->setIndex); + b2WakeSolverSet( world, bodyB->setIndex ); } // Wake bodyA if bodyB is awake and bodyA is sleeping - if (bodyB->setIndex == b2_awakeSet && bodyA->setIndex >= b2_firstSleepingSet) + if ( bodyB->setIndex == b2_awakeSet && bodyA->setIndex >= b2_firstSleepingSet ) { - b2WakeSolverSet(world, bodyA->setIndex); + b2WakeSolverSet( world, bodyA->setIndex ); } int islandIdA = bodyA->islandId; int islandIdB = bodyB->islandId; // Static bodies have null island indices. - B2_ASSERT(bodyA->setIndex != b2_staticSet || islandIdA == B2_NULL_INDEX); - B2_ASSERT(bodyB->setIndex != b2_staticSet || islandIdB == B2_NULL_INDEX); - B2_ASSERT(islandIdA != B2_NULL_INDEX || islandIdB != B2_NULL_INDEX); + B2_ASSERT( bodyA->setIndex != b2_staticSet || islandIdA == B2_NULL_INDEX ); + B2_ASSERT( bodyB->setIndex != b2_staticSet || islandIdB == B2_NULL_INDEX ); + B2_ASSERT( islandIdA != B2_NULL_INDEX || islandIdB != B2_NULL_INDEX ); - if (islandIdA == islandIdB) + if ( islandIdA == islandIdB ) { // Contact in same island - b2AddContactToIsland(world, islandIdA, contact); + b2AddContactToIsland( world, islandIdA, contact ); return; } // Union-find root of islandA b2Island* islandA = NULL; - if (islandIdA != B2_NULL_INDEX) + if ( islandIdA != B2_NULL_INDEX ) { - islandA = b2GetIsland(world, islandIdA); + islandA = b2GetIsland( world, islandIdA ); int parentId = islandA->parentIsland; - while (parentId != B2_NULL_INDEX) + while ( parentId != B2_NULL_INDEX ) { - b2Island* parent = b2GetIsland(world, parentId); - if (parent->parentIsland != B2_NULL_INDEX) + b2Island* parent = b2GetIsland( world, parentId ); + if ( parent->parentIsland != B2_NULL_INDEX ) { // path compression islandA->parentIsland = parent->parentIsland; @@ -179,14 +180,14 @@ void b2LinkContact(b2World* world, b2Contact* contact) // Union-find root of islandB b2Island* islandB = NULL; - if (islandIdB != B2_NULL_INDEX) + if ( islandIdB != B2_NULL_INDEX ) { - islandB = b2GetIsland(world, islandIdB); + islandB = b2GetIsland( world, islandIdB ); int parentId = islandB->parentIsland; - while (islandB->parentIsland != B2_NULL_INDEX) + while ( islandB->parentIsland != B2_NULL_INDEX ) { - b2Island* parent = b2GetIsland(world, parentId); - if (parent->parentIsland != B2_NULL_INDEX) + b2Island* parent = b2GetIsland( world, parentId ); + if ( parent->parentIsland != B2_NULL_INDEX ) { // path compression islandB->parentIsland = parent->parentIsland; @@ -198,64 +199,64 @@ void b2LinkContact(b2World* world, b2Contact* contact) } } - B2_ASSERT(islandA != NULL || islandB != NULL); + B2_ASSERT( islandA != NULL || islandB != NULL ); // Union-Find link island roots - if (islandA != islandB && islandA != NULL && islandB != NULL) + if ( islandA != islandB && islandA != NULL && islandB != NULL ) { - B2_ASSERT(islandA != islandB); - B2_ASSERT(islandB->parentIsland == B2_NULL_INDEX); + B2_ASSERT( islandA != islandB ); + B2_ASSERT( islandB->parentIsland == B2_NULL_INDEX ); islandB->parentIsland = islandIdA; } - if (islandA != NULL) + if ( islandA != NULL ) { - b2AddContactToIsland(world, islandIdA, contact); + b2AddContactToIsland( world, islandIdA, contact ); } else { - b2AddContactToIsland(world, islandIdB, contact); + b2AddContactToIsland( world, islandIdB, contact ); } } // This is called when a contact no longer has contact points or when a contact is destroyed. -void b2UnlinkContact(b2World* world, b2Contact* contact) +void b2UnlinkContact( b2World* world, b2Contact* contact ) { - B2_ASSERT((contact->flags & b2_contactSensorFlag) == 0); - B2_ASSERT(contact->islandId != B2_NULL_INDEX); + B2_ASSERT( ( contact->flags & b2_contactSensorFlag ) == 0 ); + B2_ASSERT( contact->islandId != B2_NULL_INDEX ); // remove from island int islandId = contact->islandId; - b2CheckIndex(world->islandArray, islandId); - b2Island* island = b2GetIsland(world, islandId); + b2CheckIndex( world->islandArray, islandId ); + b2Island* island = b2GetIsland( world, islandId ); - if (contact->islandPrev != B2_NULL_INDEX) + if ( contact->islandPrev != B2_NULL_INDEX ) { - b2CheckIndex(world->contactArray, contact->islandPrev); + b2CheckIndex( world->contactArray, contact->islandPrev ); b2Contact* prevContact = world->contactArray + contact->islandPrev; - B2_ASSERT(prevContact->islandNext == contact->contactId); + B2_ASSERT( prevContact->islandNext == contact->contactId ); prevContact->islandNext = contact->islandNext; } - if (contact->islandNext != B2_NULL_INDEX) + if ( contact->islandNext != B2_NULL_INDEX ) { - b2CheckIndex(world->contactArray, contact->islandNext); + b2CheckIndex( world->contactArray, contact->islandNext ); b2Contact* nextContact = world->contactArray + contact->islandNext; - B2_ASSERT(nextContact->islandPrev == contact->contactId); + B2_ASSERT( nextContact->islandPrev == contact->contactId ); nextContact->islandPrev = contact->islandPrev; } - if (island->headContact == contact->contactId) + if ( island->headContact == contact->contactId ) { island->headContact = contact->islandNext; } - if (island->tailContact == contact->contactId) + if ( island->tailContact == contact->contactId ) { island->tailContact = contact->islandPrev; } - B2_ASSERT(island->contactCount > 0); + B2_ASSERT( island->contactCount > 0 ); island->contactCount -= 1; island->constraintRemoveCount += 1; @@ -263,27 +264,27 @@ void b2UnlinkContact(b2World* world, b2Contact* contact) contact->islandPrev = B2_NULL_INDEX; contact->islandNext = B2_NULL_INDEX; - b2ValidateIsland(world, islandId); + b2ValidateIsland( world, islandId ); } -static void b2AddJointToIsland(b2World* world, int islandId, b2Joint* joint) +static void b2AddJointToIsland( b2World* world, int islandId, b2Joint* joint ) { - B2_ASSERT(joint->islandId == B2_NULL_INDEX); - B2_ASSERT(joint->islandPrev == B2_NULL_INDEX); - B2_ASSERT(joint->islandNext == B2_NULL_INDEX); + B2_ASSERT( joint->islandId == B2_NULL_INDEX ); + B2_ASSERT( joint->islandPrev == B2_NULL_INDEX ); + B2_ASSERT( joint->islandNext == B2_NULL_INDEX ); - b2CheckIndex(world->islandArray, islandId); + b2CheckIndex( world->islandArray, islandId ); b2Island* island = world->islandArray + islandId; - if (island->headJoint != B2_NULL_INDEX) + if ( island->headJoint != B2_NULL_INDEX ) { joint->islandNext = island->headJoint; - b2Joint* headJoint = b2GetJoint(world, island->headJoint); + b2Joint* headJoint = b2GetJoint( world, island->headJoint ); headJoint->islandPrev = joint->jointId; } island->headJoint = joint->jointId; - if (island->tailJoint == B2_NULL_INDEX) + if ( island->tailJoint == B2_NULL_INDEX ) { island->tailJoint = island->headJoint; } @@ -291,44 +292,44 @@ static void b2AddJointToIsland(b2World* world, int islandId, b2Joint* joint) island->jointCount += 1; joint->islandId = islandId; - b2ValidateIsland(world, islandId); + b2ValidateIsland( world, islandId ); } -void b2LinkJoint(b2World* world, b2Joint* joint) +void b2LinkJoint( b2World* world, b2Joint* joint ) { - b2Body* bodyA = b2GetBody(world, joint->edges[0].bodyId); - b2Body* bodyB = b2GetBody(world, joint->edges[1].bodyId); + b2Body* bodyA = b2GetBody( world, joint->edges[0].bodyId ); + b2Body* bodyB = b2GetBody( world, joint->edges[1].bodyId ); - if (bodyA->setIndex == b2_awakeSet && bodyB->setIndex >= b2_firstSleepingSet) + if ( bodyA->setIndex == b2_awakeSet && bodyB->setIndex >= b2_firstSleepingSet ) { - b2WakeSolverSet(world, bodyB->setIndex); + b2WakeSolverSet( world, bodyB->setIndex ); } - else if (bodyB->setIndex == b2_awakeSet && bodyA->setIndex >= b2_firstSleepingSet) + else if ( bodyB->setIndex == b2_awakeSet && bodyA->setIndex >= b2_firstSleepingSet ) { - b2WakeSolverSet(world, bodyA->setIndex); + b2WakeSolverSet( world, bodyA->setIndex ); } int islandIdA = bodyA->islandId; int islandIdB = bodyB->islandId; - B2_ASSERT(islandIdA != B2_NULL_INDEX || islandIdB != B2_NULL_INDEX); + B2_ASSERT( islandIdA != B2_NULL_INDEX || islandIdB != B2_NULL_INDEX ); - if (islandIdA == islandIdB) + if ( islandIdA == islandIdB ) { // Joint in same island - b2AddJointToIsland(world, islandIdA, joint); + b2AddJointToIsland( world, islandIdA, joint ); return; } // Union-find root of islandA b2Island* islandA = NULL; - if (islandIdA != B2_NULL_INDEX) + if ( islandIdA != B2_NULL_INDEX ) { - islandA = b2GetIsland(world, islandIdA); - while (islandA->parentIsland != B2_NULL_INDEX) + islandA = b2GetIsland( world, islandIdA ); + while ( islandA->parentIsland != B2_NULL_INDEX ) { - b2Island* parent = b2GetIsland(world, islandA->parentIsland); - if (parent->parentIsland != B2_NULL_INDEX) + b2Island* parent = b2GetIsland( world, islandA->parentIsland ); + if ( parent->parentIsland != B2_NULL_INDEX ) { // path compression islandA->parentIsland = parent->parentIsland; @@ -341,13 +342,13 @@ void b2LinkJoint(b2World* world, b2Joint* joint) // Union-find root of islandB b2Island* islandB = NULL; - if (islandIdB != B2_NULL_INDEX) + if ( islandIdB != B2_NULL_INDEX ) { - islandB = b2GetIsland(world, islandIdB); - while (islandB->parentIsland != B2_NULL_INDEX) + islandB = b2GetIsland( world, islandIdB ); + while ( islandB->parentIsland != B2_NULL_INDEX ) { - b2Island* parent = b2GetIsland(world, islandB->parentIsland); - if (parent->parentIsland != B2_NULL_INDEX) + b2Island* parent = b2GetIsland( world, islandB->parentIsland ); + if ( parent->parentIsland != B2_NULL_INDEX ) { // path compression islandB->parentIsland = parent->parentIsland; @@ -358,60 +359,60 @@ void b2LinkJoint(b2World* world, b2Joint* joint) } } - B2_ASSERT(islandA != NULL || islandB != NULL); + B2_ASSERT( islandA != NULL || islandB != NULL ); // Union-Find link island roots - if (islandA != islandB && islandA != NULL && islandB != NULL) + if ( islandA != islandB && islandA != NULL && islandB != NULL ) { - B2_ASSERT(islandA != islandB); - B2_ASSERT(islandB->parentIsland == B2_NULL_INDEX); + B2_ASSERT( islandA != islandB ); + B2_ASSERT( islandB->parentIsland == B2_NULL_INDEX ); islandB->parentIsland = islandIdA; } - if (islandA != NULL) + if ( islandA != NULL ) { - b2AddJointToIsland(world, islandIdA, joint); + b2AddJointToIsland( world, islandIdA, joint ); } else { - b2AddJointToIsland(world, islandIdB, joint); + b2AddJointToIsland( world, islandIdB, joint ); } } -void b2UnlinkJoint(b2World* world, b2Joint* joint) +void b2UnlinkJoint( b2World* world, b2Joint* joint ) { - B2_ASSERT(joint->islandId != B2_NULL_INDEX); + B2_ASSERT( joint->islandId != B2_NULL_INDEX ); // remove from island int islandId = joint->islandId; - b2CheckIndex(world->islandArray, islandId); + b2CheckIndex( world->islandArray, islandId ); b2Island* island = world->islandArray + islandId; - if (joint->islandPrev != B2_NULL_INDEX) + if ( joint->islandPrev != B2_NULL_INDEX ) { - b2Joint* prevJoint = b2GetJoint(world, joint->islandPrev); - B2_ASSERT(prevJoint->islandNext == joint->jointId); + b2Joint* prevJoint = b2GetJoint( world, joint->islandPrev ); + B2_ASSERT( prevJoint->islandNext == joint->jointId ); prevJoint->islandNext = joint->islandNext; } - if (joint->islandNext != B2_NULL_INDEX) + if ( joint->islandNext != B2_NULL_INDEX ) { - b2Joint* nextJoint = b2GetJoint(world, joint->islandNext); - B2_ASSERT(nextJoint->islandPrev == joint->jointId); + b2Joint* nextJoint = b2GetJoint( world, joint->islandNext ); + B2_ASSERT( nextJoint->islandPrev == joint->jointId ); nextJoint->islandPrev = joint->islandPrev; } - if (island->headJoint == joint->jointId) + if ( island->headJoint == joint->jointId ) { island->headJoint = joint->islandNext; } - if (island->tailJoint == joint->jointId) + if ( island->tailJoint == joint->jointId ) { island->tailJoint = joint->islandPrev; } - B2_ASSERT(island->jointCount > 0); + B2_ASSERT( island->jointCount > 0 ); island->jointCount -= 1; island->constraintRemoveCount += 1; @@ -419,109 +420,109 @@ void b2UnlinkJoint(b2World* world, b2Joint* joint) joint->islandPrev = B2_NULL_INDEX; joint->islandNext = B2_NULL_INDEX; - b2ValidateIsland(world, islandId); + b2ValidateIsland( world, islandId ); } // Merge an island into its root island. // todo we can assume all islands are awake here -static void b2MergeIsland(b2World* world, b2Island* island) +static void b2MergeIsland( b2World* world, b2Island* island ) { - B2_ASSERT(island->parentIsland != B2_NULL_INDEX); + B2_ASSERT( island->parentIsland != B2_NULL_INDEX ); int rootId = island->parentIsland; - b2CheckIndex(world->islandArray, rootId); + b2CheckIndex( world->islandArray, rootId ); b2Island* rootIsland = world->islandArray + rootId; - B2_ASSERT(rootIsland->parentIsland == B2_NULL_INDEX); + B2_ASSERT( rootIsland->parentIsland == B2_NULL_INDEX ); // remap island indices int bodyId = island->headBody; - while (bodyId != B2_NULL_INDEX) + while ( bodyId != B2_NULL_INDEX ) { - b2Body* body = b2GetBody(world, bodyId); + b2Body* body = b2GetBody( world, bodyId ); body->islandId = rootId; bodyId = body->islandNext; } int contactId = island->headContact; - while (contactId != B2_NULL_INDEX) + while ( contactId != B2_NULL_INDEX ) { - b2CheckIndex(world->contactArray, contactId); + b2CheckIndex( world->contactArray, contactId ); b2Contact* contact = world->contactArray + contactId; contact->islandId = rootId; contactId = contact->islandNext; } int jointId = island->headJoint; - while (jointId != B2_NULL_INDEX) + while ( jointId != B2_NULL_INDEX ) { - b2Joint* joint = b2GetJoint(world, jointId); + b2Joint* joint = b2GetJoint( world, jointId ); joint->islandId = rootId; jointId = joint->islandNext; } // connect body lists - B2_ASSERT(rootIsland->tailBody != B2_NULL_INDEX); - b2Body* tailBody = b2GetBody(world, rootIsland->tailBody); - B2_ASSERT(tailBody->islandNext == B2_NULL_INDEX); + B2_ASSERT( rootIsland->tailBody != B2_NULL_INDEX ); + b2Body* tailBody = b2GetBody( world, rootIsland->tailBody ); + B2_ASSERT( tailBody->islandNext == B2_NULL_INDEX ); tailBody->islandNext = island->headBody; - B2_ASSERT(island->headBody != B2_NULL_INDEX); - b2Body* headBody = b2GetBody(world, island->headBody); - B2_ASSERT(headBody->islandPrev == B2_NULL_INDEX); + B2_ASSERT( island->headBody != B2_NULL_INDEX ); + b2Body* headBody = b2GetBody( world, island->headBody ); + B2_ASSERT( headBody->islandPrev == B2_NULL_INDEX ); headBody->islandPrev = rootIsland->tailBody; rootIsland->tailBody = island->tailBody; rootIsland->bodyCount += island->bodyCount; // connect contact lists - if (rootIsland->headContact == B2_NULL_INDEX) + if ( rootIsland->headContact == B2_NULL_INDEX ) { // Root island has no contacts - B2_ASSERT(rootIsland->tailContact == B2_NULL_INDEX && rootIsland->contactCount == 0); + B2_ASSERT( rootIsland->tailContact == B2_NULL_INDEX && rootIsland->contactCount == 0 ); rootIsland->headContact = island->headContact; rootIsland->tailContact = island->tailContact; rootIsland->contactCount = island->contactCount; } - else if (island->headContact != B2_NULL_INDEX) + else if ( island->headContact != B2_NULL_INDEX ) { // Both islands have contacts - B2_ASSERT(island->tailContact != B2_NULL_INDEX && island->contactCount > 0); - B2_ASSERT(rootIsland->tailContact != B2_NULL_INDEX && rootIsland->contactCount > 0); + B2_ASSERT( island->tailContact != B2_NULL_INDEX && island->contactCount > 0 ); + B2_ASSERT( rootIsland->tailContact != B2_NULL_INDEX && rootIsland->contactCount > 0 ); - b2CheckIndex(world->contactArray, rootIsland->tailContact); + b2CheckIndex( world->contactArray, rootIsland->tailContact ); b2Contact* tailContact = world->contactArray + rootIsland->tailContact; - B2_ASSERT(tailContact->islandNext == B2_NULL_INDEX); + B2_ASSERT( tailContact->islandNext == B2_NULL_INDEX ); tailContact->islandNext = island->headContact; - b2CheckIndex(world->contactArray, island->headContact); + b2CheckIndex( world->contactArray, island->headContact ); b2Contact* headContact = world->contactArray + island->headContact; - B2_ASSERT(headContact->islandPrev == B2_NULL_INDEX); + B2_ASSERT( headContact->islandPrev == B2_NULL_INDEX ); headContact->islandPrev = rootIsland->tailContact; rootIsland->tailContact = island->tailContact; rootIsland->contactCount += island->contactCount; } - if (rootIsland->headJoint == B2_NULL_INDEX) + if ( rootIsland->headJoint == B2_NULL_INDEX ) { // Root island has no joints - B2_ASSERT(rootIsland->tailJoint == B2_NULL_INDEX && rootIsland->jointCount == 0); + B2_ASSERT( rootIsland->tailJoint == B2_NULL_INDEX && rootIsland->jointCount == 0 ); rootIsland->headJoint = island->headJoint; rootIsland->tailJoint = island->tailJoint; rootIsland->jointCount = island->jointCount; } - else if (island->headJoint != B2_NULL_INDEX) + else if ( island->headJoint != B2_NULL_INDEX ) { // Both islands have joints - B2_ASSERT(island->tailJoint != B2_NULL_INDEX && island->jointCount > 0); - B2_ASSERT(rootIsland->tailJoint != B2_NULL_INDEX && rootIsland->jointCount > 0); + B2_ASSERT( island->tailJoint != B2_NULL_INDEX && island->jointCount > 0 ); + B2_ASSERT( rootIsland->tailJoint != B2_NULL_INDEX && rootIsland->jointCount > 0 ); - b2Joint* tailJoint = b2GetJoint(world, rootIsland->tailJoint); - B2_ASSERT(tailJoint->islandNext == B2_NULL_INDEX); + b2Joint* tailJoint = b2GetJoint( world, rootIsland->tailJoint ); + B2_ASSERT( tailJoint->islandNext == B2_NULL_INDEX ); tailJoint->islandNext = island->headJoint; - b2Joint* headJoint = b2GetJoint(world, island->headJoint); - B2_ASSERT(headJoint->islandPrev == B2_NULL_INDEX); + b2Joint* headJoint = b2GetJoint( world, island->headJoint ); + B2_ASSERT( headJoint->islandPrev == B2_NULL_INDEX ); headJoint->islandPrev = rootIsland->tailJoint; rootIsland->tailJoint = island->tailJoint; @@ -530,17 +531,17 @@ static void b2MergeIsland(b2World* world, b2Island* island) // Track removed constraints rootIsland->constraintRemoveCount += island->constraintRemoveCount; - - b2ValidateIsland(world, rootId); + + b2ValidateIsland( world, rootId ); } // Iterate over all awake islands and merge any that need merging // Islands that get merged into a root island will be removed from the awake island array // and returned to the pool. // todo this might be faster if b2IslandSim held the connectivity data -void b2MergeAwakeIslands(b2World* world) +void b2MergeAwakeIslands( b2World* world ) { - b2TracyCZoneNC(merge_islands, "Merge Islands", b2_colorMediumTurquoise, true); + b2TracyCZoneNC( merge_islands, "Merge Islands", b2_colorMediumTurquoise, true ); b2SolverSet* awakeSet = world->solverSetArray + b2_awakeSet; b2IslandSim* islandSims = awakeSet->islands.data; @@ -549,21 +550,21 @@ void b2MergeAwakeIslands(b2World* world) // Step 1: Ensure every child island points to its root island. This avoids merging a child island with // a parent island that has already been merged with a grand-parent island. - for (int i = 0; i < awakeIslandCount; ++i) + for ( int i = 0; i < awakeIslandCount; ++i ) { int islandId = islandSims[i].islandId; - b2CheckIndex(islands, islandId); + b2CheckIndex( islands, islandId ); b2Island* island = islands + islandId; // find the root island int rootId = islandId; b2Island* rootIsland = island; - while (rootIsland->parentIsland != B2_NULL_INDEX) + while ( rootIsland->parentIsland != B2_NULL_INDEX ) { - b2CheckIndex(islands, rootIsland->parentIsland); + b2CheckIndex( islands, rootIsland->parentIsland ); b2Island* parent = islands + rootIsland->parentIsland; - if (parent->parentIsland != B2_NULL_INDEX) + if ( parent->parentIsland != B2_NULL_INDEX ) { // path compression rootIsland->parentIsland = parent->parentIsland; @@ -573,7 +574,7 @@ void b2MergeAwakeIslands(b2World* world) rootIsland = parent; } - if (rootIsland != island) + if ( rootIsland != island ) { island->parentIsland = rootId; } @@ -581,49 +582,49 @@ void b2MergeAwakeIslands(b2World* world) // Step 2: merge every awake island into its parent (which must be a root island) // Reverse to support removal from awake array. - for (int i = awakeIslandCount - 1; i >= 0; --i) + for ( int i = awakeIslandCount - 1; i >= 0; --i ) { int islandId = islandSims[i].islandId; - b2CheckIndex(islands, islandId); + b2CheckIndex( islands, islandId ); b2Island* island = islands + islandId; - if (island->parentIsland == B2_NULL_INDEX) + if ( island->parentIsland == B2_NULL_INDEX ) { continue; } - b2MergeIsland(world, island); + b2MergeIsland( world, island ); // this call does a remove swap from the end of the island sim array - b2DestroyIsland(world, islandId); + b2DestroyIsland( world, islandId ); } - b2ValidateConnectivity(world); + b2ValidateConnectivity( world ); - b2TracyCZoneEnd(merge_islands); + b2TracyCZoneEnd( merge_islands ); } #define B2_CONTACT_REMOVE_THRESHOLD 1 -void b2SplitIsland(b2World* world, int baseId) +void b2SplitIsland( b2World* world, int baseId ) { - b2CheckIndex(world->islandArray, baseId); + b2CheckIndex( world->islandArray, baseId ); b2Island* baseIsland = world->islandArray + baseId; int setIndex = baseIsland->setIndex; - if (setIndex != b2_awakeSet) + if ( setIndex != b2_awakeSet ) { // can only split awake island return; } - if (baseIsland->constraintRemoveCount == 0) + if ( baseIsland->constraintRemoveCount == 0 ) { // this island doesn't need to be split return; } - b2ValidateIsland(world, baseId); + b2ValidateIsland( world, baseId ); int bodyCount = baseIsland->bodyCount; @@ -633,14 +634,14 @@ void b2SplitIsland(b2World* world, int baseId) b2StackAllocator* alloc = &world->stackAllocator; // No lock is needed because I ensure the allocator is not used while this task is active. - int* stack = b2AllocateStackItem(alloc, bodyCount * sizeof(int), "island stack"); - int* bodyIds = b2AllocateStackItem(alloc, bodyCount * sizeof(int), "body ids"); + int* stack = b2AllocateStackItem( alloc, bodyCount * sizeof( int ), "island stack" ); + int* bodyIds = b2AllocateStackItem( alloc, bodyCount * sizeof( int ), "body ids" ); // Build array containing all body indices from base island. These // serve as seed bodies for the depth first search (DFS). int index = 0; int nextBody = baseIsland->headBody; - while (nextBody != B2_NULL_INDEX) + while ( nextBody != B2_NULL_INDEX ) { bodyIds[index++] = nextBody; b2Body* body = bodies + nextBody; @@ -650,12 +651,12 @@ void b2SplitIsland(b2World* world, int baseId) nextBody = body->islandNext; } - B2_ASSERT(index == bodyCount); + B2_ASSERT( index == bodyCount ); // Clear contact island flags. Only need to consider contacts // already in the base island. int nextContactId = baseIsland->headContact; - while (nextContactId != B2_NULL_INDEX) + while ( nextContactId != B2_NULL_INDEX ) { b2Contact* contact = contacts + nextContactId; contact->isMarked = false; @@ -664,24 +665,24 @@ void b2SplitIsland(b2World* world, int baseId) // Clear joint island flags. int nextJoint = baseIsland->headJoint; - while (nextJoint != B2_NULL_INDEX) + while ( nextJoint != B2_NULL_INDEX ) { - b2Joint* joint = b2GetJoint(world, nextJoint); + b2Joint* joint = b2GetJoint( world, nextJoint ); joint->isMarked = false; nextJoint = joint->islandNext; } // Done with the base split island. - b2DestroyIsland(world, baseId); + b2DestroyIsland( world, baseId ); // Each island is found as a depth first search starting from a seed body - for (int i = 0; i < bodyCount; ++i) + for ( int i = 0; i < bodyCount; ++i ) { int seedIndex = bodyIds[i]; b2Body* seed = bodies + seedIndex; - B2_ASSERT(seed->setIndex == setIndex); + B2_ASSERT( seed->setIndex == setIndex ); - if (seed->isMarked == true) + if ( seed->isMarked == true ) { // The body has already been visited continue; @@ -694,22 +695,22 @@ void b2SplitIsland(b2World* world, int baseId) // Create new island // No lock needed because only a single island can split per time step. No islands are being used during the constraint // solve. However, islands are touched during body finalization. - b2Island* island = b2CreateIsland(world, setIndex); + b2Island* island = b2CreateIsland( world, setIndex ); int islandId = island->islandId; // Perform a depth first search (DFS) on the constraint graph. - while (stackCount > 0) + while ( stackCount > 0 ) { // Grab the next body off the stack and add it to the island. int bodyId = stack[--stackCount]; b2Body* body = bodies + bodyId; - B2_ASSERT(body->setIndex == b2_awakeSet); - B2_ASSERT(body->isMarked == true); + B2_ASSERT( body->setIndex == b2_awakeSet ); + B2_ASSERT( body->isMarked == true ); // Add body to island body->islandId = islandId; - if (island->tailBody != B2_NULL_INDEX) + if ( island->tailBody != B2_NULL_INDEX ) { bodies[island->tailBody].islandNext = bodyId; } @@ -717,7 +718,7 @@ void b2SplitIsland(b2World* world, int baseId) body->islandNext = B2_NULL_INDEX; island->tailBody = bodyId; - if (island->headBody == B2_NULL_INDEX) + if ( island->headBody == B2_NULL_INDEX ) { island->headBody = bodyId; } @@ -726,32 +727,32 @@ void b2SplitIsland(b2World* world, int baseId) // Search all contacts connected to this body. int contactKey = body->headContactKey; - while (contactKey != B2_NULL_INDEX) + while ( contactKey != B2_NULL_INDEX ) { int contactId = contactKey >> 1; int edgeIndex = contactKey & 1; - b2CheckIndex(world->contactArray, contactId); + b2CheckIndex( world->contactArray, contactId ); b2Contact* contact = world->contactArray + contactId; - B2_ASSERT(contact->contactId == contactId); + B2_ASSERT( contact->contactId == contactId ); // Next key contactKey = contact->edges[edgeIndex].nextKey; // Has this contact already been added to this island? - if (contact->isMarked) + if ( contact->isMarked ) { continue; } // Skip sensors - if (contact->flags & b2_contactSensorFlag) + if ( contact->flags & b2_contactSensorFlag ) { continue; } // Is this contact enabled and touching? - if ((contact->flags & b2_contactTouchingFlag) == 0) + if ( ( contact->flags & b2_contactTouchingFlag ) == 0 ) { continue; } @@ -763,18 +764,18 @@ void b2SplitIsland(b2World* world, int baseId) b2Body* otherBody = bodies + otherBodyId; // Maybe add other body to stack - if (otherBody->isMarked == false && otherBody->setIndex != b2_staticSet) + if ( otherBody->isMarked == false && otherBody->setIndex != b2_staticSet ) { - B2_ASSERT(stackCount < bodyCount); + B2_ASSERT( stackCount < bodyCount ); stack[stackCount++] = otherBodyId; otherBody->isMarked = true; } // Add contact to island contact->islandId = islandId; - if (island->tailContact != B2_NULL_INDEX) + if ( island->tailContact != B2_NULL_INDEX ) { - b2CheckIndex(world->contactArray, island->tailContact); + b2CheckIndex( world->contactArray, island->tailContact ); b2Contact* tailContact = world->contactArray + island->tailContact; tailContact->islandNext = contactId; } @@ -782,7 +783,7 @@ void b2SplitIsland(b2World* world, int baseId) contact->islandNext = B2_NULL_INDEX; island->tailContact = contactId; - if (island->headContact == B2_NULL_INDEX) + if ( island->headContact == B2_NULL_INDEX ) { island->headContact = contactId; } @@ -792,19 +793,19 @@ void b2SplitIsland(b2World* world, int baseId) // Search all joints connect to this body. int jointKey = body->headJointKey; - while (jointKey != B2_NULL_INDEX) + while ( jointKey != B2_NULL_INDEX ) { int jointId = jointKey >> 1; int edgeIndex = jointKey & 1; - b2Joint* joint = b2GetJoint(world, jointId); - B2_ASSERT(joint->jointId == jointId); + b2Joint* joint = b2GetJoint( world, jointId ); + B2_ASSERT( joint->jointId == jointId ); // Next key jointKey = joint->edges[edgeIndex].nextKey; // Has this joint already been added to this island? - if (joint->isMarked) + if ( joint->isMarked ) { continue; } @@ -816,31 +817,31 @@ void b2SplitIsland(b2World* world, int baseId) b2Body* otherBody = bodies + otherBodyId; // Don't simulate joints connected to disabled bodies. - if (otherBody->setIndex == b2_disabledSet) + if ( otherBody->setIndex == b2_disabledSet ) { continue; } // Maybe add other body to stack - if (otherBody->isMarked == false && otherBody->setIndex == b2_awakeSet) + if ( otherBody->isMarked == false && otherBody->setIndex == b2_awakeSet ) { - B2_ASSERT(stackCount < bodyCount); + B2_ASSERT( stackCount < bodyCount ); stack[stackCount++] = otherBodyId; otherBody->isMarked = true; } // Add joint to island joint->islandId = islandId; - if (island->tailJoint != B2_NULL_INDEX) + if ( island->tailJoint != B2_NULL_INDEX ) { - b2Joint* tailJoint = b2GetJoint(world, island->tailJoint); + b2Joint* tailJoint = b2GetJoint( world, island->tailJoint ); tailJoint->islandNext = jointId; } joint->islandPrev = island->tailJoint; joint->islandNext = B2_NULL_INDEX; island->tailJoint = jointId; - if (island->headJoint == B2_NULL_INDEX) + if ( island->headJoint == B2_NULL_INDEX ) { island->headJoint = jointId; } @@ -849,11 +850,11 @@ void b2SplitIsland(b2World* world, int baseId) } } - b2ValidateIsland(world, islandId); + b2ValidateIsland( world, islandId ); } - b2FreeStackItem(alloc, bodyIds); - b2FreeStackItem(alloc, stack); + b2FreeStackItem( alloc, bodyIds ); + b2FreeStackItem( alloc, stack ); } // Split an island because some contacts and/or joints have been removed. @@ -863,139 +864,139 @@ void b2SplitIsland(b2World* world, int baseId) // Note: static bodies are never in an island // Note: this task interacts with some allocators without locks under the assumption that no other tasks // are interacting with these data structures. -void b2SplitIslandTask(int startIndex, int endIndex, uint32_t threadIndex, void* context) +void b2SplitIslandTask( int startIndex, int endIndex, uint32_t threadIndex, void* context ) { - b2TracyCZoneNC(split, "Split Island", b2_colorHoneydew2, true); + b2TracyCZoneNC( split, "Split Island", b2_colorHoneydew, true ); - B2_MAYBE_UNUSED(startIndex); - B2_MAYBE_UNUSED(endIndex); - B2_MAYBE_UNUSED(threadIndex); + B2_MAYBE_UNUSED( startIndex ); + B2_MAYBE_UNUSED( endIndex ); + B2_MAYBE_UNUSED( threadIndex ); b2Timer timer = b2CreateTimer(); b2World* world = context; - B2_ASSERT(world->splitIslandId != B2_NULL_INDEX); + B2_ASSERT( world->splitIslandId != B2_NULL_INDEX ); - b2SplitIsland(world, world->splitIslandId); + b2SplitIsland( world, world->splitIslandId ); - world->profile.splitIslands += b2GetMilliseconds(&timer); - b2TracyCZoneEnd(split); + world->profile.splitIslands += b2GetMilliseconds( &timer ); + b2TracyCZoneEnd( split ); } #if B2_VALIDATE -void b2ValidateIsland(b2World* world, int islandId) +void b2ValidateIsland( b2World* world, int islandId ) { - b2CheckIndex(world->islandArray, islandId); + b2CheckIndex( world->islandArray, islandId ); b2Island* island = world->islandArray + islandId; - B2_ASSERT(island->islandId == islandId); - B2_ASSERT(island->setIndex != B2_NULL_INDEX); - B2_ASSERT(island->headBody != B2_NULL_INDEX); + B2_ASSERT( island->islandId == islandId ); + B2_ASSERT( island->setIndex != B2_NULL_INDEX ); + B2_ASSERT( island->headBody != B2_NULL_INDEX ); { b2Body* bodies = world->bodyArray; - B2_ASSERT(island->tailBody != B2_NULL_INDEX); - B2_ASSERT(island->bodyCount > 0); - if (island->bodyCount > 1) + B2_ASSERT( island->tailBody != B2_NULL_INDEX ); + B2_ASSERT( island->bodyCount > 0 ); + if ( island->bodyCount > 1 ) { - B2_ASSERT(island->tailBody != island->headBody); + B2_ASSERT( island->tailBody != island->headBody ); } - B2_ASSERT(island->bodyCount <= b2GetIdCount(&world->bodyIdPool)); + B2_ASSERT( island->bodyCount <= b2GetIdCount( &world->bodyIdPool ) ); int count = 0; int bodyId = island->headBody; - while (bodyId != B2_NULL_INDEX) + while ( bodyId != B2_NULL_INDEX ) { - b2CheckIndex(bodies, bodyId); + b2CheckIndex( bodies, bodyId ); b2Body* body = bodies + bodyId; - B2_ASSERT(body->islandId == islandId); - B2_ASSERT(body->setIndex == island->setIndex); + B2_ASSERT( body->islandId == islandId ); + B2_ASSERT( body->setIndex == island->setIndex ); count += 1; - if (count == island->bodyCount) + if ( count == island->bodyCount ) { - B2_ASSERT(bodyId == island->tailBody); + B2_ASSERT( bodyId == island->tailBody ); } bodyId = body->islandNext; } - B2_ASSERT(count == island->bodyCount); + B2_ASSERT( count == island->bodyCount ); } - if (island->headContact != B2_NULL_INDEX) + if ( island->headContact != B2_NULL_INDEX ) { - B2_ASSERT(island->tailContact != B2_NULL_INDEX); - B2_ASSERT(island->contactCount > 0); - if (island->contactCount > 1) + B2_ASSERT( island->tailContact != B2_NULL_INDEX ); + B2_ASSERT( island->contactCount > 0 ); + if ( island->contactCount > 1 ) { - B2_ASSERT(island->tailContact != island->headContact); + B2_ASSERT( island->tailContact != island->headContact ); } - B2_ASSERT(island->contactCount <= b2GetIdCount(&world->contactIdPool)); + B2_ASSERT( island->contactCount <= b2GetIdCount( &world->contactIdPool ) ); int count = 0; int contactId = island->headContact; - while (contactId != B2_NULL_INDEX) + while ( contactId != B2_NULL_INDEX ) { - b2CheckIndex(world->contactArray, contactId); + b2CheckIndex( world->contactArray, contactId ); b2Contact* contact = world->contactArray + contactId; - B2_ASSERT(contact->setIndex == island->setIndex); - B2_ASSERT(contact->islandId == islandId); + B2_ASSERT( contact->setIndex == island->setIndex ); + B2_ASSERT( contact->islandId == islandId ); count += 1; - if (count == island->contactCount) + if ( count == island->contactCount ) { - B2_ASSERT(contactId == island->tailContact); + B2_ASSERT( contactId == island->tailContact ); } contactId = contact->islandNext; } - B2_ASSERT(count == island->contactCount); + B2_ASSERT( count == island->contactCount ); } else { - B2_ASSERT(island->tailContact == B2_NULL_INDEX); - B2_ASSERT(island->contactCount == 0); + B2_ASSERT( island->tailContact == B2_NULL_INDEX ); + B2_ASSERT( island->contactCount == 0 ); } - if (island->headJoint != B2_NULL_INDEX) + if ( island->headJoint != B2_NULL_INDEX ) { - B2_ASSERT(island->tailJoint != B2_NULL_INDEX); - B2_ASSERT(island->jointCount > 0); - if (island->jointCount > 1) + B2_ASSERT( island->tailJoint != B2_NULL_INDEX ); + B2_ASSERT( island->jointCount > 0 ); + if ( island->jointCount > 1 ) { - B2_ASSERT(island->tailJoint != island->headJoint); + B2_ASSERT( island->tailJoint != island->headJoint ); } - B2_ASSERT(island->jointCount <= b2GetIdCount(&world->jointIdPool)); + B2_ASSERT( island->jointCount <= b2GetIdCount( &world->jointIdPool ) ); int count = 0; int jointId = island->headJoint; - while (jointId != B2_NULL_INDEX) + while ( jointId != B2_NULL_INDEX ) { - b2CheckIndex(world->jointArray, jointId); + b2CheckIndex( world->jointArray, jointId ); b2Joint* joint = world->jointArray + jointId; - B2_ASSERT(joint->setIndex == island->setIndex); + B2_ASSERT( joint->setIndex == island->setIndex ); count += 1; - if (count == island->jointCount) + if ( count == island->jointCount ) { - B2_ASSERT(jointId == island->tailJoint); + B2_ASSERT( jointId == island->tailJoint ); } jointId = joint->islandNext; } - B2_ASSERT(count == island->jointCount); + B2_ASSERT( count == island->jointCount ); } else { - B2_ASSERT(island->tailJoint == B2_NULL_INDEX); - B2_ASSERT(island->jointCount == 0); + B2_ASSERT( island->tailJoint == B2_NULL_INDEX ); + B2_ASSERT( island->jointCount == 0 ); } } #else -void b2ValidateIsland(b2World* world, int islandId) +void b2ValidateIsland( b2World* world, int islandId ) { - B2_MAYBE_UNUSED(world); - B2_MAYBE_UNUSED(islandId); + B2_MAYBE_UNUSED( world ); + B2_MAYBE_UNUSED( islandId ); } #endif diff --git a/src/island.h b/src/island.h index 593785db..2e0384c2 100644 --- a/src/island.h +++ b/src/island.h @@ -62,26 +62,26 @@ typedef struct b2IslandSim } b2IslandSim; -b2Island* b2CreateIsland(b2World* world, int setIndex); -void b2DestroyIsland(b2World* world, int islandId); +b2Island* b2CreateIsland( b2World* world, int setIndex ); +void b2DestroyIsland( b2World* world, int islandId ); -b2Island* b2GetIsland(b2World* world, int islandId); +b2Island* b2GetIsland( b2World* world, int islandId ); // Link contacts into the island graph when it starts having contact points -void b2LinkContact(b2World* world, b2Contact* contact); +void b2LinkContact( b2World* world, b2Contact* contact ); // Unlink contact from the island graph when it stops having contact points -void b2UnlinkContact(b2World* world, b2Contact* contact); +void b2UnlinkContact( b2World* world, b2Contact* contact ); // Link a joint into the island graph when it is created -void b2LinkJoint(b2World* world, b2Joint* joint); +void b2LinkJoint( b2World* world, b2Joint* joint ); // Unlink a joint from the island graph when it is destroyed -void b2UnlinkJoint(b2World* world, b2Joint* joint); +void b2UnlinkJoint( b2World* world, b2Joint* joint ); -void b2MergeAwakeIslands(b2World* world); +void b2MergeAwakeIslands( b2World* world ); -void b2SplitIsland(b2World* world, int baseId); -void b2SplitIslandTask(int startIndex, int endIndex, uint32_t threadIndex, void* context); +void b2SplitIsland( b2World* world, int baseId ); +void b2SplitIslandTask( int startIndex, int endIndex, uint32_t threadIndex, void* context ); -void b2ValidateIsland(b2World* world, int islandId); +void b2ValidateIsland( b2World* world, int islandId ); diff --git a/src/joint.c b/src/joint.c index 06e45104..3080653c 100644 --- a/src/joint.c +++ b/src/joint.c @@ -16,18 +16,18 @@ #include -b2DistanceJointDef b2DefaultDistanceJointDef(void) +b2DistanceJointDef b2DefaultDistanceJointDef( void ) { - b2DistanceJointDef def = {0}; + b2DistanceJointDef def = { 0 }; def.length = 1.0f; def.maxLength = b2_huge; def.internalValue = B2_SECRET_COOKIE; return def; } -b2MotorJointDef b2DefaultMotorJointDef(void) +b2MotorJointDef b2DefaultMotorJointDef( void ) { - b2MotorJointDef def = {0}; + b2MotorJointDef def = { 0 }; def.maxForce = 1.0f; def.maxTorque = 1.0f; def.correctionFactor = 0.3f; @@ -35,9 +35,9 @@ b2MotorJointDef b2DefaultMotorJointDef(void) return def; } -b2MouseJointDef b2DefaultMouseJointDef(void) +b2MouseJointDef b2DefaultMouseJointDef( void ) { - b2MouseJointDef def = {0}; + b2MouseJointDef def = { 0 }; def.hertz = 4.0f; def.dampingRatio = 1.0f; def.maxForce = 1.0f; @@ -45,32 +45,32 @@ b2MouseJointDef b2DefaultMouseJointDef(void) return def; } -b2PrismaticJointDef b2DefaultPrismaticJointDef(void) +b2PrismaticJointDef b2DefaultPrismaticJointDef( void ) { - b2PrismaticJointDef def = {0}; - def.localAxisA = (b2Vec2){1.0f, 0.0f}; + b2PrismaticJointDef def = { 0 }; + def.localAxisA = ( b2Vec2 ){ 1.0f, 0.0f }; def.internalValue = B2_SECRET_COOKIE; return def; } -b2RevoluteJointDef b2DefaultRevoluteJointDef(void) +b2RevoluteJointDef b2DefaultRevoluteJointDef( void ) { - b2RevoluteJointDef def = {0}; + b2RevoluteJointDef def = { 0 }; def.drawSize = 0.25f; def.internalValue = B2_SECRET_COOKIE; return def; } -b2WeldJointDef b2DefaultWeldJointDef(void) +b2WeldJointDef b2DefaultWeldJointDef( void ) { - b2WeldJointDef def = {0}; + b2WeldJointDef def = { 0 }; def.internalValue = B2_SECRET_COOKIE; return def; } -b2WheelJointDef b2DefaultWheelJointDef(void) +b2WheelJointDef b2DefaultWheelJointDef( void ) { - b2WheelJointDef def = {0}; + b2WheelJointDef def = { 0 }; def.localAxisA.y = 1.0f; def.enableSpring = true; def.hertz = 1.0f; @@ -79,55 +79,55 @@ b2WheelJointDef b2DefaultWheelJointDef(void) return def; } -static b2Joint* b2GetJointFullId(b2World* world, b2JointId jointId) +static b2Joint* b2GetJointFullId( b2World* world, b2JointId jointId ) { int id = jointId.index1 - 1; - b2CheckIndex(world->jointArray, id); + b2CheckIndex( world->jointArray, id ); b2Joint* joint = world->jointArray + id; - b2CheckIndex(world->solverSetArray, joint->setIndex); - B2_ASSERT(joint->revision == jointId.revision); + b2CheckIndex( world->solverSetArray, joint->setIndex ); + B2_ASSERT( joint->revision == jointId.revision ); return joint; } -b2Joint* b2GetJoint(b2World* world, int jointId) +b2Joint* b2GetJoint( b2World* world, int jointId ) { - b2CheckIndex(world->jointArray, jointId); + b2CheckIndex( world->jointArray, jointId ); b2Joint* joint = world->jointArray + jointId; return joint; } -b2JointSim* b2GetJointSim(b2World* world, b2Joint* joint) +b2JointSim* b2GetJointSim( b2World* world, b2Joint* joint ) { - b2CheckIndex(world->solverSetArray, joint->setIndex); + b2CheckIndex( world->solverSetArray, joint->setIndex ); - if (joint->setIndex == b2_awakeSet) + if ( joint->setIndex == b2_awakeSet ) { - B2_ASSERT(0 <= joint->colorIndex && joint->colorIndex < b2_graphColorCount); + B2_ASSERT( 0 <= joint->colorIndex && joint->colorIndex < b2_graphColorCount ); b2GraphColor* color = world->constraintGraph.colors + joint->colorIndex; - B2_ASSERT(0 <= joint->localIndex && joint->localIndex < color->joints.count); + B2_ASSERT( 0 <= joint->localIndex && joint->localIndex < color->joints.count ); return color->joints.data + joint->localIndex; } b2SolverSet* set = world->solverSetArray + joint->setIndex; - B2_ASSERT(0 <= joint->localIndex && joint->localIndex < set->joints.count); + B2_ASSERT( 0 <= joint->localIndex && joint->localIndex < set->joints.count ); return set->joints.data + joint->localIndex; } -b2JointSim* b2GetJointSimCheckType(b2JointId jointId, b2JointType type) +b2JointSim* b2GetJointSimCheckType( b2JointId jointId, b2JointType type ) { - B2_MAYBE_UNUSED(type); + B2_MAYBE_UNUSED( type ); - b2World* world = b2GetWorld(jointId.world0); - B2_ASSERT(world->locked == false); - if (world->locked) + b2World* world = b2GetWorld( jointId.world0 ); + B2_ASSERT( world->locked == false ); + if ( world->locked ) { return NULL; } - b2Joint* joint = b2GetJointFullId(world, jointId); - B2_ASSERT(joint->type == type); - b2JointSim* jointSim = b2GetJointSim(world, joint); - B2_ASSERT(jointSim->type == type); + b2Joint* joint = b2GetJointFullId( world, jointId ); + B2_ASSERT( joint->type == type ); + b2JointSim* jointSim = b2GetJointSim( world, joint ); + B2_ASSERT( jointSim->type == type ); return jointSim; } @@ -137,17 +137,18 @@ typedef struct b2JointPair b2JointSim* jointSim; } b2JointPair; -static b2JointPair b2CreateJoint(b2World* world, b2Body* bodyA, b2Body* bodyB, void* userData, float drawSize, b2JointType type, bool collideConnected) +static b2JointPair b2CreateJoint( b2World* world, b2Body* bodyA, b2Body* bodyB, void* userData, float drawSize, b2JointType type, + bool collideConnected ) { int bodyIdA = bodyA->id; int bodyIdB = bodyB->id; - int maxSetIndex = b2MaxInt(bodyA->setIndex, bodyB->setIndex); + int maxSetIndex = b2MaxInt( bodyA->setIndex, bodyB->setIndex ); // Create joint id and joint - int jointId = b2AllocId(&world->jointIdPool); - if (jointId == b2Array(world->jointArray).count) + int jointId = b2AllocId( &world->jointIdPool ); + if ( jointId == b2Array( world->jointArray ).count ) { - b2Array_Push(world->jointArray, (b2Joint){0}); + b2Array_Push( world->jointArray, ( b2Joint ){ 0 } ); } b2Joint* joint = world->jointArray + jointId; @@ -170,11 +171,11 @@ static b2JointPair b2CreateJoint(b2World* world, b2Body* bodyA, b2Body* bodyB, v joint->edges[0].prevKey = B2_NULL_INDEX; joint->edges[0].nextKey = bodyA->headJointKey; - int keyA = (jointId << 1) | 0; - if (bodyA->headJointKey != B2_NULL_INDEX) + int keyA = ( jointId << 1 ) | 0; + if ( bodyA->headJointKey != B2_NULL_INDEX ) { - b2Joint* jointA = world->jointArray + (bodyA->headJointKey >> 1); - b2JointEdge* edgeA = jointA->edges + (bodyA->headJointKey & 1); + b2Joint* jointA = world->jointArray + ( bodyA->headJointKey >> 1 ); + b2JointEdge* edgeA = jointA->edges + ( bodyA->headJointKey & 1 ); edgeA->prevKey = keyA; } bodyA->headJointKey = keyA; @@ -185,11 +186,11 @@ static b2JointPair b2CreateJoint(b2World* world, b2Body* bodyA, b2Body* bodyB, v joint->edges[1].prevKey = B2_NULL_INDEX; joint->edges[1].nextKey = bodyB->headJointKey; - int keyB = (jointId << 1) | 1; - if (bodyB->headJointKey != B2_NULL_INDEX) + int keyB = ( jointId << 1 ) | 1; + if ( bodyB->headJointKey != B2_NULL_INDEX ) { - b2Joint* jointB = world->jointArray + (bodyB->headJointKey >> 1); - b2JointEdge* edgeB = jointB->edges + (bodyB->headJointKey & 1); + b2Joint* jointB = world->jointArray + ( bodyB->headJointKey >> 1 ); + b2JointEdge* edgeB = jointB->edges + ( bodyB->headJointKey & 1 ); edgeB->prevKey = keyB; } bodyB->headJointKey = keyB; @@ -197,41 +198,41 @@ static b2JointPair b2CreateJoint(b2World* world, b2Body* bodyA, b2Body* bodyB, v b2JointSim* jointSim; - if (bodyA->setIndex == b2_disabledSet || bodyB->setIndex == b2_disabledSet) + if ( bodyA->setIndex == b2_disabledSet || bodyB->setIndex == b2_disabledSet ) { // if either body is disabled, create in disabled set b2SolverSet* set = world->solverSetArray + b2_disabledSet; joint->setIndex = b2_disabledSet; joint->localIndex = set->joints.count; - jointSim = b2AddJoint(&set->joints); + jointSim = b2AddJoint( &set->joints ); jointSim->jointId = jointId; jointSim->bodyIdA = bodyIdA; jointSim->bodyIdB = bodyIdB; } - else if (bodyA->setIndex == b2_staticSet && bodyB->setIndex == b2_staticSet) + else if ( bodyA->setIndex == b2_staticSet && bodyB->setIndex == b2_staticSet ) { // joint is connecting static bodies b2SolverSet* set = world->solverSetArray + b2_staticSet; joint->setIndex = b2_staticSet; joint->localIndex = set->joints.count; - jointSim = b2AddJoint(&set->joints); + jointSim = b2AddJoint( &set->joints ); jointSim->jointId = jointId; jointSim->bodyIdA = bodyIdA; jointSim->bodyIdB = bodyIdB; } - else if (bodyA->setIndex == b2_awakeSet || bodyB->setIndex == b2_awakeSet) + else if ( bodyA->setIndex == b2_awakeSet || bodyB->setIndex == b2_awakeSet ) { // if either body is sleeping, wake it - if (maxSetIndex >= b2_firstSleepingSet) + if ( maxSetIndex >= b2_firstSleepingSet ) { - b2WakeSolverSet(world, maxSetIndex); + b2WakeSolverSet( world, maxSetIndex ); } joint->setIndex = b2_awakeSet; - jointSim = b2CreateJointInGraph(world, joint); + jointSim = b2CreateJointInGraph( world, joint ); jointSim->jointId = jointId; jointSim->bodyIdA = bodyIdA; jointSim->bodyIdB = bodyIdB; @@ -239,28 +240,27 @@ static b2JointPair b2CreateJoint(b2World* world, b2Body* bodyA, b2Body* bodyB, v else { // joint connected between sleeping and/or static bodies - B2_ASSERT(bodyA->setIndex >= b2_firstSleepingSet || bodyB->setIndex >= b2_firstSleepingSet); - B2_ASSERT(bodyA->setIndex != b2_staticSet || bodyB->setIndex != b2_staticSet); + B2_ASSERT( bodyA->setIndex >= b2_firstSleepingSet || bodyB->setIndex >= b2_firstSleepingSet ); + B2_ASSERT( bodyA->setIndex != b2_staticSet || bodyB->setIndex != b2_staticSet ); // joint should go into the sleeping set (not static set) int setIndex = maxSetIndex; - b2CheckIndex(world->solverSetArray, setIndex); + b2CheckIndex( world->solverSetArray, setIndex ); b2SolverSet* set = world->solverSetArray + setIndex; joint->setIndex = setIndex; joint->localIndex = set->joints.count; - jointSim = b2AddJoint(&set->joints); + jointSim = b2AddJoint( &set->joints ); jointSim->jointId = jointId; jointSim->bodyIdA = bodyIdA; jointSim->bodyIdB = bodyIdB; - if (bodyA->setIndex != bodyB->setIndex && - bodyA->setIndex >= b2_firstSleepingSet && - bodyB->setIndex >= b2_firstSleepingSet) + if ( bodyA->setIndex != bodyB->setIndex && bodyA->setIndex >= b2_firstSleepingSet && + bodyB->setIndex >= b2_firstSleepingSet ) { // merge sleeping sets - b2MergeSolverSets(world, bodyA->setIndex, bodyB->setIndex); - B2_ASSERT(bodyA->setIndex == bodyB->setIndex); + b2MergeSolverSets( world, bodyA->setIndex, bodyB->setIndex ); + B2_ASSERT( bodyA->setIndex == bodyB->setIndex ); // fix potentially invalid set index setIndex = bodyA->setIndex; @@ -269,31 +269,31 @@ static b2JointPair b2CreateJoint(b2World* world, b2Body* bodyA, b2Body* bodyB, v jointSim = world->solverSetArray[setIndex].joints.data + joint->localIndex; } - B2_ASSERT(joint->setIndex == setIndex); + B2_ASSERT( joint->setIndex == setIndex ); } - B2_ASSERT(jointSim->jointId == jointId); - B2_ASSERT(jointSim->bodyIdA == bodyIdA); - B2_ASSERT(jointSim->bodyIdB == bodyIdB); + B2_ASSERT( jointSim->jointId == jointId ); + B2_ASSERT( jointSim->bodyIdA == bodyIdA ); + B2_ASSERT( jointSim->bodyIdB == bodyIdB ); - if (joint->setIndex > b2_disabledSet) + if ( joint->setIndex > b2_disabledSet ) { // Add edge to island graph - b2LinkJoint(world, joint); + b2LinkJoint( world, joint ); } - b2ValidateSolverSets(world); + b2ValidateSolverSets( world ); - return (b2JointPair){joint, jointSim}; + return ( b2JointPair ){ joint, jointSim }; } -static void b2DestroyContactsBetweenBodies(b2World* world, b2Body* bodyA, b2Body* bodyB) +static void b2DestroyContactsBetweenBodies( b2World* world, b2Body* bodyA, b2Body* bodyB ) { int contactKey; int otherBodyId; // use the smaller of the two contact lists - if (bodyA->contactCount < bodyB->contactCount) + if ( bodyA->contactCount < bodyB->contactCount ) { contactKey = bodyA->headContactKey; otherBodyId = bodyB->id; @@ -308,59 +308,59 @@ static void b2DestroyContactsBetweenBodies(b2World* world, b2Body* bodyA, b2Body bool wakeBodies = false; // destroy the contacts - while (contactKey != B2_NULL_INDEX) + while ( contactKey != B2_NULL_INDEX ) { int contactId = contactKey >> 1; int edgeIndex = contactKey & 1; - b2CheckIndex(world->contactArray, contactId); + b2CheckIndex( world->contactArray, contactId ); b2Contact* contact = world->contactArray + contactId; contactKey = contact->edges[edgeIndex].nextKey; int otherEdgeIndex = edgeIndex ^ 1; - if (contact->edges[otherEdgeIndex].bodyId == otherBodyId) + if ( contact->edges[otherEdgeIndex].bodyId == otherBodyId ) { // Careful, this removes the contact from the current doubly linked list - b2DestroyContact(world, contact, wakeBodies); + b2DestroyContact( world, contact, wakeBodies ); } } - b2ValidateSolverSets(world); + b2ValidateSolverSets( world ); } -b2JointId b2CreateDistanceJoint(b2WorldId worldId, const b2DistanceJointDef* def) +b2JointId b2CreateDistanceJoint( b2WorldId worldId, const b2DistanceJointDef* def ) { - b2CheckDef(def); - b2World* world = b2GetWorldFromId(worldId); + b2CheckDef( def ); + b2World* world = b2GetWorldFromId( worldId ); - B2_ASSERT(world->locked == false); + B2_ASSERT( world->locked == false ); - if (world->locked) + if ( world->locked ) { - return (b2JointId){0}; + return ( b2JointId ){ 0 }; } - B2_ASSERT(b2Body_IsValid(def->bodyIdA)); - B2_ASSERT(b2Body_IsValid(def->bodyIdB)); - B2_ASSERT(b2IsValid(def->length) && def->length > 0.0f); + B2_ASSERT( b2Body_IsValid( def->bodyIdA ) ); + B2_ASSERT( b2Body_IsValid( def->bodyIdB ) ); + B2_ASSERT( b2IsValid( def->length ) && def->length > 0.0f ); - b2Body* bodyA = b2GetBodyFullId(world, def->bodyIdA); - b2Body* bodyB = b2GetBodyFullId(world, def->bodyIdB); + b2Body* bodyA = b2GetBodyFullId( world, def->bodyIdA ); + b2Body* bodyB = b2GetBodyFullId( world, def->bodyIdB ); - b2JointPair pair = b2CreateJoint(world, bodyA, bodyB, def->userData, 1.0f, b2_distanceJoint, def->collideConnected); + b2JointPair pair = b2CreateJoint( world, bodyA, bodyB, def->userData, 1.0f, b2_distanceJoint, def->collideConnected ); b2JointSim* joint = pair.jointSim; joint->type = b2_distanceJoint; joint->localOriginAnchorA = def->localAnchorA; joint->localOriginAnchorB = def->localAnchorB; - b2DistanceJoint empty = {0}; + b2DistanceJoint empty = { 0 }; joint->distanceJoint = empty; - joint->distanceJoint.length = b2MaxFloat(def->length, b2_linearSlop); + joint->distanceJoint.length = b2MaxFloat( def->length, b2_linearSlop ); joint->distanceJoint.hertz = def->hertz; joint->distanceJoint.dampingRatio = def->dampingRatio; - joint->distanceJoint.minLength = b2MaxFloat(def->minLength, b2_linearSlop); - joint->distanceJoint.maxLength = b2MaxFloat(def->minLength, def->maxLength); + joint->distanceJoint.minLength = b2MaxFloat( def->minLength, b2_linearSlop ); + joint->distanceJoint.maxLength = b2MaxFloat( def->minLength, def->maxLength ); joint->distanceJoint.maxMotorForce = def->maxMotorForce; joint->distanceJoint.motorSpeed = def->motorSpeed; joint->distanceJoint.enableSpring = def->enableSpring; @@ -372,115 +372,116 @@ b2JointId b2CreateDistanceJoint(b2WorldId worldId, const b2DistanceJointDef* def joint->distanceJoint.motorImpulse = 0.0f; // If the joint prevents collisions, then destroy all contacts between attached bodies - if (def->collideConnected == false) + if ( def->collideConnected == false ) { - b2DestroyContactsBetweenBodies(world, bodyA, bodyB); + b2DestroyContactsBetweenBodies( world, bodyA, bodyB ); } - b2JointId jointId = {joint->jointId + 1, world->worldId, pair.joint->revision}; + b2JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->revision }; return jointId; } -b2JointId b2CreateMotorJoint(b2WorldId worldId, const b2MotorJointDef* def) +b2JointId b2CreateMotorJoint( b2WorldId worldId, const b2MotorJointDef* def ) { - b2CheckDef(def); - b2World* world = b2GetWorldFromId(worldId); + b2CheckDef( def ); + b2World* world = b2GetWorldFromId( worldId ); - B2_ASSERT(world->locked == false); + B2_ASSERT( world->locked == false ); - if (world->locked) + if ( world->locked ) { - return (b2JointId){0}; + return ( b2JointId ){ 0 }; } - b2Body* bodyA = b2GetBodyFullId(world, def->bodyIdA); - b2Body* bodyB = b2GetBodyFullId(world, def->bodyIdB); + b2Body* bodyA = b2GetBodyFullId( world, def->bodyIdA ); + b2Body* bodyB = b2GetBodyFullId( world, def->bodyIdB ); - b2JointPair pair = b2CreateJoint(world, bodyA, bodyB, def->userData, 1.0f, b2_motorJoint, def->collideConnected); + b2JointPair pair = b2CreateJoint( world, bodyA, bodyB, def->userData, 1.0f, b2_motorJoint, def->collideConnected ); b2JointSim* joint = pair.jointSim; joint->type = b2_motorJoint; - joint->localOriginAnchorA = (b2Vec2){0.0f, 0.0f}; - joint->localOriginAnchorB = (b2Vec2){0.0f, 0.0f}; - joint->motorJoint = (b2MotorJoint){0}; + joint->localOriginAnchorA = ( b2Vec2 ){ 0.0f, 0.0f }; + joint->localOriginAnchorB = ( b2Vec2 ){ 0.0f, 0.0f }; + joint->motorJoint = ( b2MotorJoint ){ 0 }; joint->motorJoint.linearOffset = def->linearOffset; joint->motorJoint.angularOffset = def->angularOffset; joint->motorJoint.maxForce = def->maxForce; joint->motorJoint.maxTorque = def->maxTorque; - joint->motorJoint.correctionFactor = b2ClampFloat(def->correctionFactor, 0.0f, 1.0f); + joint->motorJoint.correctionFactor = b2ClampFloat( def->correctionFactor, 0.0f, 1.0f ); // If the joint prevents collisions, then destroy all contacts between attached bodies - if (def->collideConnected == false) + if ( def->collideConnected == false ) { - b2DestroyContactsBetweenBodies(world, bodyA, bodyB); + b2DestroyContactsBetweenBodies( world, bodyA, bodyB ); } - b2JointId jointId = {joint->jointId + 1, world->worldId, pair.joint->revision}; + b2JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->revision }; return jointId; } -b2JointId b2CreateMouseJoint(b2WorldId worldId, const b2MouseJointDef* def) +b2JointId b2CreateMouseJoint( b2WorldId worldId, const b2MouseJointDef* def ) { - b2CheckDef(def); - b2World* world = b2GetWorldFromId(worldId); + b2CheckDef( def ); + b2World* world = b2GetWorldFromId( worldId ); - B2_ASSERT(world->locked == false); + B2_ASSERT( world->locked == false ); - if (world->locked) + if ( world->locked ) { - return (b2JointId){0}; + return ( b2JointId ){ 0 }; } - b2Body* bodyA = b2GetBodyFullId(world, def->bodyIdA); - b2Body* bodyB = b2GetBodyFullId(world, def->bodyIdB); + b2Body* bodyA = b2GetBodyFullId( world, def->bodyIdA ); + b2Body* bodyB = b2GetBodyFullId( world, def->bodyIdB ); - b2Transform transformA = b2GetBodyTransformQuick(world, bodyA); - b2Transform transformB = b2GetBodyTransformQuick(world, bodyB); + b2Transform transformA = b2GetBodyTransformQuick( world, bodyA ); + b2Transform transformB = b2GetBodyTransformQuick( world, bodyB ); - b2JointPair pair = b2CreateJoint(world, bodyA, bodyB, def->userData, 1.0f, b2_mouseJoint, def->collideConnected); + b2JointPair pair = b2CreateJoint( world, bodyA, bodyB, def->userData, 1.0f, b2_mouseJoint, def->collideConnected ); b2JointSim* joint = pair.jointSim; joint->type = b2_mouseJoint; - joint->localOriginAnchorA = b2InvTransformPoint(transformA, def->target); - joint->localOriginAnchorB = b2InvTransformPoint(transformB, def->target); + joint->localOriginAnchorA = b2InvTransformPoint( transformA, def->target ); + joint->localOriginAnchorB = b2InvTransformPoint( transformB, def->target ); - b2MouseJoint empty = {0}; + b2MouseJoint empty = { 0 }; joint->mouseJoint = empty; joint->mouseJoint.targetA = def->target; joint->mouseJoint.hertz = def->hertz; joint->mouseJoint.dampingRatio = def->dampingRatio; joint->mouseJoint.maxForce = def->maxForce; - b2JointId jointId = {joint->jointId + 1, world->worldId, pair.joint->revision}; + b2JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->revision }; return jointId; } -b2JointId b2CreateRevoluteJoint(b2WorldId worldId, const b2RevoluteJointDef* def) +b2JointId b2CreateRevoluteJoint( b2WorldId worldId, const b2RevoluteJointDef* def ) { - b2CheckDef(def); - b2World* world = b2GetWorldFromId(worldId); + b2CheckDef( def ); + b2World* world = b2GetWorldFromId( worldId ); - B2_ASSERT(world->locked == false); + B2_ASSERT( world->locked == false ); - if (world->locked) + if ( world->locked ) { - return (b2JointId){0}; + return ( b2JointId ){ 0 }; } - b2Body* bodyA = b2GetBodyFullId(world, def->bodyIdA); - b2Body* bodyB = b2GetBodyFullId(world, def->bodyIdB); + b2Body* bodyA = b2GetBodyFullId( world, def->bodyIdA ); + b2Body* bodyB = b2GetBodyFullId( world, def->bodyIdB ); - b2JointPair pair = b2CreateJoint(world, bodyA, bodyB, def->userData, def->drawSize, b2_revoluteJoint, def->collideConnected); + b2JointPair pair = + b2CreateJoint( world, bodyA, bodyB, def->userData, def->drawSize, b2_revoluteJoint, def->collideConnected ); b2JointSim* joint = pair.jointSim; joint->type = b2_revoluteJoint; joint->localOriginAnchorA = def->localAnchorA; joint->localOriginAnchorB = def->localAnchorB; - b2RevoluteJoint empty = {0}; + b2RevoluteJoint empty = { 0 }; joint->revoluteJoint = empty; - joint->revoluteJoint.referenceAngle = b2ClampFloat(def->referenceAngle, -b2_pi, b2_pi); + joint->revoluteJoint.referenceAngle = b2ClampFloat( def->referenceAngle, -b2_pi, b2_pi ); joint->revoluteJoint.linearImpulse = b2Vec2_zero; joint->revoluteJoint.axialMass = 0.0f; joint->revoluteJoint.springImpulse = 0.0f; @@ -489,10 +490,10 @@ b2JointId b2CreateRevoluteJoint(b2WorldId worldId, const b2RevoluteJointDef* def joint->revoluteJoint.upperImpulse = 0.0f; joint->revoluteJoint.hertz = def->hertz; joint->revoluteJoint.dampingRatio = def->dampingRatio; - joint->revoluteJoint.lowerAngle = b2MinFloat(def->lowerAngle, def->upperAngle); - joint->revoluteJoint.upperAngle = b2MaxFloat(def->lowerAngle, def->upperAngle); - joint->revoluteJoint.lowerAngle = b2ClampFloat(joint->revoluteJoint.lowerAngle, -b2_pi, b2_pi); - joint->revoluteJoint.upperAngle = b2ClampFloat(joint->revoluteJoint.upperAngle, -b2_pi, b2_pi); + joint->revoluteJoint.lowerAngle = b2MinFloat( def->lowerAngle, def->upperAngle ); + joint->revoluteJoint.upperAngle = b2MaxFloat( def->lowerAngle, def->upperAngle ); + joint->revoluteJoint.lowerAngle = b2ClampFloat( joint->revoluteJoint.lowerAngle, -b2_pi, b2_pi ); + joint->revoluteJoint.upperAngle = b2ClampFloat( joint->revoluteJoint.upperAngle, -b2_pi, b2_pi ); joint->revoluteJoint.maxMotorTorque = def->maxMotorTorque; joint->revoluteJoint.motorSpeed = def->motorSpeed; joint->revoluteJoint.enableSpring = def->enableSpring; @@ -500,41 +501,41 @@ b2JointId b2CreateRevoluteJoint(b2WorldId worldId, const b2RevoluteJointDef* def joint->revoluteJoint.enableMotor = def->enableMotor; // If the joint prevents collisions, then destroy all contacts between attached bodies - if (def->collideConnected == false) + if ( def->collideConnected == false ) { - b2DestroyContactsBetweenBodies(world, bodyA, bodyB); + b2DestroyContactsBetweenBodies( world, bodyA, bodyB ); } - b2JointId jointId = {joint->jointId + 1, world->worldId, pair.joint->revision}; + b2JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->revision }; return jointId; } -b2JointId b2CreatePrismaticJoint(b2WorldId worldId, const b2PrismaticJointDef* def) +b2JointId b2CreatePrismaticJoint( b2WorldId worldId, const b2PrismaticJointDef* def ) { - b2CheckDef(def); - b2World* world = b2GetWorldFromId(worldId); + b2CheckDef( def ); + b2World* world = b2GetWorldFromId( worldId ); - B2_ASSERT(world->locked == false); + B2_ASSERT( world->locked == false ); - if (world->locked) + if ( world->locked ) { - return (b2JointId){0}; + return ( b2JointId ){ 0 }; } - b2Body* bodyA = b2GetBodyFullId(world, def->bodyIdA); - b2Body* bodyB = b2GetBodyFullId(world, def->bodyIdB); + b2Body* bodyA = b2GetBodyFullId( world, def->bodyIdA ); + b2Body* bodyB = b2GetBodyFullId( world, def->bodyIdB ); - b2JointPair pair = b2CreateJoint(world, bodyA, bodyB, def->userData, 1.0f, b2_prismaticJoint, def->collideConnected); + b2JointPair pair = b2CreateJoint( world, bodyA, bodyB, def->userData, 1.0f, b2_prismaticJoint, def->collideConnected ); b2JointSim* joint = pair.jointSim; joint->type = b2_prismaticJoint; joint->localOriginAnchorA = def->localAnchorA; joint->localOriginAnchorB = def->localAnchorB; - b2PrismaticJoint empty = {0}; + b2PrismaticJoint empty = { 0 }; joint->prismaticJoint = empty; - joint->prismaticJoint.localAxisA = b2Normalize(def->localAxisA); + joint->prismaticJoint.localAxisA = b2Normalize( def->localAxisA ); joint->prismaticJoint.referenceAngle = def->referenceAngle; joint->prismaticJoint.impulse = b2Vec2_zero; joint->prismaticJoint.axialMass = 0.0f; @@ -553,38 +554,38 @@ b2JointId b2CreatePrismaticJoint(b2WorldId worldId, const b2PrismaticJointDef* d joint->prismaticJoint.enableMotor = def->enableMotor; // If the joint prevents collisions, then destroy all contacts between attached bodies - if (def->collideConnected == false) + if ( def->collideConnected == false ) { - b2DestroyContactsBetweenBodies(world, bodyA, bodyB); + b2DestroyContactsBetweenBodies( world, bodyA, bodyB ); } - b2JointId jointId = {joint->jointId + 1, world->worldId, pair.joint->revision}; + b2JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->revision }; return jointId; } -b2JointId b2CreateWeldJoint(b2WorldId worldId, const b2WeldJointDef* def) +b2JointId b2CreateWeldJoint( b2WorldId worldId, const b2WeldJointDef* def ) { - b2CheckDef(def); - b2World* world = b2GetWorldFromId(worldId); + b2CheckDef( def ); + b2World* world = b2GetWorldFromId( worldId ); - B2_ASSERT(world->locked == false); + B2_ASSERT( world->locked == false ); - if (world->locked) + if ( world->locked ) { - return (b2JointId){0}; + return ( b2JointId ){ 0 }; } - b2Body* bodyA = b2GetBodyFullId(world, def->bodyIdA); - b2Body* bodyB = b2GetBodyFullId(world, def->bodyIdB); + b2Body* bodyA = b2GetBodyFullId( world, def->bodyIdA ); + b2Body* bodyB = b2GetBodyFullId( world, def->bodyIdB ); - b2JointPair pair = b2CreateJoint(world, bodyA, bodyB, def->userData, 1.0f, b2_weldJoint, def->collideConnected); + b2JointPair pair = b2CreateJoint( world, bodyA, bodyB, def->userData, 1.0f, b2_weldJoint, def->collideConnected ); b2JointSim* joint = pair.jointSim; joint->type = b2_weldJoint; joint->localOriginAnchorA = def->localAnchorA; joint->localOriginAnchorB = def->localAnchorB; - b2WeldJoint empty = {0}; + b2WeldJoint empty = { 0 }; joint->weldJoint = empty; joint->weldJoint.referenceAngle = def->referenceAngle; joint->weldJoint.linearHertz = def->linearHertz; @@ -595,39 +596,39 @@ b2JointId b2CreateWeldJoint(b2WorldId worldId, const b2WeldJointDef* def) joint->weldJoint.angularImpulse = 0.0f; // If the joint prevents collisions, then destroy all contacts between attached bodies - if (def->collideConnected == false) + if ( def->collideConnected == false ) { - b2DestroyContactsBetweenBodies(world, bodyA, bodyB); + b2DestroyContactsBetweenBodies( world, bodyA, bodyB ); } - b2JointId jointId = {joint->jointId + 1, world->worldId, pair.joint->revision}; + b2JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->revision }; return jointId; } -b2JointId b2CreateWheelJoint(b2WorldId worldId, const b2WheelJointDef* def) +b2JointId b2CreateWheelJoint( b2WorldId worldId, const b2WheelJointDef* def ) { - b2CheckDef(def); - b2World* world = b2GetWorldFromId(worldId); + b2CheckDef( def ); + b2World* world = b2GetWorldFromId( worldId ); - B2_ASSERT(world->locked == false); + B2_ASSERT( world->locked == false ); - if (world->locked) + if ( world->locked ) { - return (b2JointId){0}; + return ( b2JointId ){ 0 }; } - b2Body* bodyA = b2GetBodyFullId(world, def->bodyIdA); - b2Body* bodyB = b2GetBodyFullId(world, def->bodyIdB); + b2Body* bodyA = b2GetBodyFullId( world, def->bodyIdA ); + b2Body* bodyB = b2GetBodyFullId( world, def->bodyIdB ); - b2JointPair pair = b2CreateJoint(world, bodyA, bodyB, def->userData, 1.0f, b2_wheelJoint, def->collideConnected); + b2JointPair pair = b2CreateJoint( world, bodyA, bodyB, def->userData, 1.0f, b2_wheelJoint, def->collideConnected ); b2JointSim* joint = pair.jointSim; joint->type = b2_wheelJoint; joint->localOriginAnchorA = def->localAnchorA; joint->localOriginAnchorB = def->localAnchorB; - joint->wheelJoint = (b2WheelJoint){0}; - joint->wheelJoint.localAxisA = b2Normalize(def->localAxisA); + joint->wheelJoint = ( b2WheelJoint ){ 0 }; + joint->wheelJoint.localAxisA = b2Normalize( def->localAxisA ); joint->wheelJoint.perpMass = 0.0f; joint->wheelJoint.axialMass = 0.0f; joint->wheelJoint.motorImpulse = 0.0f; @@ -644,16 +645,16 @@ b2JointId b2CreateWheelJoint(b2WorldId worldId, const b2WheelJointDef* def) joint->wheelJoint.enableMotor = def->enableMotor; // If the joint prevents collisions, then destroy all contacts between attached bodies - if (def->collideConnected == false) + if ( def->collideConnected == false ) { - b2DestroyContactsBetweenBodies(world, bodyA, bodyB); + b2DestroyContactsBetweenBodies( world, bodyA, bodyB ); } - b2JointId jointId = {joint->jointId + 1, world->worldId, pair.joint->revision}; + b2JointId jointId = { joint->jointId + 1, world->worldId, pair.joint->revision }; return jointId; } -void b2DestroyJointInternal(b2World* world, b2Joint* joint, bool wakeBodies) +void b2DestroyJointInternal( b2World* world, b2Joint* joint, bool wakeBodies ) { int jointId = joint->jointId; @@ -662,26 +663,26 @@ void b2DestroyJointInternal(b2World* world, b2Joint* joint, bool wakeBodies) int idA = edgeA->bodyId; int idB = edgeB->bodyId; - b2Body* bodyA = b2GetBody(world, idA); - b2Body* bodyB = b2GetBody(world, idB); + b2Body* bodyA = b2GetBody( world, idA ); + b2Body* bodyB = b2GetBody( world, idB ); // Remove from body A - if (edgeA->prevKey != B2_NULL_INDEX) + if ( edgeA->prevKey != B2_NULL_INDEX ) { - b2Joint* prevJoint = world->jointArray + (edgeA->prevKey >> 1); - b2JointEdge* prevEdge = prevJoint->edges + (edgeA->prevKey & 1); + b2Joint* prevJoint = world->jointArray + ( edgeA->prevKey >> 1 ); + b2JointEdge* prevEdge = prevJoint->edges + ( edgeA->prevKey & 1 ); prevEdge->nextKey = edgeA->nextKey; } - if (edgeA->nextKey != B2_NULL_INDEX) + if ( edgeA->nextKey != B2_NULL_INDEX ) { - b2Joint* nextJoint = world->jointArray + (edgeA->nextKey >> 1); - b2JointEdge* nextEdge = nextJoint->edges + (edgeA->nextKey & 1); + b2Joint* nextJoint = world->jointArray + ( edgeA->nextKey >> 1 ); + b2JointEdge* nextEdge = nextJoint->edges + ( edgeA->nextKey & 1 ); nextEdge->prevKey = edgeA->prevKey; } - int edgeKeyA = (jointId << 1) | 0; - if (bodyA->headJointKey == edgeKeyA) + int edgeKeyA = ( jointId << 1 ) | 0; + if ( bodyA->headJointKey == edgeKeyA ) { bodyA->headJointKey = edgeA->nextKey; } @@ -689,49 +690,49 @@ void b2DestroyJointInternal(b2World* world, b2Joint* joint, bool wakeBodies) bodyA->jointCount -= 1; // Remove from body B - if (edgeB->prevKey != B2_NULL_INDEX) + if ( edgeB->prevKey != B2_NULL_INDEX ) { - b2Joint* prevJoint = world->jointArray + (edgeB->prevKey >> 1); - b2JointEdge* prevEdge = prevJoint->edges + (edgeB->prevKey & 1); + b2Joint* prevJoint = world->jointArray + ( edgeB->prevKey >> 1 ); + b2JointEdge* prevEdge = prevJoint->edges + ( edgeB->prevKey & 1 ); prevEdge->nextKey = edgeB->nextKey; } - if (edgeB->nextKey != B2_NULL_INDEX) + if ( edgeB->nextKey != B2_NULL_INDEX ) { - b2Joint* nextJoint = world->jointArray + (edgeB->nextKey >> 1); - b2JointEdge* nextEdge = nextJoint->edges + (edgeB->nextKey & 1); + b2Joint* nextJoint = world->jointArray + ( edgeB->nextKey >> 1 ); + b2JointEdge* nextEdge = nextJoint->edges + ( edgeB->nextKey & 1 ); nextEdge->prevKey = edgeB->prevKey; } - int edgeKeyB = (jointId << 1) | 1; - if (bodyB->headJointKey == edgeKeyB) + int edgeKeyB = ( jointId << 1 ) | 1; + if ( bodyB->headJointKey == edgeKeyB ) { bodyB->headJointKey = edgeB->nextKey; } bodyB->jointCount -= 1; - b2UnlinkJoint(world, joint); + b2UnlinkJoint( world, joint ); // Remove joint from solver set that owns it int setIndex = joint->setIndex; int localIndex = joint->localIndex; - if (setIndex == b2_awakeSet) + if ( setIndex == b2_awakeSet ) { - b2RemoveJointFromGraph(world, joint->edges[0].bodyId, joint->edges[1].bodyId, joint->colorIndex, localIndex); + b2RemoveJointFromGraph( world, joint->edges[0].bodyId, joint->edges[1].bodyId, joint->colorIndex, localIndex ); } else { b2SolverSet* set = world->solverSetArray + setIndex; - int movedIndex = b2RemoveJoint(&set->joints, localIndex); - if (movedIndex != B2_NULL_INDEX) + int movedIndex = b2RemoveJoint( &set->joints, localIndex ); + if ( movedIndex != B2_NULL_INDEX ) { // Fix moved joint b2JointSim* movedJointSim = set->joints.data + localIndex; int movedId = movedJointSim->jointId; b2Joint* movedJoint = world->jointArray + movedId; - B2_ASSERT(movedJoint->localIndex == movedIndex); + B2_ASSERT( movedJoint->localIndex == movedIndex ); movedJoint->localIndex = localIndex; } } @@ -741,89 +742,89 @@ void b2DestroyJointInternal(b2World* world, b2Joint* joint, bool wakeBodies) joint->localIndex = B2_NULL_INDEX; joint->colorIndex = B2_NULL_INDEX; joint->jointId = B2_NULL_INDEX; - b2FreeId(&world->jointIdPool, jointId); + b2FreeId( &world->jointIdPool, jointId ); - if (wakeBodies) + if ( wakeBodies ) { - b2WakeBody(world, bodyA); - b2WakeBody(world, bodyB); + b2WakeBody( world, bodyA ); + b2WakeBody( world, bodyB ); } - b2ValidateSolverSets(world); + b2ValidateSolverSets( world ); } -void b2DestroyJoint(b2JointId jointId) +void b2DestroyJoint( b2JointId jointId ) { - b2World* world = b2GetWorld(jointId.world0); - B2_ASSERT(world->locked == false); + b2World* world = b2GetWorld( jointId.world0 ); + B2_ASSERT( world->locked == false ); - if (world->locked) + if ( world->locked ) { return; } - b2Joint* joint = b2GetJointFullId(world, jointId); + b2Joint* joint = b2GetJointFullId( world, jointId ); - b2DestroyJointInternal(world, joint, true); + b2DestroyJointInternal( world, joint, true ); } -b2JointType b2Joint_GetType(b2JointId jointId) +b2JointType b2Joint_GetType( b2JointId jointId ) { - b2World* world = b2GetWorld(jointId.world0); - b2Joint* joint = b2GetJointFullId(world, jointId); + b2World* world = b2GetWorld( jointId.world0 ); + b2Joint* joint = b2GetJointFullId( world, jointId ); return joint->type; } -b2BodyId b2Joint_GetBodyA(b2JointId jointId) +b2BodyId b2Joint_GetBodyA( b2JointId jointId ) { - b2World* world = b2GetWorld(jointId.world0); - b2Joint* joint = b2GetJointFullId(world, jointId); - return b2MakeBodyId(world, joint->edges[0].bodyId); + b2World* world = b2GetWorld( jointId.world0 ); + b2Joint* joint = b2GetJointFullId( world, jointId ); + return b2MakeBodyId( world, joint->edges[0].bodyId ); } -b2BodyId b2Joint_GetBodyB(b2JointId jointId) +b2BodyId b2Joint_GetBodyB( b2JointId jointId ) { - b2World* world = b2GetWorld(jointId.world0); - b2Joint* joint = b2GetJointFullId(world, jointId); - return b2MakeBodyId(world, joint->edges[1].bodyId); + b2World* world = b2GetWorld( jointId.world0 ); + b2Joint* joint = b2GetJointFullId( world, jointId ); + return b2MakeBodyId( world, joint->edges[1].bodyId ); } -b2Vec2 b2Joint_GetLocalAnchorA(b2JointId jointId) +b2Vec2 b2Joint_GetLocalAnchorA( b2JointId jointId ) { - b2World* world = b2GetWorld(jointId.world0); - b2Joint* joint = b2GetJointFullId(world, jointId); - b2JointSim* jointSim = b2GetJointSim(world, joint); + b2World* world = b2GetWorld( jointId.world0 ); + b2Joint* joint = b2GetJointFullId( world, jointId ); + b2JointSim* jointSim = b2GetJointSim( world, joint ); return jointSim->localOriginAnchorA; } -b2Vec2 b2Joint_GetLocalAnchorB(b2JointId jointId) +b2Vec2 b2Joint_GetLocalAnchorB( b2JointId jointId ) { - b2World* world = b2GetWorld(jointId.world0); - b2Joint* joint = b2GetJointFullId(world, jointId); - b2JointSim* jointSim = b2GetJointSim(world, joint); + b2World* world = b2GetWorld( jointId.world0 ); + b2Joint* joint = b2GetJointFullId( world, jointId ); + b2JointSim* jointSim = b2GetJointSim( world, joint ); return jointSim->localOriginAnchorB; } -void b2Joint_SetCollideConnected(b2JointId jointId, bool shouldCollide) +void b2Joint_SetCollideConnected( b2JointId jointId, bool shouldCollide ) { - b2World* world = b2GetWorldLocked(jointId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( jointId.world0 ); + if ( world == NULL ) { return; } - b2Joint* joint = b2GetJointFullId(world, jointId); - if (joint->collideConnected == shouldCollide) + b2Joint* joint = b2GetJointFullId( world, jointId ); + if ( joint->collideConnected == shouldCollide ) { return; } joint->collideConnected = shouldCollide; - b2Body* bodyA = b2GetBody(world, joint->edges[0].bodyId); - b2Body* bodyB = b2GetBody(world, joint->edges[1].bodyId); + b2Body* bodyA = b2GetBody( world, joint->edges[0].bodyId ); + b2Body* bodyB = b2GetBody( world, joint->edges[1].bodyId ); - if (shouldCollide) + if ( shouldCollide ) { // need to tell the broad-phase to look for new pairs for one of the // two bodies. Pick the one with the fewest shapes. @@ -831,13 +832,13 @@ void b2Joint_SetCollideConnected(b2JointId jointId, bool shouldCollide) int shapeCountB = bodyB->shapeCount; int shapeId = shapeCountA < shapeCountB ? bodyA->headShapeId : bodyB->headShapeId; - while (shapeId != B2_NULL_INDEX) + while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = world->shapeArray + shapeId; - if (shape->proxyKey != B2_NULL_INDEX) + if ( shape->proxyKey != B2_NULL_INDEX ) { - b2BufferMove(&world->broadPhase, shape->proxyKey); + b2BufferMove( &world->broadPhase, shape->proxyKey ); } shapeId = shape->nextShapeId; @@ -845,348 +846,349 @@ void b2Joint_SetCollideConnected(b2JointId jointId, bool shouldCollide) } else { - b2DestroyContactsBetweenBodies(world, bodyA, bodyB); + b2DestroyContactsBetweenBodies( world, bodyA, bodyB ); } } -bool b2Joint_GetCollideConnected(b2JointId jointId) +bool b2Joint_GetCollideConnected( b2JointId jointId ) { - b2World* world = b2GetWorld(jointId.world0); - b2Joint* joint = b2GetJointFullId(world, jointId); + b2World* world = b2GetWorld( jointId.world0 ); + b2Joint* joint = b2GetJointFullId( world, jointId ); return joint->collideConnected; } -void b2Joint_SetUserData(b2JointId jointId, void* userData) +void b2Joint_SetUserData( b2JointId jointId, void* userData ) { - b2World* world = b2GetWorld(jointId.world0); - b2Joint* joint = b2GetJointFullId(world, jointId); + b2World* world = b2GetWorld( jointId.world0 ); + b2Joint* joint = b2GetJointFullId( world, jointId ); joint->userData = userData; } -void* b2Joint_GetUserData(b2JointId jointId) +void* b2Joint_GetUserData( b2JointId jointId ) { - b2World* world = b2GetWorld(jointId.world0); - b2Joint* joint = b2GetJointFullId(world, jointId); + b2World* world = b2GetWorld( jointId.world0 ); + b2Joint* joint = b2GetJointFullId( world, jointId ); return joint->userData; } -void b2Joint_WakeBodies(b2JointId jointId) +void b2Joint_WakeBodies( b2JointId jointId ) { - b2World* world = b2GetWorldLocked(jointId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( jointId.world0 ); + if ( world == NULL ) { return; } - b2Joint* joint = b2GetJointFullId(world, jointId); + b2Joint* joint = b2GetJointFullId( world, jointId ); b2Body* bodyA = world->bodyArray + joint->edges[0].bodyId; b2Body* bodyB = world->bodyArray + joint->edges[1].bodyId; - b2WakeBody(world, bodyA); - b2WakeBody(world, bodyB); + b2WakeBody( world, bodyA ); + b2WakeBody( world, bodyB ); } -extern b2Vec2 b2GetDistanceJointForce(b2World* world, b2JointSim* base); -extern b2Vec2 b2GetMotorJointForce(b2World* world, b2JointSim* base); -extern b2Vec2 b2GetMouseJointForce(b2World* world, b2JointSim* base); -extern b2Vec2 b2GetPrismaticJointForce(b2World* world, b2JointSim* base); -extern b2Vec2 b2GetRevoluteJointForce(b2World* world, b2JointSim* base); -extern b2Vec2 b2GetWeldJointForce(b2World* world, b2JointSim* base); -extern b2Vec2 b2GetWheelJointForce(b2World* world, b2JointSim* base); +extern b2Vec2 b2GetDistanceJointForce( b2World* world, b2JointSim* base ); +extern b2Vec2 b2GetMotorJointForce( b2World* world, b2JointSim* base ); +extern b2Vec2 b2GetMouseJointForce( b2World* world, b2JointSim* base ); +extern b2Vec2 b2GetPrismaticJointForce( b2World* world, b2JointSim* base ); +extern b2Vec2 b2GetRevoluteJointForce( b2World* world, b2JointSim* base ); +extern b2Vec2 b2GetWeldJointForce( b2World* world, b2JointSim* base ); +extern b2Vec2 b2GetWheelJointForce( b2World* world, b2JointSim* base ); -b2Vec2 b2Joint_GetConstraintForce(b2JointId jointId) +b2Vec2 b2Joint_GetConstraintForce( b2JointId jointId ) { - b2World* world = b2GetWorld(jointId.world0); - b2Joint* joint = b2GetJointFullId(world, jointId); - b2JointSim* base = b2GetJointSim(world, joint); + b2World* world = b2GetWorld( jointId.world0 ); + b2Joint* joint = b2GetJointFullId( world, jointId ); + b2JointSim* base = b2GetJointSim( world, joint ); - switch (joint->type) + switch ( joint->type ) { - case b2_distanceJoint: - return b2GetDistanceJointForce(world, base); + case b2_distanceJoint: + return b2GetDistanceJointForce( world, base ); - case b2_motorJoint: - return b2GetMotorJointForce(world, base); + case b2_motorJoint: + return b2GetMotorJointForce( world, base ); - case b2_mouseJoint: - return b2GetMouseJointForce(world, base); + case b2_mouseJoint: + return b2GetMouseJointForce( world, base ); - case b2_prismaticJoint: - return b2GetPrismaticJointForce(world, base); + case b2_prismaticJoint: + return b2GetPrismaticJointForce( world, base ); - case b2_revoluteJoint: - return b2GetRevoluteJointForce(world, base); + case b2_revoluteJoint: + return b2GetRevoluteJointForce( world, base ); - case b2_weldJoint: - return b2GetWeldJointForce(world, base); + case b2_weldJoint: + return b2GetWeldJointForce( world, base ); - case b2_wheelJoint: - return b2GetWheelJointForce(world, base); + case b2_wheelJoint: + return b2GetWheelJointForce( world, base ); - default: - B2_ASSERT(false); - return b2Vec2_zero; + default: + B2_ASSERT( false ); + return b2Vec2_zero; } } -extern float b2GetMotorJointTorque(b2World* world, b2JointSim* base); -extern float b2GetMouseJointTorque(b2World* world, b2JointSim* base); -extern float b2GetPrismaticJointTorque(b2World* world, b2JointSim* base); -extern float b2GetRevoluteJointTorque(b2World* world, b2JointSim* base); -extern float b2GetWeldJointTorque(b2World* world, b2JointSim* base); -extern float b2GetWheelJointTorque(b2World* world, b2JointSim* base); +extern float b2GetMotorJointTorque( b2World* world, b2JointSim* base ); +extern float b2GetMouseJointTorque( b2World* world, b2JointSim* base ); +extern float b2GetPrismaticJointTorque( b2World* world, b2JointSim* base ); +extern float b2GetRevoluteJointTorque( b2World* world, b2JointSim* base ); +extern float b2GetWeldJointTorque( b2World* world, b2JointSim* base ); +extern float b2GetWheelJointTorque( b2World* world, b2JointSim* base ); -float b2Joint_GetConstraintTorque(b2JointId jointId) +float b2Joint_GetConstraintTorque( b2JointId jointId ) { - b2World* world = b2GetWorld(jointId.world0); - b2Joint* joint = b2GetJointFullId(world, jointId); - b2JointSim* base = b2GetJointSim(world, joint); + b2World* world = b2GetWorld( jointId.world0 ); + b2Joint* joint = b2GetJointFullId( world, jointId ); + b2JointSim* base = b2GetJointSim( world, joint ); - switch (joint->type) + switch ( joint->type ) { - case b2_distanceJoint: - return 0.0f; + case b2_distanceJoint: + return 0.0f; - case b2_motorJoint: - return b2GetMotorJointTorque(world, base); + case b2_motorJoint: + return b2GetMotorJointTorque( world, base ); - case b2_mouseJoint: - return b2GetMouseJointTorque(world, base); + case b2_mouseJoint: + return b2GetMouseJointTorque( world, base ); - case b2_prismaticJoint: - return b2GetPrismaticJointTorque(world, base); + case b2_prismaticJoint: + return b2GetPrismaticJointTorque( world, base ); - case b2_revoluteJoint: - return b2GetRevoluteJointTorque(world, base); + case b2_revoluteJoint: + return b2GetRevoluteJointTorque( world, base ); - case b2_weldJoint: - return b2GetWeldJointTorque(world, base); + case b2_weldJoint: + return b2GetWeldJointTorque( world, base ); - case b2_wheelJoint: - return b2GetWheelJointTorque(world, base); + case b2_wheelJoint: + return b2GetWheelJointTorque( world, base ); - default: - B2_ASSERT(false); - return 0.0f; + default: + B2_ASSERT( false ); + return 0.0f; } } -extern void b2PrepareDistanceJoint(b2JointSim* base, b2StepContext* context); -extern void b2PrepareMotorJoint(b2JointSim* base, b2StepContext* context); -extern void b2PrepareMouseJoint(b2JointSim* base, b2StepContext* context); -extern void b2PreparePrismaticJoint(b2JointSim* base, b2StepContext* context); -extern void b2PrepareRevoluteJoint(b2JointSim* base, b2StepContext* context); -extern void b2PrepareWeldJoint(b2JointSim* base, b2StepContext* context); -extern void b2PrepareWheelJoint(b2JointSim* base, b2StepContext* context); +extern void b2PrepareDistanceJoint( b2JointSim* base, b2StepContext* context ); +extern void b2PrepareMotorJoint( b2JointSim* base, b2StepContext* context ); +extern void b2PrepareMouseJoint( b2JointSim* base, b2StepContext* context ); +extern void b2PreparePrismaticJoint( b2JointSim* base, b2StepContext* context ); +extern void b2PrepareRevoluteJoint( b2JointSim* base, b2StepContext* context ); +extern void b2PrepareWeldJoint( b2JointSim* base, b2StepContext* context ); +extern void b2PrepareWheelJoint( b2JointSim* base, b2StepContext* context ); -void b2PrepareJoint(b2JointSim* joint, b2StepContext* context) +void b2PrepareJoint( b2JointSim* joint, b2StepContext* context ) { - switch (joint->type) + switch ( joint->type ) { case b2_distanceJoint: - b2PrepareDistanceJoint(joint, context); + b2PrepareDistanceJoint( joint, context ); break; case b2_motorJoint: - b2PrepareMotorJoint(joint, context); + b2PrepareMotorJoint( joint, context ); break; case b2_mouseJoint: - b2PrepareMouseJoint(joint, context); + b2PrepareMouseJoint( joint, context ); break; case b2_prismaticJoint: - b2PreparePrismaticJoint(joint, context); + b2PreparePrismaticJoint( joint, context ); break; case b2_revoluteJoint: - b2PrepareRevoluteJoint(joint, context); + b2PrepareRevoluteJoint( joint, context ); break; case b2_weldJoint: - b2PrepareWeldJoint(joint, context); + b2PrepareWeldJoint( joint, context ); break; case b2_wheelJoint: - b2PrepareWheelJoint(joint, context); + b2PrepareWheelJoint( joint, context ); break; default: - B2_ASSERT(false); + B2_ASSERT( false ); } } -extern void b2WarmStartDistanceJoint(b2JointSim* base, b2StepContext* context); -extern void b2WarmStartMotorJoint(b2JointSim* base, b2StepContext* context); -extern void b2WarmStartMouseJoint(b2JointSim* base, b2StepContext* context); -extern void b2WarmStartPrismaticJoint(b2JointSim* base, b2StepContext* context); -extern void b2WarmStartRevoluteJoint(b2JointSim* base, b2StepContext* context); -extern void b2WarmStartWeldJoint(b2JointSim* base, b2StepContext* context); -extern void b2WarmStartWheelJoint(b2JointSim* base, b2StepContext* context); +extern void b2WarmStartDistanceJoint( b2JointSim* base, b2StepContext* context ); +extern void b2WarmStartMotorJoint( b2JointSim* base, b2StepContext* context ); +extern void b2WarmStartMouseJoint( b2JointSim* base, b2StepContext* context ); +extern void b2WarmStartPrismaticJoint( b2JointSim* base, b2StepContext* context ); +extern void b2WarmStartRevoluteJoint( b2JointSim* base, b2StepContext* context ); +extern void b2WarmStartWeldJoint( b2JointSim* base, b2StepContext* context ); +extern void b2WarmStartWheelJoint( b2JointSim* base, b2StepContext* context ); -void b2WarmStartJoint(b2JointSim* joint, b2StepContext* context) +void b2WarmStartJoint( b2JointSim* joint, b2StepContext* context ) { - switch (joint->type) + switch ( joint->type ) { case b2_distanceJoint: - b2WarmStartDistanceJoint(joint, context); + b2WarmStartDistanceJoint( joint, context ); break; case b2_motorJoint: - b2WarmStartMotorJoint(joint, context); + b2WarmStartMotorJoint( joint, context ); break; case b2_mouseJoint: - b2WarmStartMouseJoint(joint, context); + b2WarmStartMouseJoint( joint, context ); break; case b2_prismaticJoint: - b2WarmStartPrismaticJoint(joint, context); + b2WarmStartPrismaticJoint( joint, context ); break; case b2_revoluteJoint: - b2WarmStartRevoluteJoint(joint, context); + b2WarmStartRevoluteJoint( joint, context ); break; case b2_weldJoint: - b2WarmStartWeldJoint(joint, context); + b2WarmStartWeldJoint( joint, context ); break; case b2_wheelJoint: - b2WarmStartWheelJoint(joint, context); + b2WarmStartWheelJoint( joint, context ); break; default: - B2_ASSERT(false); + B2_ASSERT( false ); } } -extern void b2SolveDistanceJoint(b2JointSim* base, b2StepContext* context, bool useBias); -extern void b2SolveMotorJoint(b2JointSim* base, b2StepContext* context, bool useBias); -extern void b2SolveMouseJoint(b2JointSim* base, b2StepContext* context); -extern void b2SolvePrismaticJoint(b2JointSim* base, b2StepContext* context, bool useBias); -extern void b2SolveRevoluteJoint(b2JointSim* base, b2StepContext* context, bool useBias); -extern void b2SolveWeldJoint(b2JointSim* base, b2StepContext* context, bool useBias); -extern void b2SolveWheelJoint(b2JointSim* base, b2StepContext* context, bool useBias); +extern void b2SolveDistanceJoint( b2JointSim* base, b2StepContext* context, bool useBias ); +extern void b2SolveMotorJoint( b2JointSim* base, b2StepContext* context, bool useBias ); +extern void b2SolveMouseJoint( b2JointSim* base, b2StepContext* context ); +extern void b2SolvePrismaticJoint( b2JointSim* base, b2StepContext* context, bool useBias ); +extern void b2SolveRevoluteJoint( b2JointSim* base, b2StepContext* context, bool useBias ); +extern void b2SolveWeldJoint( b2JointSim* base, b2StepContext* context, bool useBias ); +extern void b2SolveWheelJoint( b2JointSim* base, b2StepContext* context, bool useBias ); -void b2SolveJoint(b2JointSim* joint, b2StepContext* context, bool useBias) +void b2SolveJoint( b2JointSim* joint, b2StepContext* context, bool useBias ) { - switch (joint->type) + switch ( joint->type ) { case b2_distanceJoint: - b2SolveDistanceJoint(joint, context, useBias); + b2SolveDistanceJoint( joint, context, useBias ); break; case b2_motorJoint: - b2SolveMotorJoint(joint, context, useBias); + b2SolveMotorJoint( joint, context, useBias ); break; case b2_mouseJoint: - b2SolveMouseJoint(joint, context); + b2SolveMouseJoint( joint, context ); break; case b2_prismaticJoint: - b2SolvePrismaticJoint(joint, context, useBias); + b2SolvePrismaticJoint( joint, context, useBias ); break; case b2_revoluteJoint: - b2SolveRevoluteJoint(joint, context, useBias); + b2SolveRevoluteJoint( joint, context, useBias ); break; case b2_weldJoint: - b2SolveWeldJoint(joint, context, useBias); + b2SolveWeldJoint( joint, context, useBias ); break; case b2_wheelJoint: - b2SolveWheelJoint(joint, context, useBias); + b2SolveWheelJoint( joint, context, useBias ); break; default: - B2_ASSERT(false); + B2_ASSERT( false ); } } -void b2PrepareOverflowJoints(b2StepContext* context) +void b2PrepareOverflowJoints( b2StepContext* context ) { - b2TracyCZoneNC(prepare_joints, "PrepJoints", b2_colorOldLace, true); + b2TracyCZoneNC( prepare_joints, "PrepJoints", b2_colorOldLace, true ); b2World* world = context->world; b2ConstraintGraph* graph = context->graph; b2JointSim* joints = graph->colors[b2_overflowIndex].joints.data; int jointCount = graph->colors[b2_overflowIndex].joints.count; - for (int i = 0; i < jointCount; ++i) + for ( int i = 0; i < jointCount; ++i ) { b2JointSim* joint = joints + i; - b2PrepareJoint(joint, context); + b2PrepareJoint( joint, context ); } - b2TracyCZoneEnd(prepare_joints); + b2TracyCZoneEnd( prepare_joints ); } -void b2WarmStartOverflowJoints(b2StepContext* context) +void b2WarmStartOverflowJoints( b2StepContext* context ) { - b2TracyCZoneNC(prepare_joints, "PrepJoints", b2_colorOldLace, true); + b2TracyCZoneNC( prepare_joints, "PrepJoints", b2_colorOldLace, true ); b2World* world = context->world; b2ConstraintGraph* graph = context->graph; b2JointSim* joints = graph->colors[b2_overflowIndex].joints.data; int jointCount = graph->colors[b2_overflowIndex].joints.count; - for (int i = 0; i < jointCount; ++i) + for ( int i = 0; i < jointCount; ++i ) { b2JointSim* joint = joints + i; - b2WarmStartJoint(joint, context); + b2WarmStartJoint( joint, context ); } - b2TracyCZoneEnd(prepare_joints); + b2TracyCZoneEnd( prepare_joints ); } -void b2SolveOverflowJoints(b2StepContext* context, bool useBias) +void b2SolveOverflowJoints( b2StepContext* context, bool useBias ) { - b2TracyCZoneNC(solve_joints, "SolveJoints", b2_colorLemonChiffon, true); + b2TracyCZoneNC( solve_joints, "SolveJoints", b2_colorLemonChiffon, true ); b2World* world = context->world; b2ConstraintGraph* graph = context->graph; b2JointSim* joints = graph->colors[b2_overflowIndex].joints.data; int jointCount = graph->colors[b2_overflowIndex].joints.count; - for (int i = 0; i < jointCount; ++i) + for ( int i = 0; i < jointCount; ++i ) { b2JointSim* joint = joints + i; - b2SolveJoint(joint, context, useBias); + b2SolveJoint( joint, context, useBias ); } - b2TracyCZoneEnd(solve_joints); + b2TracyCZoneEnd( solve_joints ); } -extern void b2DrawDistanceJoint(b2DebugDraw* draw, b2JointSim* base, b2Transform transformA, b2Transform transformB); -extern void b2DrawPrismaticJoint(b2DebugDraw* draw, b2JointSim* base, b2Transform transformA, b2Transform transformB); -extern void b2DrawRevoluteJoint(b2DebugDraw* draw, b2JointSim* base, b2Transform transformA, b2Transform transformB, float drawSize); -extern void b2DrawWheelJoint(b2DebugDraw* draw, b2JointSim* base, b2Transform transformA, b2Transform transformB); +extern void b2DrawDistanceJoint( b2DebugDraw* draw, b2JointSim* base, b2Transform transformA, b2Transform transformB ); +extern void b2DrawPrismaticJoint( b2DebugDraw* draw, b2JointSim* base, b2Transform transformA, b2Transform transformB ); +extern void b2DrawRevoluteJoint( b2DebugDraw* draw, b2JointSim* base, b2Transform transformA, b2Transform transformB, + float drawSize ); +extern void b2DrawWheelJoint( b2DebugDraw* draw, b2JointSim* base, b2Transform transformA, b2Transform transformB ); -void b2DrawJoint(b2DebugDraw* draw, b2World* world, b2Joint* joint) +void b2DrawJoint( b2DebugDraw* draw, b2World* world, b2Joint* joint ) { - b2Body* bodyA = b2GetBody(world, joint->edges[0].bodyId); - b2Body* bodyB = b2GetBody(world, joint->edges[1].bodyId); - if (bodyA->setIndex == b2_disabledSet || bodyB->setIndex == b2_disabledSet) + b2Body* bodyA = b2GetBody( world, joint->edges[0].bodyId ); + b2Body* bodyB = b2GetBody( world, joint->edges[1].bodyId ); + if ( bodyA->setIndex == b2_disabledSet || bodyB->setIndex == b2_disabledSet ) { return; } - b2JointSim* jointSim = b2GetJointSim(world, joint); + b2JointSim* jointSim = b2GetJointSim( world, joint ); - b2Transform transformA = b2GetBodyTransformQuick(world, bodyA); - b2Transform transformB = b2GetBodyTransformQuick(world, bodyB); - b2Vec2 pA = b2TransformPoint(transformA, jointSim->localOriginAnchorA); - b2Vec2 pB = b2TransformPoint(transformB, jointSim->localOriginAnchorB); + b2Transform transformA = b2GetBodyTransformQuick( world, bodyA ); + b2Transform transformB = b2GetBodyTransformQuick( world, bodyB ); + b2Vec2 pA = b2TransformPoint( transformA, jointSim->localOriginAnchorA ); + b2Vec2 pB = b2TransformPoint( transformB, jointSim->localOriginAnchorB ); b2HexColor color = b2_colorDarkSeaGreen; - switch (joint->type) + switch ( joint->type ) { case b2_distanceJoint: - b2DrawDistanceJoint(draw, jointSim, transformA, transformB); + b2DrawDistanceJoint( draw, jointSim, transformA, transformB ); break; case b2_mouseJoint: @@ -1194,43 +1196,43 @@ void b2DrawJoint(b2DebugDraw* draw, b2World* world, b2Joint* joint) b2Vec2 target = jointSim->mouseJoint.targetA; b2HexColor c1 = b2_colorGreen; - draw->DrawPoint(target, 4.0f, c1, draw->context); - draw->DrawPoint(pB, 4.0f, c1, draw->context); + draw->DrawPoint( target, 4.0f, c1, draw->context ); + draw->DrawPoint( pB, 4.0f, c1, draw->context ); b2HexColor c2 = b2_colorGray8; - draw->DrawSegment(target, pB, c2, draw->context); + draw->DrawSegment( target, pB, c2, draw->context ); } break; case b2_prismaticJoint: - b2DrawPrismaticJoint(draw, jointSim, transformA, transformB); + b2DrawPrismaticJoint( draw, jointSim, transformA, transformB ); break; case b2_revoluteJoint: - b2DrawRevoluteJoint(draw, jointSim, transformA, transformB, joint->drawSize); + b2DrawRevoluteJoint( draw, jointSim, transformA, transformB, joint->drawSize ); break; case b2_wheelJoint: - b2DrawWheelJoint(draw, jointSim, transformA, transformB); + b2DrawWheelJoint( draw, jointSim, transformA, transformB ); break; default: - draw->DrawSegment(transformA.p, pA, color, draw->context); - draw->DrawSegment(pA, pB, color, draw->context); - draw->DrawSegment(transformB.p, pB, color, draw->context); + draw->DrawSegment( transformA.p, pA, color, draw->context ); + draw->DrawSegment( pA, pB, color, draw->context ); + draw->DrawSegment( transformB.p, pB, color, draw->context ); } - if (draw->drawGraphColors) + if ( draw->drawGraphColors ) { - b2HexColor colors[b2_graphColorCount] = {b2_colorRed, b2_colorOrange, b2_colorYellow, b2_colorGreen, - b2_colorCyan, b2_colorBlue, b2_colorViolet, b2_colorPink, - b2_colorChocolate, b2_colorGoldenrod, b2_colorCoral, b2_colorBlack}; + b2HexColor colors[b2_graphColorCount] = { b2_colorRed, b2_colorOrange, b2_colorYellow, b2_colorGreen, + b2_colorCyan, b2_colorBlue, b2_colorViolet, b2_colorPink, + b2_colorChocolate, b2_colorGoldenrod, b2_colorCoral, b2_colorBlack }; int colorIndex = joint->colorIndex; - if (colorIndex != B2_NULL_INDEX) + if ( colorIndex != B2_NULL_INDEX ) { - b2Vec2 p = b2Lerp(pA, pB, 0.5f); - draw->DrawPoint(p, 5.0f, colors[colorIndex], draw->context); + b2Vec2 p = b2Lerp( pA, pB, 0.5f ); + draw->DrawPoint( p, 5.0f, colors[colorIndex], draw->context ); } } } diff --git a/src/joint.h b/src/joint.h index 5e82c5e3..e9b3f08c 100644 --- a/src/joint.h +++ b/src/joint.h @@ -38,7 +38,7 @@ typedef struct b2Joint // joint index within set or graph color // B2_NULL_INDEX when slot is free int localIndex; - + b2JointEdge edges[2]; int jointId; @@ -150,7 +150,7 @@ typedef struct b2PrismaticJoint float deltaAngle; float axialMass; b2Softness springSoftness; - + bool enableSpring; bool enableLimit; bool enableMotor; @@ -179,7 +179,7 @@ typedef struct b2RevoluteJoint float deltaAngle; float axialMass; b2Softness springSoftness; - + bool enableSpring; bool enableMotor; bool enableLimit; @@ -268,18 +268,18 @@ typedef struct b2JointSim }; } b2JointSim; -b2Joint* b2GetJoint(b2World* world, int jointId); -void b2DestroyJointInternal(b2World* world, b2Joint* joint, bool wakeBodies); +b2Joint* b2GetJoint( b2World* world, int jointId ); +void b2DestroyJointInternal( b2World* world, b2Joint* joint, bool wakeBodies ); -b2JointSim* b2GetJointSim(b2World* world, b2Joint* joint); -b2JointSim* b2GetJointSimCheckType(b2JointId jointId, b2JointType type); +b2JointSim* b2GetJointSim( b2World* world, b2Joint* joint ); +b2JointSim* b2GetJointSimCheckType( b2JointId jointId, b2JointType type ); -void b2PrepareJoint(b2JointSim* joint, b2StepContext* context); -void b2WarmStartJoint(b2JointSim* joint, b2StepContext* context); -void b2SolveJoint(b2JointSim* joint, b2StepContext* context, bool useBias); +void b2PrepareJoint( b2JointSim* joint, b2StepContext* context ); +void b2WarmStartJoint( b2JointSim* joint, b2StepContext* context ); +void b2SolveJoint( b2JointSim* joint, b2StepContext* context, bool useBias ); -void b2PrepareOverflowJoints(b2StepContext* context); -void b2WarmStartOverflowJoints(b2StepContext* context); -void b2SolveOverflowJoints(b2StepContext* context, bool useBias); +void b2PrepareOverflowJoints( b2StepContext* context ); +void b2WarmStartOverflowJoints( b2StepContext* context ); +void b2SolveOverflowJoints( b2StepContext* context, bool useBias ); -void b2DrawJoint(b2DebugDraw* draw, b2World* world, b2Joint* joint); +void b2DrawJoint( b2DebugDraw* draw, b2World* world, b2Joint* joint ); diff --git a/src/manifold.c b/src/manifold.c index 1c1239cb..88b98242 100644 --- a/src/manifold.c +++ b/src/manifold.c @@ -1,29 +1,28 @@ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT -#include "box2d/collision.h" - #include "core.h" +#include "box2d/collision.h" #include "box2d/math_functions.h" #include #include -#define B2_MAKE_ID(A, B) ((uint8_t)(A) << 8 | (uint8_t)(B)) +#define B2_MAKE_ID( A, B ) ( (uint8_t)( A ) << 8 | (uint8_t)( B ) ) -static b2Polygon b2MakeCapsule(b2Vec2 p1, b2Vec2 p2, float radius) +static b2Polygon b2MakeCapsule( b2Vec2 p1, b2Vec2 p2, float radius ) { - b2Polygon shape = {0}; + b2Polygon shape = { 0 }; shape.vertices[0] = p1; shape.vertices[1] = p2; - shape.centroid = b2Lerp(p1, p2, 0.5f); + shape.centroid = b2Lerp( p1, p2, 0.5f ); - b2Vec2 axis = b2NormalizeChecked(b2Sub(p2, p1)); - b2Vec2 normal = b2RightPerp(axis); + b2Vec2 axis = b2NormalizeChecked( b2Sub( p2, p1 ) ); + b2Vec2 normal = b2RightPerp( axis ); shape.normals[0] = normal; - shape.normals[1] = b2Neg(normal); + shape.normals[1] = b2Neg( normal ); shape.count = 2; shape.radius = radius; @@ -34,36 +33,36 @@ static b2Polygon b2MakeCapsule(b2Vec2 p1, b2Vec2 p2, float radius) // localAnchorB = qBc * (point - pB) // anchorB = point - pB = qA * localAnchorA + pA - pB // = anchorA + (pA - pB) -b2Manifold b2CollideCircles(const b2Circle* circleA, b2Transform xfA, const b2Circle* circleB, b2Transform xfB) +b2Manifold b2CollideCircles( const b2Circle* circleA, b2Transform xfA, const b2Circle* circleB, b2Transform xfB ) { - b2Manifold manifold = {0}; + b2Manifold manifold = { 0 }; - b2Transform xf = b2InvMulTransforms(xfA, xfB); + b2Transform xf = b2InvMulTransforms( xfA, xfB ); b2Vec2 pointA = circleA->center; - b2Vec2 pointB = b2TransformPoint(xf, circleB->center); + b2Vec2 pointB = b2TransformPoint( xf, circleB->center ); float distance; - b2Vec2 normal = b2GetLengthAndNormalize(&distance, b2Sub(pointB, pointA)); + b2Vec2 normal = b2GetLengthAndNormalize( &distance, b2Sub( pointB, pointA ) ); float radiusA = circleA->radius; float radiusB = circleB->radius; float separation = distance - radiusA - radiusB; - if (separation > b2_speculativeDistance) + if ( separation > b2_speculativeDistance ) { return manifold; } - b2Vec2 cA = b2MulAdd(pointA, radiusA, normal); - b2Vec2 cB = b2MulAdd(pointB, -radiusB, normal); - b2Vec2 contactPointA = b2Lerp(cA, cB, 0.5f); + b2Vec2 cA = b2MulAdd( pointA, radiusA, normal ); + b2Vec2 cB = b2MulAdd( pointB, -radiusB, normal ); + b2Vec2 contactPointA = b2Lerp( cA, cB, 0.5f ); - manifold.normal = b2RotateVector(xfA.q, normal); + manifold.normal = b2RotateVector( xfA.q, normal ); b2ManifoldPoint* mp = manifold.points + 0; - mp->anchorA = b2RotateVector(xfA.q, contactPointA); - mp->anchorB = b2Add(mp->anchorA, b2Sub(xfA.p, xfB.p)); - mp->point = b2Add(xfA.p, mp->anchorA); + mp->anchorA = b2RotateVector( xfA.q, contactPointA ); + mp->anchorB = b2Add( mp->anchorA, b2Sub( xfA.p, xfB.p ) ); + mp->point = b2Add( xfA.p, mp->anchorA ); mp->separation = separation; mp->id = 0; manifold.pointCount = 1; @@ -71,33 +70,33 @@ b2Manifold b2CollideCircles(const b2Circle* circleA, b2Transform xfA, const b2Ci } /// Compute the collision manifold between a capsule and circle -b2Manifold b2CollideCapsuleAndCircle(const b2Capsule* capsuleA, b2Transform xfA, const b2Circle* circleB, b2Transform xfB) +b2Manifold b2CollideCapsuleAndCircle( const b2Capsule* capsuleA, b2Transform xfA, const b2Circle* circleB, b2Transform xfB ) { - b2Manifold manifold = {0}; + b2Manifold manifold = { 0 }; - b2Transform xf = b2InvMulTransforms(xfA, xfB); + b2Transform xf = b2InvMulTransforms( xfA, xfB ); // Compute circle position in the frame of the capsule. - b2Vec2 pB = b2TransformPoint(xf, circleB->center); + b2Vec2 pB = b2TransformPoint( xf, circleB->center ); // Compute closest point b2Vec2 p1 = capsuleA->center1; b2Vec2 p2 = capsuleA->center2; - b2Vec2 e = b2Sub(p2, p1); + b2Vec2 e = b2Sub( p2, p1 ); // dot(p - pA, e) = 0 // dot(p - (p1 + s1 * e), e) = 0 // s1 = dot(p - p1, e) b2Vec2 pA; - float s1 = b2Dot(b2Sub(pB, p1), e); - float s2 = b2Dot(b2Sub(p2, pB), e); - if (s1 < 0.0f) + float s1 = b2Dot( b2Sub( pB, p1 ), e ); + float s2 = b2Dot( b2Sub( p2, pB ), e ); + if ( s1 < 0.0f ) { // p1 region pA = p1; } - else if (s2 < 0.0f) + else if ( s2 < 0.0f ) { // p2 region pA = p2; @@ -105,45 +104,45 @@ b2Manifold b2CollideCapsuleAndCircle(const b2Capsule* capsuleA, b2Transform xfA, else { // circle colliding with segment interior - float s = s1 / b2Dot(e, e); - pA = b2MulAdd(p1, s, e); + float s = s1 / b2Dot( e, e ); + pA = b2MulAdd( p1, s, e ); } float distance; - b2Vec2 normal = b2GetLengthAndNormalize(&distance, b2Sub(pB, pA)); + b2Vec2 normal = b2GetLengthAndNormalize( &distance, b2Sub( pB, pA ) ); float radiusA = capsuleA->radius; float radiusB = circleB->radius; float separation = distance - radiusA - radiusB; - if (separation > b2_speculativeDistance) + if ( separation > b2_speculativeDistance ) { return manifold; } - b2Vec2 cA = b2MulAdd(pA, radiusA, normal); - b2Vec2 cB = b2MulAdd(pB, -radiusB, normal); - b2Vec2 contactPointA = b2Lerp(cA, cB, 0.5f); + b2Vec2 cA = b2MulAdd( pA, radiusA, normal ); + b2Vec2 cB = b2MulAdd( pB, -radiusB, normal ); + b2Vec2 contactPointA = b2Lerp( cA, cB, 0.5f ); - manifold.normal = b2RotateVector(xfA.q, normal); + manifold.normal = b2RotateVector( xfA.q, normal ); b2ManifoldPoint* mp = manifold.points + 0; - mp->anchorA = b2RotateVector(xfA.q, contactPointA); - mp->anchorB = b2Add(mp->anchorA, b2Sub(xfA.p, xfB.p)); - mp->point = b2Add(xfA.p, mp->anchorA); + mp->anchorA = b2RotateVector( xfA.q, contactPointA ); + mp->anchorB = b2Add( mp->anchorA, b2Sub( xfA.p, xfB.p ) ); + mp->point = b2Add( xfA.p, mp->anchorA ); mp->separation = separation; mp->id = 0; manifold.pointCount = 1; return manifold; } -b2Manifold b2CollidePolygonAndCircle(const b2Polygon* polygonA, b2Transform xfA, const b2Circle* circleB, b2Transform xfB) +b2Manifold b2CollidePolygonAndCircle( const b2Polygon* polygonA, b2Transform xfA, const b2Circle* circleB, b2Transform xfB ) { - b2Manifold manifold = {0}; + b2Manifold manifold = { 0 }; const float speculativeDistance = b2_speculativeDistance; - b2Transform xf = b2InvMulTransforms(xfA, xfB); + b2Transform xf = b2InvMulTransforms( xfA, xfB ); // Compute circle position in the frame of the polygon. - b2Vec2 c = b2TransformPoint(xf, circleB->center); + b2Vec2 c = b2TransformPoint( xf, circleB->center ); float radiusA = polygonA->radius; float radiusB = circleB->radius; float radius = radiusA + radiusB; @@ -155,17 +154,17 @@ b2Manifold b2CollidePolygonAndCircle(const b2Polygon* polygonA, b2Transform xfA, const b2Vec2* vertices = polygonA->vertices; const b2Vec2* normals = polygonA->normals; - for (int32_t i = 0; i < vertexCount; ++i) + for ( int32_t i = 0; i < vertexCount; ++i ) { - float s = b2Dot(normals[i], b2Sub(c, vertices[i])); - if (s > separation) + float s = b2Dot( normals[i], b2Sub( c, vertices[i] ) ); + if ( s > separation ) { separation = s; normalIndex = i; } } - if (separation > radius + speculativeDistance) + if ( separation > radius + speculativeDistance ) { return manifold; } @@ -177,52 +176,52 @@ b2Manifold b2CollidePolygonAndCircle(const b2Polygon* polygonA, b2Transform xfA, b2Vec2 v2 = vertices[vertIndex2]; // Compute barycentric coordinates - float u1 = b2Dot(b2Sub(c, v1), b2Sub(v2, v1)); - float u2 = b2Dot(b2Sub(c, v2), b2Sub(v1, v2)); + float u1 = b2Dot( b2Sub( c, v1 ), b2Sub( v2, v1 ) ); + float u2 = b2Dot( b2Sub( c, v2 ), b2Sub( v1, v2 ) ); - if (u1 < 0.0f && separation > FLT_EPSILON) + if ( u1 < 0.0f && separation > FLT_EPSILON ) { // Circle center is closest to v1 and safely outside the polygon - b2Vec2 normal = b2Normalize(b2Sub(c, v1)); - separation = b2Dot(b2Sub(c, v1), normal); - if (separation > radius + speculativeDistance) + b2Vec2 normal = b2Normalize( b2Sub( c, v1 ) ); + separation = b2Dot( b2Sub( c, v1 ), normal ); + if ( separation > radius + speculativeDistance ) { return manifold; } - b2Vec2 cA = b2MulAdd(v1, radiusA, normal); - b2Vec2 cB = b2MulSub(c, radiusB, normal); - b2Vec2 contactPointA = b2Lerp(cA, cB, 0.5f); + b2Vec2 cA = b2MulAdd( v1, radiusA, normal ); + b2Vec2 cB = b2MulSub( c, radiusB, normal ); + b2Vec2 contactPointA = b2Lerp( cA, cB, 0.5f ); - manifold.normal = b2RotateVector(xfA.q, normal); + manifold.normal = b2RotateVector( xfA.q, normal ); b2ManifoldPoint* mp = manifold.points + 0; - mp->anchorA = b2RotateVector(xfA.q, contactPointA); - mp->anchorB = b2Add(mp->anchorA, b2Sub(xfA.p, xfB.p)); - mp->point = b2Add(xfA.p, mp->anchorA); - mp->separation = b2Dot(b2Sub(cB, cA), normal); + mp->anchorA = b2RotateVector( xfA.q, contactPointA ); + mp->anchorB = b2Add( mp->anchorA, b2Sub( xfA.p, xfB.p ) ); + mp->point = b2Add( xfA.p, mp->anchorA ); + mp->separation = b2Dot( b2Sub( cB, cA ), normal ); mp->id = 0; manifold.pointCount = 1; } - else if (u2 < 0.0f && separation > FLT_EPSILON) + else if ( u2 < 0.0f && separation > FLT_EPSILON ) { // Circle center is closest to v2 and safely outside the polygon - b2Vec2 normal = b2Normalize(b2Sub(c, v2)); - separation = b2Dot(b2Sub(c, v2), normal); - if (separation > radius + speculativeDistance) + b2Vec2 normal = b2Normalize( b2Sub( c, v2 ) ); + separation = b2Dot( b2Sub( c, v2 ), normal ); + if ( separation > radius + speculativeDistance ) { return manifold; } - b2Vec2 cA = b2MulAdd(v2, radiusA, normal); - b2Vec2 cB = b2MulSub(c, radiusB, normal); - b2Vec2 contactPointA = b2Lerp(cA, cB, 0.5f); + b2Vec2 cA = b2MulAdd( v2, radiusA, normal ); + b2Vec2 cB = b2MulSub( c, radiusB, normal ); + b2Vec2 contactPointA = b2Lerp( cA, cB, 0.5f ); - manifold.normal = b2RotateVector(xfA.q, normal); + manifold.normal = b2RotateVector( xfA.q, normal ); b2ManifoldPoint* mp = manifold.points + 0; - mp->anchorA = b2RotateVector(xfA.q, contactPointA); - mp->anchorB = b2Add(mp->anchorA, b2Sub(xfA.p, xfB.p)); - mp->point = b2Add(xfA.p, mp->anchorA); - mp->separation = b2Dot(b2Sub(cB, cA), normal); + mp->anchorA = b2RotateVector( xfA.q, contactPointA ); + mp->anchorB = b2Add( mp->anchorA, b2Sub( xfA.p, xfB.p ) ); + mp->point = b2Add( xfA.p, mp->anchorA ); + mp->separation = b2Dot( b2Sub( cB, cA ), normal ); mp->id = 0; manifold.pointCount = 1; } @@ -230,21 +229,21 @@ b2Manifold b2CollidePolygonAndCircle(const b2Polygon* polygonA, b2Transform xfA, { // Circle center is between v1 and v2. Center may be inside polygon b2Vec2 normal = normals[normalIndex]; - manifold.normal = b2RotateVector(xfA.q, normal); + manifold.normal = b2RotateVector( xfA.q, normal ); // cA is the projection of the circle center onto to the reference edge - b2Vec2 cA = b2MulAdd(c, radiusA - b2Dot(b2Sub(c, v1), normal), normal); + b2Vec2 cA = b2MulAdd( c, radiusA - b2Dot( b2Sub( c, v1 ), normal ), normal ); // cB is the deepest point on the circle with respect to the reference edge - b2Vec2 cB = b2MulSub(c, radiusB, normal); + b2Vec2 cB = b2MulSub( c, radiusB, normal ); - b2Vec2 contactPointA = b2Lerp(cA, cB, 0.5f); + b2Vec2 contactPointA = b2Lerp( cA, cB, 0.5f ); // The contact point is the midpoint in world space b2ManifoldPoint* mp = manifold.points + 0; - mp->anchorA = b2RotateVector(xfA.q, contactPointA); - mp->anchorB = b2Add(mp->anchorA, b2Sub(xfA.p, xfB.p)); - mp->point = b2Add(xfA.p, mp->anchorA); + mp->anchorA = b2RotateVector( xfA.q, contactPointA ); + mp->anchorB = b2Add( mp->anchorA, b2Sub( xfA.p, xfB.p ) ); + mp->point = b2Add( xfA.p, mp->anchorA ); mp->separation = separation - radius; mp->id = 0; manifold.pointCount = 1; @@ -253,30 +252,30 @@ b2Manifold b2CollidePolygonAndCircle(const b2Polygon* polygonA, b2Transform xfA, return manifold; } -b2Manifold b2CollideCapsules(const b2Capsule* capsuleA, b2Transform xfA, const b2Capsule* capsuleB, b2Transform xfB) +b2Manifold b2CollideCapsules( const b2Capsule* capsuleA, b2Transform xfA, const b2Capsule* capsuleB, b2Transform xfB ) { - b2Polygon polyA = b2MakeCapsule(capsuleA->center1, capsuleA->center2, capsuleA->radius); - b2Polygon polyB = b2MakeCapsule(capsuleB->center1, capsuleB->center2, capsuleB->radius); - return b2CollidePolygons(&polyA, xfA, &polyB, xfB); + b2Polygon polyA = b2MakeCapsule( capsuleA->center1, capsuleA->center2, capsuleA->radius ); + b2Polygon polyB = b2MakeCapsule( capsuleB->center1, capsuleB->center2, capsuleB->radius ); + return b2CollidePolygons( &polyA, xfA, &polyB, xfB ); } -b2Manifold b2CollideSegmentAndCapsule(const b2Segment* segmentA, b2Transform xfA, const b2Capsule* capsuleB, b2Transform xfB) +b2Manifold b2CollideSegmentAndCapsule( const b2Segment* segmentA, b2Transform xfA, const b2Capsule* capsuleB, b2Transform xfB ) { - b2Polygon polyA = b2MakeCapsule(segmentA->point1, segmentA->point2, 0.0f); - b2Polygon polyB = b2MakeCapsule(capsuleB->center1, capsuleB->center2, capsuleB->radius); - return b2CollidePolygons(&polyA, xfA, &polyB, xfB); + b2Polygon polyA = b2MakeCapsule( segmentA->point1, segmentA->point2, 0.0f ); + b2Polygon polyB = b2MakeCapsule( capsuleB->center1, capsuleB->center2, capsuleB->radius ); + return b2CollidePolygons( &polyA, xfA, &polyB, xfB ); } -b2Manifold b2CollidePolygonAndCapsule(const b2Polygon* polygonA, b2Transform xfA, const b2Capsule* capsuleB, b2Transform xfB) +b2Manifold b2CollidePolygonAndCapsule( const b2Polygon* polygonA, b2Transform xfA, const b2Capsule* capsuleB, b2Transform xfB ) { - b2Polygon polyB = b2MakeCapsule(capsuleB->center1, capsuleB->center2, capsuleB->radius); - return b2CollidePolygons(polygonA, xfA, &polyB, xfB); + b2Polygon polyB = b2MakeCapsule( capsuleB->center1, capsuleB->center2, capsuleB->radius ); + return b2CollidePolygons( polygonA, xfA, &polyB, xfB ); } // Polygon clipper used to compute contact points when there are potentially two contact points. -static b2Manifold b2ClipPolygons(const b2Polygon* polyA, const b2Polygon* polyB, int32_t edgeA, int32_t edgeB, bool flip) +static b2Manifold b2ClipPolygons( const b2Polygon* polyA, const b2Polygon* polyB, int32_t edgeA, int32_t edgeB, bool flip ) { - b2Manifold manifold = {0}; + b2Manifold manifold = { 0 }; // reference polygon const b2Polygon* poly1; @@ -286,7 +285,7 @@ static b2Manifold b2ClipPolygons(const b2Polygon* polyA, const b2Polygon* polyB, const b2Polygon* poly2; int32_t i21, i22; - if (flip) + if ( flip ) { poly1 = polyB; poly2 = polyA; @@ -315,14 +314,14 @@ static b2Manifold b2ClipPolygons(const b2Polygon* polyA, const b2Polygon* polyB, b2Vec2 v21 = poly2->vertices[i21]; b2Vec2 v22 = poly2->vertices[i22]; - b2Vec2 tangent = b2CrossSV(1.0f, normal); + b2Vec2 tangent = b2CrossSV( 1.0f, normal ); float lower1 = 0.0f; - float upper1 = b2Dot(b2Sub(v12, v11), tangent); + float upper1 = b2Dot( b2Sub( v12, v11 ), tangent ); // Incident edge points opposite of tangent due to CCW winding - float upper2 = b2Dot(b2Sub(v21, v11), tangent); - float lower2 = b2Dot(b2Sub(v22, v11), tangent); + float upper2 = b2Dot( b2Sub( v21, v11 ), tangent ); + float lower2 = b2Dot( b2Sub( v22, v11 ), tangent ); // This check can fail slightly due to mismatch with GJK code. // Perhaps fall back to a single point here? Otherwise we get two coincident points. @@ -334,9 +333,9 @@ static b2Manifold b2ClipPolygons(const b2Polygon* polyA, const b2Polygon* polyB, //} b2Vec2 vLower; - if (lower2 < lower1 && upper2 - lower2 > FLT_EPSILON) + if ( lower2 < lower1 && upper2 - lower2 > FLT_EPSILON ) { - vLower = b2Lerp(v22, v21, (lower1 - lower2) / (upper2 - lower2)); + vLower = b2Lerp( v22, v21, ( lower1 - lower2 ) / ( upper2 - lower2 ) ); } else { @@ -344,9 +343,9 @@ static b2Manifold b2ClipPolygons(const b2Polygon* polyA, const b2Polygon* polyB, } b2Vec2 vUpper; - if (upper2 > upper1 && upper2 - lower2 > FLT_EPSILON) + if ( upper2 > upper1 && upper2 - lower2 > FLT_EPSILON ) { - vUpper = b2Lerp(v22, v21, (upper1 - lower2) / (upper2 - lower2)); + vUpper = b2Lerp( v22, v21, ( upper1 - lower2 ) / ( upper2 - lower2 ) ); } else { @@ -355,19 +354,19 @@ static b2Manifold b2ClipPolygons(const b2Polygon* polyA, const b2Polygon* polyB, // todo vLower can be very close to vUpper, reduce to one point? - float separationLower = b2Dot(b2Sub(vLower, v11), normal); - float separationUpper = b2Dot(b2Sub(vUpper, v11), normal); + float separationLower = b2Dot( b2Sub( vLower, v11 ), normal ); + float separationUpper = b2Dot( b2Sub( vUpper, v11 ), normal ); float r1 = poly1->radius; float r2 = poly2->radius; // Put contact points at midpoint, accounting for radii - vLower = b2MulAdd(vLower, 0.5f * (r1 - r2 - separationLower), normal); - vUpper = b2MulAdd(vUpper, 0.5f * (r1 - r2 - separationUpper), normal); + vLower = b2MulAdd( vLower, 0.5f * ( r1 - r2 - separationLower ), normal ); + vUpper = b2MulAdd( vUpper, 0.5f * ( r1 - r2 - separationUpper ), normal ); float radius = r1 + r2; - if (flip == false) + if ( flip == false ) { manifold.normal = normal; b2ManifoldPoint* cp = manifold.points + 0; @@ -375,7 +374,7 @@ static b2Manifold b2ClipPolygons(const b2Polygon* polyA, const b2Polygon* polyB, { cp->anchorA = vLower; cp->separation = separationLower - radius; - cp->id = B2_MAKE_ID(i11, i22); + cp->id = B2_MAKE_ID( i11, i22 ); manifold.pointCount += 1; cp += 1; } @@ -383,19 +382,19 @@ static b2Manifold b2ClipPolygons(const b2Polygon* polyA, const b2Polygon* polyB, { cp->anchorA = vUpper; cp->separation = separationUpper - radius; - cp->id = B2_MAKE_ID(i12, i21); + cp->id = B2_MAKE_ID( i12, i21 ); manifold.pointCount += 1; } } else { - manifold.normal = b2Neg(normal); + manifold.normal = b2Neg( normal ); b2ManifoldPoint* cp = manifold.points + 0; { cp->anchorA = vUpper; cp->separation = separationUpper - radius; - cp->id = B2_MAKE_ID(i21, i12); + cp->id = B2_MAKE_ID( i21, i12 ); manifold.pointCount += 1; cp += 1; } @@ -403,7 +402,7 @@ static b2Manifold b2ClipPolygons(const b2Polygon* polyA, const b2Polygon* polyB, { cp->anchorA = vLower; cp->separation = separationLower - radius; - cp->id = B2_MAKE_ID(i22, i11); + cp->id = B2_MAKE_ID( i22, i11 ); manifold.pointCount += 1; } } @@ -412,7 +411,7 @@ static b2Manifold b2ClipPolygons(const b2Polygon* polyA, const b2Polygon* polyB, } // Find the max separation between poly1 and poly2 using edge normals from poly1. -static float b2FindMaxSeparation(int32_t* edgeIndex, const b2Polygon* poly1, const b2Polygon* poly2) +static float b2FindMaxSeparation( int32_t* edgeIndex, const b2Polygon* poly1, const b2Polygon* poly2 ) { int32_t count1 = poly1->count; int32_t count2 = poly2->count; @@ -422,7 +421,7 @@ static float b2FindMaxSeparation(int32_t* edgeIndex, const b2Polygon* poly1, con int32_t bestIndex = 0; float maxSeparation = -FLT_MAX; - for (int32_t i = 0; i < count1; ++i) + for ( int32_t i = 0; i < count1; ++i ) { // Get poly1 normal in frame2. b2Vec2 n = n1s[i]; @@ -430,16 +429,16 @@ static float b2FindMaxSeparation(int32_t* edgeIndex, const b2Polygon* poly1, con // Find the deepest point for normal i. float si = FLT_MAX; - for (int32_t j = 0; j < count2; ++j) + for ( int32_t j = 0; j < count2; ++j ) { - float sij = b2Dot(n, b2Sub(v2s[j], v1)); - if (sij < si) + float sij = b2Dot( n, b2Sub( v2s[j], v1 ) ); + if ( sij < si ) { si = sij; } } - if (si > maxSeparation) + if ( si > maxSeparation ) { maxSeparation = si; bestIndex = i; @@ -468,7 +467,7 @@ static float b2FindMaxSeparation(int32_t* edgeIndex, const b2Polygon* poly1, con // clip edges // end -b2Manifold b2CollidePolygons(const b2Polygon* polygonA, b2Transform xfA, const b2Polygon* polygonB, b2Transform xfB) +b2Manifold b2CollidePolygons( const b2Polygon* polygonA, b2Transform xfA, const b2Polygon* polygonB, b2Transform xfB ) { b2Vec2 origin = polygonA->vertices[0]; @@ -476,17 +475,17 @@ b2Manifold b2CollidePolygons(const b2Polygon* polygonA, b2Transform xfA, const b // pw = q * pb + p // pw = q * (pbs + origin) + p // pw = q * pbs + (p + q * origin) - b2Transform sfA = {b2Add(xfA.p, b2RotateVector(xfA.q, origin)), xfA.q}; - b2Transform xf = b2InvMulTransforms(sfA, xfB); + b2Transform sfA = { b2Add( xfA.p, b2RotateVector( xfA.q, origin ) ), xfA.q }; + b2Transform xf = b2InvMulTransforms( sfA, xfB ); b2Polygon localPolyA; localPolyA.count = polygonA->count; localPolyA.radius = polygonA->radius; localPolyA.vertices[0] = b2Vec2_zero; localPolyA.normals[0] = polygonA->normals[0]; - for (int i = 1; i < localPolyA.count; ++i) + for ( int i = 1; i < localPolyA.count; ++i ) { - localPolyA.vertices[i] = b2Sub(polygonA->vertices[i], origin); + localPolyA.vertices[i] = b2Sub( polygonA->vertices[i], origin ); localPolyA.normals[i] = polygonA->normals[i]; } @@ -494,28 +493,28 @@ b2Manifold b2CollidePolygons(const b2Polygon* polygonA, b2Transform xfA, const b b2Polygon localPolyB; localPolyB.count = polygonB->count; localPolyB.radius = polygonB->radius; - for (int i = 0; i < localPolyB.count; ++i) + for ( int i = 0; i < localPolyB.count; ++i ) { - localPolyB.vertices[i] = b2TransformPoint(xf, polygonB->vertices[i]); - localPolyB.normals[i] = b2RotateVector(xf.q, polygonB->normals[i]); + localPolyB.vertices[i] = b2TransformPoint( xf, polygonB->vertices[i] ); + localPolyB.normals[i] = b2RotateVector( xf.q, polygonB->normals[i] ); } int edgeA = 0; - float separationA = b2FindMaxSeparation(&edgeA, &localPolyA, &localPolyB); + float separationA = b2FindMaxSeparation( &edgeA, &localPolyA, &localPolyB ); int edgeB = 0; - float separationB = b2FindMaxSeparation(&edgeB, &localPolyB, &localPolyA); + float separationB = b2FindMaxSeparation( &edgeB, &localPolyB, &localPolyA ); float radius = localPolyA.radius + localPolyB.radius; - if (separationA > b2_speculativeDistance + radius || separationB > b2_speculativeDistance + radius) + if ( separationA > b2_speculativeDistance + radius || separationB > b2_speculativeDistance + radius ) { - return (b2Manifold){0}; + return ( b2Manifold ){ 0 }; } // Find incident edge bool flip; - if (separationA >= separationB) + if ( separationA >= separationB ) { flip = false; @@ -526,10 +525,10 @@ b2Manifold b2CollidePolygons(const b2Polygon* polygonA, b2Transform xfA, const b const b2Vec2* normals = localPolyB.normals; edgeB = 0; float minDot = FLT_MAX; - for (int i = 0; i < count; ++i) + for ( int i = 0; i < count; ++i ) { - float dot = b2Dot(searchDirection, normals[i]); - if (dot < minDot) + float dot = b2Dot( searchDirection, normals[i] ); + if ( dot < minDot ) { minDot = dot; edgeB = i; @@ -547,10 +546,10 @@ b2Manifold b2CollidePolygons(const b2Polygon* polygonA, b2Transform xfA, const b const b2Vec2* normals = localPolyA.normals; edgeA = 0; float minDot = FLT_MAX; - for (int i = 0; i < count; ++i) + for ( int i = 0; i < count; ++i ) { - float dot = b2Dot(searchDirection, normals[i]); - if (dot < minDot) + float dot = b2Dot( searchDirection, normals[i] ); + if ( dot < minDot ) { minDot = dot; edgeA = i; @@ -558,11 +557,11 @@ b2Manifold b2CollidePolygons(const b2Polygon* polygonA, b2Transform xfA, const b } } - b2Manifold manifold = {0}; + b2Manifold manifold = { 0 }; // Using slop here to ensure vertex-vertex normal vectors can be safely normalized // todo this means edge clipping needs to handle slightly non-overlapping edges. - if (separationA > 0.1f * b2_linearSlop || separationB > 0.1f * b2_linearSlop) + if ( separationA > 0.1f * b2_linearSlop || separationB > 0.1f * b2_linearSlop ) { // Polygons are disjoint. Find closest points between reference edge and incident edge // Reference edge on polygon A @@ -570,21 +569,21 @@ b2Manifold b2CollidePolygons(const b2Polygon* polygonA, b2Transform xfA, const b int i12 = edgeA + 1 < localPolyA.count ? edgeA + 1 : 0; int i21 = edgeB; int i22 = edgeB + 1 < localPolyB.count ? edgeB + 1 : 0; - + b2Vec2 v11 = localPolyA.vertices[i11]; b2Vec2 v12 = localPolyA.vertices[i12]; b2Vec2 v21 = localPolyB.vertices[i21]; b2Vec2 v22 = localPolyB.vertices[i22]; - b2SegmentDistanceResult result = b2SegmentDistance(v11, v12, v21, v22); - - if (result.fraction1 == 0.0f && result.fraction2 == 0.0f) + b2SegmentDistanceResult result = b2SegmentDistance( v11, v12, v21, v22 ); + + if ( result.fraction1 == 0.0f && result.fraction2 == 0.0f ) { // v11 - v21 - b2Vec2 normal = b2Sub(v21, v11); - B2_ASSERT(result.distanceSquared > 0.0f); - float distance = sqrtf(result.distanceSquared); - if (distance > b2_speculativeDistance + radius) + b2Vec2 normal = b2Sub( v21, v11 ); + B2_ASSERT( result.distanceSquared > 0.0f ); + float distance = sqrtf( result.distanceSquared ); + if ( distance > b2_speculativeDistance + radius ) { return manifold; } @@ -592,22 +591,22 @@ b2Manifold b2CollidePolygons(const b2Polygon* polygonA, b2Transform xfA, const b normal.x *= invDistance; normal.y *= invDistance; - b2Vec2 c1 = b2MulAdd(v11, localPolyA.radius, normal); - b2Vec2 c2 = b2MulAdd(v21, -localPolyB.radius, normal); + b2Vec2 c1 = b2MulAdd( v11, localPolyA.radius, normal ); + b2Vec2 c2 = b2MulAdd( v21, -localPolyB.radius, normal ); manifold.normal = normal; - manifold.points[0].anchorA = b2Lerp(c1, c2, 0.5f); + manifold.points[0].anchorA = b2Lerp( c1, c2, 0.5f ); manifold.points[0].separation = distance - radius; - manifold.points[0].id = B2_MAKE_ID(i11, i21); + manifold.points[0].id = B2_MAKE_ID( i11, i21 ); manifold.pointCount = 1; } - else if (result.fraction1 == 0.0f && result.fraction2 == 1.0f) + else if ( result.fraction1 == 0.0f && result.fraction2 == 1.0f ) { // v11 - v22 - b2Vec2 normal = b2Sub(v22, v11); - B2_ASSERT(result.distanceSquared > 0.0f); - float distance = sqrtf(result.distanceSquared); - if (distance > b2_speculativeDistance + radius) + b2Vec2 normal = b2Sub( v22, v11 ); + B2_ASSERT( result.distanceSquared > 0.0f ); + float distance = sqrtf( result.distanceSquared ); + if ( distance > b2_speculativeDistance + radius ) { return manifold; } @@ -615,22 +614,22 @@ b2Manifold b2CollidePolygons(const b2Polygon* polygonA, b2Transform xfA, const b normal.x *= invDistance; normal.y *= invDistance; - b2Vec2 c1 = b2MulAdd(v11, localPolyA.radius, normal); - b2Vec2 c2 = b2MulAdd(v22, -localPolyB.radius, normal); + b2Vec2 c1 = b2MulAdd( v11, localPolyA.radius, normal ); + b2Vec2 c2 = b2MulAdd( v22, -localPolyB.radius, normal ); manifold.normal = normal; - manifold.points[0].anchorA = b2Lerp(c1, c2, 0.5f); + manifold.points[0].anchorA = b2Lerp( c1, c2, 0.5f ); manifold.points[0].separation = distance - radius; - manifold.points[0].id = B2_MAKE_ID(i11, i22); + manifold.points[0].id = B2_MAKE_ID( i11, i22 ); manifold.pointCount = 1; } - else if (result.fraction1 == 1.0f && result.fraction2 == 0.0f) + else if ( result.fraction1 == 1.0f && result.fraction2 == 0.0f ) { // v12 - v21 - b2Vec2 normal = b2Sub(v21, v12); - B2_ASSERT(result.distanceSquared > 0.0f); - float distance = sqrtf(result.distanceSquared); - if (distance > b2_speculativeDistance + radius) + b2Vec2 normal = b2Sub( v21, v12 ); + B2_ASSERT( result.distanceSquared > 0.0f ); + float distance = sqrtf( result.distanceSquared ); + if ( distance > b2_speculativeDistance + radius ) { return manifold; } @@ -638,22 +637,22 @@ b2Manifold b2CollidePolygons(const b2Polygon* polygonA, b2Transform xfA, const b normal.x *= invDistance; normal.y *= invDistance; - b2Vec2 c1 = b2MulAdd(v12, localPolyA.radius, normal); - b2Vec2 c2 = b2MulAdd(v21, -localPolyB.radius, normal); + b2Vec2 c1 = b2MulAdd( v12, localPolyA.radius, normal ); + b2Vec2 c2 = b2MulAdd( v21, -localPolyB.radius, normal ); manifold.normal = normal; - manifold.points[0].anchorA = b2Lerp(c1, c2, 0.5f); + manifold.points[0].anchorA = b2Lerp( c1, c2, 0.5f ); manifold.points[0].separation = distance - radius; - manifold.points[0].id = B2_MAKE_ID(i12, i21); + manifold.points[0].id = B2_MAKE_ID( i12, i21 ); manifold.pointCount = 1; } - else if (result.fraction1 == 1.0f && result.fraction2 == 1.0f) + else if ( result.fraction1 == 1.0f && result.fraction2 == 1.0f ) { // v12 - v22 - b2Vec2 normal = b2Sub(v22, v12); - B2_ASSERT(result.distanceSquared > 0.0f); - float distance = sqrtf(result.distanceSquared); - if (distance > b2_speculativeDistance + radius) + b2Vec2 normal = b2Sub( v22, v12 ); + B2_ASSERT( result.distanceSquared > 0.0f ); + float distance = sqrtf( result.distanceSquared ); + if ( distance > b2_speculativeDistance + radius ) { return manifold; } @@ -661,106 +660,106 @@ b2Manifold b2CollidePolygons(const b2Polygon* polygonA, b2Transform xfA, const b normal.x *= invDistance; normal.y *= invDistance; - b2Vec2 c1 = b2MulAdd(v12, localPolyA.radius, normal); - b2Vec2 c2 = b2MulAdd(v22, -localPolyB.radius, normal); + b2Vec2 c1 = b2MulAdd( v12, localPolyA.radius, normal ); + b2Vec2 c2 = b2MulAdd( v22, -localPolyB.radius, normal ); manifold.normal = normal; - manifold.points[0].anchorA = b2Lerp(c1, c2, 0.5f); + manifold.points[0].anchorA = b2Lerp( c1, c2, 0.5f ); manifold.points[0].separation = distance - radius; - manifold.points[0].id = B2_MAKE_ID(i12, i22); + manifold.points[0].id = B2_MAKE_ID( i12, i22 ); manifold.pointCount = 1; } else { // Edge region - manifold = b2ClipPolygons(&localPolyA, &localPolyB, edgeA, edgeB, flip); + manifold = b2ClipPolygons( &localPolyA, &localPolyB, edgeA, edgeB, flip ); } } else { // Polygons overlap - manifold = b2ClipPolygons(&localPolyA, &localPolyB, edgeA, edgeB, flip); + manifold = b2ClipPolygons( &localPolyA, &localPolyB, edgeA, edgeB, flip ); } // Convert manifold to world space - if (manifold.pointCount > 0) + if ( manifold.pointCount > 0 ) { - manifold.normal = b2RotateVector(xfA.q, manifold.normal); - for (int i = 0; i < manifold.pointCount; ++i) + manifold.normal = b2RotateVector( xfA.q, manifold.normal ); + for ( int i = 0; i < manifold.pointCount; ++i ) { b2ManifoldPoint* mp = manifold.points + i; // anchor points relative to shape origin in world space - mp->anchorA = b2RotateVector(xfA.q, b2Add(mp->anchorA, origin)); - mp->anchorB = b2Add(mp->anchorA, b2Sub(xfA.p, xfB.p)); - mp->point = b2Add(xfA.p, mp->anchorA); + mp->anchorA = b2RotateVector( xfA.q, b2Add( mp->anchorA, origin ) ); + mp->anchorB = b2Add( mp->anchorA, b2Sub( xfA.p, xfB.p ) ); + mp->point = b2Add( xfA.p, mp->anchorA ); } } return manifold; } -b2Manifold b2CollideSegmentAndCircle(const b2Segment* segmentA, b2Transform xfA, const b2Circle* circleB, b2Transform xfB) +b2Manifold b2CollideSegmentAndCircle( const b2Segment* segmentA, b2Transform xfA, const b2Circle* circleB, b2Transform xfB ) { - b2Capsule capsuleA = {segmentA->point1, segmentA->point2, 0.0f}; - return b2CollideCapsuleAndCircle(&capsuleA, xfA, circleB, xfB); + b2Capsule capsuleA = { segmentA->point1, segmentA->point2, 0.0f }; + return b2CollideCapsuleAndCircle( &capsuleA, xfA, circleB, xfB ); } -b2Manifold b2CollideSegmentAndPolygon(const b2Segment* segmentA, b2Transform xfA, const b2Polygon* polygonB, b2Transform xfB) +b2Manifold b2CollideSegmentAndPolygon( const b2Segment* segmentA, b2Transform xfA, const b2Polygon* polygonB, b2Transform xfB ) { - b2Polygon polygonA = b2MakeCapsule(segmentA->point1, segmentA->point2, 0.0f); - return b2CollidePolygons(&polygonA, xfA, polygonB, xfB); + b2Polygon polygonA = b2MakeCapsule( segmentA->point1, segmentA->point2, 0.0f ); + return b2CollidePolygons( &polygonA, xfA, polygonB, xfB ); } -b2Manifold b2CollideSmoothSegmentAndCircle(const b2SmoothSegment* smoothSegmentA, b2Transform xfA, const b2Circle* circleB, - b2Transform xfB) +b2Manifold b2CollideSmoothSegmentAndCircle( const b2SmoothSegment* smoothSegmentA, b2Transform xfA, const b2Circle* circleB, + b2Transform xfB ) { - b2Manifold manifold = {0}; + b2Manifold manifold = { 0 }; - b2Transform xf = b2InvMulTransforms(xfA, xfB); + b2Transform xf = b2InvMulTransforms( xfA, xfB ); // Compute circle in frame of segment - b2Vec2 pB = b2TransformPoint(xf, circleB->center); + b2Vec2 pB = b2TransformPoint( xf, circleB->center ); b2Vec2 p1 = smoothSegmentA->segment.point1; b2Vec2 p2 = smoothSegmentA->segment.point2; - b2Vec2 e = b2Sub(p2, p1); + b2Vec2 e = b2Sub( p2, p1 ); // Normal points to the right - float offset = b2Dot(b2RightPerp(e), b2Sub(pB, p1)); - if (offset < 0.0f) + float offset = b2Dot( b2RightPerp( e ), b2Sub( pB, p1 ) ); + if ( offset < 0.0f ) { // collision is one-sided return manifold; } // Barycentric coordinates - float u = b2Dot(e, b2Sub(p2, pB)); - float v = b2Dot(e, b2Sub(pB, p1)); + float u = b2Dot( e, b2Sub( p2, pB ) ); + float v = b2Dot( e, b2Sub( pB, p1 ) ); b2Vec2 pA; - if (v <= 0.0f) + if ( v <= 0.0f ) { // Behind point1? // Is pB in the Voronoi region of the previous edge? - b2Vec2 prevEdge = b2Sub(p1, smoothSegmentA->ghost1); - float uPrev = b2Dot(prevEdge, b2Sub(pB, p1)); - if (uPrev <= 0.0f) + b2Vec2 prevEdge = b2Sub( p1, smoothSegmentA->ghost1 ); + float uPrev = b2Dot( prevEdge, b2Sub( pB, p1 ) ); + if ( uPrev <= 0.0f ) { return manifold; } pA = p1; } - else if (u <= 0.0f) + else if ( u <= 0.0f ) { // Ahead of point2? - b2Vec2 nextEdge = b2Sub(smoothSegmentA->ghost2, p2); - float vNext = b2Dot(nextEdge, b2Sub(pB, p2)); + b2Vec2 nextEdge = b2Sub( smoothSegmentA->ghost2, p2 ); + float vNext = b2Dot( nextEdge, b2Sub( pB, p2 ) ); // Is pB in the Voronoi region of the next edge? - if (vNext > 0.0f) + if ( vNext > 0.0f ) { return manifold; } @@ -769,69 +768,69 @@ b2Manifold b2CollideSmoothSegmentAndCircle(const b2SmoothSegment* smoothSegmentA } else { - float ee = b2Dot(e, e); - pA = (b2Vec2){u * p1.x + v * p2.x, u * p1.y + v * p2.y}; - pA = ee > 0.0f ? b2MulSV(1.0f / ee, pA) : p1; + float ee = b2Dot( e, e ); + pA = ( b2Vec2 ){ u * p1.x + v * p2.x, u * p1.y + v * p2.y }; + pA = ee > 0.0f ? b2MulSV( 1.0f / ee, pA ) : p1; } float distance; - b2Vec2 normal = b2GetLengthAndNormalize(&distance, b2Sub(pB, pA)); + b2Vec2 normal = b2GetLengthAndNormalize( &distance, b2Sub( pB, pA ) ); float radius = circleB->radius; float separation = distance - radius; - if (separation > b2_speculativeDistance) + if ( separation > b2_speculativeDistance ) { return manifold; } b2Vec2 cA = pA; - b2Vec2 cB = b2MulAdd(pB, -radius, normal); - b2Vec2 contactPointA = b2Lerp(cA, cB, 0.5f); + b2Vec2 cB = b2MulAdd( pB, -radius, normal ); + b2Vec2 contactPointA = b2Lerp( cA, cB, 0.5f ); - manifold.normal = b2RotateVector(xfA.q, normal); + manifold.normal = b2RotateVector( xfA.q, normal ); b2ManifoldPoint* mp = manifold.points + 0; - mp->anchorA = b2RotateVector(xfA.q, contactPointA); - mp->anchorB = b2Add(mp->anchorA, b2Sub(xfA.p, xfB.p)); - mp->point = b2Add(xfA.p, mp->anchorA); + mp->anchorA = b2RotateVector( xfA.q, contactPointA ); + mp->anchorB = b2Add( mp->anchorA, b2Sub( xfA.p, xfB.p ) ); + mp->point = b2Add( xfA.p, mp->anchorA ); mp->separation = separation; mp->id = 0; manifold.pointCount = 1; return manifold; } -b2Manifold b2CollideSmoothSegmentAndCapsule(const b2SmoothSegment* segmentA, b2Transform xfA, const b2Capsule* capsuleB, - b2Transform xfB, b2DistanceCache* cache) +b2Manifold b2CollideSmoothSegmentAndCapsule( const b2SmoothSegment* segmentA, b2Transform xfA, const b2Capsule* capsuleB, + b2Transform xfB, b2DistanceCache* cache ) { - b2Polygon polyB = b2MakeCapsule(capsuleB->center1, capsuleB->center2, capsuleB->radius); - return b2CollideSmoothSegmentAndPolygon(segmentA, xfA, &polyB, xfB, cache); + b2Polygon polyB = b2MakeCapsule( capsuleB->center1, capsuleB->center2, capsuleB->radius ); + return b2CollideSmoothSegmentAndPolygon( segmentA, xfA, &polyB, xfB, cache ); } -static b2Manifold b2ClipSegments(b2Vec2 a1, b2Vec2 a2, b2Vec2 b1, b2Vec2 b2, b2Vec2 normal, float ra, float rb, uint16_t id1, - uint16_t id2) +static b2Manifold b2ClipSegments( b2Vec2 a1, b2Vec2 a2, b2Vec2 b1, b2Vec2 b2, b2Vec2 normal, float ra, float rb, uint16_t id1, + uint16_t id2 ) { - b2Manifold manifold = {0}; + b2Manifold manifold = { 0 }; - b2Vec2 tangent = b2LeftPerp(normal); + b2Vec2 tangent = b2LeftPerp( normal ); // Barycentric coordinates of each point relative to a1 along tangent float lower1 = 0.0f; - float upper1 = b2Dot(b2Sub(a2, a1), tangent); + float upper1 = b2Dot( b2Sub( a2, a1 ), tangent ); // Incident edge points opposite of tangent due to CCW winding - float upper2 = b2Dot(b2Sub(b1, a1), tangent); - float lower2 = b2Dot(b2Sub(b2, a1), tangent); + float upper2 = b2Dot( b2Sub( b1, a1 ), tangent ); + float lower2 = b2Dot( b2Sub( b2, a1 ), tangent ); // Do segments overlap? - if (upper2 < lower1 || upper1 < lower2) + if ( upper2 < lower1 || upper1 < lower2 ) { return manifold; } b2Vec2 vLower; - if (lower2 < lower1 && upper2 - lower2 > FLT_EPSILON) + if ( lower2 < lower1 && upper2 - lower2 > FLT_EPSILON ) { - vLower = b2Lerp(b2, b1, (lower1 - lower2) / (upper2 - lower2)); + vLower = b2Lerp( b2, b1, ( lower1 - lower2 ) / ( upper2 - lower2 ) ); } else { @@ -839,9 +838,9 @@ static b2Manifold b2ClipSegments(b2Vec2 a1, b2Vec2 a2, b2Vec2 b1, b2Vec2 b2, b2V } b2Vec2 vUpper; - if (upper2 > upper1 && upper2 - lower2 > FLT_EPSILON) + if ( upper2 > upper1 && upper2 - lower2 > FLT_EPSILON ) { - vUpper = b2Lerp(b2, b1, (upper1 - lower2) / (upper2 - lower2)); + vUpper = b2Lerp( b2, b1, ( upper1 - lower2 ) / ( upper2 - lower2 ) ); } else { @@ -850,12 +849,12 @@ static b2Manifold b2ClipSegments(b2Vec2 a1, b2Vec2 a2, b2Vec2 b1, b2Vec2 b2, b2V // todo vLower can be very close to vUpper, reduce to one point? - float separationLower = b2Dot(b2Sub(vLower, a1), normal); - float separationUpper = b2Dot(b2Sub(vUpper, a1), normal); + float separationLower = b2Dot( b2Sub( vLower, a1 ), normal ); + float separationUpper = b2Dot( b2Sub( vUpper, a1 ), normal ); // Put contact points at midpoint, accounting for radii - vLower = b2MulAdd(vLower, 0.5f * (ra - rb - separationLower), normal); - vUpper = b2MulAdd(vUpper, 0.5f * (ra - rb - separationUpper), normal); + vLower = b2MulAdd( vLower, 0.5f * ( ra - rb - separationLower ), normal ); + vUpper = b2MulAdd( vUpper, 0.5f * ( ra - rb - separationUpper ), normal ); float radius = ra + rb; @@ -902,16 +901,16 @@ struct b2SmoothSegmentParams // Evaluate Gauss map // See https://box2d.org/posts/2020/06/ghost-collisions/ -static enum b2NormalType b2ClassifyNormal(struct b2SmoothSegmentParams params, b2Vec2 normal) +static enum b2NormalType b2ClassifyNormal( struct b2SmoothSegmentParams params, b2Vec2 normal ) { const float sinTol = 0.01f; - if (b2Dot(normal, params.edge1) <= 0.0f) + if ( b2Dot( normal, params.edge1 ) <= 0.0f ) { // Normal points towards the segment tail - if (params.convex1) + if ( params.convex1 ) { - if (b2Cross(normal, params.normal0) > sinTol) + if ( b2Cross( normal, params.normal0 ) > sinTol ) { return b2_normalSkip; } @@ -926,9 +925,9 @@ static enum b2NormalType b2ClassifyNormal(struct b2SmoothSegmentParams params, b else { // Normal points towards segment head - if (params.convex2) + if ( params.convex2 ) { - if (b2Cross(params.normal2, normal) > sinTol) + if ( b2Cross( params.normal2, normal ) > sinTol ) { return b2_normalSkip; } @@ -942,49 +941,49 @@ static enum b2NormalType b2ClassifyNormal(struct b2SmoothSegmentParams params, b } } -b2Manifold b2CollideSmoothSegmentAndPolygon(const b2SmoothSegment* smoothSegmentA, b2Transform xfA, const b2Polygon* polygonB, - b2Transform xfB, b2DistanceCache* cache) +b2Manifold b2CollideSmoothSegmentAndPolygon( const b2SmoothSegment* smoothSegmentA, b2Transform xfA, const b2Polygon* polygonB, + b2Transform xfB, b2DistanceCache* cache ) { - b2Manifold manifold = {0}; + b2Manifold manifold = { 0 }; - b2Transform xf = b2InvMulTransforms(xfA, xfB); + b2Transform xf = b2InvMulTransforms( xfA, xfB ); - b2Vec2 centroidB = b2TransformPoint(xf, polygonB->centroid); + b2Vec2 centroidB = b2TransformPoint( xf, polygonB->centroid ); float radiusB = polygonB->radius; b2Vec2 p1 = smoothSegmentA->segment.point1; b2Vec2 p2 = smoothSegmentA->segment.point2; - b2Vec2 edge1 = b2Normalize(b2Sub(p2, p1)); + b2Vec2 edge1 = b2Normalize( b2Sub( p2, p1 ) ); - struct b2SmoothSegmentParams smoothParams = {0}; + struct b2SmoothSegmentParams smoothParams = { 0 }; smoothParams.edge1 = edge1; const float convexTol = 0.01f; - b2Vec2 edge0 = b2Normalize(b2Sub(p1, smoothSegmentA->ghost1)); - smoothParams.normal0 = b2RightPerp(edge0); - smoothParams.convex1 = b2Cross(edge0, edge1) >= convexTol; + b2Vec2 edge0 = b2Normalize( b2Sub( p1, smoothSegmentA->ghost1 ) ); + smoothParams.normal0 = b2RightPerp( edge0 ); + smoothParams.convex1 = b2Cross( edge0, edge1 ) >= convexTol; - b2Vec2 edge2 = b2Normalize(b2Sub(smoothSegmentA->ghost2, p2)); - smoothParams.normal2 = b2RightPerp(edge2); - smoothParams.convex2 = b2Cross(edge1, edge2) >= convexTol; + b2Vec2 edge2 = b2Normalize( b2Sub( smoothSegmentA->ghost2, p2 ) ); + smoothParams.normal2 = b2RightPerp( edge2 ); + smoothParams.convex2 = b2Cross( edge1, edge2 ) >= convexTol; // Normal points to the right - b2Vec2 normal1 = b2RightPerp(edge1); - bool behind1 = b2Dot(normal1, b2Sub(centroidB, p1)) < 0.0f; + b2Vec2 normal1 = b2RightPerp( edge1 ); + bool behind1 = b2Dot( normal1, b2Sub( centroidB, p1 ) ) < 0.0f; bool behind0 = true; bool behind2 = true; - if (smoothParams.convex1) + if ( smoothParams.convex1 ) { - behind0 = b2Dot(smoothParams.normal0, b2Sub(centroidB, p1)) < 0.0f; + behind0 = b2Dot( smoothParams.normal0, b2Sub( centroidB, p1 ) ) < 0.0f; } - if (smoothParams.convex2) + if ( smoothParams.convex2 ) { - behind2 = b2Dot(smoothParams.normal2, b2Sub(centroidB, p2)) < 0.0f; + behind2 = b2Dot( smoothParams.normal2, b2Sub( centroidB, p2 ) ) < 0.0f; } - if (behind1 && behind0 && behind2) + if ( behind1 && behind0 && behind2 ) { // one-sided collision return manifold; @@ -994,23 +993,23 @@ b2Manifold b2CollideSmoothSegmentAndPolygon(const b2SmoothSegment* smoothSegment int32_t count = polygonB->count; b2Vec2 vertices[b2_maxPolygonVertices]; b2Vec2 normals[b2_maxPolygonVertices]; - for (int32_t i = 0; i < count; ++i) + for ( int32_t i = 0; i < count; ++i ) { - vertices[i] = b2TransformPoint(xf, polygonB->vertices[i]); - normals[i] = b2RotateVector(xf.q, polygonB->normals[i]); + vertices[i] = b2TransformPoint( xf, polygonB->vertices[i] ); + normals[i] = b2RotateVector( xf.q, polygonB->normals[i] ); } // Distance doesn't work correctly with partial polygons b2DistanceInput input; - input.proxyA = b2MakeProxy(&smoothSegmentA->segment.point1, 2, 0.0f); - input.proxyB = b2MakeProxy(vertices, count, 0.0f); + input.proxyA = b2MakeProxy( &smoothSegmentA->segment.point1, 2, 0.0f ); + input.proxyB = b2MakeProxy( vertices, count, 0.0f ); input.transformA = b2Transform_identity; input.transformB = b2Transform_identity; input.useRadii = false; - b2DistanceOutput output = b2ShapeDistance(cache, &input, NULL, 0); + b2DistanceOutput output = b2ShapeDistance( cache, &input, NULL, 0 ); - if (output.distance > radiusB + b2_speculativeDistance) + if ( output.distance > radiusB + b2_speculativeDistance ) { return manifold; } @@ -1023,34 +1022,34 @@ b2Manifold b2CollideSmoothSegmentAndPolygon(const b2SmoothSegment* smoothSegment int32_t incidentIndex = -1; int32_t incidentNormal = -1; - if (behind1 == false && output.distance > 0.1f * b2_linearSlop) + if ( behind1 == false && output.distance > 0.1f * b2_linearSlop ) { // The closest features may be two vertices or an edge and a vertex even when there should // be face contact - if (cache->count == 1) + if ( cache->count == 1 ) { // vertex-vertex collision b2Vec2 pA = output.pointA; b2Vec2 pB = output.pointB; - b2Vec2 normal = b2Normalize(b2Sub(pB, pA)); + b2Vec2 normal = b2Normalize( b2Sub( pB, pA ) ); - enum b2NormalType type = b2ClassifyNormal(smoothParams, normal); - if (type == b2_normalSkip) + enum b2NormalType type = b2ClassifyNormal( smoothParams, normal ); + if ( type == b2_normalSkip ) { return manifold; } - - if (type == b2_normalAdmit) + + if ( type == b2_normalAdmit ) { - manifold.normal = b2RotateVector(xfA.q, normal); + manifold.normal = b2RotateVector( xfA.q, normal ); b2ManifoldPoint* cp = manifold.points + 0; - cp->anchorA = b2RotateVector(xfA.q, pA); - cp->anchorB = b2Add(cp->anchorA, b2Sub(xfA.p, xfB.p)); - cp->point = b2Add(xfA.p, cp->anchorA); + cp->anchorA = b2RotateVector( xfA.q, pA ); + cp->anchorB = b2Add( cp->anchorA, b2Sub( xfA.p, xfB.p ) ); + cp->point = b2Add( xfA.p, cp->anchorA ); cp->separation = output.distance - radiusB; - cp->id = B2_MAKE_ID(cache->indexA[0], cache->indexB[0]); + cp->id = B2_MAKE_ID( cache->indexA[0], cache->indexB[0] ); manifold.pointCount = 1; return manifold; } @@ -1061,35 +1060,35 @@ b2Manifold b2CollideSmoothSegmentAndPolygon(const b2SmoothSegment* smoothSegment else { // vertex-edge collision - B2_ASSERT(cache->count == 2); + B2_ASSERT( cache->count == 2 ); int32_t ia1 = cache->indexA[0]; int32_t ia2 = cache->indexA[1]; int32_t ib1 = cache->indexB[0]; int32_t ib2 = cache->indexB[1]; - if (ia1 == ia2) + if ( ia1 == ia2 ) { // 1 point on A, expect 2 points on B - B2_ASSERT(ib1 != ib2); + B2_ASSERT( ib1 != ib2 ); // Find polygon normal most aligned with vector between closest points. // This effectively sorts ib1 and ib2 - b2Vec2 normalB = b2Sub(output.pointA, output.pointB); - float dot1 = b2Dot(normalB, normals[ib1]); - float dot2 = b2Dot(normalB, normals[ib2]); + b2Vec2 normalB = b2Sub( output.pointA, output.pointB ); + float dot1 = b2Dot( normalB, normals[ib1] ); + float dot2 = b2Dot( normalB, normals[ib2] ); int32_t ib = dot1 > dot2 ? ib1 : ib2; // Use accurate normal normalB = normals[ib]; - enum b2NormalType type = b2ClassifyNormal(smoothParams, b2Neg(normalB)); - if (type == b2_normalSkip) + enum b2NormalType type = b2ClassifyNormal( smoothParams, b2Neg( normalB ) ); + if ( type == b2_normalSkip ) { return manifold; } - - if (type == b2_normalAdmit) + + if ( type == b2_normalAdmit ) { // Get polygon edge associated with normal ib1 = ib; @@ -1099,12 +1098,12 @@ b2Manifold b2CollideSmoothSegmentAndPolygon(const b2SmoothSegment* smoothSegment b2Vec2 b2 = vertices[ib2]; // Find incident segment vertex - dot1 = b2Dot(normalB, b2Sub(p1, b1)); - dot2 = b2Dot(normalB, b2Sub(p2, b1)); + dot1 = b2Dot( normalB, b2Sub( p1, b1 ) ); + dot2 = b2Dot( normalB, b2Sub( p2, b1 ) ); - if (dot1 < dot2) + if ( dot1 < dot2 ) { - if (b2Dot(n0, normalB) < b2Dot(normal1, normalB)) + if ( b2Dot( n0, normalB ) < b2Dot( normal1, normalB ) ) { // Neighbor is incident return manifold; @@ -1112,22 +1111,23 @@ b2Manifold b2CollideSmoothSegmentAndPolygon(const b2SmoothSegment* smoothSegment } else { - if (b2Dot(n2, normalB) < b2Dot(normal1, normalB)) + if ( b2Dot( n2, normalB ) < b2Dot( normal1, normalB ) ) { // Neighbor is incident return manifold; } } - manifold = b2ClipSegments(b1, b2, p1, p2, normalB, radiusB, 0.0f, B2_MAKE_ID(ib1, 1), B2_MAKE_ID(ib2, 0)); - manifold.normal = b2RotateVector(xfA.q, b2Neg(normalB)); - manifold.points[0].anchorA = b2RotateVector(xfA.q, manifold.points[0].anchorA); - manifold.points[1].anchorA = b2RotateVector(xfA.q, manifold.points[1].anchorA); - b2Vec2 pAB = b2Sub(xfA.p, xfB.p); - manifold.points[0].anchorB = b2Add(manifold.points[0].anchorA, pAB); - manifold.points[1].anchorB = b2Add(manifold.points[1].anchorA, pAB); - manifold.points[0].point = b2Add(xfA.p, manifold.points[0].anchorA); - manifold.points[1].point = b2Add(xfA.p, manifold.points[1].anchorA); + manifold = + b2ClipSegments( b1, b2, p1, p2, normalB, radiusB, 0.0f, B2_MAKE_ID( ib1, 1 ), B2_MAKE_ID( ib2, 0 ) ); + manifold.normal = b2RotateVector( xfA.q, b2Neg( normalB ) ); + manifold.points[0].anchorA = b2RotateVector( xfA.q, manifold.points[0].anchorA ); + manifold.points[1].anchorA = b2RotateVector( xfA.q, manifold.points[1].anchorA ); + b2Vec2 pAB = b2Sub( xfA.p, xfB.p ); + manifold.points[0].anchorB = b2Add( manifold.points[0].anchorA, pAB ); + manifold.points[1].anchorB = b2Add( manifold.points[1].anchorA, pAB ); + manifold.points[0].point = b2Add( xfA.p, manifold.points[0].anchorA ); + manifold.points[1].point = b2Add( xfA.p, manifold.points[1].anchorA ); return manifold; } @@ -1137,8 +1137,8 @@ b2Manifold b2CollideSmoothSegmentAndPolygon(const b2SmoothSegment* smoothSegment else { // Get index of incident polygonB vertex - float dot1 = b2Dot(normal1, b2Sub(vertices[ib1], p1)); - float dot2 = b2Dot(normal1, b2Sub(vertices[ib2], p2)); + float dot1 = b2Dot( normal1, b2Sub( vertices[ib1], p1 ) ); + float dot2 = b2Dot( normal1, b2Sub( vertices[ib2], p2 ) ); incidentIndex = dot1 < dot2 ? ib1 : ib2; } } @@ -1148,10 +1148,10 @@ b2Manifold b2CollideSmoothSegmentAndPolygon(const b2SmoothSegment* smoothSegment // SAT edge normal float edgeSeparation = FLT_MAX; - for (int32_t i = 0; i < count; ++i) + for ( int32_t i = 0; i < count; ++i ) { - float s = b2Dot(normal1, b2Sub(vertices[i], p1)); - if (s < edgeSeparation) + float s = b2Dot( normal1, b2Sub( vertices[i], p1 ) ); + if ( s < edgeSeparation ) { edgeSeparation = s; incidentIndex = i; @@ -1159,20 +1159,20 @@ b2Manifold b2CollideSmoothSegmentAndPolygon(const b2SmoothSegment* smoothSegment } // Check convex neighbor for edge separation - if (smoothParams.convex1) + if ( smoothParams.convex1 ) { float s0 = FLT_MAX; - for (int32_t i = 0; i < count; ++i) + for ( int32_t i = 0; i < count; ++i ) { - float s = b2Dot(smoothParams.normal0, b2Sub(vertices[i], p1)); - if (s < s0) + float s = b2Dot( smoothParams.normal0, b2Sub( vertices[i], p1 ) ); + if ( s < s0 ) { s0 = s; } } - if (s0 > edgeSeparation) + if ( s0 > edgeSeparation ) { edgeSeparation = s0; @@ -1182,20 +1182,20 @@ b2Manifold b2CollideSmoothSegmentAndPolygon(const b2SmoothSegment* smoothSegment } // Check convex neighbor for edge separation - if (smoothParams.convex2) + if ( smoothParams.convex2 ) { float s2 = FLT_MAX; - for (int32_t i = 0; i < count; ++i) + for ( int32_t i = 0; i < count; ++i ) { - float s = b2Dot(smoothParams.normal2, b2Sub(vertices[i], p2)); - if (s < s2) + float s = b2Dot( smoothParams.normal2, b2Sub( vertices[i], p2 ) ); + if ( s < s2 ) { s2 = s; } } - if (s2 > edgeSeparation) + if ( s2 > edgeSeparation ) { edgeSeparation = s2; @@ -1208,33 +1208,33 @@ b2Manifold b2CollideSmoothSegmentAndPolygon(const b2SmoothSegment* smoothSegment float polygonSeparation = -FLT_MAX; int32_t referenceIndex = -1; - for (int32_t i = 0; i < count; ++i) + for ( int32_t i = 0; i < count; ++i ) { b2Vec2 n = normals[i]; - enum b2NormalType type = b2ClassifyNormal(smoothParams, b2Neg(n)); - if (type != b2_normalAdmit) + enum b2NormalType type = b2ClassifyNormal( smoothParams, b2Neg( n ) ); + if ( type != b2_normalAdmit ) { continue; } // Check the infinite sides of the partial polygon - //if ((smoothParams.convex1 && b2Cross(n0, n) > 0.0f) || (smoothParams.convex2 && b2Cross(n, n2) > 0.0f)) + // if ((smoothParams.convex1 && b2Cross(n0, n) > 0.0f) || (smoothParams.convex2 && b2Cross(n, n2) > 0.0f)) //{ // continue; //} b2Vec2 p = vertices[i]; - float s = b2MinFloat(b2Dot(n, b2Sub(p2, p)), b2Dot(n, b2Sub(p1, p))); + float s = b2MinFloat( b2Dot( n, b2Sub( p2, p ) ), b2Dot( n, b2Sub( p1, p ) ) ); - if (s > polygonSeparation) + if ( s > polygonSeparation ) { polygonSeparation = s; referenceIndex = i; } } - if (polygonSeparation > edgeSeparation) + if ( polygonSeparation > edgeSeparation ) { int32_t ia1 = referenceIndex; int32_t ia2 = ia1 < count - 1 ? ia1 + 1 : 0; @@ -1243,12 +1243,12 @@ b2Manifold b2CollideSmoothSegmentAndPolygon(const b2SmoothSegment* smoothSegment b2Vec2 n = normals[ia1]; - float dot1 = b2Dot(n, b2Sub(p1, a1)); - float dot2 = b2Dot(n, b2Sub(p2, a1)); + float dot1 = b2Dot( n, b2Sub( p1, a1 ) ); + float dot2 = b2Dot( n, b2Sub( p2, a1 ) ); - if (dot1 < dot2) + if ( dot1 < dot2 ) { - if (b2Dot(n0, n) < b2Dot(normal1, n)) + if ( b2Dot( n0, n ) < b2Dot( normal1, n ) ) { // Neighbor is incident return manifold; @@ -1256,26 +1256,26 @@ b2Manifold b2CollideSmoothSegmentAndPolygon(const b2SmoothSegment* smoothSegment } else { - if (b2Dot(n2, n) < b2Dot(normal1, n)) + if ( b2Dot( n2, n ) < b2Dot( normal1, n ) ) { // Neighbor is incident return manifold; } } - manifold = b2ClipSegments(a1, a2, p1, p2, normals[ia1], radiusB, 0.0f, B2_MAKE_ID(ia1, 1), B2_MAKE_ID(ia2, 0)); - manifold.normal = b2RotateVector(xfA.q, b2Neg(normals[ia1])); - manifold.points[0].anchorA = b2RotateVector(xfA.q, manifold.points[0].anchorA); - manifold.points[1].anchorA = b2RotateVector(xfA.q, manifold.points[1].anchorA); - b2Vec2 pAB = b2Sub(xfA.p, xfB.p); - manifold.points[0].anchorB = b2Add(manifold.points[0].anchorA, pAB); - manifold.points[1].anchorB = b2Add(manifold.points[1].anchorA, pAB); - manifold.points[0].point = b2Add(xfA.p, manifold.points[0].anchorA); - manifold.points[1].point = b2Add(xfA.p, manifold.points[1].anchorA); + manifold = b2ClipSegments( a1, a2, p1, p2, normals[ia1], radiusB, 0.0f, B2_MAKE_ID( ia1, 1 ), B2_MAKE_ID( ia2, 0 ) ); + manifold.normal = b2RotateVector( xfA.q, b2Neg( normals[ia1] ) ); + manifold.points[0].anchorA = b2RotateVector( xfA.q, manifold.points[0].anchorA ); + manifold.points[1].anchorA = b2RotateVector( xfA.q, manifold.points[1].anchorA ); + b2Vec2 pAB = b2Sub( xfA.p, xfB.p ); + manifold.points[0].anchorB = b2Add( manifold.points[0].anchorA, pAB ); + manifold.points[1].anchorB = b2Add( manifold.points[1].anchorA, pAB ); + manifold.points[0].point = b2Add( xfA.p, manifold.points[0].anchorA ); + manifold.points[1].point = b2Add( xfA.p, manifold.points[1].anchorA ); return manifold; } - if (incidentIndex == -1) + if ( incidentIndex == -1 ) { // neighboring segment is the separating axis return manifold; @@ -1284,7 +1284,7 @@ b2Manifold b2CollideSmoothSegmentAndPolygon(const b2SmoothSegment* smoothSegment // fall through segment normal axis } - B2_ASSERT(incidentNormal != -1 || incidentIndex != -1); + B2_ASSERT( incidentNormal != -1 || incidentIndex != -1 ); // Segment normal @@ -1292,7 +1292,7 @@ b2Manifold b2CollideSmoothSegmentAndPolygon(const b2SmoothSegment* smoothSegment b2Vec2 b1, b2; int32_t ib1, ib2; - if (incidentNormal != -1) + if ( incidentNormal != -1 ) { ib1 = incidentNormal; ib2 = ib1 < count - 1 ? ib1 + 1 : 0; @@ -1303,9 +1303,9 @@ b2Manifold b2CollideSmoothSegmentAndPolygon(const b2SmoothSegment* smoothSegment { int32_t i2 = incidentIndex; int32_t i1 = i2 > 0 ? i2 - 1 : count - 1; - float d1 = b2Dot(normal1, normals[i1]); - float d2 = b2Dot(normal1, normals[i2]); - if (d1 < d2) + float d1 = b2Dot( normal1, normals[i1] ); + float d2 = b2Dot( normal1, normals[i2] ); + if ( d1 < d2 ) { ib1 = i1, ib2 = i2; b1 = vertices[ib1]; @@ -1319,15 +1319,15 @@ b2Manifold b2CollideSmoothSegmentAndPolygon(const b2SmoothSegment* smoothSegment } } - manifold = b2ClipSegments(p1, p2, b1, b2, normal1, 0.0f, radiusB, B2_MAKE_ID(0, ib2), B2_MAKE_ID(1, ib1)); - manifold.normal = b2RotateVector(xfA.q, manifold.normal); - manifold.points[0].anchorA = b2RotateVector(xfA.q, manifold.points[0].anchorA); - manifold.points[1].anchorA = b2RotateVector(xfA.q, manifold.points[1].anchorA); - b2Vec2 pAB = b2Sub(xfA.p, xfB.p); - manifold.points[0].anchorB = b2Add(manifold.points[0].anchorA, pAB); - manifold.points[1].anchorB = b2Add(manifold.points[1].anchorA, pAB); - manifold.points[0].point = b2Add(xfA.p, manifold.points[0].anchorA); - manifold.points[1].point = b2Add(xfA.p, manifold.points[1].anchorA); + manifold = b2ClipSegments( p1, p2, b1, b2, normal1, 0.0f, radiusB, B2_MAKE_ID( 0, ib2 ), B2_MAKE_ID( 1, ib1 ) ); + manifold.normal = b2RotateVector( xfA.q, manifold.normal ); + manifold.points[0].anchorA = b2RotateVector( xfA.q, manifold.points[0].anchorA ); + manifold.points[1].anchorA = b2RotateVector( xfA.q, manifold.points[1].anchorA ); + b2Vec2 pAB = b2Sub( xfA.p, xfB.p ); + manifold.points[0].anchorB = b2Add( manifold.points[0].anchorA, pAB ); + manifold.points[1].anchorB = b2Add( manifold.points[1].anchorA, pAB ); + manifold.points[0].point = b2Add( xfA.p, manifold.points[0].anchorA ); + manifold.points[1].point = b2Add( xfA.p, manifold.points[1].anchorA ); return manifold; } diff --git a/src/math_functions.c b/src/math_functions.c index 2e06d440..d3b1c047 100644 --- a/src/math_functions.c +++ b/src/math_functions.c @@ -1,20 +1,20 @@ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT -#include "core.h" - #include "box2d/math_functions.h" +#include "core.h" + #include -bool b2IsValid(float a) +bool b2IsValid( float a ) { - if (isnan(a)) + if ( isnan( a ) ) { return false; } - if (isinf(a)) + if ( isinf( a ) ) { return false; } @@ -22,14 +22,14 @@ bool b2IsValid(float a) return true; } -bool b2Vec2_IsValid(b2Vec2 v) +bool b2Vec2_IsValid( b2Vec2 v ) { - if (isnan(v.x) || isnan(v.y)) + if ( isnan( v.x ) || isnan( v.y ) ) { return false; } - if (isinf(v.x) || isinf(v.y)) + if ( isinf( v.x ) || isinf( v.y ) ) { return false; } @@ -37,57 +37,57 @@ bool b2Vec2_IsValid(b2Vec2 v) return true; } -bool b2Rot_IsValid(b2Rot q) +bool b2Rot_IsValid( b2Rot q ) { - if (isnan(q.s) || isnan(q.c)) + if ( isnan( q.s ) || isnan( q.c ) ) { return false; } - if (isinf(q.s) || isinf(q.c)) + if ( isinf( q.s ) || isinf( q.c ) ) { return false; } - return b2IsNormalized(q); + return b2IsNormalized( q ); } -b2Vec2 b2Normalize(b2Vec2 v) +b2Vec2 b2Normalize( b2Vec2 v ) { - float length = b2Length(v); - if (length < FLT_EPSILON) + float length = b2Length( v ); + if ( length < FLT_EPSILON ) { return b2Vec2_zero; } float invLength = 1.0f / length; - b2Vec2 n = {invLength * v.x, invLength * v.y}; + b2Vec2 n = { invLength * v.x, invLength * v.y }; return n; } -b2Vec2 b2NormalizeChecked(b2Vec2 v) +b2Vec2 b2NormalizeChecked( b2Vec2 v ) { - float length = b2Length(v); - if (length < FLT_EPSILON) + float length = b2Length( v ); + if ( length < FLT_EPSILON ) { - B2_ASSERT(false); + B2_ASSERT( false ); return b2Vec2_zero; } float invLength = 1.0f / length; - b2Vec2 n = {invLength * v.x, invLength * v.y}; + b2Vec2 n = { invLength * v.x, invLength * v.y }; return n; } -b2Vec2 b2GetLengthAndNormalize(float* length, b2Vec2 v) +b2Vec2 b2GetLengthAndNormalize( float* length, b2Vec2 v ) { - *length = b2Length(v); - if (*length < FLT_EPSILON) + *length = b2Length( v ); + if ( *length < FLT_EPSILON ) { return b2Vec2_zero; } float invLength = 1.0f / *length; - b2Vec2 n = {invLength * v.x, invLength * v.y}; + b2Vec2 n = { invLength * v.x, invLength * v.y }; return n; } diff --git a/src/motor_joint.c b/src/motor_joint.c index 26749795..9bfba1bb 100644 --- a/src/motor_joint.c +++ b/src/motor_joint.c @@ -11,73 +11,73 @@ // needed for dll export #include "box2d/box2d.h" -void b2MotorJoint_SetLinearOffset(b2JointId jointId, b2Vec2 linearOffset) +void b2MotorJoint_SetLinearOffset( b2JointId jointId, b2Vec2 linearOffset ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_motorJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); joint->motorJoint.linearOffset = linearOffset; } -b2Vec2 b2MotorJoint_GetLinearOffset(b2JointId jointId) +b2Vec2 b2MotorJoint_GetLinearOffset( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_motorJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); return joint->motorJoint.linearOffset; } -void b2MotorJoint_SetAngularOffset(b2JointId jointId, float angularOffset) +void b2MotorJoint_SetAngularOffset( b2JointId jointId, float angularOffset ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_motorJoint); - joint->motorJoint.angularOffset = b2ClampFloat(angularOffset, -b2_pi, b2_pi); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); + joint->motorJoint.angularOffset = b2ClampFloat( angularOffset, -b2_pi, b2_pi ); } -float b2MotorJoint_GetAngularOffset(b2JointId jointId) +float b2MotorJoint_GetAngularOffset( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_motorJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); return joint->motorJoint.angularOffset; } -void b2MotorJoint_SetMaxForce(b2JointId jointId, float maxForce) +void b2MotorJoint_SetMaxForce( b2JointId jointId, float maxForce ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_motorJoint); - joint->motorJoint.maxForce = b2MaxFloat(0.0f, maxForce); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); + joint->motorJoint.maxForce = b2MaxFloat( 0.0f, maxForce ); } -float b2MotorJoint_GetMaxForce(b2JointId jointId) +float b2MotorJoint_GetMaxForce( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_motorJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); return joint->motorJoint.maxForce; } -void b2MotorJoint_SetMaxTorque(b2JointId jointId, float maxTorque) +void b2MotorJoint_SetMaxTorque( b2JointId jointId, float maxTorque ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_motorJoint); - joint->motorJoint.maxTorque = b2MaxFloat(0.0f, maxTorque); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); + joint->motorJoint.maxTorque = b2MaxFloat( 0.0f, maxTorque ); } -float b2MotorJoint_GetMaxTorque(b2JointId jointId) +float b2MotorJoint_GetMaxTorque( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_motorJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); return joint->motorJoint.maxTorque; } -void b2MotorJoint_SetCorrectionFactor(b2JointId jointId, float correctionFactor) +void b2MotorJoint_SetCorrectionFactor( b2JointId jointId, float correctionFactor ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_motorJoint); - joint->motorJoint.correctionFactor = b2ClampFloat(correctionFactor, 0.0f, 1.0f); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); + joint->motorJoint.correctionFactor = b2ClampFloat( correctionFactor, 0.0f, 1.0f ); } -float b2MotorJoint_GetCorrectionFactor(b2JointId jointId) +float b2MotorJoint_GetCorrectionFactor( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_motorJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_motorJoint ); return joint->motorJoint.correctionFactor; } -b2Vec2 b2GetMotorJointForce(b2World* world, b2JointSim* base) +b2Vec2 b2GetMotorJointForce( b2World* world, b2JointSim* base ) { - b2Vec2 force = b2MulSV(world->inv_h, base->motorJoint.linearImpulse); + b2Vec2 force = b2MulSV( world->inv_h, base->motorJoint.linearImpulse ); return force; } -float b2GetMotorJointTorque(b2World* world, b2JointSim* base) +float b2GetMotorJointTorque( b2World* world, b2JointSim* base ) { return world->inv_h * base->motorJoint.angularImpulse; } @@ -96,9 +96,9 @@ float b2GetMotorJointTorque(b2World* world, b2JointSim* base) // J = [0 0 -1 0 0 1] // K = invI1 + invI2 -void b2PrepareMotorJoint(b2JointSim* base, b2StepContext* context) +void b2PrepareMotorJoint( b2JointSim* base, b2StepContext* context ) { - B2_ASSERT(base->type == b2_motorJoint); + B2_ASSERT( base->type == b2_motorJoint ); // chase body id to the solver set where the body lives int idA = base->bodyIdA; @@ -107,15 +107,15 @@ void b2PrepareMotorJoint(b2JointSim* base, b2StepContext* context) b2World* world = context->world; b2Body* bodies = world->bodyArray; - b2CheckIndex(bodies, idA); - b2CheckIndex(bodies, idB); + b2CheckIndex( bodies, idA ); + b2CheckIndex( bodies, idB ); b2Body* bodyA = bodies + idA; b2Body* bodyB = bodies + idB; - B2_ASSERT(bodyA->setIndex == b2_awakeSet || bodyB->setIndex == b2_awakeSet); - b2CheckIndex(world->solverSetArray, bodyA->setIndex); - b2CheckIndex(world->solverSetArray, bodyB->setIndex); + B2_ASSERT( bodyA->setIndex == b2_awakeSet || bodyB->setIndex == b2_awakeSet ); + b2CheckIndex( world->solverSetArray, bodyA->setIndex ); + b2CheckIndex( world->solverSetArray, bodyB->setIndex ); b2SolverSet* setA = world->solverSetArray + bodyA->setIndex; b2SolverSet* setB = world->solverSetArray + bodyB->setIndex; @@ -123,8 +123,8 @@ void b2PrepareMotorJoint(b2JointSim* base, b2StepContext* context) int localIndexA = bodyA->localIndex; int localIndexB = bodyB->localIndex; - B2_ASSERT(0 <= localIndexA && localIndexA <= setA->sims.count); - B2_ASSERT(0 <= localIndexB && localIndexB <= setB->sims.count); + B2_ASSERT( 0 <= localIndexA && localIndexA <= setA->sims.count ); + B2_ASSERT( 0 <= localIndexB && localIndexB <= setB->sims.count ); b2BodySim* bodySimA = setA->sims.data + bodyA->localIndex; b2BodySim* bodySimB = setB->sims.data + bodyB->localIndex; @@ -143,11 +143,11 @@ void b2PrepareMotorJoint(b2JointSim* base, b2StepContext* context) joint->indexA = bodyA->setIndex == b2_awakeSet ? localIndexA : B2_NULL_INDEX; joint->indexB = bodyB->setIndex == b2_awakeSet ? localIndexB : B2_NULL_INDEX; - joint->anchorA = b2RotateVector(bodySimA->transform.q, b2Sub(base->localOriginAnchorA, bodySimA->localCenter)); - joint->anchorB = b2RotateVector(bodySimB->transform.q, b2Sub(base->localOriginAnchorB, bodySimB->localCenter)); - joint->deltaCenter = b2Sub(b2Sub(bodySimB->center, bodySimA->center), joint->linearOffset); - joint->deltaAngle = b2RelativeAngle(bodySimB->transform.q, bodySimA->transform.q) - joint->angularOffset; - joint->deltaAngle = b2UnwindAngle(joint->deltaAngle); + joint->anchorA = b2RotateVector( bodySimA->transform.q, b2Sub( base->localOriginAnchorA, bodySimA->localCenter ) ); + joint->anchorB = b2RotateVector( bodySimB->transform.q, b2Sub( base->localOriginAnchorB, bodySimB->localCenter ) ); + joint->deltaCenter = b2Sub( b2Sub( bodySimB->center, bodySimA->center ), joint->linearOffset ); + joint->deltaAngle = b2RelativeAngle( bodySimB->transform.q, bodySimA->transform.q ) - joint->angularOffset; + joint->deltaAngle = b2UnwindAngle( joint->deltaAngle ); b2Vec2 rA = joint->anchorA; b2Vec2 rB = joint->anchorB; @@ -157,19 +157,19 @@ void b2PrepareMotorJoint(b2JointSim* base, b2StepContext* context) K.cx.y = -rA.y * rA.x * iA - rB.y * rB.x * iB; K.cy.x = K.cx.y; K.cy.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; - joint->linearMass = b2GetInverse22(K); + joint->linearMass = b2GetInverse22( K ); float ka = iA + iB; joint->angularMass = ka > 0.0f ? 1.0f / ka : 0.0f; - if (context->enableWarmStarting == false) + if ( context->enableWarmStarting == false ) { joint->linearImpulse = b2Vec2_zero; joint->angularImpulse = 0.0f; } } -void b2WarmStartMotorJoint(b2JointSim* base, b2StepContext* context) +void b2WarmStartMotorJoint( b2JointSim* base, b2StepContext* context ) { float mA = base->invMassA; float mB = base->invMassB; @@ -184,18 +184,18 @@ void b2WarmStartMotorJoint(b2JointSim* base, b2StepContext* context) b2BodyState* bodyA = joint->indexA == B2_NULL_INDEX ? &dummyState : context->states + joint->indexA; b2BodyState* bodyB = joint->indexB == B2_NULL_INDEX ? &dummyState : context->states + joint->indexB; - b2Vec2 rA = b2RotateVector(bodyA->deltaRotation, joint->anchorA); - b2Vec2 rB = b2RotateVector(bodyB->deltaRotation, joint->anchorB); + b2Vec2 rA = b2RotateVector( bodyA->deltaRotation, joint->anchorA ); + b2Vec2 rB = b2RotateVector( bodyB->deltaRotation, joint->anchorB ); - bodyA->linearVelocity = b2MulSub(bodyA->linearVelocity, mA, joint->linearImpulse); - bodyA->angularVelocity -= iA * (b2Cross(rA, joint->linearImpulse) + joint->angularImpulse); - bodyB->linearVelocity = b2MulAdd(bodyB->linearVelocity, mB, joint->linearImpulse); - bodyB->angularVelocity += iB * (b2Cross(rB, joint->linearImpulse) + joint->angularImpulse); + bodyA->linearVelocity = b2MulSub( bodyA->linearVelocity, mA, joint->linearImpulse ); + bodyA->angularVelocity -= iA * ( b2Cross( rA, joint->linearImpulse ) + joint->angularImpulse ); + bodyB->linearVelocity = b2MulAdd( bodyB->linearVelocity, mB, joint->linearImpulse ); + bodyB->angularVelocity += iB * ( b2Cross( rB, joint->linearImpulse ) + joint->angularImpulse ); } -void b2SolveMotorJoint(b2JointSim* base, const b2StepContext* context, bool useBias) +void b2SolveMotorJoint( b2JointSim* base, b2StepContext* context, bool useBias ) { - B2_ASSERT(base->type == b2_motorJoint); + B2_ASSERT( base->type == b2_motorJoint ); float mA = base->invMassA; float mB = base->invMassB; @@ -216,17 +216,17 @@ void b2SolveMotorJoint(b2JointSim* base, const b2StepContext* context, bool useB // angular constraint { - float angularSeperation = b2RelativeAngle(bodyB->deltaRotation, bodyA->deltaRotation) + joint->deltaAngle; - angularSeperation = b2UnwindAngle(angularSeperation); + float angularSeperation = b2RelativeAngle( bodyB->deltaRotation, bodyA->deltaRotation ) + joint->deltaAngle; + angularSeperation = b2UnwindAngle( angularSeperation ); float angularBias = context->inv_h * joint->correctionFactor * angularSeperation; float Cdot = wB - wA; - float impulse = -joint->angularMass * (Cdot + angularBias); + float impulse = -joint->angularMass * ( Cdot + angularBias ); float oldImpulse = joint->angularImpulse; float maxImpulse = context->h * joint->maxTorque; - joint->angularImpulse = b2ClampFloat(joint->angularImpulse + impulse, -maxImpulse, maxImpulse); + joint->angularImpulse = b2ClampFloat( joint->angularImpulse + impulse, -maxImpulse, maxImpulse ); impulse = joint->angularImpulse - oldImpulse; wA -= iA * impulse; @@ -235,34 +235,34 @@ void b2SolveMotorJoint(b2JointSim* base, const b2StepContext* context, bool useB // linear constraint { - b2Vec2 rA = b2RotateVector(bodyA->deltaRotation, joint->anchorA); - b2Vec2 rB = b2RotateVector(bodyB->deltaRotation, joint->anchorB); + b2Vec2 rA = b2RotateVector( bodyA->deltaRotation, joint->anchorA ); + b2Vec2 rB = b2RotateVector( bodyB->deltaRotation, joint->anchorB ); - b2Vec2 ds = b2Add(b2Sub(bodyB->deltaPosition, bodyA->deltaPosition), b2Sub(rB, rA)); - b2Vec2 linearSeparation = b2Add(joint->deltaCenter, ds); - b2Vec2 linearBias = b2MulSV(context->inv_h * joint->correctionFactor, linearSeparation); + b2Vec2 ds = b2Add( b2Sub( bodyB->deltaPosition, bodyA->deltaPosition ), b2Sub( rB, rA ) ); + b2Vec2 linearSeparation = b2Add( joint->deltaCenter, ds ); + b2Vec2 linearBias = b2MulSV( context->inv_h * joint->correctionFactor, linearSeparation ); - b2Vec2 Cdot = b2Sub(b2Add(vB, b2CrossSV(wB, rB)), b2Add(vA, b2CrossSV(wA, rA))); - b2Vec2 b = b2MulMV(joint->linearMass, b2Add(Cdot, linearBias)); - b2Vec2 impulse = {-b.x, -b.y}; + b2Vec2 Cdot = b2Sub( b2Add( vB, b2CrossSV( wB, rB ) ), b2Add( vA, b2CrossSV( wA, rA ) ) ); + b2Vec2 b = b2MulMV( joint->linearMass, b2Add( Cdot, linearBias ) ); + b2Vec2 impulse = { -b.x, -b.y }; b2Vec2 oldImpulse = joint->linearImpulse; - float maxImpulse = context->h * joint->maxForce; - joint->linearImpulse = b2Add(joint->linearImpulse, impulse); + float maxImpulse = context->h * joint->maxForce; + joint->linearImpulse = b2Add( joint->linearImpulse, impulse ); - if (b2LengthSquared(joint->linearImpulse) > maxImpulse * maxImpulse) + if ( b2LengthSquared( joint->linearImpulse ) > maxImpulse * maxImpulse ) { - joint->linearImpulse = b2Normalize(joint->linearImpulse); + joint->linearImpulse = b2Normalize( joint->linearImpulse ); joint->linearImpulse.x *= maxImpulse; joint->linearImpulse.y *= maxImpulse; } - impulse = b2Sub(joint->linearImpulse, oldImpulse); + impulse = b2Sub( joint->linearImpulse, oldImpulse ); - vA = b2MulSub(vA, mA, impulse); - wA -= iA * b2Cross(rA, impulse); - vB = b2MulAdd(vB, mB, impulse); - wB += iB * b2Cross(rB, impulse); + vA = b2MulSub( vA, mA, impulse ); + wA -= iA * b2Cross( rA, impulse ); + vB = b2MulAdd( vB, mB, impulse ); + wB += iB * b2Cross( rB, impulse ); } bodyA->linearVelocity = vA; diff --git a/src/mouse_joint.c b/src/mouse_joint.c index 97f18b94..8856e90f 100644 --- a/src/mouse_joint.c +++ b/src/mouse_joint.c @@ -11,72 +11,72 @@ // needed for dll export #include "box2d/box2d.h" -void b2MouseJoint_SetTarget(b2JointId jointId, b2Vec2 target) +void b2MouseJoint_SetTarget( b2JointId jointId, b2Vec2 target ) { - B2_ASSERT(b2Vec2_IsValid(target)); - b2JointSim* base = b2GetJointSimCheckType(jointId, b2_mouseJoint); + B2_ASSERT( b2Vec2_IsValid( target ) ); + b2JointSim* base = b2GetJointSimCheckType( jointId, b2_mouseJoint ); base->mouseJoint.targetA = target; } -b2Vec2 b2MouseJoint_GetTarget(b2JointId jointId) +b2Vec2 b2MouseJoint_GetTarget( b2JointId jointId ) { - b2JointSim* base = b2GetJointSimCheckType(jointId, b2_mouseJoint); + b2JointSim* base = b2GetJointSimCheckType( jointId, b2_mouseJoint ); return base->mouseJoint.targetA; } -void b2MouseJoint_SetSpringHertz(b2JointId jointId, float hertz) +void b2MouseJoint_SetSpringHertz( b2JointId jointId, float hertz ) { - B2_ASSERT(b2IsValid(hertz) && hertz >= 0.0f); - b2JointSim* base = b2GetJointSimCheckType(jointId, b2_mouseJoint); + B2_ASSERT( b2IsValid( hertz ) && hertz >= 0.0f ); + b2JointSim* base = b2GetJointSimCheckType( jointId, b2_mouseJoint ); base->mouseJoint.hertz = hertz; } -float b2MouseJoint_GetSpringHertz(b2JointId jointId) +float b2MouseJoint_GetSpringHertz( b2JointId jointId ) { - b2JointSim* base = b2GetJointSimCheckType(jointId, b2_mouseJoint); + b2JointSim* base = b2GetJointSimCheckType( jointId, b2_mouseJoint ); return base->mouseJoint.hertz; } -void b2MouseJoint_SetSpringDampingRatio(b2JointId jointId, float dampingRatio) +void b2MouseJoint_SetSpringDampingRatio( b2JointId jointId, float dampingRatio ) { - B2_ASSERT(b2IsValid(dampingRatio) && dampingRatio >= 0.0f); - b2JointSim* base = b2GetJointSimCheckType(jointId, b2_mouseJoint); + B2_ASSERT( b2IsValid( dampingRatio ) && dampingRatio >= 0.0f ); + b2JointSim* base = b2GetJointSimCheckType( jointId, b2_mouseJoint ); base->mouseJoint.dampingRatio = dampingRatio; } -float b2MouseJoint_GetSpringDampingRatio(b2JointId jointId) +float b2MouseJoint_GetSpringDampingRatio( b2JointId jointId ) { - b2JointSim* base = b2GetJointSimCheckType(jointId, b2_mouseJoint); + b2JointSim* base = b2GetJointSimCheckType( jointId, b2_mouseJoint ); return base->mouseJoint.dampingRatio; } -void b2MouseJoint_SetMaxForce(b2JointId jointId, float maxForce) +void b2MouseJoint_SetMaxForce( b2JointId jointId, float maxForce ) { - B2_ASSERT(b2IsValid(maxForce) && maxForce >= 0.0f); - b2JointSim* base = b2GetJointSimCheckType(jointId, b2_mouseJoint); + B2_ASSERT( b2IsValid( maxForce ) && maxForce >= 0.0f ); + b2JointSim* base = b2GetJointSimCheckType( jointId, b2_mouseJoint ); base->mouseJoint.maxForce = maxForce; } -float b2MouseJoint_GetMaxForce(b2JointId jointId) +float b2MouseJoint_GetMaxForce( b2JointId jointId ) { - b2JointSim* base = b2GetJointSimCheckType(jointId, b2_mouseJoint); + b2JointSim* base = b2GetJointSimCheckType( jointId, b2_mouseJoint ); return base->mouseJoint.maxForce; } -b2Vec2 b2GetMouseJointForce(b2World* world, b2JointSim* base) +b2Vec2 b2GetMouseJointForce( b2World* world, b2JointSim* base ) { - b2Vec2 force = b2MulSV(world->inv_h, base->mouseJoint.linearImpulse); + b2Vec2 force = b2MulSV( world->inv_h, base->mouseJoint.linearImpulse ); return force; } -float b2GetMouseJointTorque(b2World* world, b2JointSim* base) +float b2GetMouseJointTorque( b2World* world, b2JointSim* base ) { return world->inv_h * base->mouseJoint.angularImpulse; } -void b2PrepareMouseJoint(b2JointSim* base, b2StepContext* context) +void b2PrepareMouseJoint( b2JointSim* base, b2StepContext* context ) { - B2_ASSERT(base->type == b2_mouseJoint); + B2_ASSERT( base->type == b2_mouseJoint ); // chase body id to the solver set where the body lives int idB = base->bodyIdB; @@ -84,17 +84,17 @@ void b2PrepareMouseJoint(b2JointSim* base, b2StepContext* context) b2World* world = context->world; b2Body* bodies = world->bodyArray; - b2CheckIndex(bodies, idB); + b2CheckIndex( bodies, idB ); b2Body* bodyB = bodies + idB; - B2_ASSERT(bodyB->setIndex == b2_awakeSet); - b2CheckIndex(world->solverSetArray, bodyB->setIndex); + B2_ASSERT( bodyB->setIndex == b2_awakeSet ); + b2CheckIndex( world->solverSetArray, bodyB->setIndex ); b2SolverSet* setB = world->solverSetArray + bodyB->setIndex; int localIndexB = bodyB->localIndex; - B2_ASSERT(0 <= localIndexB && localIndexB <= setB->sims.count); + B2_ASSERT( 0 <= localIndexB && localIndexB <= setB->sims.count ); b2BodySim* bodySimB = setB->sims.data + localIndexB; @@ -103,13 +103,13 @@ void b2PrepareMouseJoint(b2JointSim* base, b2StepContext* context) b2MouseJoint* joint = &base->mouseJoint; joint->indexB = bodyB->setIndex == b2_awakeSet ? localIndexB : B2_NULL_INDEX; - joint->anchorB = b2RotateVector(bodySimB->transform.q, b2Sub(base->localOriginAnchorB, bodySimB->localCenter)); + joint->anchorB = b2RotateVector( bodySimB->transform.q, b2Sub( base->localOriginAnchorB, bodySimB->localCenter ) ); - joint->linearSoftness = b2MakeSoft(joint->hertz, joint->dampingRatio, context->h); + joint->linearSoftness = b2MakeSoft( joint->hertz, joint->dampingRatio, context->h ); float angularHertz = 0.5f; float angularDampingRatio = 0.1f; - joint->angularSoftness = b2MakeSoft(angularHertz, angularDampingRatio, context->h); + joint->angularSoftness = b2MakeSoft( angularHertz, angularDampingRatio, context->h ); b2Vec2 rB = joint->anchorB; float mB = bodySimB->invMass; @@ -124,19 +124,19 @@ void b2PrepareMouseJoint(b2JointSim* base, b2StepContext* context) K.cy.x = K.cx.y; K.cy.y = mB + iB * rB.x * rB.x; - joint->linearMass = b2GetInverse22(K); - joint->deltaCenter = b2Sub(bodySimB->center, joint->targetA); + joint->linearMass = b2GetInverse22( K ); + joint->deltaCenter = b2Sub( bodySimB->center, joint->targetA ); - if (context->enableWarmStarting == false) + if ( context->enableWarmStarting == false ) { joint->linearImpulse = b2Vec2_zero; joint->angularImpulse = 0.0f; } } -void b2WarmStartMouseJoint(b2JointSim* base, b2StepContext* context) +void b2WarmStartMouseJoint( b2JointSim* base, b2StepContext* context ) { - B2_ASSERT(base->type == b2_mouseJoint); + B2_ASSERT( base->type == b2_mouseJoint ); float mB = base->invMassB; float iB = base->invIB; @@ -148,16 +148,16 @@ void b2WarmStartMouseJoint(b2JointSim* base, b2StepContext* context) float wB = stateB->angularVelocity; b2Rot dqB = stateB->deltaRotation; - b2Vec2 rB = b2RotateVector(dqB, joint->anchorB); + b2Vec2 rB = b2RotateVector( dqB, joint->anchorB ); - vB = b2MulAdd(vB, mB, joint->linearImpulse); - wB += iB * (b2Cross(rB, joint->linearImpulse) + joint->angularImpulse); + vB = b2MulAdd( vB, mB, joint->linearImpulse ); + wB += iB * ( b2Cross( rB, joint->linearImpulse ) + joint->angularImpulse ); stateB->linearVelocity = vB; stateB->angularVelocity = wB; } -void b2SolveMouseJoint(b2JointSim* base, b2StepContext* context) +void b2SolveMouseJoint( b2JointSim* base, b2StepContext* context ) { float mB = base->invMassB; float iB = base->invIB; @@ -184,16 +184,16 @@ void b2SolveMouseJoint(b2JointSim* base, b2StepContext* context) { b2Rot dqB = stateB->deltaRotation; - b2Vec2 rB = b2RotateVector(dqB, joint->anchorB); - b2Vec2 Cdot = b2Add(vB, b2CrossSV(wB, rB)); + b2Vec2 rB = b2RotateVector( dqB, joint->anchorB ); + b2Vec2 Cdot = b2Add( vB, b2CrossSV( wB, rB ) ); - b2Vec2 separation = b2Add(b2Add(stateB->deltaPosition, rB), joint->deltaCenter); - b2Vec2 bias = b2MulSV(joint->linearSoftness.biasRate, separation); + b2Vec2 separation = b2Add( b2Add( stateB->deltaPosition, rB ), joint->deltaCenter ); + b2Vec2 bias = b2MulSV( joint->linearSoftness.biasRate, separation ); float massScale = joint->linearSoftness.massScale; float impulseScale = joint->linearSoftness.impulseScale; - b2Vec2 b = b2MulMV(joint->linearMass, b2Add(Cdot, bias)); + b2Vec2 b = b2MulMV( joint->linearMass, b2Add( Cdot, bias ) ); b2Vec2 impulse; impulse.x = -massScale * b.x - impulseScale * joint->linearImpulse.x; @@ -203,17 +203,17 @@ void b2SolveMouseJoint(b2JointSim* base, b2StepContext* context) joint->linearImpulse.x += impulse.x; joint->linearImpulse.y += impulse.y; - float mag = b2Length(joint->linearImpulse); - if (mag > maxImpulse) + float mag = b2Length( joint->linearImpulse ); + if ( mag > maxImpulse ) { - joint->linearImpulse = b2MulSV(maxImpulse, b2Normalize(joint->linearImpulse)); + joint->linearImpulse = b2MulSV( maxImpulse, b2Normalize( joint->linearImpulse ) ); } impulse.x = joint->linearImpulse.x - oldImpulse.x; impulse.y = joint->linearImpulse.y - oldImpulse.y; - vB = b2MulAdd(vB, mB, impulse); - wB += iB * b2Cross(rB, impulse); + vB = b2MulAdd( vB, mB, impulse ); + wB += iB * b2Cross( rB, impulse ); } stateB->linearVelocity = vB; diff --git a/src/prismatic_joint.c b/src/prismatic_joint.c index 88ad1ebe..ee62f06c 100644 --- a/src/prismatic_joint.c +++ b/src/prismatic_joint.c @@ -13,50 +13,50 @@ #include -void b2PrismaticJoint_EnableSpring(b2JointId jointId, bool enableSpring) +void b2PrismaticJoint_EnableSpring( b2JointId jointId, bool enableSpring ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_prismaticJoint); - if (enableSpring != joint->prismaticJoint.enableSpring) + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); + if ( enableSpring != joint->prismaticJoint.enableSpring ) { joint->prismaticJoint.enableSpring = enableSpring; joint->prismaticJoint.springImpulse = 0.0f; } } -bool b2PrismaticJoint_IsSpringEnabled(b2JointId jointId) +bool b2PrismaticJoint_IsSpringEnabled( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_prismaticJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); return joint->prismaticJoint.enableSpring; } -void b2PrismaticJoint_SetSpringHertz(b2JointId jointId, float hertz) +void b2PrismaticJoint_SetSpringHertz( b2JointId jointId, float hertz ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_prismaticJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); joint->prismaticJoint.hertz = hertz; } -float b2PrismaticJoint_GetSpringHertz(b2JointId jointId) +float b2PrismaticJoint_GetSpringHertz( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_prismaticJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); return joint->prismaticJoint.hertz; } -void b2PrismaticJoint_SetSpringDampingRatio(b2JointId jointId, float dampingRatio) +void b2PrismaticJoint_SetSpringDampingRatio( b2JointId jointId, float dampingRatio ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_prismaticJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); joint->prismaticJoint.dampingRatio = dampingRatio; } -float b2PrismaticJoint_GetSpringDampingRatio(b2JointId jointId) +float b2PrismaticJoint_GetSpringDampingRatio( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_prismaticJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); return joint->prismaticJoint.dampingRatio; } -void b2PrismaticJoint_EnableLimit(b2JointId jointId, bool enableLimit) +void b2PrismaticJoint_EnableLimit( b2JointId jointId, bool enableLimit ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_prismaticJoint); - if (enableLimit != joint->prismaticJoint.enableLimit) + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); + if ( enableLimit != joint->prismaticJoint.enableLimit ) { joint->prismaticJoint.enableLimit = enableLimit; joint->prismaticJoint.lowerImpulse = 0.0f; @@ -64,102 +64,102 @@ void b2PrismaticJoint_EnableLimit(b2JointId jointId, bool enableLimit) } } -bool b2PrismaticJoint_IsLimitEnabled(b2JointId jointId) +bool b2PrismaticJoint_IsLimitEnabled( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_prismaticJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); return joint->prismaticJoint.enableLimit; } -float b2PrismaticJoint_GetLowerLimit(b2JointId jointId) +float b2PrismaticJoint_GetLowerLimit( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_prismaticJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); return joint->prismaticJoint.lowerTranslation; } -float b2PrismaticJoint_GetUpperLimit(b2JointId jointId) +float b2PrismaticJoint_GetUpperLimit( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_prismaticJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); return joint->prismaticJoint.upperTranslation; } -void b2PrismaticJoint_SetLimits(b2JointId jointId, float lower, float upper) +void b2PrismaticJoint_SetLimits( b2JointId jointId, float lower, float upper ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_prismaticJoint); - if (lower != joint->prismaticJoint.lowerTranslation || upper != joint->prismaticJoint.upperTranslation) + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); + if ( lower != joint->prismaticJoint.lowerTranslation || upper != joint->prismaticJoint.upperTranslation ) { - joint->prismaticJoint.lowerTranslation = b2MinFloat(lower, upper); - joint->prismaticJoint.upperTranslation = b2MaxFloat(lower, upper); + joint->prismaticJoint.lowerTranslation = b2MinFloat( lower, upper ); + joint->prismaticJoint.upperTranslation = b2MaxFloat( lower, upper ); joint->prismaticJoint.lowerImpulse = 0.0f; joint->prismaticJoint.upperImpulse = 0.0f; } } -void b2PrismaticJoint_EnableMotor(b2JointId jointId, bool enableMotor) +void b2PrismaticJoint_EnableMotor( b2JointId jointId, bool enableMotor ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_prismaticJoint); - if (enableMotor != joint->prismaticJoint.enableMotor) + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); + if ( enableMotor != joint->prismaticJoint.enableMotor ) { joint->prismaticJoint.enableMotor = enableMotor; joint->prismaticJoint.motorImpulse = 0.0f; } } -bool b2PrismaticJoint_IsMotorEnabled(b2JointId jointId) +bool b2PrismaticJoint_IsMotorEnabled( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_prismaticJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); return joint->prismaticJoint.enableMotor; } -void b2PrismaticJoint_SetMotorSpeed(b2JointId jointId, float motorSpeed) +void b2PrismaticJoint_SetMotorSpeed( b2JointId jointId, float motorSpeed ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_prismaticJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); joint->prismaticJoint.motorSpeed = motorSpeed; } -float b2PrismaticJoint_GetMotorSpeed(b2JointId jointId) +float b2PrismaticJoint_GetMotorSpeed( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_prismaticJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); return joint->prismaticJoint.motorSpeed; } -float b2PrismaticJoint_GetMotorForce(b2JointId jointId) +float b2PrismaticJoint_GetMotorForce( b2JointId jointId ) { - b2World* world = b2GetWorld(jointId.world0); - b2JointSim* base = b2GetJointSimCheckType(jointId, b2_prismaticJoint); + b2World* world = b2GetWorld( jointId.world0 ); + b2JointSim* base = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); return world->inv_h * base->prismaticJoint.motorImpulse; } -void b2PrismaticJoint_SetMaxMotorForce(b2JointId jointId, float force) +void b2PrismaticJoint_SetMaxMotorForce( b2JointId jointId, float force ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_prismaticJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); joint->prismaticJoint.maxMotorForce = force; } -float b2PrismaticJoint_GetMaxMotorForce(b2JointId jointId) +float b2PrismaticJoint_GetMaxMotorForce( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_prismaticJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_prismaticJoint ); return joint->prismaticJoint.maxMotorForce; } -b2Vec2 b2GetPrismaticJointForce(b2World* world, b2JointSim* base) +b2Vec2 b2GetPrismaticJointForce( b2World* world, b2JointSim* base ) { int idA = base->bodyIdA; - b2Transform transformA = b2GetBodyTransform(world, idA); + b2Transform transformA = b2GetBodyTransform( world, idA ); b2PrismaticJoint* joint = &base->prismaticJoint; - b2Vec2 axisA = b2RotateVector(transformA.q, joint->localAxisA); - b2Vec2 perpA = b2LeftPerp(axisA); + b2Vec2 axisA = b2RotateVector( transformA.q, joint->localAxisA ); + b2Vec2 perpA = b2LeftPerp( axisA ); float inv_h = world->inv_h; float perpForce = inv_h * joint->impulse.x; - float axialForce = inv_h * (joint->motorImpulse + joint->lowerImpulse - joint->upperImpulse); + float axialForce = inv_h * ( joint->motorImpulse + joint->lowerImpulse - joint->upperImpulse ); - b2Vec2 force = b2Add(b2MulSV(perpForce, perpA), b2MulSV(axialForce, axisA)); + b2Vec2 force = b2Add( b2MulSV( perpForce, perpA ), b2MulSV( axialForce, axisA ) ); return force; } -float b2GetPrismaticJointTorque(b2World* world, b2JointSim* base) +float b2GetPrismaticJointTorque( b2World* world, b2JointSim* base ) { return world->inv_h * base->prismaticJoint.impulse.y; } @@ -209,9 +209,9 @@ float b2GetPrismaticJointTorque(b2World* world, b2JointSim* base) // s1 = cross(d + r1, u), s2 = cross(r2, u) // a1 = cross(d + r1, v), a2 = cross(r2, v) -void b2PreparePrismaticJoint(b2JointSim* base, b2StepContext* context) +void b2PreparePrismaticJoint( b2JointSim* base, b2StepContext* context ) { - B2_ASSERT(base->type == b2_prismaticJoint); + B2_ASSERT( base->type == b2_prismaticJoint ); // chase body id to the solver set where the body lives int idA = base->bodyIdA; @@ -220,15 +220,15 @@ void b2PreparePrismaticJoint(b2JointSim* base, b2StepContext* context) b2World* world = context->world; b2Body* bodies = world->bodyArray; - b2CheckIndex(bodies, idA); - b2CheckIndex(bodies, idB); + b2CheckIndex( bodies, idA ); + b2CheckIndex( bodies, idB ); b2Body* bodyA = bodies + idA; b2Body* bodyB = bodies + idB; - B2_ASSERT(bodyA->setIndex == b2_awakeSet || bodyB->setIndex == b2_awakeSet); - b2CheckIndex(world->solverSetArray, bodyA->setIndex); - b2CheckIndex(world->solverSetArray, bodyB->setIndex); + B2_ASSERT( bodyA->setIndex == b2_awakeSet || bodyB->setIndex == b2_awakeSet ); + b2CheckIndex( world->solverSetArray, bodyA->setIndex ); + b2CheckIndex( world->solverSetArray, bodyB->setIndex ); b2SolverSet* setA = world->solverSetArray + bodyA->setIndex; b2SolverSet* setB = world->solverSetArray + bodyB->setIndex; @@ -236,8 +236,8 @@ void b2PreparePrismaticJoint(b2JointSim* base, b2StepContext* context) int localIndexA = bodyA->localIndex; int localIndexB = bodyB->localIndex; - B2_ASSERT(0 <= localIndexA && localIndexA <= setA->sims.count); - B2_ASSERT(0 <= localIndexB && localIndexB <= setB->sims.count); + B2_ASSERT( 0 <= localIndexA && localIndexA <= setA->sims.count ); + B2_ASSERT( 0 <= localIndexB && localIndexB <= setB->sims.count ); b2BodySim* bodySimA = setA->sims.data + bodyA->localIndex; b2BodySim* bodySimB = setB->sims.data + bodyB->localIndex; @@ -259,26 +259,26 @@ void b2PreparePrismaticJoint(b2JointSim* base, b2StepContext* context) b2Rot qA = bodySimA->transform.q; b2Rot qB = bodySimB->transform.q; - joint->anchorA = b2RotateVector(qA, b2Sub(base->localOriginAnchorA, bodySimA->localCenter)); - joint->anchorB = b2RotateVector(qB, b2Sub(base->localOriginAnchorB, bodySimB->localCenter)); - joint->axisA = b2RotateVector(qA, joint->localAxisA); - joint->deltaCenter = b2Sub(bodySimB->center, bodySimA->center); - joint->deltaAngle = b2RelativeAngle(qB, qA) - joint->referenceAngle; + joint->anchorA = b2RotateVector( qA, b2Sub( base->localOriginAnchorA, bodySimA->localCenter ) ); + joint->anchorB = b2RotateVector( qB, b2Sub( base->localOriginAnchorB, bodySimB->localCenter ) ); + joint->axisA = b2RotateVector( qA, joint->localAxisA ); + joint->deltaCenter = b2Sub( bodySimB->center, bodySimA->center ); + joint->deltaAngle = b2RelativeAngle( qB, qA ) - joint->referenceAngle; b2Vec2 rA = joint->anchorA; b2Vec2 rB = joint->anchorB; - b2Vec2 d = b2Add(joint->deltaCenter, b2Sub(rB, rA)); - float a1 = b2Cross(b2Add(d, rA), joint->axisA); - float a2 = b2Cross(rB, joint->axisA); + b2Vec2 d = b2Add( joint->deltaCenter, b2Sub( rB, rA ) ); + float a1 = b2Cross( b2Add( d, rA ), joint->axisA ); + float a2 = b2Cross( rB, joint->axisA ); // effective masses float k = mA + mB + iA * a1 * a1 + iB * a2 * a2; joint->axialMass = k > 0.0f ? 1.0f / k : 0.0f; - joint->springSoftness = b2MakeSoft(joint->hertz, joint->dampingRatio, context->h); - - if (context->enableWarmStarting == false) + joint->springSoftness = b2MakeSoft( joint->hertz, joint->dampingRatio, context->h ); + + if ( context->enableWarmStarting == false ) { joint->impulse = b2Vec2_zero; joint->springImpulse = 0.0f; @@ -288,9 +288,9 @@ void b2PreparePrismaticJoint(b2JointSim* base, b2StepContext* context) } } -void b2WarmStartPrismaticJoint(b2JointSim* base, b2StepContext* context) +void b2WarmStartPrismaticJoint( b2JointSim* base, b2StepContext* context ) { - B2_ASSERT(base->type == b2_prismaticJoint); + B2_ASSERT( base->type == b2_prismaticJoint ); float mA = base->invMassA; float mB = base->invMassB; @@ -305,37 +305,37 @@ void b2WarmStartPrismaticJoint(b2JointSim* base, b2StepContext* context) b2BodyState* stateA = joint->indexA == B2_NULL_INDEX ? &dummyState : context->states + joint->indexA; b2BodyState* stateB = joint->indexB == B2_NULL_INDEX ? &dummyState : context->states + joint->indexB; - b2Vec2 rA = b2RotateVector(stateA->deltaRotation, joint->anchorA); - b2Vec2 rB = b2RotateVector(stateB->deltaRotation, joint->anchorB); + b2Vec2 rA = b2RotateVector( stateA->deltaRotation, joint->anchorA ); + b2Vec2 rB = b2RotateVector( stateB->deltaRotation, joint->anchorB ); - b2Vec2 d = b2Add(b2Add(b2Sub(stateB->deltaPosition, stateA->deltaPosition), joint->deltaCenter), b2Sub(rB, rA)); - b2Vec2 axisA = b2RotateVector(stateA->deltaRotation, joint->axisA); + b2Vec2 d = b2Add( b2Add( b2Sub( stateB->deltaPosition, stateA->deltaPosition ), joint->deltaCenter ), b2Sub( rB, rA ) ); + b2Vec2 axisA = b2RotateVector( stateA->deltaRotation, joint->axisA ); // impulse is applied at anchor point on body B - float a1 = b2Cross(b2Add(d, rA), axisA); - float a2 = b2Cross(rB, axisA); + float a1 = b2Cross( b2Add( d, rA ), axisA ); + float a2 = b2Cross( rB, axisA ); float axialImpulse = joint->springImpulse + joint->motorImpulse + joint->lowerImpulse - joint->upperImpulse; // perpendicular constraint - b2Vec2 perpA = b2LeftPerp(axisA); - float s1 = b2Cross(b2Add(d, rA), perpA); - float s2 = b2Cross(rB, perpA); + b2Vec2 perpA = b2LeftPerp( axisA ); + float s1 = b2Cross( b2Add( d, rA ), perpA ); + float s2 = b2Cross( rB, perpA ); float perpImpulse = joint->impulse.x; float angleImpulse = joint->impulse.y; - b2Vec2 P = b2Add(b2MulSV(axialImpulse, axisA), b2MulSV(perpImpulse, perpA)); + b2Vec2 P = b2Add( b2MulSV( axialImpulse, axisA ), b2MulSV( perpImpulse, perpA ) ); float LA = axialImpulse * a1 + perpImpulse * s1 + angleImpulse; float LB = axialImpulse * a2 + perpImpulse * s2 + angleImpulse; - stateA->linearVelocity = b2MulSub(stateA->linearVelocity, mA, P); + stateA->linearVelocity = b2MulSub( stateA->linearVelocity, mA, P ); stateA->angularVelocity -= iA * LA; - stateB->linearVelocity = b2MulAdd(stateB->linearVelocity, mB, P); + stateB->linearVelocity = b2MulAdd( stateB->linearVelocity, mB, P ); stateB->angularVelocity += iB * LB; } -void b2SolvePrismaticJoint(b2JointSim* base, b2StepContext* context, bool useBias) +void b2SolvePrismaticJoint( b2JointSim* base, b2StepContext* context, bool useBias ) { - B2_ASSERT(base->type == b2_prismaticJoint); + B2_ASSERT( base->type == b2_prismaticJoint ); float mA = base->invMassA; float mB = base->invMassB; @@ -356,19 +356,19 @@ void b2SolvePrismaticJoint(b2JointSim* base, b2StepContext* context, bool useBia float wB = stateB->angularVelocity; // current anchors - b2Vec2 rA = b2RotateVector(stateA->deltaRotation, joint->anchorA); - b2Vec2 rB = b2RotateVector(stateB->deltaRotation, joint->anchorB); + b2Vec2 rA = b2RotateVector( stateA->deltaRotation, joint->anchorA ); + b2Vec2 rB = b2RotateVector( stateB->deltaRotation, joint->anchorB ); + + b2Vec2 d = b2Add( b2Add( b2Sub( stateB->deltaPosition, stateA->deltaPosition ), joint->deltaCenter ), b2Sub( rB, rA ) ); + b2Vec2 axisA = b2RotateVector( stateA->deltaRotation, joint->axisA ); + float translation = b2Dot( axisA, d ); - b2Vec2 d = b2Add(b2Add(b2Sub(stateB->deltaPosition, stateA->deltaPosition), joint->deltaCenter), b2Sub(rB, rA)); - b2Vec2 axisA = b2RotateVector(stateA->deltaRotation, joint->axisA); - float translation = b2Dot(axisA, d); - // These scalars are for torques generated by axial forces - float a1 = b2Cross(b2Add(d, rA), axisA); - float a2 = b2Cross(rB, axisA); + float a1 = b2Cross( b2Add( d, rA ), axisA ); + float a2 = b2Cross( rB, axisA ); // spring constraint - if (joint->enableSpring) + if ( joint->enableSpring ) { // This is a real spring and should be applied even during relax float C = translation; @@ -376,41 +376,41 @@ void b2SolvePrismaticJoint(b2JointSim* base, b2StepContext* context, bool useBia float massScale = joint->springSoftness.massScale; float impulseScale = joint->springSoftness.impulseScale; - float Cdot = b2Dot(axisA, b2Sub(vB, vA)) + a2 * wB - a1 * wA; - float impulse = -massScale * joint->axialMass * (Cdot + bias) - impulseScale * joint->springImpulse; + float Cdot = b2Dot( axisA, b2Sub( vB, vA ) ) + a2 * wB - a1 * wA; + float impulse = -massScale * joint->axialMass * ( Cdot + bias ) - impulseScale * joint->springImpulse; joint->springImpulse += impulse; - b2Vec2 P = b2MulSV(impulse, axisA); + b2Vec2 P = b2MulSV( impulse, axisA ); float LA = impulse * a1; float LB = impulse * a2; - vA = b2MulSub(vA, mA, P); + vA = b2MulSub( vA, mA, P ); wA -= iA * LA; - vB = b2MulAdd(vB, mB, P); + vB = b2MulAdd( vB, mB, P ); wB += iB * LB; } // Solve motor constraint - if (joint->enableMotor) + if ( joint->enableMotor ) { - float Cdot = b2Dot(axisA, b2Sub(vB, vA)) + a2 * wB - a1 * wA; - float impulse = joint->axialMass * (joint->motorSpeed - Cdot); + float Cdot = b2Dot( axisA, b2Sub( vB, vA ) ) + a2 * wB - a1 * wA; + float impulse = joint->axialMass * ( joint->motorSpeed - Cdot ); float oldImpulse = joint->motorImpulse; float maxImpulse = context->h * joint->maxMotorForce; - joint->motorImpulse = b2ClampFloat(joint->motorImpulse + impulse, -maxImpulse, maxImpulse); + joint->motorImpulse = b2ClampFloat( joint->motorImpulse + impulse, -maxImpulse, maxImpulse ); impulse = joint->motorImpulse - oldImpulse; - b2Vec2 P = b2MulSV(impulse, axisA); + b2Vec2 P = b2MulSV( impulse, axisA ); float LA = impulse * a1; float LB = impulse * a2; - vA = b2MulSub(vA, mA, P); + vA = b2MulSub( vA, mA, P ); wA -= iA * LA; - vB = b2MulAdd(vB, mB, P); + vB = b2MulAdd( vB, mB, P ); wB += iB * LB; } - if (joint->enableLimit) + if ( joint->enableLimit ) { // Lower limit { @@ -419,12 +419,12 @@ void b2SolvePrismaticJoint(b2JointSim* base, b2StepContext* context, bool useBia float massScale = 1.0f; float impulseScale = 0.0f; - if (C > 0.0f) + if ( C > 0.0f ) { // speculation bias = C * context->inv_h; } - else if (useBias) + else if ( useBias ) { bias = context->jointSoftness.biasRate * C; massScale = context->jointSoftness.massScale; @@ -432,18 +432,18 @@ void b2SolvePrismaticJoint(b2JointSim* base, b2StepContext* context, bool useBia } float oldImpulse = joint->lowerImpulse; - float Cdot = b2Dot(axisA, b2Sub(vB, vA)) + a2 * wB - a1 * wA; - float impulse = -joint->axialMass * massScale * (Cdot + bias) - impulseScale * oldImpulse; - joint->lowerImpulse = b2MaxFloat(oldImpulse + impulse, 0.0f); + float Cdot = b2Dot( axisA, b2Sub( vB, vA ) ) + a2 * wB - a1 * wA; + float impulse = -joint->axialMass * massScale * ( Cdot + bias ) - impulseScale * oldImpulse; + joint->lowerImpulse = b2MaxFloat( oldImpulse + impulse, 0.0f ); impulse = joint->lowerImpulse - oldImpulse; - b2Vec2 P = b2MulSV(impulse, axisA); + b2Vec2 P = b2MulSV( impulse, axisA ); float LA = impulse * a1; float LB = impulse * a2; - vA = b2MulSub(vA, mA, P); + vA = b2MulSub( vA, mA, P ); wA -= iA * LA; - vB = b2MulAdd(vB, mB, P); + vB = b2MulAdd( vB, mB, P ); wB += iB * LB; } @@ -457,12 +457,12 @@ void b2SolvePrismaticJoint(b2JointSim* base, b2StepContext* context, bool useBia float massScale = 1.0f; float impulseScale = 0.0f; - if (C > 0.0f) + if ( C > 0.0f ) { // speculation bias = C * context->inv_h; } - else if (useBias) + else if ( useBias ) { bias = context->jointSoftness.biasRate * C; massScale = context->jointSoftness.massScale; @@ -471,45 +471,45 @@ void b2SolvePrismaticJoint(b2JointSim* base, b2StepContext* context, bool useBia float oldImpulse = joint->upperImpulse; // sign flipped - float Cdot = b2Dot(axisA, b2Sub(vA, vB)) + a1 * wA - a2 * wB; - float impulse = -joint->axialMass * massScale * (Cdot + bias) - impulseScale * oldImpulse; - joint->upperImpulse = b2MaxFloat(oldImpulse + impulse, 0.0f); + float Cdot = b2Dot( axisA, b2Sub( vA, vB ) ) + a1 * wA - a2 * wB; + float impulse = -joint->axialMass * massScale * ( Cdot + bias ) - impulseScale * oldImpulse; + joint->upperImpulse = b2MaxFloat( oldImpulse + impulse, 0.0f ); impulse = joint->upperImpulse - oldImpulse; - b2Vec2 P = b2MulSV(impulse, axisA); + b2Vec2 P = b2MulSV( impulse, axisA ); float LA = impulse * a1; float LB = impulse * a2; // sign flipped - vA = b2MulAdd(vA, mA, P); + vA = b2MulAdd( vA, mA, P ); wA += iA * LA; - vB = b2MulSub(vB, mB, P); + vB = b2MulSub( vB, mB, P ); wB -= iB * LB; } } // Solve the prismatic constraint in block form { - b2Vec2 perpA = b2LeftPerp(axisA); + b2Vec2 perpA = b2LeftPerp( axisA ); // These scalars are for torques generated by the perpendicular constraint force - float s1 = b2Cross(b2Add(d, rA), perpA); - float s2 = b2Cross(rB, perpA); + float s1 = b2Cross( b2Add( d, rA ), perpA ); + float s2 = b2Cross( rB, perpA ); b2Vec2 Cdot; - Cdot.x = b2Dot(perpA, b2Sub(vB, vA)) + s2 * wB - s1 * wA; + Cdot.x = b2Dot( perpA, b2Sub( vB, vA ) ) + s2 * wB - s1 * wA; Cdot.y = wB - wA; b2Vec2 bias = b2Vec2_zero; float massScale = 1.0f; float impulseScale = 0.0f; - if (useBias) + if ( useBias ) { b2Vec2 C; - C.x = b2Dot(perpA, d); - C.y = b2RelativeAngle(stateB->deltaRotation, stateA->deltaRotation) + joint->deltaAngle; + C.x = b2Dot( perpA, d ); + C.y = b2RelativeAngle( stateB->deltaRotation, stateA->deltaRotation ) + joint->deltaAngle; - bias = b2MulSV(context->jointSoftness.biasRate, C); + bias = b2MulSV( context->jointSoftness.biasRate, C ); massScale = context->jointSoftness.massScale; impulseScale = context->jointSoftness.impulseScale; } @@ -517,15 +517,15 @@ void b2SolvePrismaticJoint(b2JointSim* base, b2StepContext* context, bool useBia float k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; float k12 = iA * s1 + iB * s2; float k22 = iA + iB; - if (k22 == 0.0f) + if ( k22 == 0.0f ) { // For bodies with fixed rotation. k22 = 1.0f; } - b2Mat22 K = {{k11, k12}, {k12, k22}}; + b2Mat22 K = { { k11, k12 }, { k12, k22 } }; - b2Vec2 b = b2Solve22(K, b2Add(Cdot, bias)); + b2Vec2 b = b2Solve22( K, b2Add( Cdot, bias ) ); b2Vec2 impulse; impulse.x = -massScale * b.x - impulseScale * joint->impulse.x; impulse.y = -massScale * b.y - impulseScale * joint->impulse.y; @@ -533,13 +533,13 @@ void b2SolvePrismaticJoint(b2JointSim* base, b2StepContext* context, bool useBia joint->impulse.x += impulse.x; joint->impulse.y += impulse.y; - b2Vec2 P = b2MulSV(impulse.x, perpA); + b2Vec2 P = b2MulSV( impulse.x, perpA ); float LA = impulse.x * s1 + impulse.y; float LB = impulse.x * s2 + impulse.y; - vA = b2MulSub(vA, mA, P); + vA = b2MulSub( vA, mA, P ); wA -= iA * LA; - vB = b2MulAdd(vB, mB, P); + vB = b2MulAdd( vB, mB, P ); wB += iB * LB; } @@ -572,39 +572,39 @@ void b2PrismaticJoint::Dump() } #endif -void b2DrawPrismaticJoint(b2DebugDraw* draw, b2JointSim* base, b2Transform transformA, b2Transform transformB) +void b2DrawPrismaticJoint( b2DebugDraw* draw, b2JointSim* base, b2Transform transformA, b2Transform transformB ) { - B2_ASSERT(base->type == b2_prismaticJoint); + B2_ASSERT( base->type == b2_prismaticJoint ); b2PrismaticJoint* joint = &base->prismaticJoint; - b2Vec2 pA = b2TransformPoint(transformA, base->localOriginAnchorA); - b2Vec2 pB = b2TransformPoint(transformB, base->localOriginAnchorB); + b2Vec2 pA = b2TransformPoint( transformA, base->localOriginAnchorA ); + b2Vec2 pB = b2TransformPoint( transformB, base->localOriginAnchorB ); - b2Vec2 axis = b2RotateVector(transformA.q, joint->localAxisA); + b2Vec2 axis = b2RotateVector( transformA.q, joint->localAxisA ); b2HexColor c1 = b2_colorGray7; b2HexColor c2 = b2_colorGreen; b2HexColor c3 = b2_colorRed; b2HexColor c4 = b2_colorBlue; b2HexColor c5 = b2_colorGray4; - - draw->DrawSegment(pA, pB, c5, draw->context); - if (joint->enableLimit) + draw->DrawSegment( pA, pB, c5, draw->context ); + + if ( joint->enableLimit ) { - b2Vec2 lower = b2MulAdd(pA, joint->lowerTranslation, axis); - b2Vec2 upper = b2MulAdd(pA, joint->upperTranslation, axis); - b2Vec2 perp = b2LeftPerp(axis); - draw->DrawSegment(lower, upper, c1, draw->context); - draw->DrawSegment(b2MulSub(lower, 0.1f, perp), b2MulAdd(lower, 0.1f, perp), c2, draw->context); - draw->DrawSegment(b2MulSub(upper, 0.1f, perp), b2MulAdd(upper, 0.1f, perp), c3, draw->context); + b2Vec2 lower = b2MulAdd( pA, joint->lowerTranslation, axis ); + b2Vec2 upper = b2MulAdd( pA, joint->upperTranslation, axis ); + b2Vec2 perp = b2LeftPerp( axis ); + draw->DrawSegment( lower, upper, c1, draw->context ); + draw->DrawSegment( b2MulSub( lower, 0.1f, perp ), b2MulAdd( lower, 0.1f, perp ), c2, draw->context ); + draw->DrawSegment( b2MulSub( upper, 0.1f, perp ), b2MulAdd( upper, 0.1f, perp ), c3, draw->context ); } else { - draw->DrawSegment(b2MulSub(pA, 1.0f, axis), b2MulAdd(pA, 1.0f, axis), c1, draw->context); + draw->DrawSegment( b2MulSub( pA, 1.0f, axis ), b2MulAdd( pA, 1.0f, axis ), c1, draw->context ); } - draw->DrawPoint(pA, 5.0f, c1, draw->context); - draw->DrawPoint(pB, 5.0f, c4, draw->context); + draw->DrawPoint( pA, 5.0f, c1, draw->context ); + draw->DrawPoint( pB, 5.0f, c4, draw->context ); } diff --git a/src/revolute_joint.c b/src/revolute_joint.c index c653924d..afa7858e 100644 --- a/src/revolute_joint.c +++ b/src/revolute_joint.c @@ -15,62 +15,62 @@ #include -void b2RevoluteJoint_EnableSpring(b2JointId jointId, bool enableSpring) +void b2RevoluteJoint_EnableSpring( b2JointId jointId, bool enableSpring ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_revoluteJoint); - if (enableSpring != joint->revoluteJoint.enableSpring) + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); + if ( enableSpring != joint->revoluteJoint.enableSpring ) { joint->revoluteJoint.enableSpring = enableSpring; joint->revoluteJoint.springImpulse = 0.0f; } } -bool b2RevoluteJoint_IsSpringEnabled(b2JointId jointId) +bool b2RevoluteJoint_IsSpringEnabled( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_revoluteJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); return joint->revoluteJoint.enableSpring; } -void b2RevoluteJoint_SetSpringHertz(b2JointId jointId, float hertz) +void b2RevoluteJoint_SetSpringHertz( b2JointId jointId, float hertz ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_revoluteJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); joint->revoluteJoint.hertz = hertz; } -float b2RevoluteJoint_GetSpringHertz(b2JointId jointId) +float b2RevoluteJoint_GetSpringHertz( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_revoluteJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); return joint->revoluteJoint.hertz; } -void b2RevoluteJoint_SetSpringDampingRatio(b2JointId jointId, float dampingRatio) +void b2RevoluteJoint_SetSpringDampingRatio( b2JointId jointId, float dampingRatio ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_revoluteJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); joint->revoluteJoint.dampingRatio = dampingRatio; } -float b2RevoluteJoint_GetSpringDampingRatio(b2JointId jointId) +float b2RevoluteJoint_GetSpringDampingRatio( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_revoluteJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); return joint->revoluteJoint.dampingRatio; } -float b2RevoluteJoint_GetAngle(b2JointId jointId) +float b2RevoluteJoint_GetAngle( b2JointId jointId ) { - b2World* world = b2GetWorld(jointId.world0); - b2JointSim* jointSim = b2GetJointSimCheckType(jointId, b2_revoluteJoint); - b2Transform transformA = b2GetBodyTransform(world, jointSim->bodyIdA); - b2Transform transformB = b2GetBodyTransform(world, jointSim->bodyIdB); + b2World* world = b2GetWorld( jointId.world0 ); + b2JointSim* jointSim = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); + b2Transform transformA = b2GetBodyTransform( world, jointSim->bodyIdA ); + b2Transform transformB = b2GetBodyTransform( world, jointSim->bodyIdB ); - float angle = b2RelativeAngle(transformB.q, transformA.q) - jointSim->revoluteJoint.referenceAngle; - angle = b2UnwindAngle(angle); + float angle = b2RelativeAngle( transformB.q, transformA.q ) - jointSim->revoluteJoint.referenceAngle; + angle = b2UnwindAngle( angle ); return angle; } -void b2RevoluteJoint_EnableLimit(b2JointId jointId, bool enableLimit) +void b2RevoluteJoint_EnableLimit( b2JointId jointId, bool enableLimit ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_revoluteJoint); - if (enableLimit != joint->revoluteJoint.enableLimit) + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); + if ( enableLimit != joint->revoluteJoint.enableLimit ) { joint->revoluteJoint.enableLimit = enableLimit; joint->revoluteJoint.lowerImpulse = 0.0f; @@ -78,93 +78,93 @@ void b2RevoluteJoint_EnableLimit(b2JointId jointId, bool enableLimit) } } -bool b2RevoluteJoint_IsLimitEnabled(b2JointId jointId) +bool b2RevoluteJoint_IsLimitEnabled( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_revoluteJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); return joint->revoluteJoint.enableLimit; } -float b2RevoluteJoint_GetLowerLimit(b2JointId jointId) +float b2RevoluteJoint_GetLowerLimit( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_revoluteJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); return joint->revoluteJoint.lowerAngle; } -float b2RevoluteJoint_GetUpperLimit(b2JointId jointId) +float b2RevoluteJoint_GetUpperLimit( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_revoluteJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); return joint->revoluteJoint.upperAngle; } -void b2RevoluteJoint_SetLimits(b2JointId jointId, float lower, float upper) +void b2RevoluteJoint_SetLimits( b2JointId jointId, float lower, float upper ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_revoluteJoint); - if (lower != joint->revoluteJoint.lowerAngle || upper != joint->revoluteJoint.upperAngle) + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); + if ( lower != joint->revoluteJoint.lowerAngle || upper != joint->revoluteJoint.upperAngle ) { - joint->revoluteJoint.lowerAngle = b2MinFloat(lower, upper); - joint->revoluteJoint.upperAngle = b2MaxFloat(lower, upper); + joint->revoluteJoint.lowerAngle = b2MinFloat( lower, upper ); + joint->revoluteJoint.upperAngle = b2MaxFloat( lower, upper ); joint->revoluteJoint.lowerImpulse = 0.0f; joint->revoluteJoint.upperImpulse = 0.0f; } } -void b2RevoluteJoint_EnableMotor(b2JointId jointId, bool enableMotor) +void b2RevoluteJoint_EnableMotor( b2JointId jointId, bool enableMotor ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_revoluteJoint); - if (enableMotor != joint->revoluteJoint.enableMotor) + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); + if ( enableMotor != joint->revoluteJoint.enableMotor ) { joint->revoluteJoint.enableMotor = enableMotor; joint->revoluteJoint.motorImpulse = 0.0f; } } -bool b2RevoluteJoint_IsMotorEnabled(b2JointId jointId) +bool b2RevoluteJoint_IsMotorEnabled( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_revoluteJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); return joint->revoluteJoint.enableMotor; } -void b2RevoluteJoint_SetMotorSpeed(b2JointId jointId, float motorSpeed) +void b2RevoluteJoint_SetMotorSpeed( b2JointId jointId, float motorSpeed ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_revoluteJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); joint->revoluteJoint.motorSpeed = motorSpeed; } -float b2RevoluteJoint_GetMotorSpeed(b2JointId jointId) +float b2RevoluteJoint_GetMotorSpeed( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_revoluteJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); return joint->revoluteJoint.motorSpeed; } -float b2RevoluteJoint_GetMotorTorque(b2JointId jointId) +float b2RevoluteJoint_GetMotorTorque( b2JointId jointId ) { - b2World* world = b2GetWorld(jointId.world0); - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_revoluteJoint); + b2World* world = b2GetWorld( jointId.world0 ); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); return world->inv_h * joint->revoluteJoint.motorImpulse; } -void b2RevoluteJoint_SetMaxMotorTorque(b2JointId jointId, float torque) +void b2RevoluteJoint_SetMaxMotorTorque( b2JointId jointId, float torque ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_revoluteJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); joint->revoluteJoint.maxMotorTorque = torque; } -float b2RevoluteJoint_GetMaxMotorTorque(b2JointId jointId) +float b2RevoluteJoint_GetMaxMotorTorque( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_revoluteJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_revoluteJoint ); return joint->revoluteJoint.maxMotorTorque; } -b2Vec2 b2GetRevoluteJointForce(b2World* world, b2JointSim* base) +b2Vec2 b2GetRevoluteJointForce( b2World* world, b2JointSim* base ) { - b2Vec2 force = b2MulSV(world->inv_h, base->revoluteJoint.linearImpulse); + b2Vec2 force = b2MulSV( world->inv_h, base->revoluteJoint.linearImpulse ); return force; } -float b2GetRevoluteJointTorque(b2World* world, b2JointSim* base) +float b2GetRevoluteJointTorque( b2World* world, b2JointSim* base ) { const b2RevoluteJoint* revolute = &base->revoluteJoint; - float torque = world->inv_h * (revolute->motorImpulse + revolute->lowerImpulse - revolute->upperImpulse); + float torque = world->inv_h * ( revolute->motorImpulse + revolute->lowerImpulse - revolute->upperImpulse ); return torque; } @@ -188,18 +188,19 @@ float b2GetRevoluteJointTorque(b2World* world, b2JointSim* base) // This causes some trouble when computing anchors. I rotate the anchors using the body rotation every sub-step. For static // bodies the anchor doesn't rotate. Body A or B could be static and this can lead to lots of branching. This branching // should be minimized. -// +// // Solution 1: -// Use delta rotations. This means anchors need to be prepared in world space. The delta rotation for static bodies will be identity. -// Base separation and angles need to be computed. Manifolds will be behind a frame, but that is probably best if bodies move fast. +// Use delta rotations. This means anchors need to be prepared in world space. The delta rotation for static bodies will be +// identity. Base separation and angles need to be computed. Manifolds will be behind a frame, but that is probably best if bodies +// move fast. // // Solution 2: -// Use full rotation. The anchors for static bodies will be in world space while the anchors for dynamic bodies will be in local space. -// Potentially confusing and bug prone. +// Use full rotation. The anchors for static bodies will be in world space while the anchors for dynamic bodies will be in local +// space. Potentially confusing and bug prone. -void b2PrepareRevoluteJoint(b2JointSim* base, b2StepContext* context) +void b2PrepareRevoluteJoint( b2JointSim* base, b2StepContext* context ) { - B2_ASSERT(base->type == b2_revoluteJoint); + B2_ASSERT( base->type == b2_revoluteJoint ); // chase body id to the solver set where the body lives int idA = base->bodyIdA; @@ -208,15 +209,15 @@ void b2PrepareRevoluteJoint(b2JointSim* base, b2StepContext* context) b2World* world = context->world; b2Body* bodies = world->bodyArray; - b2CheckIndex(bodies, idA); - b2CheckIndex(bodies, idB); + b2CheckIndex( bodies, idA ); + b2CheckIndex( bodies, idB ); b2Body* bodyA = bodies + idA; b2Body* bodyB = bodies + idB; - B2_ASSERT(bodyA->setIndex == b2_awakeSet || bodyB->setIndex == b2_awakeSet); - b2CheckIndex(world->solverSetArray, bodyA->setIndex); - b2CheckIndex(world->solverSetArray, bodyB->setIndex); + B2_ASSERT( bodyA->setIndex == b2_awakeSet || bodyB->setIndex == b2_awakeSet ); + b2CheckIndex( world->solverSetArray, bodyA->setIndex ); + b2CheckIndex( world->solverSetArray, bodyB->setIndex ); b2SolverSet* setA = world->solverSetArray + bodyA->setIndex; b2SolverSet* setB = world->solverSetArray + bodyB->setIndex; @@ -224,8 +225,8 @@ void b2PrepareRevoluteJoint(b2JointSim* base, b2StepContext* context) int localIndexA = bodyA->localIndex; int localIndexB = bodyB->localIndex; - B2_ASSERT(0 <= localIndexA && localIndexA <= setA->sims.count); - B2_ASSERT(0 <= localIndexB && localIndexB <= setB->sims.count); + B2_ASSERT( 0 <= localIndexA && localIndexA <= setA->sims.count ); + B2_ASSERT( 0 <= localIndexB && localIndexB <= setB->sims.count ); b2BodySim* bodySimA = setA->sims.data + bodyA->localIndex; b2BodySim* bodySimB = setB->sims.data + bodyB->localIndex; @@ -246,16 +247,18 @@ void b2PrepareRevoluteJoint(b2JointSim* base, b2StepContext* context) joint->indexB = bodyB->setIndex == b2_awakeSet ? localIndexB : B2_NULL_INDEX; // initial anchors in world space - joint->anchorA = b2RotateVector(bodySimA->transform.q, b2Sub(base->localOriginAnchorA, bodySimA->localCenter)); - joint->anchorB = b2RotateVector(bodySimB->transform.q, b2Sub(base->localOriginAnchorB, bodySimB->localCenter)); - joint->deltaCenter = b2Sub(bodySimB->center, bodySimA->center); - joint->deltaAngle = b2RelativeAngle(bodySimB->transform.q, bodySimA->transform.q) - joint->referenceAngle; - joint->deltaAngle = b2UnwindAngle(joint->deltaAngle); + joint->anchorA = b2RotateVector( bodySimA->transform.q, b2Sub( base->localOriginAnchorA, bodySimA->localCenter ) ); + joint->anchorB = b2RotateVector( bodySimB->transform.q, b2Sub( base->localOriginAnchorB, bodySimB->localCenter ) ); + joint->deltaCenter = b2Sub( bodySimB->center, bodySimA->center ); + joint->deltaAngle = b2RelativeAngle( bodySimB->transform.q, bodySimA->transform.q ) - joint->referenceAngle; + joint->deltaAngle = b2UnwindAngle( joint->deltaAngle ); float k = iA + iB; joint->axialMass = k > 0.0f ? 1.0f / k : 0.0f; - if (context->enableWarmStarting == false) + joint->springSoftness = b2MakeSoft( joint->hertz, joint->dampingRatio, context->h ); + + if ( context->enableWarmStarting == false ) { joint->linearImpulse = b2Vec2_zero; joint->springImpulse = 0.0f; @@ -265,9 +268,9 @@ void b2PrepareRevoluteJoint(b2JointSim* base, b2StepContext* context) } } -void b2WarmStartRevoluteJoint(b2JointSim* base, b2StepContext* context) +void b2WarmStartRevoluteJoint( b2JointSim* base, b2StepContext* context ) { - B2_ASSERT(base->type == b2_revoluteJoint); + B2_ASSERT( base->type == b2_revoluteJoint ); float mA = base->invMassA; float mB = base->invMassB; @@ -281,23 +284,21 @@ void b2WarmStartRevoluteJoint(b2JointSim* base, b2StepContext* context) b2BodyState* stateA = joint->indexA == B2_NULL_INDEX ? &dummyState : context->states + joint->indexA; b2BodyState* stateB = joint->indexB == B2_NULL_INDEX ? &dummyState : context->states + joint->indexB; - b2Vec2 rA = b2RotateVector(stateA->deltaRotation, joint->anchorA); - b2Vec2 rB = b2RotateVector(stateB->deltaRotation, joint->anchorB); + b2Vec2 rA = b2RotateVector( stateA->deltaRotation, joint->anchorA ); + b2Vec2 rB = b2RotateVector( stateB->deltaRotation, joint->anchorB ); float axialImpulse = joint->springImpulse + joint->motorImpulse + joint->lowerImpulse - joint->upperImpulse; - joint->springSoftness = b2MakeSoft(joint->hertz, joint->dampingRatio, context->h); - - stateA->linearVelocity = b2MulSub(stateA->linearVelocity, mA, joint->linearImpulse); - stateA->angularVelocity -= iA * (b2Cross(rA, joint->linearImpulse) + axialImpulse); + stateA->linearVelocity = b2MulSub( stateA->linearVelocity, mA, joint->linearImpulse ); + stateA->angularVelocity -= iA * ( b2Cross( rA, joint->linearImpulse ) + axialImpulse ); - stateB->linearVelocity = b2MulAdd(stateB->linearVelocity, mB, joint->linearImpulse); - stateB->angularVelocity += iB * (b2Cross(rB, joint->linearImpulse) + axialImpulse); + stateB->linearVelocity = b2MulAdd( stateB->linearVelocity, mB, joint->linearImpulse ); + stateB->angularVelocity += iB * ( b2Cross( rB, joint->linearImpulse ) + axialImpulse ); } -void b2SolveRevoluteJoint(b2JointSim* base, b2StepContext* context, bool useBias) +void b2SolveRevoluteJoint( b2JointSim* base, b2StepContext* context, bool useBias ) { - B2_ASSERT(base->type == b2_revoluteJoint); + B2_ASSERT( base->type == b2_revoluteJoint ); float mA = base->invMassA; float mB = base->invMassB; @@ -317,43 +318,43 @@ void b2SolveRevoluteJoint(b2JointSim* base, b2StepContext* context, bool useBias b2Vec2 vB = stateB->linearVelocity; float wB = stateB->angularVelocity; - bool fixedRotation = (iA + iB == 0.0f); - //const float maxBias = context->maxBiasVelocity; + bool fixedRotation = ( iA + iB == 0.0f ); + // const float maxBias = context->maxBiasVelocity; // Solve spring. - if (joint->enableSpring && fixedRotation == false) + if ( joint->enableSpring && fixedRotation == false ) { - float C = b2RelativeAngle(stateB->deltaRotation, stateA->deltaRotation) + joint->deltaAngle; + float C = b2RelativeAngle( stateB->deltaRotation, stateA->deltaRotation ) + joint->deltaAngle; float bias = joint->springSoftness.biasRate * C; float massScale = joint->springSoftness.massScale; float impulseScale = joint->springSoftness.impulseScale; float Cdot = wB - wA; - float impulse = -massScale * joint->axialMass * (Cdot + bias) - impulseScale * joint->springImpulse; + float impulse = -massScale * joint->axialMass * ( Cdot + bias ) - impulseScale * joint->springImpulse; joint->springImpulse += impulse; wA -= iA * impulse; wB += iB * impulse; } - + // Solve motor constraint. - if (joint->enableMotor && fixedRotation == false) + if ( joint->enableMotor && fixedRotation == false ) { float Cdot = wB - wA - joint->motorSpeed; float impulse = -joint->axialMass * Cdot; float oldImpulse = joint->motorImpulse; float maxImpulse = context->h * joint->maxMotorTorque; - joint->motorImpulse = b2ClampFloat(joint->motorImpulse + impulse, -maxImpulse, maxImpulse); + joint->motorImpulse = b2ClampFloat( joint->motorImpulse + impulse, -maxImpulse, maxImpulse ); impulse = joint->motorImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } - if (joint->enableLimit && fixedRotation == false) + if ( joint->enableLimit && fixedRotation == false ) { - float jointAngle = b2RelativeAngle(stateB->deltaRotation, stateA->deltaRotation) + joint->deltaAngle; - jointAngle = b2UnwindAngle(jointAngle); + float jointAngle = b2RelativeAngle( stateB->deltaRotation, stateA->deltaRotation ) + joint->deltaAngle; + jointAngle = b2UnwindAngle( jointAngle ); // Lower limit { @@ -361,12 +362,12 @@ void b2SolveRevoluteJoint(b2JointSim* base, b2StepContext* context, bool useBias float bias = 0.0f; float massScale = 1.0f; float impulseScale = 0.0f; - if (C > 0.0f) + if ( C > 0.0f ) { // speculation bias = C * context->inv_h; } - else if (useBias) + else if ( useBias ) { bias = context->jointSoftness.biasRate * C; massScale = context->jointSoftness.massScale; @@ -374,9 +375,9 @@ void b2SolveRevoluteJoint(b2JointSim* base, b2StepContext* context, bool useBias } float Cdot = wB - wA; - float impulse = -massScale * joint->axialMass * (Cdot + bias) - impulseScale * joint->lowerImpulse; + float impulse = -massScale * joint->axialMass * ( Cdot + bias ) - impulseScale * joint->lowerImpulse; float oldImpulse = joint->lowerImpulse; - joint->lowerImpulse = b2MaxFloat(joint->lowerImpulse + impulse, 0.0f); + joint->lowerImpulse = b2MaxFloat( joint->lowerImpulse + impulse, 0.0f ); impulse = joint->lowerImpulse - oldImpulse; wA -= iA * impulse; @@ -391,12 +392,12 @@ void b2SolveRevoluteJoint(b2JointSim* base, b2StepContext* context, bool useBias float bias = 0.0f; float massScale = 1.0f; float impulseScale = 0.0f; - if (C > 0.0f) + if ( C > 0.0f ) { // speculation bias = C * context->inv_h; } - else if (useBias) + else if ( useBias ) { bias = context->jointSoftness.biasRate * C; massScale = context->jointSoftness.massScale; @@ -405,9 +406,9 @@ void b2SolveRevoluteJoint(b2JointSim* base, b2StepContext* context, bool useBias // sign flipped on Cdot float Cdot = wA - wB; - float impulse = -massScale * joint->axialMass * (Cdot + bias) - impulseScale * joint->lowerImpulse; + float impulse = -massScale * joint->axialMass * ( Cdot + bias ) - impulseScale * joint->lowerImpulse; float oldImpulse = joint->upperImpulse; - joint->upperImpulse = b2MaxFloat(joint->upperImpulse + impulse, 0.0f); + joint->upperImpulse = b2MaxFloat( joint->upperImpulse + impulse, 0.0f ); impulse = joint->upperImpulse - oldImpulse; // sign flipped on applied impulse @@ -424,21 +425,21 @@ void b2SolveRevoluteJoint(b2JointSim* base, b2StepContext* context, bool useBias // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB] // current anchors - b2Vec2 rA = b2RotateVector(stateA->deltaRotation, joint->anchorA); - b2Vec2 rB = b2RotateVector(stateB->deltaRotation, joint->anchorB); + b2Vec2 rA = b2RotateVector( stateA->deltaRotation, joint->anchorA ); + b2Vec2 rB = b2RotateVector( stateB->deltaRotation, joint->anchorB ); - b2Vec2 Cdot = b2Sub(b2Add(vB, b2CrossSV(wB, rB)), b2Add(vA, b2CrossSV(wA, rA))); + b2Vec2 Cdot = b2Sub( b2Add( vB, b2CrossSV( wB, rB ) ), b2Add( vA, b2CrossSV( wA, rA ) ) ); b2Vec2 bias = b2Vec2_zero; float massScale = 1.0f; float impulseScale = 0.0f; - if (useBias) + if ( useBias ) { b2Vec2 dcA = stateA->deltaPosition; b2Vec2 dcB = stateB->deltaPosition; - b2Vec2 separation = b2Add(b2Add(b2Sub(dcB, dcA), b2Sub(rB, rA)), joint->deltaCenter); - bias = b2MulSV(context->jointSoftness.biasRate, separation); + b2Vec2 separation = b2Add( b2Add( b2Sub( dcB, dcA ), b2Sub( rB, rA ) ), joint->deltaCenter ); + bias = b2MulSV( context->jointSoftness.biasRate, separation ); massScale = context->jointSoftness.massScale; impulseScale = context->jointSoftness.impulseScale; } @@ -448,18 +449,18 @@ void b2SolveRevoluteJoint(b2JointSim* base, b2StepContext* context, bool useBias K.cy.x = -rA.y * rA.x * iA - rB.y * rB.x * iB; K.cx.y = K.cy.x; K.cy.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; - b2Vec2 b = b2Solve22(K, b2Add(Cdot, bias)); - + b2Vec2 b = b2Solve22( K, b2Add( Cdot, bias ) ); + b2Vec2 impulse; impulse.x = -massScale * b.x - impulseScale * joint->linearImpulse.x; impulse.y = -massScale * b.y - impulseScale * joint->linearImpulse.y; joint->linearImpulse.x += impulse.x; joint->linearImpulse.y += impulse.y; - - vA = b2MulSub(vA, mA, impulse); - wA -= iA * b2Cross(rA, impulse); - vB = b2MulAdd(vB, mB, impulse); - wB += iB * b2Cross(rB, impulse); + + vA = b2MulSub( vA, mA, impulse ); + wA -= iA * b2Cross( rA, impulse ); + vB = b2MulAdd( vB, mB, impulse ); + wB += iB * b2Cross( rB, impulse ); } stateA->linearVelocity = vA; @@ -491,57 +492,57 @@ void b2RevoluteJoint::Dump() } #endif -void b2DrawRevoluteJoint(b2DebugDraw* draw, b2JointSim* base, b2Transform transformA, b2Transform transformB, float drawSize) +void b2DrawRevoluteJoint( b2DebugDraw* draw, b2JointSim* base, b2Transform transformA, b2Transform transformB, float drawSize ) { - B2_ASSERT(base->type == b2_revoluteJoint); + B2_ASSERT( base->type == b2_revoluteJoint ); b2RevoluteJoint* joint = &base->revoluteJoint; - b2Vec2 pA = b2TransformPoint(transformA, base->localOriginAnchorA); - b2Vec2 pB = b2TransformPoint(transformB, base->localOriginAnchorB); + b2Vec2 pA = b2TransformPoint( transformA, base->localOriginAnchorA ); + b2Vec2 pB = b2TransformPoint( transformB, base->localOriginAnchorB ); b2HexColor c1 = b2_colorGray7; b2HexColor c2 = b2_colorGreen; b2HexColor c3 = b2_colorRed; const float L = drawSize; - //draw->DrawPoint(pA, 3.0f, b2_colorGray40, draw->context); - //draw->DrawPoint(pB, 3.0f, b2_colorLightBlue, draw->context); - draw->DrawCircle(pB, L, c1, draw->context); + // draw->DrawPoint(pA, 3.0f, b2_colorGray40, draw->context); + // draw->DrawPoint(pB, 3.0f, b2_colorLightBlue, draw->context); + draw->DrawCircle( pB, L, c1, draw->context ); - float angle = b2RelativeAngle(transformB.q, transformA.q); + float angle = b2RelativeAngle( transformB.q, transformA.q ); - b2Vec2 r = {L * cosf(angle), L * sinf(angle)}; - b2Vec2 pC = b2Add(pB, r); - draw->DrawSegment(pB, pC, c1, draw->context); + b2Vec2 r = { L * cosf( angle ), L * sinf( angle ) }; + b2Vec2 pC = b2Add( pB, r ); + draw->DrawSegment( pB, pC, c1, draw->context ); - if (draw->drawJointExtras) + if ( draw->drawJointExtras ) { - float jointAngle = b2UnwindAngle(angle - joint->referenceAngle); + float jointAngle = b2UnwindAngle( angle - joint->referenceAngle ); char buffer[32]; - snprintf(buffer, 32, " %.1f deg", 180.0f * jointAngle / b2_pi); - draw->DrawString(pC, buffer, draw->context); + snprintf( buffer, 32, " %.1f deg", 180.0f * jointAngle / b2_pi ); + draw->DrawString( pC, buffer, draw->context ); } float lowerAngle = joint->lowerAngle + joint->referenceAngle; float upperAngle = joint->upperAngle + joint->referenceAngle; - if (joint->enableLimit) + if ( joint->enableLimit ) { - b2Vec2 rlo = {L * cosf(lowerAngle), L * sinf(lowerAngle)}; - b2Vec2 rhi = {L * cosf(upperAngle), L * sinf(upperAngle)}; + b2Vec2 rlo = { L * cosf( lowerAngle ), L * sinf( lowerAngle ) }; + b2Vec2 rhi = { L * cosf( upperAngle ), L * sinf( upperAngle ) }; - draw->DrawSegment(pB, b2Add(pB, rlo), c2, draw->context); - draw->DrawSegment(pB, b2Add(pB, rhi), c3, draw->context); + draw->DrawSegment( pB, b2Add( pB, rlo ), c2, draw->context ); + draw->DrawSegment( pB, b2Add( pB, rhi ), c3, draw->context ); - b2Vec2 ref = (b2Vec2){L * cosf(joint->referenceAngle), L * sinf(joint->referenceAngle)}; - draw->DrawSegment(pB, b2Add(pB, ref), b2_colorBlue, draw->context); + b2Vec2 ref = ( b2Vec2 ){ L * cosf( joint->referenceAngle ), L * sinf( joint->referenceAngle ) }; + draw->DrawSegment( pB, b2Add( pB, ref ), b2_colorBlue, draw->context ); } b2HexColor color = b2_colorGold; - draw->DrawSegment(transformA.p, pA, color, draw->context); - draw->DrawSegment(pA, pB, color, draw->context); - draw->DrawSegment(transformB.p, pB, color, draw->context); + draw->DrawSegment( transformA.p, pA, color, draw->context ); + draw->DrawSegment( pA, pB, color, draw->context ); + draw->DrawSegment( transformB.p, pB, color, draw->context ); // char buffer[32]; // sprintf(buffer, "%.1f", b2Length(joint->impulse)); diff --git a/src/shape.c b/src/shape.c index 54ae3652..637ec31b 100644 --- a/src/shape.c +++ b/src/shape.c @@ -14,34 +14,34 @@ #include -static b2Shape* b2GetShape(b2World* world, b2ShapeId shapeId) +static b2Shape* b2GetShape( b2World* world, b2ShapeId shapeId ) { int id = shapeId.index1 - 1; - b2CheckIdAndRevision(world->shapeArray, id, shapeId.revision); + b2CheckIdAndRevision( world->shapeArray, id, shapeId.revision ); b2Shape* shape = world->shapeArray + id; return shape; } -b2Transform b2GetOwnerTransform(b2World* world, b2Shape* shape) +b2Transform b2GetOwnerTransform( b2World* world, b2Shape* shape ) { - return b2GetBodyTransform(world, shape->bodyId); + return b2GetBodyTransform( world, shape->bodyId ); } -static b2ChainShape* b2GetChainShape(b2World* world, b2ChainId chainId) +static b2ChainShape* b2GetChainShape( b2World* world, b2ChainId chainId ) { int id = chainId.index1 - 1; - b2CheckIdAndRevision(world->chainArray, id, chainId.revision); + b2CheckIdAndRevision( world->chainArray, id, chainId.revision ); b2ChainShape* chain = world->chainArray + id; return chain; } -static void b2UpdateShapeAABBs(b2Shape* shape, b2Transform transform, b2BodyType proxyType) +static void b2UpdateShapeAABBs( b2Shape* shape, b2Transform transform, b2BodyType proxyType ) { // Compute a bounding box with a speculative margin const float speculativeDistance = b2_speculativeDistance; const float aabbMargin = b2_aabbMargin; - b2AABB aabb = b2ComputeShapeAABB(shape, transform); + b2AABB aabb = b2ComputeShapeAABB( shape, transform ); aabb.lowerBound.x -= speculativeDistance; aabb.lowerBound.y -= speculativeDistance; aabb.upperBound.x += speculativeDistance; @@ -58,28 +58,28 @@ static void b2UpdateShapeAABBs(b2Shape* shape, b2Transform transform, b2BodyType shape->fatAABB = fatAABB; } -static b2Shape* b2CreateShapeInternal(b2World* world, b2Body* body, b2Transform transform, - const b2ShapeDef* def, const void* geometry, b2ShapeType shapeType) +static b2Shape* b2CreateShapeInternal( b2World* world, b2Body* body, b2Transform transform, const b2ShapeDef* def, + const void* geometry, b2ShapeType shapeType ) { - B2_ASSERT(b2IsValid(def->density) && def->density >= 0.0f); - B2_ASSERT(b2IsValid(def->friction) && def->friction >= 0.0f); - B2_ASSERT(b2IsValid(def->restitution) && def->restitution >= 0.0f); + B2_ASSERT( b2IsValid( def->density ) && def->density >= 0.0f ); + B2_ASSERT( b2IsValid( def->friction ) && def->friction >= 0.0f ); + B2_ASSERT( b2IsValid( def->restitution ) && def->restitution >= 0.0f ); - int shapeId = b2AllocId(&world->shapeIdPool); + int shapeId = b2AllocId( &world->shapeIdPool ); - if (shapeId == b2Array(world->shapeArray).count) + if ( shapeId == b2Array( world->shapeArray ).count ) { - b2Array_Push(world->shapeArray, (b2Shape){0}); + b2Array_Push( world->shapeArray, ( b2Shape ){ 0 } ); } else { - B2_ASSERT(world->shapeArray[shapeId].id == B2_NULL_INDEX); + B2_ASSERT( world->shapeArray[shapeId].id == B2_NULL_INDEX ); } - b2CheckIndex(world->shapeArray, shapeId); + b2CheckIndex( world->shapeArray, shapeId ); b2Shape* shape = world->shapeArray + shapeId; - switch (shapeType) + switch ( shapeType ) { case b2_capsuleShape: shape->capsule = *(const b2Capsule*)geometry; @@ -102,7 +102,7 @@ static b2Shape* b2CreateShapeInternal(b2World* world, b2Body* body, b2Transform break; default: - B2_ASSERT(false); + B2_ASSERT( false ); break; } @@ -114,6 +114,7 @@ static b2Shape* b2CreateShapeInternal(b2World* world, b2Body* body, b2Transform shape->restitution = def->restitution; shape->filter = def->filter; shape->userData = def->userData; + shape->customColor = def->customColor; shape->isSensor = def->isSensor; shape->enlargedAABB = false; shape->enableSensorEvents = def->enableSensorEvents; @@ -122,21 +123,21 @@ static b2Shape* b2CreateShapeInternal(b2World* world, b2Body* body, b2Transform shape->enablePreSolveEvents = def->enablePreSolveEvents; shape->isFast = false; shape->proxyKey = B2_NULL_INDEX; - shape->localCentroid = b2GetShapeCentroid(shape); - shape->aabb = (b2AABB){b2Vec2_zero, b2Vec2_zero}; - shape->fatAABB = (b2AABB){b2Vec2_zero, b2Vec2_zero}; + shape->localCentroid = b2GetShapeCentroid( shape ); + shape->aabb = ( b2AABB ){ b2Vec2_zero, b2Vec2_zero }; + shape->fatAABB = ( b2AABB ){ b2Vec2_zero, b2Vec2_zero }; shape->revision += 1; - if (body->setIndex != b2_disabledSet) + if ( body->setIndex != b2_disabledSet ) { b2BodyType proxyType = body->type; - b2CreateShapeProxy(shape, &world->broadPhase, proxyType, transform, def->forceContactCreation); + b2CreateShapeProxy( shape, &world->broadPhase, proxyType, transform, def->forceContactCreation ); } // Add to shape doubly linked list - if (body->headShapeId != B2_NULL_INDEX) + if ( body->headShapeId != B2_NULL_INDEX ) { - b2CheckId(world->shapeArray, body->headShapeId); + b2CheckId( world->shapeArray, body->headShapeId ); b2Shape* headShape = world->shapeArray + body->headShapeId; headShape->prevShapeId = shapeId; } @@ -146,94 +147,94 @@ static b2Shape* b2CreateShapeInternal(b2World* world, b2Body* body, b2Transform body->headShapeId = shapeId; body->shapeCount += 1; - b2ValidateSolverSets(world); + b2ValidateSolverSets( world ); return shape; } -b2ShapeId b2CreateShape(b2BodyId bodyId, const b2ShapeDef* def, const void* geometry, b2ShapeType shapeType) +b2ShapeId b2CreateShape( b2BodyId bodyId, const b2ShapeDef* def, const void* geometry, b2ShapeType shapeType ) { - b2CheckDef(def); - B2_ASSERT(b2IsValid(def->density) && def->density >= 0.0f); - B2_ASSERT(b2IsValid(def->friction) && def->friction >= 0.0f); - B2_ASSERT(b2IsValid(def->restitution) && def->restitution >= 0.0f); + b2CheckDef( def ); + B2_ASSERT( b2IsValid( def->density ) && def->density >= 0.0f ); + B2_ASSERT( b2IsValid( def->friction ) && def->friction >= 0.0f ); + B2_ASSERT( b2IsValid( def->restitution ) && def->restitution >= 0.0f ); - b2World* world = b2GetWorldLocked(bodyId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( bodyId.world0 ); + if ( world == NULL ) { - return (b2ShapeId){0}; + return ( b2ShapeId ){ 0 }; } - b2Body* body = b2GetBodyFullId(world, bodyId); - b2Transform transform = b2GetBodyTransformQuick(world, body); + b2Body* body = b2GetBodyFullId( world, bodyId ); + b2Transform transform = b2GetBodyTransformQuick( world, body ); - b2Shape* shape = b2CreateShapeInternal(world, body, transform, def, geometry, shapeType); + b2Shape* shape = b2CreateShapeInternal( world, body, transform, def, geometry, shapeType ); - if (body->automaticMass == true) + if ( body->automaticMass == true ) { - b2UpdateBodyMassData(world, body); + b2UpdateBodyMassData( world, body ); } - b2ValidateSolverSets(world); + b2ValidateSolverSets( world ); - b2ShapeId id = {shape->id + 1, bodyId.world0, shape->revision}; + b2ShapeId id = { shape->id + 1, bodyId.world0, shape->revision }; return id; } -b2ShapeId b2CreateCircleShape(b2BodyId bodyId, const b2ShapeDef* def, const b2Circle* circle) +b2ShapeId b2CreateCircleShape( b2BodyId bodyId, const b2ShapeDef* def, const b2Circle* circle ) { - return b2CreateShape(bodyId, def, circle, b2_circleShape); + return b2CreateShape( bodyId, def, circle, b2_circleShape ); } -b2ShapeId b2CreateCapsuleShape(b2BodyId bodyId, const b2ShapeDef* def, const b2Capsule* capsule) +b2ShapeId b2CreateCapsuleShape( b2BodyId bodyId, const b2ShapeDef* def, const b2Capsule* capsule ) { - float lengthSqr = b2DistanceSquared(capsule->center1, capsule->center2); - if (lengthSqr <= b2_linearSlop * b2_linearSlop) + float lengthSqr = b2DistanceSquared( capsule->center1, capsule->center2 ); + if ( lengthSqr <= b2_linearSlop * b2_linearSlop ) { - b2Circle circle = {b2Lerp(capsule->center1, capsule->center2, 0.5f), capsule->radius}; - return b2CreateShape(bodyId, def, &circle, b2_circleShape); + b2Circle circle = { b2Lerp( capsule->center1, capsule->center2, 0.5f ), capsule->radius }; + return b2CreateShape( bodyId, def, &circle, b2_circleShape ); } - return b2CreateShape(bodyId, def, capsule, b2_capsuleShape); + return b2CreateShape( bodyId, def, capsule, b2_capsuleShape ); } -b2ShapeId b2CreatePolygonShape(b2BodyId bodyId, const b2ShapeDef* def, const b2Polygon* polygon) +b2ShapeId b2CreatePolygonShape( b2BodyId bodyId, const b2ShapeDef* def, const b2Polygon* polygon ) { - B2_ASSERT(b2IsValid(polygon->radius) && polygon->radius >= 0.0f); - return b2CreateShape(bodyId, def, polygon, b2_polygonShape); + B2_ASSERT( b2IsValid( polygon->radius ) && polygon->radius >= 0.0f ); + return b2CreateShape( bodyId, def, polygon, b2_polygonShape ); } -b2ShapeId b2CreateSegmentShape(b2BodyId bodyId, const b2ShapeDef* def, const b2Segment* segment) +b2ShapeId b2CreateSegmentShape( b2BodyId bodyId, const b2ShapeDef* def, const b2Segment* segment ) { - float lengthSqr = b2DistanceSquared(segment->point1, segment->point2); - if (lengthSqr <= b2_linearSlop * b2_linearSlop) + float lengthSqr = b2DistanceSquared( segment->point1, segment->point2 ); + if ( lengthSqr <= b2_linearSlop * b2_linearSlop ) { - B2_ASSERT(false); + B2_ASSERT( false ); return b2_nullShapeId; } - return b2CreateShape(bodyId, def, segment, b2_segmentShape); + return b2CreateShape( bodyId, def, segment, b2_segmentShape ); } // Destroy a shape on a body. This doesn't need to be called when destroying a body. -void b2DestroyShapeInternal(b2World* world, b2Shape* shape, b2Body* body, bool wakeBodies) +void b2DestroyShapeInternal( b2World* world, b2Shape* shape, b2Body* body, bool wakeBodies ) { int shapeId = shape->id; // Remove the shape from the body's doubly linked list. - if (shape->prevShapeId != B2_NULL_INDEX) + if ( shape->prevShapeId != B2_NULL_INDEX ) { - b2CheckId(world->shapeArray, shape->prevShapeId); + b2CheckId( world->shapeArray, shape->prevShapeId ); world->shapeArray[shape->prevShapeId].nextShapeId = shape->nextShapeId; } - if (shape->nextShapeId != B2_NULL_INDEX) + if ( shape->nextShapeId != B2_NULL_INDEX ) { - b2CheckId(world->shapeArray, shape->nextShapeId); + b2CheckId( world->shapeArray, shape->nextShapeId ); world->shapeArray[shape->nextShapeId].prevShapeId = shape->prevShapeId; } - if (shapeId == body->headShapeId) + if ( shapeId == body->headShapeId ) { body->headShapeId = shape->nextShapeId; } @@ -241,81 +242,81 @@ void b2DestroyShapeInternal(b2World* world, b2Shape* shape, b2Body* body, bool w body->shapeCount -= 1; // Remove from broad-phase. - b2DestroyShapeProxy(shape, &world->broadPhase); + b2DestroyShapeProxy( shape, &world->broadPhase ); // Destroy any contacts associated with the shape. int contactKey = body->headContactKey; - while (contactKey != B2_NULL_INDEX) + while ( contactKey != B2_NULL_INDEX ) { int contactId = contactKey >> 1; int edgeIndex = contactKey & 1; - b2CheckIndex(world->contactArray, contactId); + b2CheckIndex( world->contactArray, contactId ); b2Contact* contact = world->contactArray + contactId; contactKey = contact->edges[edgeIndex].nextKey; - if (contact->shapeIdA == shapeId || contact->shapeIdB == shapeId) + if ( contact->shapeIdA == shapeId || contact->shapeIdB == shapeId ) { - b2DestroyContact(world, contact, wakeBodies); + b2DestroyContact( world, contact, wakeBodies ); } } // Return shape to free list. - b2FreeId(&world->shapeIdPool, shapeId); + b2FreeId( &world->shapeIdPool, shapeId ); shape->id = B2_NULL_INDEX; - b2ValidateSolverSets(world); + b2ValidateSolverSets( world ); } -void b2DestroyShape(b2ShapeId shapeId) +void b2DestroyShape( b2ShapeId shapeId ) { - b2World* world = b2GetWorldLocked(shapeId.world0); + b2World* world = b2GetWorldLocked( shapeId.world0 ); int id = shapeId.index1 - 1; - b2CheckIdAndRevision(world->shapeArray, id, shapeId.revision); + b2CheckIdAndRevision( world->shapeArray, id, shapeId.revision ); b2Shape* shape = world->shapeArray + id; // need to wake bodies because this might be a static body bool wakeBodies = true; - b2Body* body = b2GetBody(world, shape->bodyId); - b2DestroyShapeInternal(world, shape, body, wakeBodies); + b2Body* body = b2GetBody( world, shape->bodyId ); + b2DestroyShapeInternal( world, shape, body, wakeBodies ); - if (body->automaticMass == true) + if ( body->automaticMass == true ) { - b2UpdateBodyMassData(world, body); + b2UpdateBodyMassData( world, body ); } } -b2ChainId b2CreateChain(b2BodyId bodyId, const b2ChainDef* def) +b2ChainId b2CreateChain( b2BodyId bodyId, const b2ChainDef* def ) { - b2CheckDef(def); - B2_ASSERT(b2IsValid(def->friction) && def->friction >= 0.0f); - B2_ASSERT(b2IsValid(def->restitution) && def->restitution >= 0.0f); - B2_ASSERT(def->count >= 4); + b2CheckDef( def ); + B2_ASSERT( b2IsValid( def->friction ) && def->friction >= 0.0f ); + B2_ASSERT( b2IsValid( def->restitution ) && def->restitution >= 0.0f ); + B2_ASSERT( def->count >= 4 ); - b2World* world = b2GetWorldLocked(bodyId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( bodyId.world0 ); + if ( world == NULL ) { - return (b2ChainId){0}; + return ( b2ChainId ){ 0 }; } - b2Body* body = b2GetBodyFullId(world, bodyId); - b2Transform transform = b2GetBodyTransformQuick(world, body); + b2Body* body = b2GetBodyFullId( world, bodyId ); + b2Transform transform = b2GetBodyTransformQuick( world, body ); - int chainId = b2AllocId(&world->chainIdPool); + int chainId = b2AllocId( &world->chainIdPool ); - if (chainId == b2Array(world->chainArray).count) + if ( chainId == b2Array( world->chainArray ).count ) { - b2Array_Push(world->chainArray, (b2ChainShape){0}); + b2Array_Push( world->chainArray, ( b2ChainShape ){ 0 } ); } else { - B2_ASSERT(world->chainArray[chainId].id == B2_NULL_INDEX); + B2_ASSERT( world->chainArray[chainId].id == B2_NULL_INDEX ); } - b2CheckIndex(world->chainArray, chainId); + b2CheckIndex( world->chainArray, chainId ); b2ChainShape* chainShape = world->chainArray + chainId; chainShape->id = chainId; @@ -336,15 +337,15 @@ b2ChainId b2CreateChain(b2BodyId bodyId, const b2ChainDef* def) int n = def->count; const b2Vec2* points = def->points; - if (def->isLoop) + if ( def->isLoop ) { chainShape->count = n; - chainShape->shapeIndices = b2Alloc(n * sizeof(int)); + chainShape->shapeIndices = b2Alloc( n * sizeof( int ) ); b2SmoothSegment smoothSegment; int prevIndex = n - 1; - for (int i = 0; i < n - 2; ++i) + for ( int i = 0; i < n - 2; ++i ) { smoothSegment.ghost1 = points[prevIndex]; smoothSegment.segment.point1 = points[i]; @@ -353,7 +354,7 @@ b2ChainId b2CreateChain(b2BodyId bodyId, const b2ChainDef* def) smoothSegment.chainId = chainId; prevIndex = i; - b2Shape* shape = b2CreateShapeInternal(world, body, transform, &shapeDef, &smoothSegment, b2_smoothSegmentShape); + b2Shape* shape = b2CreateShapeInternal( world, body, transform, &shapeDef, &smoothSegment, b2_smoothSegmentShape ); chainShape->shapeIndices[i] = shape->id; } @@ -363,7 +364,7 @@ b2ChainId b2CreateChain(b2BodyId bodyId, const b2ChainDef* def) smoothSegment.segment.point2 = points[n - 1]; smoothSegment.ghost2 = points[0]; smoothSegment.chainId = chainId; - b2Shape* shape = b2CreateShapeInternal(world, body, transform, &shapeDef, &smoothSegment, b2_smoothSegmentShape); + b2Shape* shape = b2CreateShapeInternal( world, body, transform, &shapeDef, &smoothSegment, b2_smoothSegmentShape ); chainShape->shapeIndices[n - 2] = shape->id; } @@ -373,18 +374,18 @@ b2ChainId b2CreateChain(b2BodyId bodyId, const b2ChainDef* def) smoothSegment.segment.point2 = points[0]; smoothSegment.ghost2 = points[1]; smoothSegment.chainId = chainId; - b2Shape* shape = b2CreateShapeInternal(world, body, transform, &shapeDef, &smoothSegment, b2_smoothSegmentShape); + b2Shape* shape = b2CreateShapeInternal( world, body, transform, &shapeDef, &smoothSegment, b2_smoothSegmentShape ); chainShape->shapeIndices[n - 1] = shape->id; } } else { chainShape->count = n - 3; - chainShape->shapeIndices = b2Alloc(n * sizeof(int)); + chainShape->shapeIndices = b2Alloc( n * sizeof( int ) ); b2SmoothSegment smoothSegment; - for (int i = 0; i < n - 3; ++i) + for ( int i = 0; i < n - 3; ++i ) { smoothSegment.ghost1 = points[i]; smoothSegment.segment.point1 = points[i + 1]; @@ -392,116 +393,117 @@ b2ChainId b2CreateChain(b2BodyId bodyId, const b2ChainDef* def) smoothSegment.ghost2 = points[i + 3]; smoothSegment.chainId = chainId; - b2Shape* shape = b2CreateShapeInternal(world, body, transform, &shapeDef, &smoothSegment, b2_smoothSegmentShape); + b2Shape* shape = b2CreateShapeInternal( world, body, transform, &shapeDef, &smoothSegment, b2_smoothSegmentShape ); chainShape->shapeIndices[i] = shape->id; } } - b2ChainId id = {chainId + 1, world->worldId, chainShape->revision}; + b2ChainId id = { chainId + 1, world->worldId, chainShape->revision }; return id; } -void b2DestroyChain(b2ChainId chainId) +void b2DestroyChain( b2ChainId chainId ) { - b2World* world = b2GetWorldLocked(chainId.world0); + b2World* world = b2GetWorldLocked( chainId.world0 ); int id = chainId.index1 - 1; - b2CheckIdAndRevision(world->chainArray, id, chainId.revision); + b2CheckIdAndRevision( world->chainArray, id, chainId.revision ); b2ChainShape* chain = world->chainArray + id; bool wakeBodies = true; - b2Body* body = b2GetBody(world, chain->bodyId); + b2Body* body = b2GetBody( world, chain->bodyId ); // Remove the chain from the body's singly linked list. int* chainIdPtr = &body->headChainId; bool found = false; - while (*chainIdPtr != B2_NULL_INDEX) + while ( *chainIdPtr != B2_NULL_INDEX ) { - if (*chainIdPtr == chain->id) + if ( *chainIdPtr == chain->id ) { *chainIdPtr = chain->nextChainId; found = true; break; } - chainIdPtr = &(world->chainArray[*chainIdPtr].nextChainId); + chainIdPtr = &( world->chainArray[*chainIdPtr].nextChainId ); } - B2_ASSERT(found == true); - if (found == false) + B2_ASSERT( found == true ); + if ( found == false ) { return; } int count = chain->count; - for (int i = 0; i < count; ++i) + for ( int i = 0; i < count; ++i ) { int shapeId = chain->shapeIndices[i]; - b2CheckId(world->shapeArray, shapeId); + b2CheckId( world->shapeArray, shapeId ); b2Shape* shape = world->shapeArray + shapeId; - b2DestroyShapeInternal(world, shape, body, wakeBodies); + b2DestroyShapeInternal( world, shape, body, wakeBodies ); } - b2Free(chain->shapeIndices, chain->count * sizeof(int)); + b2Free( chain->shapeIndices, chain->count * sizeof( int ) ); chain->shapeIndices = NULL; // Return chain to free list. - b2FreeId(&world->chainIdPool, id); + b2FreeId( &world->chainIdPool, id ); chain->id = B2_NULL_INDEX; - b2ValidateSolverSets(world); + b2ValidateSolverSets( world ); } -b2AABB b2ComputeShapeAABB(const b2Shape* shape, b2Transform xf) +b2AABB b2ComputeShapeAABB( const b2Shape* shape, b2Transform xf ) { - switch (shape->type) + switch ( shape->type ) { case b2_capsuleShape: - return b2ComputeCapsuleAABB(&shape->capsule, xf); + return b2ComputeCapsuleAABB( &shape->capsule, xf ); case b2_circleShape: - return b2ComputeCircleAABB(&shape->circle, xf); + return b2ComputeCircleAABB( &shape->circle, xf ); case b2_polygonShape: - return b2ComputePolygonAABB(&shape->polygon, xf); + return b2ComputePolygonAABB( &shape->polygon, xf ); case b2_segmentShape: - return b2ComputeSegmentAABB(&shape->segment, xf); + return b2ComputeSegmentAABB( &shape->segment, xf ); case b2_smoothSegmentShape: - return b2ComputeSegmentAABB(&shape->smoothSegment.segment, xf); + return b2ComputeSegmentAABB( &shape->smoothSegment.segment, xf ); default: { - B2_ASSERT(false); - b2AABB empty = {xf.p, xf.p}; + B2_ASSERT( false ); + b2AABB empty = { xf.p, xf.p }; return empty; } } } -b2Vec2 b2GetShapeCentroid(const b2Shape* shape) +b2Vec2 b2GetShapeCentroid( const b2Shape* shape ) { - switch (shape->type) + switch ( shape->type ) { case b2_capsuleShape: - return b2Lerp(shape->capsule.center1, shape->capsule.center2, 0.5f); + return b2Lerp( shape->capsule.center1, shape->capsule.center2, 0.5f ); case b2_circleShape: return shape->circle.center; case b2_polygonShape: return shape->polygon.centroid; case b2_segmentShape: - return b2Lerp(shape->segment.point1, shape->segment.point2, 0.5f); + return b2Lerp( shape->segment.point1, shape->segment.point2, 0.5f ); case b2_smoothSegmentShape: - return b2Lerp(shape->smoothSegment.segment.point1, shape->smoothSegment.segment.point2, 0.5f); + return b2Lerp( shape->smoothSegment.segment.point1, shape->smoothSegment.segment.point2, 0.5f ); default: return b2Vec2_zero; } } // todo maybe compute this on shape creation -float b2GetShapePerimeter(const b2Shape* shape) +float b2GetShapePerimeter( const b2Shape* shape ) { - switch (shape->type) + switch ( shape->type ) { case b2_capsuleShape: - return 2.0f * b2Length(b2Sub(shape->capsule.center1, shape->capsule.center2)) + 2.0f * b2_pi * shape->capsule.radius; + return 2.0f * b2Length( b2Sub( shape->capsule.center1, shape->capsule.center2 ) ) + + 2.0f * b2_pi * shape->capsule.radius; case b2_circleShape: return 2.0f * b2_pi * shape->circle.radius; case b2_polygonShape: @@ -509,56 +511,56 @@ float b2GetShapePerimeter(const b2Shape* shape) const b2Vec2* points = shape->polygon.vertices; int count = shape->polygon.count; float perimeter = 2.0f * b2_pi * shape->polygon.radius; - B2_ASSERT(count > 0); + B2_ASSERT( count > 0 ); b2Vec2 prev = points[count - 1]; - for (int i = 0; i < count; ++i) + for ( int i = 0; i < count; ++i ) { b2Vec2 next = points[i]; - perimeter += b2Length(b2Sub(next, prev)); + perimeter += b2Length( b2Sub( next, prev ) ); prev = next; } return perimeter; } case b2_segmentShape: - return 2.0f * b2Length(b2Sub(shape->segment.point1, shape->segment.point2)); + return 2.0f * b2Length( b2Sub( shape->segment.point1, shape->segment.point2 ) ); case b2_smoothSegmentShape: - return 2.0f * b2Length(b2Sub(shape->smoothSegment.segment.point1, shape->smoothSegment.segment.point2)); + return 2.0f * b2Length( b2Sub( shape->smoothSegment.segment.point1, shape->smoothSegment.segment.point2 ) ); default: return 0.0f; } } -b2MassData b2ComputeShapeMass(const b2Shape* shape) +b2MassData b2ComputeShapeMass( const b2Shape* shape ) { - switch (shape->type) + switch ( shape->type ) { case b2_capsuleShape: - return b2ComputeCapsuleMass(&shape->capsule, shape->density); + return b2ComputeCapsuleMass( &shape->capsule, shape->density ); case b2_circleShape: - return b2ComputeCircleMass(&shape->circle, shape->density); + return b2ComputeCircleMass( &shape->circle, shape->density ); case b2_polygonShape: - return b2ComputePolygonMass(&shape->polygon, shape->density); + return b2ComputePolygonMass( &shape->polygon, shape->density ); default: { - return (b2MassData){0}; + return ( b2MassData ){ 0 }; } } } -b2ShapeExtent b2ComputeShapeExtent(const b2Shape* shape, b2Vec2 localCenter) +b2ShapeExtent b2ComputeShapeExtent( const b2Shape* shape, b2Vec2 localCenter ) { - b2ShapeExtent extent = {0}; + b2ShapeExtent extent = { 0 }; - switch (shape->type) + switch ( shape->type ) { case b2_capsuleShape: { float radius = shape->capsule.radius; extent.minExtent = radius; - b2Vec2 c1 = b2Sub(shape->capsule.center1, localCenter); - b2Vec2 c2 = b2Sub(shape->capsule.center2, localCenter); - extent.maxExtent = sqrtf(b2MaxFloat(b2LengthSquared(c1), b2LengthSquared(c2))) + radius; + b2Vec2 c1 = b2Sub( shape->capsule.center1, localCenter ); + b2Vec2 c2 = b2Sub( shape->capsule.center2, localCenter ); + extent.maxExtent = sqrtf( b2MaxFloat( b2LengthSquared( c1 ), b2LengthSquared( c2 ) ) ) + radius; } break; @@ -566,7 +568,7 @@ b2ShapeExtent b2ComputeShapeExtent(const b2Shape* shape, b2Vec2 localCenter) { float radius = shape->circle.radius; extent.minExtent = radius; - extent.maxExtent = b2Length(b2Sub(shape->circle.center, localCenter)) + radius; + extent.maxExtent = b2Length( b2Sub( shape->circle.center, localCenter ) ) + radius; } break; @@ -576,36 +578,36 @@ b2ShapeExtent b2ComputeShapeExtent(const b2Shape* shape, b2Vec2 localCenter) float minExtent = b2_huge; float maxExtentSqr = 0.0f; int count = poly->count; - for (int i = 0; i < count; ++i) + for ( int i = 0; i < count; ++i ) { b2Vec2 v = poly->vertices[i]; - float planeOffset = b2Dot(poly->normals[i], b2Sub(v, poly->centroid)); - minExtent = b2MinFloat(minExtent, planeOffset); + float planeOffset = b2Dot( poly->normals[i], b2Sub( v, poly->centroid ) ); + minExtent = b2MinFloat( minExtent, planeOffset ); - float distanceSqr = b2LengthSquared(b2Sub(v, localCenter)); - maxExtentSqr = b2MaxFloat(maxExtentSqr, distanceSqr); + float distanceSqr = b2LengthSquared( b2Sub( v, localCenter ) ); + maxExtentSqr = b2MaxFloat( maxExtentSqr, distanceSqr ); } extent.minExtent = minExtent + poly->radius; - extent.maxExtent = sqrtf(maxExtentSqr) + poly->radius; + extent.maxExtent = sqrtf( maxExtentSqr ) + poly->radius; } break; case b2_segmentShape: { extent.minExtent = 0.0f; - b2Vec2 c1 = b2Sub(shape->segment.point1, localCenter); - b2Vec2 c2 = b2Sub(shape->segment.point2, localCenter); - extent.maxExtent = sqrtf(b2MaxFloat(b2LengthSquared(c1), b2LengthSquared(c2))); + b2Vec2 c1 = b2Sub( shape->segment.point1, localCenter ); + b2Vec2 c2 = b2Sub( shape->segment.point2, localCenter ); + extent.maxExtent = sqrtf( b2MaxFloat( b2LengthSquared( c1 ), b2LengthSquared( c2 ) ) ); } break; case b2_smoothSegmentShape: { extent.minExtent = 0.0f; - b2Vec2 c1 = b2Sub(shape->smoothSegment.segment.point1, localCenter); - b2Vec2 c2 = b2Sub(shape->smoothSegment.segment.point2, localCenter); - extent.maxExtent = sqrtf(b2MaxFloat(b2LengthSquared(c1), b2LengthSquared(c2))); + b2Vec2 c1 = b2Sub( shape->smoothSegment.segment.point1, localCenter ); + b2Vec2 c2 = b2Sub( shape->smoothSegment.segment.point2, localCenter ); + extent.maxExtent = sqrtf( b2MaxFloat( b2LengthSquared( c1 ), b2LengthSquared( c2 ) ) ); } break; @@ -616,234 +618,235 @@ b2ShapeExtent b2ComputeShapeExtent(const b2Shape* shape, b2Vec2 localCenter) return extent; } -b2CastOutput b2RayCastShape(const b2RayCastInput* input, const b2Shape* shape, b2Transform transform) +b2CastOutput b2RayCastShape( const b2RayCastInput* input, const b2Shape* shape, b2Transform transform ) { b2RayCastInput localInput = *input; - localInput.origin = b2InvTransformPoint(transform, input->origin); - localInput.translation = b2InvRotateVector(transform.q, input->translation); + localInput.origin = b2InvTransformPoint( transform, input->origin ); + localInput.translation = b2InvRotateVector( transform.q, input->translation ); - b2CastOutput output = {0}; - switch (shape->type) + b2CastOutput output = { 0 }; + switch ( shape->type ) { case b2_capsuleShape: - output = b2RayCastCapsule(&localInput, &shape->capsule); + output = b2RayCastCapsule( &localInput, &shape->capsule ); break; case b2_circleShape: - output = b2RayCastCircle(&localInput, &shape->circle); + output = b2RayCastCircle( &localInput, &shape->circle ); break; case b2_polygonShape: - output = b2RayCastPolygon(&localInput, &shape->polygon); + output = b2RayCastPolygon( &localInput, &shape->polygon ); break; case b2_segmentShape: - output = b2RayCastSegment(&localInput, &shape->segment, false); + output = b2RayCastSegment( &localInput, &shape->segment, false ); break; case b2_smoothSegmentShape: - output = b2RayCastSegment(&localInput, &shape->smoothSegment.segment, true); + output = b2RayCastSegment( &localInput, &shape->smoothSegment.segment, true ); break; default: return output; } - output.point = b2TransformPoint(transform, output.point); - output.normal = b2RotateVector(transform.q, output.normal); + output.point = b2TransformPoint( transform, output.point ); + output.normal = b2RotateVector( transform.q, output.normal ); return output; } -b2CastOutput b2ShapeCastShape(const b2ShapeCastInput* input, const b2Shape* shape, b2Transform transform) +b2CastOutput b2ShapeCastShape( const b2ShapeCastInput* input, const b2Shape* shape, b2Transform transform ) { b2ShapeCastInput localInput = *input; - for (int i = 0; i < localInput.count; ++i) + for ( int i = 0; i < localInput.count; ++i ) { - localInput.points[i] = b2InvTransformPoint(transform, input->points[i]); + localInput.points[i] = b2InvTransformPoint( transform, input->points[i] ); } - localInput.translation = b2InvRotateVector(transform.q, input->translation); + localInput.translation = b2InvRotateVector( transform.q, input->translation ); - b2CastOutput output = {0}; - switch (shape->type) + b2CastOutput output = { 0 }; + switch ( shape->type ) { case b2_capsuleShape: - output = b2ShapeCastCapsule(&localInput, &shape->capsule); + output = b2ShapeCastCapsule( &localInput, &shape->capsule ); break; case b2_circleShape: - output = b2ShapeCastCircle(&localInput, &shape->circle); + output = b2ShapeCastCircle( &localInput, &shape->circle ); break; case b2_polygonShape: - output = b2ShapeCastPolygon(&localInput, &shape->polygon); + output = b2ShapeCastPolygon( &localInput, &shape->polygon ); break; case b2_segmentShape: - output = b2ShapeCastSegment(&localInput, &shape->segment); + output = b2ShapeCastSegment( &localInput, &shape->segment ); break; case b2_smoothSegmentShape: - output = b2ShapeCastSegment(&localInput, &shape->smoothSegment.segment); + output = b2ShapeCastSegment( &localInput, &shape->smoothSegment.segment ); break; default: return output; } - output.point = b2TransformPoint(transform, output.point); - output.normal = b2RotateVector(transform.q, output.normal); + output.point = b2TransformPoint( transform, output.point ); + output.normal = b2RotateVector( transform.q, output.normal ); return output; } -void b2CreateShapeProxy(b2Shape* shape, b2BroadPhase* bp, b2BodyType type, b2Transform transform, bool forcePairCreation) +void b2CreateShapeProxy( b2Shape* shape, b2BroadPhase* bp, b2BodyType type, b2Transform transform, bool forcePairCreation ) { - B2_ASSERT(shape->proxyKey == B2_NULL_INDEX); + B2_ASSERT( shape->proxyKey == B2_NULL_INDEX ); - b2UpdateShapeAABBs(shape, transform, type); + b2UpdateShapeAABBs( shape, transform, type ); // Create proxies in the broad-phase. - shape->proxyKey = b2BroadPhase_CreateProxy(bp, type, shape->fatAABB, shape->filter.categoryBits, shape->id, forcePairCreation); - B2_ASSERT(B2_PROXY_TYPE(shape->proxyKey) < b2_bodyTypeCount); + shape->proxyKey = + b2BroadPhase_CreateProxy( bp, type, shape->fatAABB, shape->filter.categoryBits, shape->id, forcePairCreation ); + B2_ASSERT( B2_PROXY_TYPE( shape->proxyKey ) < b2_bodyTypeCount ); } -void b2DestroyShapeProxy(b2Shape* shape, b2BroadPhase* bp) +void b2DestroyShapeProxy( b2Shape* shape, b2BroadPhase* bp ) { - if (shape->proxyKey != B2_NULL_INDEX) + if ( shape->proxyKey != B2_NULL_INDEX ) { - b2BroadPhase_DestroyProxy(bp, shape->proxyKey); + b2BroadPhase_DestroyProxy( bp, shape->proxyKey ); shape->proxyKey = B2_NULL_INDEX; } } -b2DistanceProxy b2MakeShapeDistanceProxy(const b2Shape* shape) +b2DistanceProxy b2MakeShapeDistanceProxy( const b2Shape* shape ) { - switch (shape->type) + switch ( shape->type ) { case b2_capsuleShape: - return b2MakeProxy(&shape->capsule.center1, 2, shape->capsule.radius); + return b2MakeProxy( &shape->capsule.center1, 2, shape->capsule.radius ); case b2_circleShape: - return b2MakeProxy(&shape->circle.center, 1, shape->circle.radius); + return b2MakeProxy( &shape->circle.center, 1, shape->circle.radius ); case b2_polygonShape: - return b2MakeProxy(shape->polygon.vertices, shape->polygon.count, shape->polygon.radius); + return b2MakeProxy( shape->polygon.vertices, shape->polygon.count, shape->polygon.radius ); case b2_segmentShape: - return b2MakeProxy(&shape->segment.point1, 2, 0.0f); + return b2MakeProxy( &shape->segment.point1, 2, 0.0f ); case b2_smoothSegmentShape: - return b2MakeProxy(&shape->smoothSegment.segment.point1, 2, 0.0f); + return b2MakeProxy( &shape->smoothSegment.segment.point1, 2, 0.0f ); default: { - B2_ASSERT(false); - b2DistanceProxy empty = {0}; + B2_ASSERT( false ); + b2DistanceProxy empty = { 0 }; return empty; } } } -b2BodyId b2Shape_GetBody(b2ShapeId shapeId) +b2BodyId b2Shape_GetBody( b2ShapeId shapeId ) { - b2World* world = b2GetWorld(shapeId.world0); - b2Shape* shape = b2GetShape(world, shapeId); - return b2MakeBodyId(world, shape->bodyId); + b2World* world = b2GetWorld( shapeId.world0 ); + b2Shape* shape = b2GetShape( world, shapeId ); + return b2MakeBodyId( world, shape->bodyId ); } -void b2Shape_SetUserData(b2ShapeId shapeId, void* userData) +void b2Shape_SetUserData( b2ShapeId shapeId, void* userData ) { - b2World* world = b2GetWorld(shapeId.world0); - b2Shape* shape = b2GetShape(world, shapeId); + b2World* world = b2GetWorld( shapeId.world0 ); + b2Shape* shape = b2GetShape( world, shapeId ); shape->userData = userData; } -void* b2Shape_GetUserData(b2ShapeId shapeId) +void* b2Shape_GetUserData( b2ShapeId shapeId ) { - b2World* world = b2GetWorld(shapeId.world0); - b2Shape* shape = b2GetShape(world, shapeId); + b2World* world = b2GetWorld( shapeId.world0 ); + b2Shape* shape = b2GetShape( world, shapeId ); return shape->userData; } -bool b2Shape_IsSensor(b2ShapeId shapeId) +bool b2Shape_IsSensor( b2ShapeId shapeId ) { - b2World* world = b2GetWorld(shapeId.world0); - b2Shape* shape = b2GetShape(world, shapeId); + b2World* world = b2GetWorld( shapeId.world0 ); + b2Shape* shape = b2GetShape( world, shapeId ); return shape->isSensor; } -bool b2Shape_TestPoint(b2ShapeId shapeId, b2Vec2 point) +bool b2Shape_TestPoint( b2ShapeId shapeId, b2Vec2 point ) { - b2World* world = b2GetWorld(shapeId.world0); - b2Shape* shape = b2GetShape(world, shapeId); + b2World* world = b2GetWorld( shapeId.world0 ); + b2Shape* shape = b2GetShape( world, shapeId ); - b2Transform transform = b2GetOwnerTransform(world, shape); - b2Vec2 localPoint = b2InvTransformPoint(transform, point); + b2Transform transform = b2GetOwnerTransform( world, shape ); + b2Vec2 localPoint = b2InvTransformPoint( transform, point ); - switch (shape->type) + switch ( shape->type ) { case b2_capsuleShape: - return b2PointInCapsule(localPoint, &shape->capsule); + return b2PointInCapsule( localPoint, &shape->capsule ); case b2_circleShape: - return b2PointInCircle(localPoint, &shape->circle); + return b2PointInCircle( localPoint, &shape->circle ); case b2_polygonShape: - return b2PointInPolygon(localPoint, &shape->polygon); + return b2PointInPolygon( localPoint, &shape->polygon ); default: return false; } } -b2CastOutput b2Shape_RayCast(b2ShapeId shapeId, b2Vec2 origin, b2Vec2 translation) +b2CastOutput b2Shape_RayCast( b2ShapeId shapeId, b2Vec2 origin, b2Vec2 translation ) { - b2World* world = b2GetWorld(shapeId.world0); - b2Shape* shape = b2GetShape(world, shapeId); + b2World* world = b2GetWorld( shapeId.world0 ); + b2Shape* shape = b2GetShape( world, shapeId ); - b2Transform transform = b2GetOwnerTransform(world, shape); + b2Transform transform = b2GetOwnerTransform( world, shape ); // input in local coordinates b2RayCastInput input; input.maxFraction = 1.0f; - input.origin = b2InvTransformPoint(transform, origin); - input.translation = b2InvRotateVector(transform.q, translation); + input.origin = b2InvTransformPoint( transform, origin ); + input.translation = b2InvRotateVector( transform.q, translation ); - b2CastOutput output = {0}; - switch (shape->type) + b2CastOutput output = { 0 }; + switch ( shape->type ) { case b2_capsuleShape: - output = b2RayCastCapsule(&input, &shape->capsule); + output = b2RayCastCapsule( &input, &shape->capsule ); break; case b2_circleShape: - output = b2RayCastCircle(&input, &shape->circle); + output = b2RayCastCircle( &input, &shape->circle ); break; case b2_segmentShape: - output = b2RayCastSegment(&input, &shape->segment, false); + output = b2RayCastSegment( &input, &shape->segment, false ); break; case b2_polygonShape: - output = b2RayCastPolygon(&input, &shape->polygon); + output = b2RayCastPolygon( &input, &shape->polygon ); break; case b2_smoothSegmentShape: - output = b2RayCastSegment(&input, &shape->smoothSegment.segment, true); + output = b2RayCastSegment( &input, &shape->smoothSegment.segment, true ); break; default: - B2_ASSERT(false); + B2_ASSERT( false ); return output; } - if (output.hit) + if ( output.hit ) { // convert to world coordinates - output.normal = b2RotateVector(transform.q, output.normal); - output.point = b2TransformPoint(transform, output.point); + output.normal = b2RotateVector( transform.q, output.normal ); + output.point = b2TransformPoint( transform, output.point ); } return output; } -void b2Shape_SetDensity(b2ShapeId shapeId, float density) +void b2Shape_SetDensity( b2ShapeId shapeId, float density ) { - B2_ASSERT(b2IsValid(density) && density >= 0.0f); + B2_ASSERT( b2IsValid( density ) && density >= 0.0f ); - b2World* world = b2GetWorldLocked(shapeId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( shapeId.world0 ); + if ( world == NULL ) { return; } - b2Shape* shape = b2GetShape(world, shapeId); - if (density == shape->density) + b2Shape* shape = b2GetShape( world, shapeId ); + if ( density == shape->density ) { // early return to avoid expensive function return; @@ -852,127 +855,126 @@ void b2Shape_SetDensity(b2ShapeId shapeId, float density) shape->density = density; } -float b2Shape_GetDensity(b2ShapeId shapeId) +float b2Shape_GetDensity( b2ShapeId shapeId ) { - b2World* world = b2GetWorld(shapeId.world0); - b2Shape* shape = b2GetShape(world, shapeId); + b2World* world = b2GetWorld( shapeId.world0 ); + b2Shape* shape = b2GetShape( world, shapeId ); return shape->density; } -void b2Shape_SetFriction(b2ShapeId shapeId, float friction) +void b2Shape_SetFriction( b2ShapeId shapeId, float friction ) { - B2_ASSERT(b2IsValid(friction) && friction >= 0.0f); + B2_ASSERT( b2IsValid( friction ) && friction >= 0.0f ); - b2World* world = b2GetWorld(shapeId.world0); - B2_ASSERT(world->locked == false); - if (world->locked) + b2World* world = b2GetWorld( shapeId.world0 ); + B2_ASSERT( world->locked == false ); + if ( world->locked ) { return; } - b2Shape* shape = b2GetShape(world, shapeId); + b2Shape* shape = b2GetShape( world, shapeId ); shape->friction = friction; } -float b2Shape_GetFriction(b2ShapeId shapeId) +float b2Shape_GetFriction( b2ShapeId shapeId ) { - b2World* world = b2GetWorld(shapeId.world0); - b2Shape* shape = b2GetShape(world, shapeId); + b2World* world = b2GetWorld( shapeId.world0 ); + b2Shape* shape = b2GetShape( world, shapeId ); return shape->friction; } -void b2Shape_SetRestitution(b2ShapeId shapeId, float restitution) +void b2Shape_SetRestitution( b2ShapeId shapeId, float restitution ) { - B2_ASSERT(b2IsValid(restitution) && restitution >= 0.0f); + B2_ASSERT( b2IsValid( restitution ) && restitution >= 0.0f ); - b2World* world = b2GetWorld(shapeId.world0); - B2_ASSERT(world->locked == false); - if (world->locked) + b2World* world = b2GetWorld( shapeId.world0 ); + B2_ASSERT( world->locked == false ); + if ( world->locked ) { return; } - b2Shape* shape = b2GetShape(world, shapeId); + b2Shape* shape = b2GetShape( world, shapeId ); shape->restitution = restitution; } -float b2Shape_GetRestitution(b2ShapeId shapeId) +float b2Shape_GetRestitution( b2ShapeId shapeId ) { - b2World* world = b2GetWorld(shapeId.world0); - b2Shape* shape = b2GetShape(world, shapeId); + b2World* world = b2GetWorld( shapeId.world0 ); + b2Shape* shape = b2GetShape( world, shapeId ); return shape->restitution; } -b2Filter b2Shape_GetFilter(b2ShapeId shapeId) +b2Filter b2Shape_GetFilter( b2ShapeId shapeId ) { - b2World* world = b2GetWorld(shapeId.world0); - b2Shape* shape = b2GetShape(world, shapeId); + b2World* world = b2GetWorld( shapeId.world0 ); + b2Shape* shape = b2GetShape( world, shapeId ); return shape->filter; } -static void b2ResetProxy(b2World* world, b2Shape* shape, bool wakeBodies, bool destroyProxy) +static void b2ResetProxy( b2World* world, b2Shape* shape, bool wakeBodies, bool destroyProxy ) { - b2Body* body = b2GetBody(world, shape->bodyId); + b2Body* body = b2GetBody( world, shape->bodyId ); int shapeId = shape->id; // destroy all contacts associated with this shape int contactKey = body->headContactKey; - while (contactKey != B2_NULL_INDEX) + while ( contactKey != B2_NULL_INDEX ) { int contactId = contactKey >> 1; int edgeIndex = contactKey & 1; - b2CheckIndex(world->contactArray, contactId); + b2CheckIndex( world->contactArray, contactId ); b2Contact* contact = world->contactArray + contactId; contactKey = contact->edges[edgeIndex].nextKey; - if (contact->shapeIdA == shapeId || contact->shapeIdB == shapeId) + if ( contact->shapeIdA == shapeId || contact->shapeIdB == shapeId ) { - b2DestroyContact(world, contact, wakeBodies); + b2DestroyContact( world, contact, wakeBodies ); } } - b2Transform transform = b2GetBodyTransformQuick(world, body); - if (shape->proxyKey != B2_NULL_INDEX) + b2Transform transform = b2GetBodyTransformQuick( world, body ); + if ( shape->proxyKey != B2_NULL_INDEX ) { - b2BodyType proxyType = B2_PROXY_TYPE(shape->proxyKey); - b2UpdateShapeAABBs(shape, transform, proxyType); + b2BodyType proxyType = B2_PROXY_TYPE( shape->proxyKey ); + b2UpdateShapeAABBs( shape, transform, proxyType ); - if (destroyProxy) + if ( destroyProxy ) { - b2BroadPhase_DestroyProxy(&world->broadPhase, shape->proxyKey); + b2BroadPhase_DestroyProxy( &world->broadPhase, shape->proxyKey ); bool forcePairCreation = true; - shape->proxyKey = b2BroadPhase_CreateProxy(&world->broadPhase, proxyType, shape->fatAABB, shape->filter.categoryBits, - shapeId, forcePairCreation); + shape->proxyKey = b2BroadPhase_CreateProxy( &world->broadPhase, proxyType, shape->fatAABB, shape->filter.categoryBits, + shapeId, forcePairCreation ); } else { - b2BroadPhase_MoveProxy(&world->broadPhase, shape->proxyKey, shape->fatAABB); + b2BroadPhase_MoveProxy( &world->broadPhase, shape->proxyKey, shape->fatAABB ); } } else { b2BodyType proxyType = body->type; - b2UpdateShapeAABBs(shape, transform, proxyType); + b2UpdateShapeAABBs( shape, transform, proxyType ); } - b2ValidateSolverSets(world); + b2ValidateSolverSets( world ); } -void b2Shape_SetFilter(b2ShapeId shapeId, b2Filter filter) +void b2Shape_SetFilter( b2ShapeId shapeId, b2Filter filter ) { - b2World* world = b2GetWorldLocked(shapeId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( shapeId.world0 ); + if ( world == NULL ) { return; } - b2Shape* shape = b2GetShape(world, shapeId); - if (filter.maskBits == shape->filter.maskBits && - filter.categoryBits == shape->filter.categoryBits && - filter.groupIndex == shape->filter.groupIndex) + b2Shape* shape = b2GetShape( world, shapeId ); + if ( filter.maskBits == shape->filter.maskBits && filter.categoryBits == shape->filter.categoryBits && + filter.groupIndex == shape->filter.groupIndex ) { return; } @@ -984,323 +986,322 @@ void b2Shape_SetFilter(b2ShapeId shapeId, b2Filter filter) // need to wake bodies because a filter change may destroy contacts bool wakeBodies = true; - b2ResetProxy(world, shape, wakeBodies, destroyProxy); + b2ResetProxy( world, shape, wakeBodies, destroyProxy ); } -void b2Shape_EnableSensorEvents(b2ShapeId shapeId, bool flag) +void b2Shape_EnableSensorEvents( b2ShapeId shapeId, bool flag ) { - b2World* world = b2GetWorldLocked(shapeId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( shapeId.world0 ); + if ( world == NULL ) { return; } - b2Shape* shape = b2GetShape(world, shapeId); + b2Shape* shape = b2GetShape( world, shapeId ); shape->enableSensorEvents = flag; } -bool b2Shape_AreSensorEventsEnabled(b2ShapeId shapeId) +bool b2Shape_AreSensorEventsEnabled( b2ShapeId shapeId ) { - b2World* world = b2GetWorld(shapeId.world0); - b2Shape* shape = b2GetShape(world, shapeId); + b2World* world = b2GetWorld( shapeId.world0 ); + b2Shape* shape = b2GetShape( world, shapeId ); return shape->enableSensorEvents; } -void b2Shape_EnableContactEvents(b2ShapeId shapeId, bool flag) +void b2Shape_EnableContactEvents( b2ShapeId shapeId, bool flag ) { - b2World* world = b2GetWorldLocked(shapeId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( shapeId.world0 ); + if ( world == NULL ) { return; } - b2Shape* shape = b2GetShape(world, shapeId); + b2Shape* shape = b2GetShape( world, shapeId ); shape->enableContactEvents = flag; } -bool b2Shape_AreContactEventsEnabled(b2ShapeId shapeId) +bool b2Shape_AreContactEventsEnabled( b2ShapeId shapeId ) { - b2World* world = b2GetWorld(shapeId.world0); - b2Shape* shape = b2GetShape(world, shapeId); + b2World* world = b2GetWorld( shapeId.world0 ); + b2Shape* shape = b2GetShape( world, shapeId ); return shape->enableContactEvents; } -void b2Shape_EnablePreSolveEvents(b2ShapeId shapeId, bool flag) +void b2Shape_EnablePreSolveEvents( b2ShapeId shapeId, bool flag ) { - b2World* world = b2GetWorldLocked(shapeId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( shapeId.world0 ); + if ( world == NULL ) { return; } - b2Shape* shape = b2GetShape(world, shapeId); + b2Shape* shape = b2GetShape( world, shapeId ); shape->enablePreSolveEvents = flag; } -bool b2Shape_ArePreSolveEventsEnabled(b2ShapeId shapeId) +bool b2Shape_ArePreSolveEventsEnabled( b2ShapeId shapeId ) { - b2World* world = b2GetWorld(shapeId.world0); - b2Shape* shape = b2GetShape(world, shapeId); + b2World* world = b2GetWorld( shapeId.world0 ); + b2Shape* shape = b2GetShape( world, shapeId ); return shape->enablePreSolveEvents; } -void b2Shape_EnableHitEvents(b2ShapeId shapeId, bool flag) +void b2Shape_EnableHitEvents( b2ShapeId shapeId, bool flag ) { - b2World* world = b2GetWorldLocked(shapeId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( shapeId.world0 ); + if ( world == NULL ) { return; } - b2Shape* shape = b2GetShape(world, shapeId); + b2Shape* shape = b2GetShape( world, shapeId ); shape->enableHitEvents = flag; } -bool b2Shape_AreHitEventsEnabled(b2ShapeId shapeId) +bool b2Shape_AreHitEventsEnabled( b2ShapeId shapeId ) { - b2World* world = b2GetWorld(shapeId.world0); - b2Shape* shape = b2GetShape(world, shapeId); + b2World* world = b2GetWorld( shapeId.world0 ); + b2Shape* shape = b2GetShape( world, shapeId ); return shape->enableHitEvents; } - -b2ShapeType b2Shape_GetType(b2ShapeId shapeId) +b2ShapeType b2Shape_GetType( b2ShapeId shapeId ) { - b2World* world = b2GetWorld(shapeId.world0); - b2Shape* shape = b2GetShape(world, shapeId); + b2World* world = b2GetWorld( shapeId.world0 ); + b2Shape* shape = b2GetShape( world, shapeId ); return shape->type; } -b2Circle b2Shape_GetCircle(b2ShapeId shapeId) +b2Circle b2Shape_GetCircle( b2ShapeId shapeId ) { - b2World* world = b2GetWorld(shapeId.world0); - b2Shape* shape = b2GetShape(world, shapeId); - B2_ASSERT(shape->type == b2_circleShape); + b2World* world = b2GetWorld( shapeId.world0 ); + b2Shape* shape = b2GetShape( world, shapeId ); + B2_ASSERT( shape->type == b2_circleShape ); return shape->circle; } -b2Segment b2Shape_GetSegment(b2ShapeId shapeId) +b2Segment b2Shape_GetSegment( b2ShapeId shapeId ) { - b2World* world = b2GetWorld(shapeId.world0); - b2Shape* shape = b2GetShape(world, shapeId); - B2_ASSERT(shape->type == b2_segmentShape); + b2World* world = b2GetWorld( shapeId.world0 ); + b2Shape* shape = b2GetShape( world, shapeId ); + B2_ASSERT( shape->type == b2_segmentShape ); return shape->segment; } -b2SmoothSegment b2Shape_GetSmoothSegment(b2ShapeId shapeId) +b2SmoothSegment b2Shape_GetSmoothSegment( b2ShapeId shapeId ) { - b2World* world = b2GetWorld(shapeId.world0); - b2Shape* shape = b2GetShape(world, shapeId); - B2_ASSERT(shape->type == b2_smoothSegmentShape); + b2World* world = b2GetWorld( shapeId.world0 ); + b2Shape* shape = b2GetShape( world, shapeId ); + B2_ASSERT( shape->type == b2_smoothSegmentShape ); return shape->smoothSegment; } -b2Capsule b2Shape_GetCapsule(b2ShapeId shapeId) +b2Capsule b2Shape_GetCapsule( b2ShapeId shapeId ) { - b2World* world = b2GetWorld(shapeId.world0); - b2Shape* shape = b2GetShape(world, shapeId); - B2_ASSERT(shape->type == b2_capsuleShape); + b2World* world = b2GetWorld( shapeId.world0 ); + b2Shape* shape = b2GetShape( world, shapeId ); + B2_ASSERT( shape->type == b2_capsuleShape ); return shape->capsule; } -b2Polygon b2Shape_GetPolygon(b2ShapeId shapeId) +b2Polygon b2Shape_GetPolygon( b2ShapeId shapeId ) { - b2World* world = b2GetWorld(shapeId.world0); - b2Shape* shape = b2GetShape(world, shapeId); - B2_ASSERT(shape->type == b2_polygonShape); + b2World* world = b2GetWorld( shapeId.world0 ); + b2Shape* shape = b2GetShape( world, shapeId ); + B2_ASSERT( shape->type == b2_polygonShape ); return shape->polygon; } -void b2Shape_SetCircle(b2ShapeId shapeId, const b2Circle* circle) +void b2Shape_SetCircle( b2ShapeId shapeId, const b2Circle* circle ) { - b2World* world = b2GetWorldLocked(shapeId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( shapeId.world0 ); + if ( world == NULL ) { return; } - b2Shape* shape = b2GetShape(world, shapeId); + b2Shape* shape = b2GetShape( world, shapeId ); shape->circle = *circle; shape->type = b2_circleShape; // need to wake bodies so they can react to the shape change bool wakeBodies = true; bool destroyProxy = true; - b2ResetProxy(world, shape, wakeBodies, destroyProxy); + b2ResetProxy( world, shape, wakeBodies, destroyProxy ); } -void b2Shape_SetCapsule(b2ShapeId shapeId, const b2Capsule* capsule) +void b2Shape_SetCapsule( b2ShapeId shapeId, const b2Capsule* capsule ) { - b2World* world = b2GetWorldLocked(shapeId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( shapeId.world0 ); + if ( world == NULL ) { return; } - b2Shape* shape = b2GetShape(world, shapeId); + b2Shape* shape = b2GetShape( world, shapeId ); shape->capsule = *capsule; shape->type = b2_capsuleShape; // need to wake bodies so they can react to the shape change bool wakeBodies = true; bool destroyProxy = true; - b2ResetProxy(world, shape, wakeBodies, destroyProxy); + b2ResetProxy( world, shape, wakeBodies, destroyProxy ); } -void b2Shape_SetSegment(b2ShapeId shapeId, const b2Segment* segment) +void b2Shape_SetSegment( b2ShapeId shapeId, const b2Segment* segment ) { - b2World* world = b2GetWorldLocked(shapeId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( shapeId.world0 ); + if ( world == NULL ) { return; } - b2Shape* shape = b2GetShape(world, shapeId); + b2Shape* shape = b2GetShape( world, shapeId ); shape->segment = *segment; shape->type = b2_segmentShape; // need to wake bodies so they can react to the shape change bool wakeBodies = true; bool destroyProxy = true; - b2ResetProxy(world, shape, wakeBodies, destroyProxy); + b2ResetProxy( world, shape, wakeBodies, destroyProxy ); } -void b2Shape_SetPolygon(b2ShapeId shapeId, const b2Polygon* polygon) +void b2Shape_SetPolygon( b2ShapeId shapeId, const b2Polygon* polygon ) { - b2World* world = b2GetWorldLocked(shapeId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( shapeId.world0 ); + if ( world == NULL ) { return; } - b2Shape* shape = b2GetShape(world, shapeId); + b2Shape* shape = b2GetShape( world, shapeId ); shape->polygon = *polygon; shape->type = b2_polygonShape; // need to wake bodies so they can react to the shape change bool wakeBodies = true; bool destroyProxy = true; - b2ResetProxy(world, shape, wakeBodies, destroyProxy); + b2ResetProxy( world, shape, wakeBodies, destroyProxy ); } -b2ChainId b2Shape_GetParentChain(b2ShapeId shapeId) +b2ChainId b2Shape_GetParentChain( b2ShapeId shapeId ) { - b2World* world = b2GetWorld(shapeId.world0); - b2Shape* shape = b2GetShape(world, shapeId); - if (shape->type == b2_smoothSegmentShape) + b2World* world = b2GetWorld( shapeId.world0 ); + b2Shape* shape = b2GetShape( world, shapeId ); + if ( shape->type == b2_smoothSegmentShape ) { int chainId = shape->smoothSegment.chainId; - if (chainId != B2_NULL_INDEX) + if ( chainId != B2_NULL_INDEX ) { - b2CheckId(world->chainArray, chainId); + b2CheckId( world->chainArray, chainId ); b2ChainShape* chain = world->chainArray + chainId; - b2ChainId id = {chainId + 1, shapeId.world0, chain->revision}; + b2ChainId id = { chainId + 1, shapeId.world0, chain->revision }; return id; } } - return (b2ChainId){0}; + return ( b2ChainId ){ 0 }; } -void b2Chain_SetFriction(b2ChainId chainId, float friction) +void b2Chain_SetFriction( b2ChainId chainId, float friction ) { - b2World* world = b2GetWorldLocked(chainId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( chainId.world0 ); + if ( world == NULL ) { return; } - b2ChainShape* chainShape = b2GetChainShape(world, chainId); + b2ChainShape* chainShape = b2GetChainShape( world, chainId ); int count = chainShape->count; - for (int i = 0; i < count; ++i) + for ( int i = 0; i < count; ++i ) { int shapeId = chainShape->shapeIndices[i]; - b2CheckId(world->shapeArray, shapeId); + b2CheckId( world->shapeArray, shapeId ); b2Shape* shape = world->shapeArray + shapeId; shape->friction = friction; } } -void b2Chain_SetRestitution(b2ChainId chainId, float restitution) +void b2Chain_SetRestitution( b2ChainId chainId, float restitution ) { - b2World* world = b2GetWorldLocked(chainId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( chainId.world0 ); + if ( world == NULL ) { return; } - b2ChainShape* chainShape = b2GetChainShape(world, chainId); + b2ChainShape* chainShape = b2GetChainShape( world, chainId ); int count = chainShape->count; - for (int i = 0; i < count; ++i) + for ( int i = 0; i < count; ++i ) { int shapeId = chainShape->shapeIndices[i]; - b2CheckId(world->shapeArray, shapeId); + b2CheckId( world->shapeArray, shapeId ); b2Shape* shape = world->shapeArray + shapeId; shape->restitution = restitution; } } -int b2Shape_GetContactCapacity(b2ShapeId shapeId) +int b2Shape_GetContactCapacity( b2ShapeId shapeId ) { - b2World* world = b2GetWorldLocked(shapeId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( shapeId.world0 ); + if ( world == NULL ) { return 0; } - b2Shape* shape = b2GetShape(world, shapeId); - if (shape->isSensor) + b2Shape* shape = b2GetShape( world, shapeId ); + if ( shape->isSensor ) { return 0; } - b2Body* body = b2GetBody(world, shape->bodyId); + b2Body* body = b2GetBody( world, shape->bodyId ); // Conservative and fast return body->contactCount; } // todo sample needed -int b2Shape_GetContactData(b2ShapeId shapeId, b2ContactData* contactData, int capacity) +int b2Shape_GetContactData( b2ShapeId shapeId, b2ContactData* contactData, int capacity ) { - b2World* world = b2GetWorldLocked(shapeId.world0); - if (world == NULL) + b2World* world = b2GetWorldLocked( shapeId.world0 ); + if ( world == NULL ) { return 0; } - b2Shape* shape = b2GetShape(world, shapeId); - if (shape->isSensor) + b2Shape* shape = b2GetShape( world, shapeId ); + if ( shape->isSensor ) { return 0; } - b2Body* body = b2GetBody(world, shape->bodyId); + b2Body* body = b2GetBody( world, shape->bodyId ); int contactKey = body->headContactKey; int index = 0; - while (contactKey != B2_NULL_INDEX && index < capacity) + while ( contactKey != B2_NULL_INDEX && index < capacity ) { int contactId = contactKey >> 1; int edgeIndex = contactKey & 1; - b2CheckIndex(world->contactArray, contactId); + b2CheckIndex( world->contactArray, contactId ); b2Contact* contact = world->contactArray + contactId; // Does contact involve this shape and is it touching? - if ((contact->shapeIdA == shapeId.index1 - 1 || contact->shapeIdB == shapeId.index1 - 1) && - (contact->flags & b2_contactTouchingFlag) != 0) + if ( ( contact->shapeIdA == shapeId.index1 - 1 || contact->shapeIdB == shapeId.index1 - 1 ) && + ( contact->flags & b2_contactTouchingFlag ) != 0 ) { b2Shape* shapeA = world->shapeArray + contact->shapeIdA; b2Shape* shapeB = world->shapeArray + contact->shapeIdB; - contactData[index].shapeIdA = (b2ShapeId){shapeA->id + 1, shapeId.world0, shapeA->revision}; - contactData[index].shapeIdB = (b2ShapeId){shapeB->id + 1, shapeId.world0, shapeB->revision}; + contactData[index].shapeIdA = ( b2ShapeId ){ shapeA->id + 1, shapeId.world0, shapeA->revision }; + contactData[index].shapeIdB = ( b2ShapeId ){ shapeB->id + 1, shapeId.world0, shapeB->revision }; - b2ContactSim* contactSim = b2GetContactSim(world, contact); + b2ContactSim* contactSim = b2GetContactSim( world, contact ); contactData[index].manifold = contactSim->manifold; index += 1; } @@ -1308,44 +1309,44 @@ int b2Shape_GetContactData(b2ShapeId shapeId, b2ContactData* contactData, int ca contactKey = contact->edges[edgeIndex].nextKey; } - B2_ASSERT(index <= capacity); + B2_ASSERT( index <= capacity ); return index; } -b2AABB b2Shape_GetAABB(b2ShapeId shapeId) +b2AABB b2Shape_GetAABB( b2ShapeId shapeId ) { - b2World* world = b2GetWorld(shapeId.world0); - if (world == NULL) + b2World* world = b2GetWorld( shapeId.world0 ); + if ( world == NULL ) { - return (b2AABB){0}; + return ( b2AABB ){ 0 }; } - b2Shape* shape = b2GetShape(world, shapeId); + b2Shape* shape = b2GetShape( world, shapeId ); return shape->aabb; } -b2Vec2 b2Shape_GetClosestPoint(b2ShapeId shapeId, b2Vec2 target) +b2Vec2 b2Shape_GetClosestPoint( b2ShapeId shapeId, b2Vec2 target ) { - b2World* world = b2GetWorld(shapeId.world0); - if (world == NULL) + b2World* world = b2GetWorld( shapeId.world0 ); + if ( world == NULL ) { - return (b2Vec2){0}; + return ( b2Vec2 ){ 0 }; } - b2Shape* shape = b2GetShape(world, shapeId); - b2Body* body = b2GetBody(world, shape->bodyId); - b2Transform transform = b2GetBodyTransformQuick(world, body); + b2Shape* shape = b2GetShape( world, shapeId ); + b2Body* body = b2GetBody( world, shape->bodyId ); + b2Transform transform = b2GetBodyTransformQuick( world, body ); b2DistanceInput input; - input.proxyA = b2MakeShapeDistanceProxy(shape); - input.proxyB = b2MakeProxy(&target, 1, 0.0f); + input.proxyA = b2MakeShapeDistanceProxy( shape ); + input.proxyB = b2MakeProxy( &target, 1, 0.0f ); input.transformA = transform; input.transformB = b2Transform_identity; input.useRadii = true; - b2DistanceCache cache = {0}; - b2DistanceOutput output = b2ShapeDistance(&cache, &input, NULL, 0); + b2DistanceCache cache = { 0 }; + b2DistanceOutput output = b2ShapeDistance( &cache, &input, NULL, 0 ); return output.pointA; } diff --git a/src/shape.h b/src/shape.h index 92eeaccb..b089730a 100644 --- a/src/shape.h +++ b/src/shape.h @@ -28,6 +28,7 @@ typedef struct b2Shape b2Filter filter; void* userData; + uint32_t customColor; union { @@ -64,18 +65,18 @@ typedef struct b2ShapeExtent float maxExtent; } b2ShapeExtent; -void b2CreateShapeProxy(b2Shape* shape, b2BroadPhase* bp, b2BodyType type, b2Transform transform, bool forcePairCreation); -void b2DestroyShapeProxy(b2Shape* shape, b2BroadPhase* bp); +void b2CreateShapeProxy( b2Shape* shape, b2BroadPhase* bp, b2BodyType type, b2Transform transform, bool forcePairCreation ); +void b2DestroyShapeProxy( b2Shape* shape, b2BroadPhase* bp ); -b2MassData b2ComputeShapeMass(const b2Shape* shape); -b2ShapeExtent b2ComputeShapeExtent(const b2Shape* shape, b2Vec2 localCenter); -b2AABB b2ComputeShapeAABB(const b2Shape* shape, b2Transform transform); -b2Vec2 b2GetShapeCentroid(const b2Shape* shape); -float b2GetShapePerimeter(const b2Shape* shape); +b2MassData b2ComputeShapeMass( const b2Shape* shape ); +b2ShapeExtent b2ComputeShapeExtent( const b2Shape* shape, b2Vec2 localCenter ); +b2AABB b2ComputeShapeAABB( const b2Shape* shape, b2Transform transform ); +b2Vec2 b2GetShapeCentroid( const b2Shape* shape ); +float b2GetShapePerimeter( const b2Shape* shape ); -b2DistanceProxy b2MakeShapeDistanceProxy(const b2Shape* shape); +b2DistanceProxy b2MakeShapeDistanceProxy( const b2Shape* shape ); -b2CastOutput b2RayCastShape(const b2RayCastInput* input, const b2Shape* shape, b2Transform transform); -b2CastOutput b2ShapeCastShape(const b2ShapeCastInput* input, const b2Shape* shape, b2Transform transform); +b2CastOutput b2RayCastShape( const b2RayCastInput* input, const b2Shape* shape, b2Transform transform ); +b2CastOutput b2ShapeCastShape( const b2ShapeCastInput* input, const b2Shape* shape, b2Transform transform ); -b2Transform b2GetOwnerTransform(b2World* world, b2Shape* shape); +b2Transform b2GetOwnerTransform( b2World* world, b2Shape* shape ); diff --git a/src/solver.c b/src/solver.c index 3d2f930e..567b4067 100644 --- a/src/solver.c +++ b/src/solver.c @@ -31,9 +31,9 @@ typedef struct b2WorkerContext } b2WorkerContext; // Integrate velocities and apply damping -static void b2IntegrateVelocitiesTask(int startIndex, int endIndex, b2StepContext* context) +static void b2IntegrateVelocitiesTask( int startIndex, int endIndex, b2StepContext* context ) { - b2TracyCZoneNC(integrate_velocity, "IntVel", b2_colorDeepPink, true); + b2TracyCZoneNC( integrate_velocity, "IntVel", b2_colorDeepPink, true ); b2BodyState* states = context->states; b2BodySim* sims = context->sims; @@ -45,7 +45,7 @@ static void b2IntegrateVelocitiesTask(int startIndex, int endIndex, b2StepContex float maxLinearSpeedSquared = maxLinearSpeed * maxLinearSpeed; float maxAngularSpeedSquared = maxAngularSpeed * maxAngularSpeed; - for (int i = startIndex; i < endIndex; ++i) + for ( int i = startIndex; i < endIndex; ++i ) { b2BodySim* sim = sims + i; b2BodyState* state = states + i; @@ -61,26 +61,26 @@ static void b2IntegrateVelocitiesTask(int startIndex, int endIndex, b2StepContex // v2 = exp(-c * dt) * v1 // Pade approximation: // v2 = v1 * 1 / (1 + c * dt) - float linearDamping = 1.0f / (1.0f + h * sim->linearDamping); - float angularDamping = 1.0f / (1.0f + h * sim->angularDamping); - b2Vec2 linearVelocityDelta = b2MulSV(h * sim->invMass, b2MulAdd(sim->force, sim->mass * sim->gravityScale, gravity)); + float linearDamping = 1.0f / ( 1.0f + h * sim->linearDamping ); + float angularDamping = 1.0f / ( 1.0f + h * sim->angularDamping ); + b2Vec2 linearVelocityDelta = b2MulSV( h * sim->invMass, b2MulAdd( sim->force, sim->mass * sim->gravityScale, gravity ) ); float angularVelocityDelta = h * sim->invInertia * sim->torque; - v = b2MulAdd(linearVelocityDelta, linearDamping, v); + v = b2MulAdd( linearVelocityDelta, linearDamping, v ); w = angularVelocityDelta + angularDamping * w; // Clamp to max linear speed - if (b2Dot(v, v) > maxLinearSpeedSquared) + if ( b2Dot( v, v ) > maxLinearSpeedSquared ) { - float ratio = maxLinearSpeed / b2Length(v); - v = b2MulSV(ratio, v); + float ratio = maxLinearSpeed / b2Length( v ); + v = b2MulSV( ratio, v ); sim->isSpeedCapped = true; } // Clamp to max angular speed - if (w * w > maxAngularSpeedSquared) + if ( w * w > maxAngularSpeedSquared ) { - float ratio = maxAngularSpeed / b2AbsFloat(w); + float ratio = maxAngularSpeed / b2AbsFloat( w ); w *= ratio; sim->isSpeedCapped = true; } @@ -89,82 +89,82 @@ static void b2IntegrateVelocitiesTask(int startIndex, int endIndex, b2StepContex state->angularVelocity = w; } - b2TracyCZoneEnd(integrate_velocity); + b2TracyCZoneEnd( integrate_velocity ); } -static void b2PrepareJointsTask(int startIndex, int endIndex, b2StepContext* context) +static void b2PrepareJointsTask( int startIndex, int endIndex, b2StepContext* context ) { - b2TracyCZoneNC(prepare_joints, "PrepJoints", b2_colorOldLace, true); + b2TracyCZoneNC( prepare_joints, "PrepJoints", b2_colorOldLace, true ); b2JointSim** joints = context->joints; - for (int i = startIndex; i < endIndex; ++i) + for ( int i = startIndex; i < endIndex; ++i ) { b2JointSim* joint = joints[i]; - b2PrepareJoint(joint, context); + b2PrepareJoint( joint, context ); } - b2TracyCZoneEnd(prepare_joints); + b2TracyCZoneEnd( prepare_joints ); } -static void b2WarmStartJointsTask(int startIndex, int endIndex, b2StepContext* context, int colorIndex) +static void b2WarmStartJointsTask( int startIndex, int endIndex, b2StepContext* context, int colorIndex ) { - b2TracyCZoneNC(warm_joints, "WarmJoints", b2_colorGold, true); + b2TracyCZoneNC( warm_joints, "WarmJoints", b2_colorGold, true ); b2GraphColor* color = context->graph->colors + colorIndex; b2JointSim* joints = color->joints.data; - B2_ASSERT(0 <= startIndex && startIndex < color->joints.count); - B2_ASSERT(startIndex <= endIndex && endIndex <= color->joints.count); + B2_ASSERT( 0 <= startIndex && startIndex < color->joints.count ); + B2_ASSERT( startIndex <= endIndex && endIndex <= color->joints.count ); - for (int i = startIndex; i < endIndex; ++i) + for ( int i = startIndex; i < endIndex; ++i ) { b2JointSim* joint = joints + i; - b2WarmStartJoint(joint, context); + b2WarmStartJoint( joint, context ); } - b2TracyCZoneEnd(warm_joints); + b2TracyCZoneEnd( warm_joints ); } -static void b2SolveJointsTask(int startIndex, int endIndex, b2StepContext* context, int colorIndex, bool useBias) +static void b2SolveJointsTask( int startIndex, int endIndex, b2StepContext* context, int colorIndex, bool useBias ) { - b2TracyCZoneNC(solve_joints, "SolveJoints", b2_colorLemonChiffon, true); + b2TracyCZoneNC( solve_joints, "SolveJoints", b2_colorLemonChiffon, true ); b2GraphColor* color = context->graph->colors + colorIndex; b2JointSim* joints = color->joints.data; - B2_ASSERT(0 <= startIndex && startIndex < color->joints.count); - B2_ASSERT(startIndex <= endIndex && endIndex <= color->joints.count); + B2_ASSERT( 0 <= startIndex && startIndex < color->joints.count ); + B2_ASSERT( startIndex <= endIndex && endIndex <= color->joints.count ); - for (int i = startIndex; i < endIndex; ++i) + for ( int i = startIndex; i < endIndex; ++i ) { b2JointSim* joint = joints + i; - b2SolveJoint(joint, context, useBias); + b2SolveJoint( joint, context, useBias ); } - b2TracyCZoneEnd(solve_joints); + b2TracyCZoneEnd( solve_joints ); } -static void b2IntegratePositionsTask(int startIndex, int endIndex, b2StepContext* context) +static void b2IntegratePositionsTask( int startIndex, int endIndex, b2StepContext* context ) { - b2TracyCZoneNC(integrate_positions, "IntPos", b2_colorDarkSeaGreen, true); + b2TracyCZoneNC( integrate_positions, "IntPos", b2_colorDarkSeaGreen, true ); b2BodyState* states = context->states; float h = context->h; - B2_ASSERT(startIndex <= endIndex); + B2_ASSERT( startIndex <= endIndex ); - for (int i = startIndex; i < endIndex; ++i) + for ( int i = startIndex; i < endIndex; ++i ) { b2BodyState* state = states + i; - state->deltaRotation = b2IntegrateRotation(state->deltaRotation, h * state->angularVelocity); - state->deltaPosition = b2MulAdd(state->deltaPosition, h, state->linearVelocity); + state->deltaRotation = b2IntegrateRotation( state->deltaRotation, h * state->angularVelocity ); + state->deltaPosition = b2MulAdd( state->deltaPosition, h, state->linearVelocity ); } - b2TracyCZoneEnd(integrate_positions); + b2TracyCZoneEnd( integrate_positions ); } -static void b2FinalizeBodiesTask(int startIndex, int endIndex, uint32_t threadIndex, void* context) +static void b2FinalizeBodiesTask( int startIndex, int endIndex, uint32_t threadIndex, void* context ) { - b2TracyCZoneNC(finalize_bodies, "FinalizeBodies", b2_colorViolet, true); + b2TracyCZoneNC( finalize_bodies, "FinalizeBodies", b2_colorViolet, true ); b2StepContext* stepContext = context; b2World* world = stepContext->world; @@ -189,9 +189,9 @@ static void b2FinalizeBodiesTask(int startIndex, int endIndex, uint32_t threadIn const float speculativeDistance = b2_speculativeDistance; const float aabbMargin = b2_aabbMargin; - B2_ASSERT(startIndex <= endIndex); + B2_ASSERT( startIndex <= endIndex ); - for (int simIndex = startIndex; simIndex < endIndex; ++simIndex) + for ( int simIndex = startIndex; simIndex < endIndex; ++simIndex ) { b2BodyState* state = states + simIndex; b2BodySim* sim = sims + simIndex; @@ -199,34 +199,34 @@ static void b2FinalizeBodiesTask(int startIndex, int endIndex, uint32_t threadIn b2Vec2 v = state->linearVelocity; float w = state->angularVelocity; - B2_ASSERT(b2Vec2_IsValid(v)); - B2_ASSERT(b2IsValid(w)); + B2_ASSERT( b2Vec2_IsValid( v ) ); + B2_ASSERT( b2IsValid( w ) ); - sim->center = b2Add(sim->center, state->deltaPosition); - sim->transform.q = b2NormalizeRot(b2MulRot(state->deltaRotation, sim->transform.q)); + sim->center = b2Add( sim->center, state->deltaPosition ); + sim->transform.q = b2NormalizeRot( b2MulRot( state->deltaRotation, sim->transform.q ) ); // Use the velocity of the farthest point on the body to account for rotation. - float maxVelocity = b2Length(v) + b2AbsFloat(w) * sim->maxExtent; + float maxVelocity = b2Length( v ) + b2AbsFloat( w ) * sim->maxExtent; // Sleep needs to observe position correction as well as true velocity. - float maxDeltaPosition = b2Length(state->deltaPosition) + b2AbsFloat(state->deltaRotation.s) * sim->maxExtent; - + float maxDeltaPosition = b2Length( state->deltaPosition ) + b2AbsFloat( state->deltaRotation.s ) * sim->maxExtent; + // Position correction is not as important for sleep as true velocity. float positionSleepFactor = 0.5f; - float sleepVelocity = b2MaxFloat(maxVelocity, positionSleepFactor * invTimeStep * maxDeltaPosition); + float sleepVelocity = b2MaxFloat( maxVelocity, positionSleepFactor * invTimeStep * maxDeltaPosition ); // reset state deltas state->deltaPosition = b2Vec2_zero; state->deltaRotation = b2Rot_identity; - sim->transform.p = b2Sub(sim->center, b2RotateVector(sim->transform.q, sim->localCenter)); + sim->transform.p = b2Sub( sim->center, b2RotateVector( sim->transform.q, sim->localCenter ) ); // cache miss here, however I need the shape list below b2Body* body = bodies + sim->bodyId; body->bodyMoveIndex = simIndex; moveEvents[simIndex].transform = sim->transform; - moveEvents[simIndex].bodyId = (b2BodyId){sim->bodyId + 1, worldId, body->revision}; + moveEvents[simIndex].bodyId = ( b2BodyId ){ sim->bodyId + 1, worldId, body->revision }; moveEvents[simIndex].userData = body->userData; moveEvents[simIndex].fellAsleep = false; @@ -236,27 +236,27 @@ static void b2FinalizeBodiesTask(int startIndex, int endIndex, uint32_t threadIn body->isSpeedCapped = sim->isSpeedCapped; sim->isSpeedCapped = false; - + sim->isFast = false; - if (enableSleep == false || body->enableSleep == false || sleepVelocity > body->sleepThreshold) + if ( enableSleep == false || body->enableSleep == false || sleepVelocity > body->sleepThreshold ) { // Body is not sleepy body->sleepTime = 0.0f; const float saftetyFactor = 0.5f; - if (body->type == b2_dynamicBody && enableContinuous && maxVelocity * timeStep > saftetyFactor * sim->minExtent) + if ( body->type == b2_dynamicBody && enableContinuous && maxVelocity * timeStep > saftetyFactor * sim->minExtent ) { // Store in fast array for the continuous collision stage // This is deterministic because the order of TOI sweeps doesn't matter - if (sim->isBullet) + if ( sim->isBullet ) { - int bulletIndex = atomic_fetch_add(&stepContext->bulletBodyCount, 1); + int bulletIndex = atomic_fetch_add( &stepContext->bulletBodyCount, 1 ); stepContext->bulletBodies[bulletIndex] = simIndex; } else { - int fastIndex = atomic_fetch_add(&stepContext->fastBodyCount, 1); + int fastIndex = atomic_fetch_add( &stepContext->fastBodyCount, 1 ); stepContext->fastBodies[fastIndex] = simIndex; } @@ -278,18 +278,18 @@ static void b2FinalizeBodiesTask(int startIndex, int endIndex, uint32_t threadIn } // Any single body in an island can keep it awake - b2CheckIndex(islands, body->islandId); + b2CheckIndex( islands, body->islandId ); b2Island* island = islands + body->islandId; - if (body->sleepTime < b2_timeToSleep) + if ( body->sleepTime < b2_timeToSleep ) { // keep island awake int islandIndex = island->localIndex; - b2SetBit(awakeIslandBitSet, islandIndex); + b2SetBit( awakeIslandBitSet, islandIndex ); } - else if (island->constraintRemoveCount > 0) + else if ( island->constraintRemoveCount > 0 ) { // body wants to sleep but its island needs splitting first - if (body->sleepTime > taskContext->splitSleepTime) + if ( body->sleepTime > taskContext->splitSleepTime ) { // pick the sleepiest candidate taskContext->splitIslandId = body->islandId; @@ -301,33 +301,33 @@ static void b2FinalizeBodiesTask(int startIndex, int endIndex, uint32_t threadIn b2Transform transform = sim->transform; bool isFast = sim->isFast; int shapeId = body->headShapeId; - while (shapeId != B2_NULL_INDEX) + while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = world->shapeArray + shapeId; - B2_ASSERT(shape->isFast == false); + B2_ASSERT( shape->isFast == false ); - if (isFast) + if ( isFast ) { // The AABB is updated after continuous collision. // Add to moved shapes regardless of AABB changes. shape->isFast = true; // Bit-set to keep the move array sorted - b2SetBit(enlargedSimBitSet, simIndex); + b2SetBit( enlargedSimBitSet, simIndex ); } else { - b2AABB aabb = b2ComputeShapeAABB(shape, transform); + b2AABB aabb = b2ComputeShapeAABB( shape, transform ); aabb.lowerBound.x -= speculativeDistance; aabb.lowerBound.y -= speculativeDistance; aabb.upperBound.x += speculativeDistance; aabb.upperBound.y += speculativeDistance; shape->aabb = aabb; - B2_ASSERT(shape->enlargedAABB == false); + B2_ASSERT( shape->enlargedAABB == false ); - if (b2AABB_Contains(shape->fatAABB, aabb) == false) + if ( b2AABB_Contains( shape->fatAABB, aabb ) == false ) { b2AABB fatAABB; fatAABB.lowerBound.x = aabb.lowerBound.x - aabbMargin; @@ -339,7 +339,7 @@ static void b2FinalizeBodiesTask(int startIndex, int endIndex, uint32_t threadIn shape->enlargedAABB = true; // Bit-set to keep the move array sorted - b2SetBit(enlargedSimBitSet, simIndex); + b2SetBit( enlargedSimBitSet, simIndex ); } } @@ -347,7 +347,7 @@ static void b2FinalizeBodiesTask(int startIndex, int endIndex, uint32_t threadIn } } - b2TracyCZoneEnd(finalize_bodies); + b2TracyCZoneEnd( finalize_bodies ); } /* @@ -374,93 +374,93 @@ typedef enum b2SolverBlockType } b2SolverBlockType; */ -static void b2ExecuteBlock(b2SolverStage* stage, b2StepContext* context, b2SolverBlock* block) +static void b2ExecuteBlock( b2SolverStage* stage, b2StepContext* context, b2SolverBlock* block ) { b2SolverStageType stageType = stage->type; b2SolverBlockType blockType = block->blockType; int startIndex = block->startIndex; int endIndex = startIndex + block->count; - switch (stageType) + switch ( stageType ) { case b2_stagePrepareJoints: - b2PrepareJointsTask(startIndex, endIndex, context); + b2PrepareJointsTask( startIndex, endIndex, context ); break; case b2_stagePrepareContacts: - b2PrepareContactsTask(startIndex, endIndex, context); + b2PrepareContactsTask( startIndex, endIndex, context ); break; case b2_stageIntegrateVelocities: - b2IntegrateVelocitiesTask(startIndex, endIndex, context); + b2IntegrateVelocitiesTask( startIndex, endIndex, context ); break; case b2_stageWarmStart: - if (context->world->enableWarmStarting) + if ( context->world->enableWarmStarting ) { - if (blockType == b2_graphContactBlock) + if ( blockType == b2_graphContactBlock ) { - b2WarmStartContactsTask(startIndex, endIndex, context, stage->colorIndex); + b2WarmStartContactsTask( startIndex, endIndex, context, stage->colorIndex ); } - else if (blockType == b2_graphJointBlock) + else if ( blockType == b2_graphJointBlock ) { - b2WarmStartJointsTask(startIndex, endIndex, context, stage->colorIndex); + b2WarmStartJointsTask( startIndex, endIndex, context, stage->colorIndex ); } } break; case b2_stageSolve: - if (blockType == b2_graphContactBlock) + if ( blockType == b2_graphContactBlock ) { - b2SolveContactsTask(startIndex, endIndex, context, stage->colorIndex, true); + b2SolveContactsTask( startIndex, endIndex, context, stage->colorIndex, true ); } - else if (blockType == b2_graphJointBlock) + else if ( blockType == b2_graphJointBlock ) { - b2SolveJointsTask(startIndex, endIndex, context, stage->colorIndex, true); + b2SolveJointsTask( startIndex, endIndex, context, stage->colorIndex, true ); } break; case b2_stageIntegratePositions: - b2IntegratePositionsTask(startIndex, endIndex, context); + b2IntegratePositionsTask( startIndex, endIndex, context ); break; case b2_stageRelax: - if (blockType == b2_graphContactBlock) + if ( blockType == b2_graphContactBlock ) { - b2SolveContactsTask(startIndex, endIndex, context, stage->colorIndex, false); + b2SolveContactsTask( startIndex, endIndex, context, stage->colorIndex, false ); } - else if (blockType == b2_graphJointBlock) + else if ( blockType == b2_graphJointBlock ) { - b2SolveJointsTask(startIndex, endIndex, context, stage->colorIndex, false); + b2SolveJointsTask( startIndex, endIndex, context, stage->colorIndex, false ); } break; case b2_stageRestitution: - if (blockType == b2_graphContactBlock) + if ( blockType == b2_graphContactBlock ) { - b2ApplyRestitutionTask(startIndex, endIndex, context, stage->colorIndex); + b2ApplyRestitutionTask( startIndex, endIndex, context, stage->colorIndex ); } break; case b2_stageStoreImpulses: - b2StoreImpulsesTask(startIndex, endIndex, context); + b2StoreImpulsesTask( startIndex, endIndex, context ); break; } } -static inline int GetWorkerStartIndex(int workerIndex, int blockCount, int workerCount) +static inline int GetWorkerStartIndex( int workerIndex, int blockCount, int workerCount ) { - if (blockCount <= workerCount) + if ( blockCount <= workerCount ) { return workerIndex < blockCount ? workerIndex : B2_NULL_INDEX; } int blocksPerWorker = blockCount / workerCount; int remainder = blockCount - blocksPerWorker * workerCount; - return blocksPerWorker * workerIndex + b2MinInt(remainder, workerIndex); + return blocksPerWorker * workerIndex + b2MinInt( remainder, workerIndex ); } -static void b2ExecuteStage(b2SolverStage* stage, b2StepContext* context, int previousSyncIndex, int syncIndex, int workerIndex) +static void b2ExecuteStage( b2SolverStage* stage, b2StepContext* context, int previousSyncIndex, int syncIndex, int workerIndex ) { int completedCount = 0; b2SolverBlock* blocks = stage->blocks; @@ -468,28 +468,28 @@ static void b2ExecuteStage(b2SolverStage* stage, b2StepContext* context, int pre int expectedSyncIndex = previousSyncIndex; - int startIndex = GetWorkerStartIndex(workerIndex, blockCount, context->workerCount); - if (startIndex == B2_NULL_INDEX) + int startIndex = GetWorkerStartIndex( workerIndex, blockCount, context->workerCount ); + if ( startIndex == B2_NULL_INDEX ) { return; } - B2_ASSERT(0 <= startIndex && startIndex < blockCount); + B2_ASSERT( 0 <= startIndex && startIndex < blockCount ); int blockIndex = startIndex; // Caution: this can change expectedSyncIndex - while (atomic_compare_exchange_strong(&blocks[blockIndex].syncIndex, &expectedSyncIndex, syncIndex) == true) + while ( atomic_compare_exchange_strong( &blocks[blockIndex].syncIndex, &expectedSyncIndex, syncIndex ) == true ) { - B2_ASSERT(stage->type != b2_stagePrepareContacts || syncIndex < 2); + B2_ASSERT( stage->type != b2_stagePrepareContacts || syncIndex < 2 ); - B2_ASSERT(completedCount < blockCount); + B2_ASSERT( completedCount < blockCount ); - b2ExecuteBlock(stage, context, blocks + blockIndex); + b2ExecuteBlock( stage, context, blocks + blockIndex ); completedCount += 1; blockIndex += 1; - if (blockIndex >= blockCount) + if ( blockIndex >= blockCount ) { // Keep looking for work blockIndex = 0; @@ -500,9 +500,9 @@ static void b2ExecuteStage(b2SolverStage* stage, b2StepContext* context, int pre // Search backwards for blocks blockIndex = startIndex - 1; - while (true) + while ( true ) { - if (blockIndex < 0) + if ( blockIndex < 0 ) { blockIndex = blockCount - 1; } @@ -510,57 +510,57 @@ static void b2ExecuteStage(b2SolverStage* stage, b2StepContext* context, int pre expectedSyncIndex = previousSyncIndex; // Caution: this can change expectedSyncIndex - if (atomic_compare_exchange_strong(&blocks[blockIndex].syncIndex, &expectedSyncIndex, syncIndex) == false) + if ( atomic_compare_exchange_strong( &blocks[blockIndex].syncIndex, &expectedSyncIndex, syncIndex ) == false ) { break; } - b2ExecuteBlock(stage, context, blocks + blockIndex); + b2ExecuteBlock( stage, context, blocks + blockIndex ); completedCount += 1; blockIndex -= 1; } - (void)atomic_fetch_add(&stage->completionCount, completedCount); + (void)atomic_fetch_add( &stage->completionCount, completedCount ); } -static void b2ExecuteMainStage(b2SolverStage* stage, b2StepContext* context, uint32_t syncBits) +static void b2ExecuteMainStage( b2SolverStage* stage, b2StepContext* context, uint32_t syncBits ) { int blockCount = stage->blockCount; - if (blockCount == 0) + if ( blockCount == 0 ) { return; } - if (blockCount == 1) + if ( blockCount == 1 ) { - b2ExecuteBlock(stage, context, stage->blocks); + b2ExecuteBlock( stage, context, stage->blocks ); } else { - atomic_store(&context->atomicSyncBits, syncBits); + atomic_store( &context->atomicSyncBits, syncBits ); - int syncIndex = (syncBits >> 16) & 0xFFFF; - B2_ASSERT(syncIndex > 0); + int syncIndex = ( syncBits >> 16 ) & 0xFFFF; + B2_ASSERT( syncIndex > 0 ); int previousSyncIndex = syncIndex - 1; - b2ExecuteStage(stage, context, previousSyncIndex, syncIndex, 0); + b2ExecuteStage( stage, context, previousSyncIndex, syncIndex, 0 ); // todo consider using the cycle counter as well - while (atomic_load(&stage->completionCount) != blockCount) + while ( atomic_load( &stage->completionCount ) != blockCount ) { simde_mm_pause(); } - atomic_store(&stage->completionCount, 0); + atomic_store( &stage->completionCount, 0 ); } } // This should not use the thread index because thread 0 can be called twice by enkiTS. -void b2SolverTask(int startIndex, int endIndex, uint32_t threadIndexDontUse, void* taskContext) +void b2SolverTask( int startIndex, int endIndex, uint32_t threadIndexDontUse, void* taskContext ) { - B2_MAYBE_UNUSED(startIndex); - B2_MAYBE_UNUSED(endIndex); - B2_MAYBE_UNUSED(threadIndexDontUse); + B2_MAYBE_UNUSED( startIndex ); + B2_MAYBE_UNUSED( endIndex ); + B2_MAYBE_UNUSED( threadIndexDontUse ); b2WorkerContext* workerContext = taskContext; int workerIndex = workerContext->workerIndex; @@ -569,7 +569,7 @@ void b2SolverTask(int startIndex, int endIndex, uint32_t threadIndexDontUse, voi b2SolverStage* stages = context->stages; b2Profile* profile = &context->world->profile; - if (workerIndex == 0) + if ( workerIndex == 0 ) { // Main thread synchronizes the workers and does work itself. // @@ -598,99 +598,99 @@ void b2SolverTask(int startIndex, int endIndex, uint32_t threadIndexDontUse, voi // This stage loops over all awake joints uint32_t jointSyncIndex = 1; - uint32_t syncBits = (jointSyncIndex << 16) | stageIndex; - B2_ASSERT(stages[stageIndex].type == b2_stagePrepareJoints); - b2ExecuteMainStage(stages + stageIndex, context, syncBits); + uint32_t syncBits = ( jointSyncIndex << 16 ) | stageIndex; + B2_ASSERT( stages[stageIndex].type == b2_stagePrepareJoints ); + b2ExecuteMainStage( stages + stageIndex, context, syncBits ); stageIndex += 1; jointSyncIndex += 1; // This stage loops over all contact constraints uint32_t contactSyncIndex = 1; - syncBits = (contactSyncIndex << 16) | stageIndex; - B2_ASSERT(stages[stageIndex].type == b2_stagePrepareContacts); - b2ExecuteMainStage(stages + stageIndex, context, syncBits); + syncBits = ( contactSyncIndex << 16 ) | stageIndex; + B2_ASSERT( stages[stageIndex].type == b2_stagePrepareContacts ); + b2ExecuteMainStage( stages + stageIndex, context, syncBits ); stageIndex += 1; contactSyncIndex += 1; int graphSyncIndex = 1; // Single-threaded overflow work. These constraints don't fit in the graph coloring. - b2PrepareOverflowJoints(context); - b2PrepareOverflowContacts(context); + b2PrepareOverflowJoints( context ); + b2PrepareOverflowContacts( context ); - profile->prepareConstraints += b2GetMillisecondsAndReset(&timer); + profile->prepareConstraints += b2GetMillisecondsAndReset( &timer ); int subStepCount = context->subStepCount; - for (int i = 0; i < subStepCount; ++i) + for ( int i = 0; i < subStepCount; ++i ) { // stage index restarted each iteration // syncBits still increases monotonically because the upper bits increase each iteration int iterStageIndex = stageIndex; // integrate velocities - syncBits = (bodySyncIndex << 16) | iterStageIndex; - B2_ASSERT(stages[iterStageIndex].type == b2_stageIntegrateVelocities); - b2ExecuteMainStage(stages + iterStageIndex, context, syncBits); + syncBits = ( bodySyncIndex << 16 ) | iterStageIndex; + B2_ASSERT( stages[iterStageIndex].type == b2_stageIntegrateVelocities ); + b2ExecuteMainStage( stages + iterStageIndex, context, syncBits ); iterStageIndex += 1; bodySyncIndex += 1; - profile->integrateVelocities += b2GetMillisecondsAndReset(&timer); + profile->integrateVelocities += b2GetMillisecondsAndReset( &timer ); // warm start constraints - b2WarmStartOverflowJoints(context); - b2WarmStartOverflowContacts(context); + b2WarmStartOverflowJoints( context ); + b2WarmStartOverflowContacts( context ); - for (int colorIndex = 0; colorIndex < activeColorCount; ++colorIndex) + for ( int colorIndex = 0; colorIndex < activeColorCount; ++colorIndex ) { - syncBits = (graphSyncIndex << 16) | iterStageIndex; - B2_ASSERT(stages[iterStageIndex].type == b2_stageWarmStart); - b2ExecuteMainStage(stages + iterStageIndex, context, syncBits); + syncBits = ( graphSyncIndex << 16 ) | iterStageIndex; + B2_ASSERT( stages[iterStageIndex].type == b2_stageWarmStart ); + b2ExecuteMainStage( stages + iterStageIndex, context, syncBits ); iterStageIndex += 1; } graphSyncIndex += 1; - profile->warmStart += b2GetMillisecondsAndReset(&timer); + profile->warmStart += b2GetMillisecondsAndReset( &timer ); // solve constraints bool useBias = true; - b2SolveOverflowJoints(context, useBias); - b2SolveOverflowContacts(context, useBias); + b2SolveOverflowJoints( context, useBias ); + b2SolveOverflowContacts( context, useBias ); - for (int colorIndex = 0; colorIndex < activeColorCount; ++colorIndex) + for ( int colorIndex = 0; colorIndex < activeColorCount; ++colorIndex ) { - syncBits = (graphSyncIndex << 16) | iterStageIndex; - B2_ASSERT(stages[iterStageIndex].type == b2_stageSolve); - b2ExecuteMainStage(stages + iterStageIndex, context, syncBits); + syncBits = ( graphSyncIndex << 16 ) | iterStageIndex; + B2_ASSERT( stages[iterStageIndex].type == b2_stageSolve ); + b2ExecuteMainStage( stages + iterStageIndex, context, syncBits ); iterStageIndex += 1; } graphSyncIndex += 1; - profile->solveVelocities += b2GetMillisecondsAndReset(&timer); + profile->solveVelocities += b2GetMillisecondsAndReset( &timer ); // integrate positions - B2_ASSERT(stages[iterStageIndex].type == b2_stageIntegratePositions); - syncBits = (bodySyncIndex << 16) | iterStageIndex; - b2ExecuteMainStage(stages + iterStageIndex, context, syncBits); + B2_ASSERT( stages[iterStageIndex].type == b2_stageIntegratePositions ); + syncBits = ( bodySyncIndex << 16 ) | iterStageIndex; + b2ExecuteMainStage( stages + iterStageIndex, context, syncBits ); iterStageIndex += 1; bodySyncIndex += 1; - profile->integratePositions += b2GetMillisecondsAndReset(&timer); + profile->integratePositions += b2GetMillisecondsAndReset( &timer ); // relax constraints useBias = false; - b2SolveOverflowJoints(context, useBias); - b2SolveOverflowContacts(context, useBias); + b2SolveOverflowJoints( context, useBias ); + b2SolveOverflowContacts( context, useBias ); - for (int colorIndex = 0; colorIndex < activeColorCount; ++colorIndex) + for ( int colorIndex = 0; colorIndex < activeColorCount; ++colorIndex ) { - syncBits = (graphSyncIndex << 16) | iterStageIndex; - B2_ASSERT(stages[iterStageIndex].type == b2_stageRelax); - b2ExecuteMainStage(stages + iterStageIndex, context, syncBits); + syncBits = ( graphSyncIndex << 16 ) | iterStageIndex; + B2_ASSERT( stages[iterStageIndex].type == b2_stageRelax ); + b2ExecuteMainStage( stages + iterStageIndex, context, syncBits ); iterStageIndex += 1; } graphSyncIndex += 1; - profile->relaxVelocities += b2GetMillisecondsAndReset(&timer); + profile->relaxVelocities += b2GetMillisecondsAndReset( &timer ); } // advance the stage according to the sub-stepping tasks just completed @@ -699,49 +699,49 @@ void b2SolverTask(int startIndex, int endIndex, uint32_t threadIndexDontUse, voi // Restitution { - b2ApplyOverflowRestitution(context); + b2ApplyOverflowRestitution( context ); int iterStageIndex = stageIndex; - for (int colorIndex = 0; colorIndex < activeColorCount; ++colorIndex) + for ( int colorIndex = 0; colorIndex < activeColorCount; ++colorIndex ) { - syncBits = (graphSyncIndex << 16) | iterStageIndex; - B2_ASSERT(stages[iterStageIndex].type == b2_stageRestitution); - b2ExecuteMainStage(stages + iterStageIndex, context, syncBits); + syncBits = ( graphSyncIndex << 16 ) | iterStageIndex; + B2_ASSERT( stages[iterStageIndex].type == b2_stageRestitution ); + b2ExecuteMainStage( stages + iterStageIndex, context, syncBits ); iterStageIndex += 1; } // graphSyncIndex += 1; stageIndex += activeColorCount; } - profile->applyRestitution += b2GetMillisecondsAndReset(&timer); + profile->applyRestitution += b2GetMillisecondsAndReset( &timer ); - b2StoreOverflowImpulses(context); + b2StoreOverflowImpulses( context ); - syncBits = (contactSyncIndex << 16) | stageIndex; - B2_ASSERT(stages[stageIndex].type == b2_stageStoreImpulses); - b2ExecuteMainStage(stages + stageIndex, context, syncBits); + syncBits = ( contactSyncIndex << 16 ) | stageIndex; + B2_ASSERT( stages[stageIndex].type == b2_stageStoreImpulses ); + b2ExecuteMainStage( stages + stageIndex, context, syncBits ); - profile->storeImpulses += b2GetMillisecondsAndReset(&timer); + profile->storeImpulses += b2GetMillisecondsAndReset( &timer ); // Signal workers to finish - atomic_store(&context->atomicSyncBits, UINT_MAX); + atomic_store( &context->atomicSyncBits, UINT_MAX ); - B2_ASSERT(stageIndex + 1 == context->stageCount); + B2_ASSERT( stageIndex + 1 == context->stageCount ); return; } // Worker spins and waits for work uint32_t lastSyncBits = 0; - //uint64_t maxSpinTime = 10; - while (true) + // uint64_t maxSpinTime = 10; + while ( true ) { // Spin until main thread bumps changes the sync bits. This can waste significant time overall, but it is necessary for // parallel simulation with graph coloring. uint32_t syncBits; int spinCount = 0; - while ((syncBits = atomic_load(&context->atomicSyncBits)) == lastSyncBits) + while ( ( syncBits = atomic_load( &context->atomicSyncBits ) ) == lastSyncBits ) { - if (spinCount > 5) + if ( spinCount > 5 ) { b2Yield(); spinCount = 0; @@ -750,35 +750,35 @@ void b2SolverTask(int startIndex, int endIndex, uint32_t threadIndexDontUse, voi { // Using the cycle counter helps to account for variation in mm_pause timing across different // CPUs. However, this is X64 only. - //uint64_t prev = __rdtsc(); - //do + // uint64_t prev = __rdtsc(); + // do //{ // simde_mm_pause(); //} - //while ((__rdtsc() - prev) < maxSpinTime); - //maxSpinTime += 10; + // while ((__rdtsc() - prev) < maxSpinTime); + // maxSpinTime += 10; simde_mm_pause(); simde_mm_pause(); spinCount += 1; } } - if (syncBits == UINT_MAX) + if ( syncBits == UINT_MAX ) { // sentinel hit break; } int stageIndex = syncBits & 0xFFFF; - B2_ASSERT(stageIndex < context->stageCount); + B2_ASSERT( stageIndex < context->stageCount ); - int syncIndex = (syncBits >> 16) & 0xFFFF; - B2_ASSERT(syncIndex > 0); + int syncIndex = ( syncBits >> 16 ) & 0xFFFF; + B2_ASSERT( syncIndex > 0 ); int previousSyncIndex = syncIndex - 1; b2SolverStage* stage = stages + stageIndex; - b2ExecuteStage(stage, context, previousSyncIndex, syncIndex, workerIndex); + b2ExecuteStage( stage, context, previousSyncIndex, syncIndex, workerIndex ); lastSyncBits = syncBits; } @@ -795,90 +795,90 @@ struct b2ContinuousContext }; // todo this may lead to pauses for scenarios where pre-solve would disable collision -static bool b2ContinuousQueryCallback(int proxyId, int shapeId, void* context) +static bool b2ContinuousQueryCallback( int proxyId, int shapeId, void* context ) { - B2_MAYBE_UNUSED(proxyId); + B2_MAYBE_UNUSED( proxyId ); struct b2ContinuousContext* continuousContext = context; b2Shape* fastShape = continuousContext->fastShape; b2BodySim* fastBodySim = continuousContext->fastBodySim; // Skip same shape - if (shapeId == fastShape->id) + if ( shapeId == fastShape->id ) { return true; } b2World* world = continuousContext->world; - b2CheckId(world->shapeArray, shapeId); + b2CheckId( world->shapeArray, shapeId ); b2Shape* shape = world->shapeArray + shapeId; // Skip same body - if (shape->bodyId == fastShape->bodyId) + if ( shape->bodyId == fastShape->bodyId ) { return true; } // Skip filtered shapes - bool canCollide = b2ShouldShapesCollide(fastShape->filter, shape->filter); - if (canCollide == false) + bool canCollide = b2ShouldShapesCollide( fastShape->filter, shape->filter ); + if ( canCollide == false ) { return true; } // Skip sensors - if (shape->isSensor == true) + if ( shape->isSensor == true ) { return true; } - b2CheckIndex(world->bodyArray, shape->bodyId); + b2CheckIndex( world->bodyArray, shape->bodyId ); b2Body* body = world->bodyArray + shape->bodyId; - b2BodySim* bodySim = b2GetBodySim(world, body); - B2_ASSERT(body->type == b2_staticBody || fastBodySim->isBullet); + b2BodySim* bodySim = b2GetBodySim( world, body ); + B2_ASSERT( body->type == b2_staticBody || fastBodySim->isBullet ); // Skip bullets - if (bodySim->isBullet) + if ( bodySim->isBullet ) { return true; } // Skip filtered bodies - b2CheckIndex(world->bodyArray, fastBodySim->bodyId); + b2CheckIndex( world->bodyArray, fastBodySim->bodyId ); b2Body* fastBody = world->bodyArray + fastBodySim->bodyId; - canCollide = b2ShouldBodiesCollide(world, fastBody, body); - if (canCollide == false) + canCollide = b2ShouldBodiesCollide( world, fastBody, body ); + if ( canCollide == false ) { return true; } // Custom user filtering b2CustomFilterFcn* customFilterFcn = world->customFilterFcn; - if (customFilterFcn != NULL) + if ( customFilterFcn != NULL ) { - b2ShapeId idA = {shape->id + 1, world->worldId, shape->revision}; - b2ShapeId idB = {fastShape->id + 1, world->worldId, fastShape->revision}; - canCollide = customFilterFcn(idA, idB, world->customFilterContext); - if (canCollide == false) + b2ShapeId idA = { shape->id + 1, world->worldId, shape->revision }; + b2ShapeId idB = { fastShape->id + 1, world->worldId, fastShape->revision }; + canCollide = customFilterFcn( idA, idB, world->customFilterContext ); + if ( canCollide == false ) { return true; } } // Prevent pausing on smooth segment junctions - if (shape->type == b2_smoothSegmentShape) + if ( shape->type == b2_smoothSegmentShape ) { b2Transform transform = bodySim->transform; - b2Vec2 p1 = b2TransformPoint(transform, shape->smoothSegment.segment.point1); - b2Vec2 p2 = b2TransformPoint(transform, shape->smoothSegment.segment.point2); - b2Vec2 e = b2Sub(p2, p1); + b2Vec2 p1 = b2TransformPoint( transform, shape->smoothSegment.segment.point1 ); + b2Vec2 p2 = b2TransformPoint( transform, shape->smoothSegment.segment.point2 ); + b2Vec2 e = b2Sub( p2, p1 ); b2Vec2 c1 = continuousContext->centroid1; b2Vec2 c2 = continuousContext->centroid2; - float offset1 = b2Cross(b2Sub(c1, p1), e); - float offset2 = b2Cross(b2Sub(c2, p1), e); + float offset1 = b2Cross( b2Sub( c1, p1 ), e ); + float offset2 = b2Cross( b2Sub( c2, p1 ), e ); - if (offset1 < 0.0f || offset2 > 0.0f) + if ( offset1 < 0.0f || offset2 > 0.0f ) { // Started behind or finished in front return true; @@ -886,24 +886,24 @@ static bool b2ContinuousQueryCallback(int proxyId, int shapeId, void* context) } b2TOIInput input; - input.proxyA = b2MakeShapeDistanceProxy(shape); - input.proxyB = b2MakeShapeDistanceProxy(fastShape); - input.sweepA = b2MakeSweep(bodySim); + input.proxyA = b2MakeShapeDistanceProxy( shape ); + input.proxyB = b2MakeShapeDistanceProxy( fastShape ); + input.sweepA = b2MakeSweep( bodySim ); input.sweepB = continuousContext->sweep; input.tMax = continuousContext->fraction; - b2TOIOutput output = b2TimeOfImpact(&input); - if (0.0f < output.t && output.t < continuousContext->fraction) + b2TOIOutput output = b2TimeOfImpact( &input ); + if ( 0.0f < output.t && output.t < continuousContext->fraction ) { continuousContext->fraction = output.t; } - else if (0.0f == output.t) + else if ( 0.0f == output.t ) { // fallback to TOI of a small circle around the fast shape centroid - b2Vec2 centroid = b2GetShapeCentroid(fastShape); - input.proxyB = b2MakeProxy(¢roid, 1, b2_speculativeDistance); - output = b2TimeOfImpact(&input); - if (0.0f < output.t && output.t < continuousContext->fraction) + b2Vec2 centroid = b2GetShapeCentroid( fastShape ); + input.proxyB = b2MakeProxy( ¢roid, 1, b2_speculativeDistance ); + output = b2TimeOfImpact( &input ); + if ( 0.0f < output.t && output.t < continuousContext->fraction ) { continuousContext->fraction = output.t; } @@ -913,24 +913,24 @@ static bool b2ContinuousQueryCallback(int proxyId, int shapeId, void* context) } // Continuous collision of dynamic versus static -static void b2SolveContinuous(b2World* world, int bodySimIndex) +static void b2SolveContinuous( b2World* world, int bodySimIndex ) { b2SolverSet* awakeSet = world->solverSetArray + b2_awakeSet; - B2_ASSERT(0 <= bodySimIndex && bodySimIndex < awakeSet->sims.count); + B2_ASSERT( 0 <= bodySimIndex && bodySimIndex < awakeSet->sims.count ); b2BodySim* fastBodySim = awakeSet->sims.data + bodySimIndex; - B2_ASSERT(fastBodySim->isFast); + B2_ASSERT( fastBodySim->isFast ); b2Shape* shapes = world->shapeArray; - b2Sweep sweep = b2MakeSweep(fastBodySim); + b2Sweep sweep = b2MakeSweep( fastBodySim ); b2Transform xf1; xf1.q = sweep.q1; - xf1.p = b2Sub(sweep.c1, b2RotateVector(sweep.q1, sweep.localCenter)); + xf1.p = b2Sub( sweep.c1, b2RotateVector( sweep.q1, sweep.localCenter ) ); b2Transform xf2; xf2.q = sweep.q2; - xf2.p = b2Sub(sweep.c2, b2RotateVector(sweep.q2, sweep.localCenter)); + xf2.p = b2Sub( sweep.c2, b2RotateVector( sweep.q2, sweep.localCenter ) ); b2DynamicTree* staticTree = world->broadPhase.trees + b2_staticBody; b2DynamicTree* kinematicTree = world->broadPhase.trees + b2_kinematicBody; @@ -945,14 +945,14 @@ static void b2SolveContinuous(b2World* world, int bodySimIndex) bool isBullet = fastBodySim->isBullet; // todo consider moving shape list to body sim - b2CheckIndex(world->bodyArray, fastBodySim->bodyId); + b2CheckIndex( world->bodyArray, fastBodySim->bodyId ); b2Body* fastBody = world->bodyArray + fastBodySim->bodyId; int shapeId = fastBody->headShapeId; - while (shapeId != B2_NULL_INDEX) + while ( shapeId != B2_NULL_INDEX ) { - b2CheckId(shapes, shapeId); + b2CheckId( shapes, shapeId ); b2Shape* fastShape = shapes + shapeId; - B2_ASSERT(fastShape->isFast == true); + B2_ASSERT( fastShape->isFast == true ); shapeId = fastShape->nextShapeId; @@ -960,43 +960,43 @@ static void b2SolveContinuous(b2World* world, int bodySimIndex) fastShape->isFast = false; context.fastShape = fastShape; - context.centroid1 = b2TransformPoint(xf1, fastShape->localCentroid); - context.centroid2 = b2TransformPoint(xf2, fastShape->localCentroid); + context.centroid1 = b2TransformPoint( xf1, fastShape->localCentroid ); + context.centroid2 = b2TransformPoint( xf2, fastShape->localCentroid ); b2AABB box1 = fastShape->aabb; - b2AABB box2 = b2ComputeShapeAABB(fastShape, xf2); - b2AABB box = b2AABB_Union(box1, box2); + b2AABB box2 = b2ComputeShapeAABB( fastShape, xf2 ); + b2AABB box = b2AABB_Union( box1, box2 ); // Store this for later fastShape->aabb = box2; // No continuous collision for sensors - if (fastShape->isSensor) + if ( fastShape->isSensor ) { continue; } - b2DynamicTree_Query(staticTree, box, b2_defaultMaskBits, b2ContinuousQueryCallback, &context); + b2DynamicTree_Query( staticTree, box, b2_defaultMaskBits, b2ContinuousQueryCallback, &context ); - if (isBullet) + if ( isBullet ) { - b2DynamicTree_Query(kinematicTree, box, b2_defaultMaskBits, b2ContinuousQueryCallback, &context); - b2DynamicTree_Query(dynamicTree, box, b2_defaultMaskBits, b2ContinuousQueryCallback, &context); + b2DynamicTree_Query( kinematicTree, box, b2_defaultMaskBits, b2ContinuousQueryCallback, &context ); + b2DynamicTree_Query( dynamicTree, box, b2_defaultMaskBits, b2ContinuousQueryCallback, &context ); } } const float speculativeDistance = b2_speculativeDistance; const float aabbMargin = b2_aabbMargin; - if (context.fraction < 1.0f) + if ( context.fraction < 1.0f ) { // Handle time of impact event - b2Rot q = b2NLerp(sweep.q1, sweep.q2, context.fraction); - b2Vec2 c = b2Lerp(sweep.c1, sweep.c2, context.fraction); - b2Vec2 origin = b2Sub(c, b2RotateVector(q, sweep.localCenter)); + b2Rot q = b2NLerp( sweep.q1, sweep.q2, context.fraction ); + b2Vec2 c = b2Lerp( sweep.c1, sweep.c2, context.fraction ); + b2Vec2 origin = b2Sub( c, b2RotateVector( q, sweep.localCenter ) ); // Advance body - b2Transform transform = {origin, q}; + b2Transform transform = { origin, q }; fastBodySim->transform = transform; fastBodySim->center = c; fastBodySim->rotation0 = q; @@ -1004,19 +1004,19 @@ static void b2SolveContinuous(b2World* world, int bodySimIndex) // Prepare AABBs for broad-phase shapeId = fastBody->headShapeId; - while (shapeId != B2_NULL_INDEX) + while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = shapes + shapeId; // Must recompute aabb at the interpolated transform - b2AABB aabb = b2ComputeShapeAABB(shape, transform); + b2AABB aabb = b2ComputeShapeAABB( shape, transform ); aabb.lowerBound.x -= speculativeDistance; aabb.lowerBound.y -= speculativeDistance; aabb.upperBound.x += speculativeDistance; aabb.upperBound.y += speculativeDistance; shape->aabb = aabb; - if (b2AABB_Contains(shape->fatAABB, aabb) == false) + if ( b2AABB_Contains( shape->fatAABB, aabb ) == false ) { b2AABB fatAABB; fatAABB.lowerBound.x = aabb.lowerBound.x - aabbMargin; @@ -1042,13 +1042,13 @@ static void b2SolveContinuous(b2World* world, int bodySimIndex) // Prepare AABBs for broad-phase shapeId = fastBody->headShapeId; - while (shapeId != B2_NULL_INDEX) + while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = shapes + shapeId; // shape->aabb is still valid - if (b2AABB_Contains(shape->fatAABB, shape->aabb) == false) + if ( b2AABB_Contains( shape->fatAABB, shape->aabb ) == false ) { b2AABB fatAABB; fatAABB.lowerBound.x = shape->aabb.lowerBound.x - aabbMargin; @@ -1066,84 +1066,84 @@ static void b2SolveContinuous(b2World* world, int bodySimIndex) } } -static void b2FastBodyTask(int startIndex, int endIndex, uint32_t threadIndex, void* taskContext) +static void b2FastBodyTask( int startIndex, int endIndex, uint32_t threadIndex, void* taskContext ) { - B2_MAYBE_UNUSED(threadIndex); + B2_MAYBE_UNUSED( threadIndex ); - b2TracyCZoneNC(fast_body_task, "Fast Body Task", b2_colorAqua, true); + b2TracyCZoneNC( fast_body_task, "Fast Body Task", b2_colorAqua, true ); b2StepContext* stepContext = taskContext; - B2_ASSERT(startIndex <= endIndex); + B2_ASSERT( startIndex <= endIndex ); - for (int i = startIndex; i < endIndex; ++i) + for ( int i = startIndex; i < endIndex; ++i ) { int simIndex = stepContext->fastBodies[i]; - b2SolveContinuous(stepContext->world, simIndex); + b2SolveContinuous( stepContext->world, simIndex ); } - b2TracyCZoneEnd(fast_body_task); + b2TracyCZoneEnd( fast_body_task ); } -static void b2BulletBodyTask(int startIndex, int endIndex, uint32_t threadIndex, void* taskContext) +static void b2BulletBodyTask( int startIndex, int endIndex, uint32_t threadIndex, void* taskContext ) { - B2_MAYBE_UNUSED(threadIndex); + B2_MAYBE_UNUSED( threadIndex ); - b2TracyCZoneNC(bullet_body_task, "Bullet Body Task", b2_colorLightSkyBlue, true); + b2TracyCZoneNC( bullet_body_task, "Bullet Body Task", b2_colorLightSkyBlue, true ); b2StepContext* stepContext = taskContext; - B2_ASSERT(startIndex <= endIndex); + B2_ASSERT( startIndex <= endIndex ); - for (int i = startIndex; i < endIndex; ++i) + for ( int i = startIndex; i < endIndex; ++i ) { int simIndex = stepContext->bulletBodies[i]; - b2SolveContinuous(stepContext->world, simIndex); + b2SolveContinuous( stepContext->world, simIndex ); } - b2TracyCZoneEnd(bullet_body_task); + b2TracyCZoneEnd( bullet_body_task ); } // Solve with graph coloring -void b2Solve(b2World* world, b2StepContext* stepContext) +void b2Solve( b2World* world, b2StepContext* stepContext ) { b2Timer timer = b2CreateTimer(); world->stepIndex += 1; - b2MergeAwakeIslands(world); + b2MergeAwakeIslands( world ); - world->profile.buildIslands = b2GetMillisecondsAndReset(&timer); + world->profile.buildIslands = b2GetMillisecondsAndReset( &timer ); b2SolverSet* awakeSet = world->solverSetArray + b2_awakeSet; int awakeBodyCount = awakeSet->sims.count; - if (awakeBodyCount == 0) + if ( awakeBodyCount == 0 ) { // Nothing to simulate, however I must still finish the broad-phase rebuild. - if (world->userTreeTask != NULL) + if ( world->userTreeTask != NULL ) { - world->finishTaskFcn(world->userTreeTask, world->userTaskContext); + world->finishTaskFcn( world->userTreeTask, world->userTaskContext ); world->userTreeTask = NULL; world->activeTaskCount -= 1; } - b2ValidateNoEnlarged(&world->broadPhase); + b2ValidateNoEnlarged( &world->broadPhase ); return; } - b2TracyCZoneNC(solve, "Solve", b2_colorMistyRose, true); + b2TracyCZoneNC( solve, "Solve", b2_colorMistyRose, true ); // Prepare buffers for continuous collision (fast bodies) stepContext->fastBodyCount = 0; - stepContext->fastBodies = b2AllocateStackItem(&world->stackAllocator, awakeBodyCount * sizeof(int), "fast bodies"); + stepContext->fastBodies = b2AllocateStackItem( &world->stackAllocator, awakeBodyCount * sizeof( int ), "fast bodies" ); stepContext->bulletBodyCount = 0; - stepContext->bulletBodies = b2AllocateStackItem(&world->stackAllocator, awakeBodyCount * sizeof(int), "bullet bodies"); + stepContext->bulletBodies = b2AllocateStackItem( &world->stackAllocator, awakeBodyCount * sizeof( int ), "bullet bodies" ); - b2TracyCZoneNC(graph_solver, "Graph", b2_colorSeaGreen, true); + b2TracyCZoneNC( graph_solver, "Graph", b2_colorSeaGreen, true ); // Solve constraints using graph coloring { - b2TracyCZoneNC(prepare_stages, "Prepare Stages", b2_colorDarkOrange, true); + b2TracyCZoneNC( prepare_stages, "Prepare Stages", b2_colorDarkOrange, true ); b2ConstraintGraph* graph = &world->constraintGraph; b2GraphColor* colors = graph->colors; @@ -1155,7 +1155,7 @@ void b2Solve(b2World* world, b2StepContext* stepContext) int awakeContactCount = 0; int awakeJointCount = 0; int activeColorCount = 0; - for (int i = 0; i < b2_graphColorCount - 1; ++i) + for ( int i = 0; i < b2_graphColorCount - 1; ++i ) { int perColorContactCount = colors[i].contacts.count; int perColorJointCount = colors[i].joints.count; @@ -1168,7 +1168,7 @@ void b2Solve(b2World* world, b2StepContext* stepContext) // Deal with void** { void* bodyMoveEventArray = world->bodyMoveEventArray; - b2Array_Resize(&bodyMoveEventArray, sizeof(b2BodyMoveEvent), awakeBodyCount); + b2Array_Resize( &bodyMoveEventArray, sizeof( b2BodyMoveEvent ), awakeBodyCount ); world->bodyMoveEventArray = bodyMoveEventArray; } @@ -1187,7 +1187,7 @@ void b2Solve(b2World* world, b2StepContext* stepContext) // Configure blocks for tasks that parallel-for bodies int bodyBlockSize = 1 << 5; int bodyBlockCount; - if (awakeBodyCount > bodyBlockSize * maxBlockCount) + if ( awakeBodyCount > bodyBlockSize * maxBlockCount ) { // Too many blocks, increase block size bodyBlockSize = awakeBodyCount / maxBlockCount; @@ -1195,7 +1195,7 @@ void b2Solve(b2World* world, b2StepContext* stepContext) } else { - bodyBlockCount = ((awakeBodyCount - 1) >> 5) + 1; + bodyBlockCount = ( ( awakeBodyCount - 1 ) >> 5 ) + 1; } // Configure blocks for tasks parallel-for each active graph color @@ -1215,32 +1215,32 @@ void b2Solve(b2World* world, b2StepContext* stepContext) // c is the active color index int simdContactCount = 0; int c = 0; - for (int i = 0; i < b2_graphColorCount - 1; ++i) + for ( int i = 0; i < b2_graphColorCount - 1; ++i ) { int colorContactCount = colors[i].contacts.count; int colorJointCount = colors[i].joints.count; - if (colorContactCount + colorJointCount > 0) + if ( colorContactCount + colorJointCount > 0 ) { activeColorIndices[c] = i; // 8-way SIMD - int colorContactCountSIMD = colorContactCount > 0 ? ((colorContactCount - 1) >> 3) + 1 : 0; + int colorContactCountSIMD = colorContactCount > 0 ? ( ( colorContactCount - 1 ) >> 3 ) + 1 : 0; colorContactCounts[c] = colorContactCountSIMD; // determine the number of contact work blocks for this color - if (colorContactCountSIMD > blocksPerWorker * maxBlockCount) + if ( colorContactCountSIMD > blocksPerWorker * maxBlockCount ) { // too many contact blocks colorContactBlockSizes[c] = colorContactCountSIMD / maxBlockCount; colorContactBlockCounts[c] = maxBlockCount; } - else if (colorContactCountSIMD > 0) + else if ( colorContactCountSIMD > 0 ) { // dividing by blocksPerWorker (4) colorContactBlockSizes[c] = blocksPerWorker; - colorContactBlockCounts[c] = ((colorContactCountSIMD - 1) >> 2) + 1; + colorContactBlockCounts[c] = ( ( colorContactCountSIMD - 1 ) >> 2 ) + 1; } else { @@ -1252,17 +1252,17 @@ void b2Solve(b2World* world, b2StepContext* stepContext) colorJointCounts[c] = colorJointCount; // determine number of joint work blocks for this color - if (colorJointCount > blocksPerWorker * maxBlockCount) + if ( colorJointCount > blocksPerWorker * maxBlockCount ) { // too many joint blocks colorJointBlockSizes[c] = colorJointCount / maxBlockCount; colorJointBlockCounts[c] = maxBlockCount; } - else if (colorJointCount > 0) + else if ( colorJointCount > 0 ) { // dividing by blocksPerWorker (4) colorJointBlockSizes[c] = blocksPerWorker; - colorJointBlockCounts[c] = ((colorJointCount - 1) >> 2) + 1; + colorJointBlockCounts[c] = ( ( colorJointCount - 1 ) >> 2 ) + 1; } else { @@ -1279,17 +1279,18 @@ void b2Solve(b2World* world, b2StepContext* stepContext) // Gather contact pointers for easy parallel-for traversal. Some may be NULL due to SIMD remainders. b2ContactSim** contacts = - b2AllocateStackItem(&world->stackAllocator, 8 * simdContactCount * sizeof(b2ContactSim*), "contact pointers"); + b2AllocateStackItem( &world->stackAllocator, 8 * simdContactCount * sizeof( b2ContactSim* ), "contact pointers" ); // Gather joint pointers for easy parallel-for traversal. - b2JointSim** joints = b2AllocateStackItem(&world->stackAllocator, awakeJointCount * sizeof(b2JointSim*), "joint pointers"); + b2JointSim** joints = + b2AllocateStackItem( &world->stackAllocator, awakeJointCount * sizeof( b2JointSim* ), "joint pointers" ); - b2ContactConstraintSIMD* simdContactConstraints = - b2AllocateStackItem(&world->stackAllocator, simdContactCount * sizeof(b2ContactConstraintSIMD), "contact constraint"); + b2ContactConstraintSIMD* simdContactConstraints = b2AllocateStackItem( + &world->stackAllocator, simdContactCount * sizeof( b2ContactConstraintSIMD ), "contact constraint" ); int overflowContactCount = colors[b2_overflowIndex].contacts.count; b2ContactConstraint* overflowContactConstraints = b2AllocateStackItem( - &world->stackAllocator, overflowContactCount * sizeof(b2ContactConstraint), "overflow contact constraint"); + &world->stackAllocator, overflowContactCount * sizeof( b2ContactConstraint ), "overflow contact constraint" ); graph->colors[b2_overflowIndex].overflowConstraints = overflowContactConstraints; @@ -1297,14 +1298,14 @@ void b2Solve(b2World* world, b2StepContext* stepContext) { int contactBase = 0; int jointBase = 0; - for (int i = 0; i < activeColorCount; ++i) + for ( int i = 0; i < activeColorCount; ++i ) { int j = activeColorIndices[i]; b2GraphColor* color = colors + j; int colorContactCount = color->contacts.count; - if (colorContactCount == 0) + if ( colorContactCount == 0 ) { color->simdConstraints = NULL; } @@ -1312,14 +1313,14 @@ void b2Solve(b2World* world, b2StepContext* stepContext) { color->simdConstraints = simdContactConstraints + contactBase; - for (int k = 0; k < colorContactCount; ++k) + for ( int k = 0; k < colorContactCount; ++k ) { contacts[8 * contactBase + k] = color->contacts.data + k; } // remainder - int colorContactCountSIMD = ((colorContactCount - 1) >> 3) + 1; - for (int k = colorContactCount; k < 8 * colorContactCountSIMD; ++k) + int colorContactCountSIMD = ( ( colorContactCount - 1 ) >> 3 ) + 1; + for ( int k = colorContactCount; k < 8 * colorContactCountSIMD; ++k ) { contacts[8 * contactBase + k] = NULL; } @@ -1328,21 +1329,21 @@ void b2Solve(b2World* world, b2StepContext* stepContext) } int colorJointCount = color->joints.count; - for (int k = 0; k < colorJointCount; ++k) + for ( int k = 0; k < colorJointCount; ++k ) { joints[jointBase + k] = color->joints.data + k; } jointBase += colorJointCount; } - B2_ASSERT(contactBase == simdContactCount); - B2_ASSERT(jointBase == awakeJointCount); + B2_ASSERT( contactBase == simdContactCount ); + B2_ASSERT( jointBase == awakeJointCount ); } // Define work blocks for preparing contacts and storing contact impulses int contactBlockSize = blocksPerWorker; - int contactBlockCount = simdContactCount > 0 ? ((simdContactCount - 1) >> 2) + 1 : 0; - if (simdContactCount > contactBlockSize * maxBlockCount) + int contactBlockCount = simdContactCount > 0 ? ( ( simdContactCount - 1 ) >> 2 ) + 1 : 0; + if ( simdContactCount > contactBlockSize * maxBlockCount ) { // Too many blocks, increase block size contactBlockSize = simdContactCount / maxBlockCount; @@ -1351,8 +1352,8 @@ void b2Solve(b2World* world, b2StepContext* stepContext) // Define work blocks for preparing joints int jointBlockSize = blocksPerWorker; - int jointBlockCount = awakeJointCount > 0 ? ((awakeJointCount - 1) >> 2) + 1 : 0; - if (awakeJointCount > jointBlockSize * maxBlockCount) + int jointBlockCount = awakeJointCount > 0 ? ( ( awakeJointCount - 1 ) >> 2 ) + 1 : 0; + if ( awakeJointCount > jointBlockSize * maxBlockCount ) { // Too many blocks, increase block size jointBlockSize = awakeJointCount / maxBlockCount; @@ -1380,15 +1381,15 @@ void b2Solve(b2World* world, b2StepContext* stepContext) // b2_stageStoreImpulses stageCount += 1; - b2SolverStage* stages = b2AllocateStackItem(&world->stackAllocator, stageCount * sizeof(b2SolverStage), "stages"); + b2SolverStage* stages = b2AllocateStackItem( &world->stackAllocator, stageCount * sizeof( b2SolverStage ), "stages" ); b2SolverBlock* bodyBlocks = - b2AllocateStackItem(&world->stackAllocator, bodyBlockCount * sizeof(b2SolverBlock), "body blocks"); + b2AllocateStackItem( &world->stackAllocator, bodyBlockCount * sizeof( b2SolverBlock ), "body blocks" ); b2SolverBlock* contactBlocks = - b2AllocateStackItem(&world->stackAllocator, contactBlockCount * sizeof(b2SolverBlock), "contact blocks"); + b2AllocateStackItem( &world->stackAllocator, contactBlockCount * sizeof( b2SolverBlock ), "contact blocks" ); b2SolverBlock* jointBlocks = - b2AllocateStackItem(&world->stackAllocator, jointBlockCount * sizeof(b2SolverBlock), "joint blocks"); + b2AllocateStackItem( &world->stackAllocator, jointBlockCount * sizeof( b2SolverBlock ), "joint blocks" ); b2SolverBlock* graphBlocks = - b2AllocateStackItem(&world->stackAllocator, graphBlockCount * sizeof(b2SolverBlock), "graph blocks"); + b2AllocateStackItem( &world->stackAllocator, graphBlockCount * sizeof( b2SolverBlock ), "graph blocks" ); // Split an awake island. This modifies: // - stack allocator @@ -1397,15 +1398,15 @@ void b2Solve(b2World* world, b2StepContext* stepContext) // I'm squeezing this task in here because it may be expensive and this is a safe place to put it. // Note: cannot split islands in parallel with FinalizeBodies void* splitIslandTask = NULL; - if (world->splitIslandId != B2_NULL_INDEX) + if ( world->splitIslandId != B2_NULL_INDEX ) { - splitIslandTask = world->enqueueTaskFcn(&b2SplitIslandTask, 1, 1, world, world->userTaskContext); + splitIslandTask = world->enqueueTaskFcn( &b2SplitIslandTask, 1, 1, world, world->userTaskContext ); world->taskCount += 1; world->activeTaskCount += splitIslandTask == NULL ? 0 : 1; } // Prepare body work blocks - for (int i = 0; i < bodyBlockCount; ++i) + for ( int i = 0; i < bodyBlockCount; ++i ) { b2SolverBlock* block = bodyBlocks + i; block->startIndex = i * bodyBlockSize; @@ -1413,10 +1414,10 @@ void b2Solve(b2World* world, b2StepContext* stepContext) block->blockType = b2_bodyBlock; block->syncIndex = 0; } - bodyBlocks[bodyBlockCount - 1].count = (int16_t)(awakeBodyCount - (bodyBlockCount - 1) * bodyBlockSize); + bodyBlocks[bodyBlockCount - 1].count = (int16_t)( awakeBodyCount - ( bodyBlockCount - 1 ) * bodyBlockSize ); // Prepare joint work blocks - for (int i = 0; i < jointBlockCount; ++i) + for ( int i = 0; i < jointBlockCount; ++i ) { b2SolverBlock* block = jointBlocks + i; block->startIndex = i * jointBlockSize; @@ -1425,13 +1426,13 @@ void b2Solve(b2World* world, b2StepContext* stepContext) block->syncIndex = 0; } - if (jointBlockCount > 0) + if ( jointBlockCount > 0 ) { - jointBlocks[jointBlockCount - 1].count = (int16_t)(awakeJointCount - (jointBlockCount - 1) * jointBlockSize); + jointBlocks[jointBlockCount - 1].count = (int16_t)( awakeJointCount - ( jointBlockCount - 1 ) * jointBlockSize ); } // Prepare contact work blocks - for (int i = 0; i < contactBlockCount; ++i) + for ( int i = 0; i < contactBlockCount; ++i ) { b2SolverBlock* block = contactBlocks + i; block->startIndex = i * contactBlockSize; @@ -1440,22 +1441,23 @@ void b2Solve(b2World* world, b2StepContext* stepContext) block->syncIndex = 0; } - if (contactBlockCount > 0) + if ( contactBlockCount > 0 ) { - contactBlocks[contactBlockCount - 1].count = (int16_t)(simdContactCount - (contactBlockCount - 1) * contactBlockSize); + contactBlocks[contactBlockCount - 1].count = + (int16_t)( simdContactCount - ( contactBlockCount - 1 ) * contactBlockSize ); } // Prepare graph work blocks b2SolverBlock* graphColorBlocks[b2_graphColorCount]; b2SolverBlock* baseGraphBlock = graphBlocks; - for (int i = 0; i < activeColorCount; ++i) + for ( int i = 0; i < activeColorCount; ++i ) { graphColorBlocks[i] = baseGraphBlock; int colorJointBlockCount = colorJointBlockCounts[i]; int colorJointBlockSize = colorJointBlockSizes[i]; - for (int j = 0; j < colorJointBlockCount; ++j) + for ( int j = 0; j < colorJointBlockCount; ++j ) { b2SolverBlock* block = baseGraphBlock + j; block->startIndex = j * colorJointBlockSize; @@ -1464,16 +1466,16 @@ void b2Solve(b2World* world, b2StepContext* stepContext) block->syncIndex = 0; } - if (colorJointBlockCount > 0) + if ( colorJointBlockCount > 0 ) { baseGraphBlock[colorJointBlockCount - 1].count = - (int16_t)(colorJointCounts[i] - (colorJointBlockCount - 1) * colorJointBlockSize); + (int16_t)( colorJointCounts[i] - ( colorJointBlockCount - 1 ) * colorJointBlockSize ); baseGraphBlock += colorJointBlockCount; } int colorContactBlockCount = colorContactBlockCounts[i]; int colorContactBlockSize = colorContactBlockSizes[i]; - for (int j = 0; j < colorContactBlockCount; ++j) + for ( int j = 0; j < colorContactBlockCount; ++j ) { b2SolverBlock* block = baseGraphBlock + j; block->startIndex = j * colorContactBlockSize; @@ -1482,16 +1484,16 @@ void b2Solve(b2World* world, b2StepContext* stepContext) block->syncIndex = 0; } - if (colorContactBlockCount > 0) + if ( colorContactBlockCount > 0 ) { baseGraphBlock[colorContactBlockCount - 1].count = - (int16_t)(colorContactCounts[i] - (colorContactBlockCount - 1) * colorContactBlockSize); + (int16_t)( colorContactCounts[i] - ( colorContactBlockCount - 1 ) * colorContactBlockSize ); baseGraphBlock += colorContactBlockCount; } } ptrdiff_t blockDiff = baseGraphBlock - graphBlocks; - B2_ASSERT(blockDiff == graphBlockCount); + B2_ASSERT( blockDiff == graphBlockCount ); b2SolverStage* stage = stages; @@ -1520,7 +1522,7 @@ void b2Solve(b2World* world, b2StepContext* stepContext) stage += 1; // Warm start - for (int i = 0; i < activeColorCount; ++i) + for ( int i = 0; i < activeColorCount; ++i ) { stage->type = b2_stageWarmStart; stage->blocks = graphColorBlocks[i]; @@ -1531,7 +1533,7 @@ void b2Solve(b2World* world, b2StepContext* stepContext) } // Solve graph - for (int i = 0; i < activeColorCount; ++i) + for ( int i = 0; i < activeColorCount; ++i ) { stage->type = b2_stageSolve; stage->blocks = graphColorBlocks[i]; @@ -1550,7 +1552,7 @@ void b2Solve(b2World* world, b2StepContext* stepContext) stage += 1; // Relax constraints - for (int i = 0; i < activeColorCount; ++i) + for ( int i = 0; i < activeColorCount; ++i ) { stage->type = b2_stageRelax; stage->blocks = graphColorBlocks[i]; @@ -1562,7 +1564,7 @@ void b2Solve(b2World* world, b2StepContext* stepContext) // Restitution // Note: joint blocks mixed in, could have joint limit restitution - for (int i = 0; i < activeColorCount; ++i) + for ( int i = 0; i < activeColorCount; ++i ) { stage->type = b2_stageRestitution; stage->blocks = graphColorBlocks[i]; @@ -1580,9 +1582,9 @@ void b2Solve(b2World* world, b2StepContext* stepContext) stage->completionCount = 0; stage += 1; - B2_ASSERT((int)(stage - stages) == stageCount); + B2_ASSERT( (int)( stage - stages ) == stageCount ); - B2_ASSERT(workerCount <= b2_maxWorkers); + B2_ASSERT( workerCount <= b2_maxWorkers ); b2WorkerContext workerContext[b2_maxWorkers]; stepContext->graph = graph; @@ -1595,107 +1597,106 @@ void b2Solve(b2World* world, b2StepContext* stepContext) stepContext->stages = stages; stepContext->atomicSyncBits = 0; - world->profile.prepareTasks = b2GetMillisecondsAndReset(&timer); + world->profile.prepareTasks = b2GetMillisecondsAndReset( &timer ); - b2TracyCZoneEnd(prepare_stages); + b2TracyCZoneEnd( prepare_stages ); // Must use worker index because thread 0 can be assigned multiple tasks by enkiTS - for (int i = 0; i < workerCount; ++i) + for ( int i = 0; i < workerCount; ++i ) { workerContext[i].context = stepContext; workerContext[i].workerIndex = i; - workerContext[i].userTask = world->enqueueTaskFcn(b2SolverTask, 1, 1, workerContext + i, world->userTaskContext); + workerContext[i].userTask = world->enqueueTaskFcn( b2SolverTask, 1, 1, workerContext + i, world->userTaskContext ); world->taskCount += 1; world->activeTaskCount += workerContext[i].userTask == NULL ? 0 : 1; } // Finish island split - if (splitIslandTask != NULL) + if ( splitIslandTask != NULL ) { - world->finishTaskFcn(splitIslandTask, world->userTaskContext); + world->finishTaskFcn( splitIslandTask, world->userTaskContext ); world->activeTaskCount -= 1; } world->splitIslandId = B2_NULL_INDEX; // Finish constraint solve - for (int i = 0; i < workerCount; ++i) + for ( int i = 0; i < workerCount; ++i ) { - if (workerContext[i].userTask != NULL) + if ( workerContext[i].userTask != NULL ) { - world->finishTaskFcn(workerContext[i].userTask, world->userTaskContext); + world->finishTaskFcn( workerContext[i].userTask, world->userTaskContext ); world->activeTaskCount -= 1; } } - world->profile.solverTasks = b2GetMillisecondsAndReset(&timer); + world->profile.solverTasks = b2GetMillisecondsAndReset( &timer ); // Prepare contact, enlarged body, and island bit sets used in body finalization. int awakeIslandCount = awakeSet->islands.count; - for (int i = 0; i < world->workerCount; ++i) + for ( int i = 0; i < world->workerCount; ++i ) { b2TaskContext* taskContext = world->taskContextArray + i; - b2SetBitCountAndClear(&taskContext->enlargedSimBitSet, awakeBodyCount); - b2SetBitCountAndClear(&taskContext->awakeIslandBitSet, awakeIslandCount); + b2SetBitCountAndClear( &taskContext->enlargedSimBitSet, awakeBodyCount ); + b2SetBitCountAndClear( &taskContext->awakeIslandBitSet, awakeIslandCount ); taskContext->splitIslandId = B2_NULL_INDEX; taskContext->splitSleepTime = 0.0f; } // Finalize bodies. Must happen after the constraint solver and after island splitting. void* finalizeBodiesTask = - world->enqueueTaskFcn(b2FinalizeBodiesTask, awakeBodyCount, 64, stepContext, world->userTaskContext); + world->enqueueTaskFcn( b2FinalizeBodiesTask, awakeBodyCount, 64, stepContext, world->userTaskContext ); world->taskCount += 1; - if (finalizeBodiesTask != NULL) + if ( finalizeBodiesTask != NULL ) { - world->finishTaskFcn(finalizeBodiesTask, world->userTaskContext); + world->finishTaskFcn( finalizeBodiesTask, world->userTaskContext ); } - world->profile.finalizeBodies = b2GetMillisecondsAndReset(&timer); - - - b2FreeStackItem(&world->stackAllocator, graphBlocks); - b2FreeStackItem(&world->stackAllocator, jointBlocks); - b2FreeStackItem(&world->stackAllocator, contactBlocks); - b2FreeStackItem(&world->stackAllocator, bodyBlocks); - b2FreeStackItem(&world->stackAllocator, stages); - b2FreeStackItem(&world->stackAllocator, overflowContactConstraints); - b2FreeStackItem(&world->stackAllocator, simdContactConstraints); - b2FreeStackItem(&world->stackAllocator, joints); - b2FreeStackItem(&world->stackAllocator, contacts); + world->profile.finalizeBodies = b2GetMillisecondsAndReset( &timer ); + + b2FreeStackItem( &world->stackAllocator, graphBlocks ); + b2FreeStackItem( &world->stackAllocator, jointBlocks ); + b2FreeStackItem( &world->stackAllocator, contactBlocks ); + b2FreeStackItem( &world->stackAllocator, bodyBlocks ); + b2FreeStackItem( &world->stackAllocator, stages ); + b2FreeStackItem( &world->stackAllocator, overflowContactConstraints ); + b2FreeStackItem( &world->stackAllocator, simdContactConstraints ); + b2FreeStackItem( &world->stackAllocator, joints ); + b2FreeStackItem( &world->stackAllocator, contacts ); } - b2TracyCZoneEnd(graph_solver); - world->profile.solveConstraints = b2GetMillisecondsAndReset(&timer); + b2TracyCZoneEnd( graph_solver ); + world->profile.solveConstraints = b2GetMillisecondsAndReset( &timer ); // Report hit events // todo perhaps optimize this with a bitset { - B2_ASSERT(b2Array(world->contactHitArray).count == 0); + B2_ASSERT( b2Array( world->contactHitArray ).count == 0 ); float threshold = world->hitEventThreshold; b2GraphColor* colors = world->constraintGraph.colors; - for (int i = 0; i < b2_graphColorCount; ++i) + for ( int i = 0; i < b2_graphColorCount; ++i ) { b2GraphColor* color = colors + i; int contactCount = color->contacts.count; b2ContactSim* contactSims = color->contacts.data; - for (int j = 0; j < contactCount; ++j) + for ( int j = 0; j < contactCount; ++j ) { b2ContactSim* contactSim = contactSims + j; - if ((contactSim->simFlags & b2_simEnableHitEvent) == 0) + if ( ( contactSim->simFlags & b2_simEnableHitEvent ) == 0 ) { continue; } - b2ContactHitEvent event = {0}; + b2ContactHitEvent event = { 0 }; event.approachSpeed = threshold; bool hit = false; int pointCount = contactSim->manifold.pointCount; - for (int k = 0; k < pointCount; ++k) + for ( int k = 0; k < pointCount; ++k ) { b2ManifoldPoint* mp = contactSim->manifold.points + k; float approachSpeed = -mp->normalVelocity; - if (approachSpeed > event.approachSpeed && mp->normalImpulse > 0.0f) + if ( approachSpeed > event.approachSpeed && mp->normalImpulse > 0.0f ) { event.approachSpeed = approachSpeed; event.point = mp->point; @@ -1703,45 +1704,45 @@ void b2Solve(b2World* world, b2StepContext* stepContext) } } - if (hit == true) + if ( hit == true ) { event.normal = contactSim->manifold.normal; - b2CheckId(world->shapeArray, contactSim->shapeIdA); - b2CheckId(world->shapeArray, contactSim->shapeIdB); + b2CheckId( world->shapeArray, contactSim->shapeIdA ); + b2CheckId( world->shapeArray, contactSim->shapeIdB ); b2Shape* shapeA = world->shapeArray + contactSim->shapeIdA; b2Shape* shapeB = world->shapeArray + contactSim->shapeIdB; - event.shapeIdA = (b2ShapeId){shapeA->id + 1, world->worldId, shapeA->revision}; - event.shapeIdB = (b2ShapeId){shapeB->id + 1, world->worldId, shapeB->revision}; + event.shapeIdA = ( b2ShapeId ){ shapeA->id + 1, world->worldId, shapeA->revision }; + event.shapeIdB = ( b2ShapeId ){ shapeB->id + 1, world->worldId, shapeB->revision }; - b2Array_Push(world->contactHitArray, event); + b2Array_Push( world->contactHitArray, event ); } } } } - world->profile.hitEvents = b2GetMillisecondsAndReset(&timer); + world->profile.hitEvents = b2GetMillisecondsAndReset( &timer ); // Finish the user tree task that was queued earlier in the time step. This must be complete before touching the broad-phase. - if (world->userTreeTask != NULL) + if ( world->userTreeTask != NULL ) { - world->finishTaskFcn(world->userTreeTask, world->userTaskContext); + world->finishTaskFcn( world->userTreeTask, world->userTaskContext ); world->userTreeTask = NULL; world->activeTaskCount -= 1; } - b2ValidateNoEnlarged(&world->broadPhase); + b2ValidateNoEnlarged( &world->broadPhase ); - b2TracyCZoneNC(broad_phase, "Broadphase", b2_colorPurple, true); + b2TracyCZoneNC( broad_phase, "Broadphase", b2_colorPurple, true ); - b2TracyCZoneNC(enlarge_proxies, "Enlarge Proxies", b2_colorDarkTurquoise, true); + b2TracyCZoneNC( enlarge_proxies, "Enlarge Proxies", b2_colorDarkTurquoise, true ); // Gather bits for all sim bodies that have enlarged AABBs b2BitSet* simBitSet = &world->taskContextArray[0].enlargedSimBitSet; - for (int i = 1; i < world->workerCount; ++i) + for ( int i = 1; i < world->workerCount; ++i ) { - b2InPlaceUnion(simBitSet, &world->taskContextArray[i].enlargedSimBitSet); + b2InPlaceUnion( simBitSet, &world->taskContextArray[i].enlargedSimBitSet ); } // Enlarge broad-phase proxies and build move array @@ -1752,69 +1753,70 @@ void b2Solve(b2World* world, b2StepContext* stepContext) b2Shape* shapes = world->shapeArray; uint32_t wordCount = simBitSet->blockCount; uint64_t* bits = simBitSet->bits; - for (uint32_t k = 0; k < wordCount; ++k) + for ( uint32_t k = 0; k < wordCount; ++k ) { uint64_t word = bits[k]; - while (word != 0) + while ( word != 0 ) { - uint32_t ctz = b2CTZ64(word); + uint32_t ctz = b2CTZ64( word ); uint32_t bodySimIndex = 64 * k + ctz; // cache misses - B2_ASSERT(bodySimIndex < awakeSet->sims.count); + B2_ASSERT( bodySimIndex < awakeSet->sims.count ); b2BodySim* bodySim = awakeSet->sims.data + bodySimIndex; - b2CheckIndex(world->bodyArray, bodySim->bodyId); + b2CheckIndex( world->bodyArray, bodySim->bodyId ); b2Body* body = world->bodyArray + bodySim->bodyId; int shapeId = body->headShapeId; - while (shapeId != B2_NULL_INDEX) + while ( shapeId != B2_NULL_INDEX ) { - b2CheckId(shapes, shapeId); + b2CheckId( shapes, shapeId ); b2Shape* shape = shapes + shapeId; - if (shape->enlargedAABB) + if ( shape->enlargedAABB ) { - B2_ASSERT(shape->isFast == false); + B2_ASSERT( shape->isFast == false ); - b2BroadPhase_EnlargeProxy(broadPhase, shape->proxyKey, shape->fatAABB); + b2BroadPhase_EnlargeProxy( broadPhase, shape->proxyKey, shape->fatAABB ); shape->enlargedAABB = false; } - else if (shape->isFast) + else if ( shape->isFast ) { // Shape is fast. It's aabb will be enlarged in continuous collision. - b2BufferMove(broadPhase, shape->proxyKey); + b2BufferMove( broadPhase, shape->proxyKey ); } shapeId = shape->nextShapeId; } // Clear the smallest set bit - word = word & (word - 1); + word = word & ( word - 1 ); } } } - b2TracyCZoneEnd(enlarge_proxies); + b2TracyCZoneEnd( enlarge_proxies ); - b2ValidateBroadphase(&world->broadPhase); + b2ValidateBroadphase( &world->broadPhase ); - world->profile.broadphase = b2GetMillisecondsAndReset(&timer); + world->profile.broadphase = b2GetMillisecondsAndReset( &timer ); - b2TracyCZoneEnd(broad_phase); + b2TracyCZoneEnd( broad_phase ); - b2TracyCZoneNC(continuous_collision, "Continuous", b2_colorDarkGoldenrod, true); + b2TracyCZoneNC( continuous_collision, "Continuous", b2_colorDarkGoldenrod, true ); // Parallel continuous collision + if ( stepContext->fastBodyCount > 0 ) { // fast bodies int minRange = 8; void* userFastBodyTask = - world->enqueueTaskFcn(&b2FastBodyTask, stepContext->fastBodyCount, minRange, stepContext, world->userTaskContext); + world->enqueueTaskFcn( &b2FastBodyTask, stepContext->fastBodyCount, minRange, stepContext, world->userTaskContext ); world->taskCount += 1; - if (userFastBodyTask != NULL) + if ( userFastBodyTask != NULL ) { - world->finishTaskFcn(userFastBodyTask, world->userTaskContext); + world->finishTaskFcn( userFastBodyTask, world->userTaskContext ); } } @@ -1830,11 +1832,11 @@ void b2Solve(b2World* world, b2StepContext* stepContext) int fastBodyCount = stepContext->fastBodyCount; // This loop has non-deterministic order but it shouldn't affect the result - for (int i = 0; i < fastBodyCount; ++i) + for ( int i = 0; i < fastBodyCount; ++i ) { - B2_ASSERT(0 <= fastBodies[i] && fastBodies[i] < awakeSet->sims.count); + B2_ASSERT( 0 <= fastBodies[i] && fastBodies[i] < awakeSet->sims.count ); b2BodySim* fastBodySim = awakeSet->sims.data + fastBodies[i]; - if (fastBodySim->enlargeAABB == false) + if ( fastBodySim->enlargeAABB == false ) { continue; } @@ -1842,14 +1844,14 @@ void b2Solve(b2World* world, b2StepContext* stepContext) // clear flag fastBodySim->enlargeAABB = false; - b2CheckIndex(bodies, fastBodySim->bodyId); + b2CheckIndex( bodies, fastBodySim->bodyId ); b2Body* fastBody = bodies + fastBodySim->bodyId; int shapeId = fastBody->headShapeId; - while (shapeId != B2_NULL_INDEX) + while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = shapes + shapeId; - if (shape->enlargedAABB == false) + if ( shape->enlargedAABB == false ) { shapeId = shape->nextShapeId; continue; @@ -1859,28 +1861,29 @@ void b2Solve(b2World* world, b2StepContext* stepContext) shape->enlargedAABB = false; int proxyKey = shape->proxyKey; - int proxyId = B2_PROXY_ID(proxyKey); - B2_ASSERT(B2_PROXY_TYPE(proxyKey) == b2_dynamicBody); + int proxyId = B2_PROXY_ID( proxyKey ); + B2_ASSERT( B2_PROXY_TYPE( proxyKey ) == b2_dynamicBody ); // all fast shapes should already be in the move buffer - B2_ASSERT(b2ContainsKey(&broadPhase->moveSet, proxyKey + 1)); + B2_ASSERT( b2ContainsKey( &broadPhase->moveSet, proxyKey + 1 ) ); - b2DynamicTree_EnlargeProxy(dynamicTree, proxyId, shape->fatAABB); + b2DynamicTree_EnlargeProxy( dynamicTree, proxyId, shape->fatAABB ); shapeId = shape->nextShapeId; } } } + if ( stepContext->bulletBodyCount > 0 ) { // bullet bodies int minRange = 8; - void* userBulletBodyTask = - world->enqueueTaskFcn(&b2BulletBodyTask, stepContext->bulletBodyCount, minRange, stepContext, world->userTaskContext); + void* userBulletBodyTask = world->enqueueTaskFcn( &b2BulletBodyTask, stepContext->bulletBodyCount, minRange, stepContext, + world->userTaskContext ); world->taskCount += 1; - if (userBulletBodyTask != NULL) + if ( userBulletBodyTask != NULL ) { - world->finishTaskFcn(userBulletBodyTask, world->userTaskContext); + world->finishTaskFcn( userBulletBodyTask, world->userTaskContext ); } } @@ -1896,11 +1899,11 @@ void b2Solve(b2World* world, b2StepContext* stepContext) int bulletBodyCount = stepContext->bulletBodyCount; // This loop has non-deterministic order but it shouldn't affect the result - for (int i = 0; i < bulletBodyCount; ++i) + for ( int i = 0; i < bulletBodyCount; ++i ) { - B2_ASSERT(0 <= bulletBodies[i] && bulletBodies[i] < awakeSet->sims.count); + B2_ASSERT( 0 <= bulletBodies[i] && bulletBodies[i] < awakeSet->sims.count ); b2BodySim* bulletBodySim = awakeSet->sims.data + bulletBodies[i]; - if (bulletBodySim->enlargeAABB == false) + if ( bulletBodySim->enlargeAABB == false ) { continue; } @@ -1908,14 +1911,14 @@ void b2Solve(b2World* world, b2StepContext* stepContext) // clear flag bulletBodySim->enlargeAABB = false; - b2CheckIndex(bodies, bulletBodySim->bodyId); + b2CheckIndex( bodies, bulletBodySim->bodyId ); b2Body* bulletBody = bodies + bulletBodySim->bodyId; int shapeId = bulletBody->headShapeId; - while (shapeId != B2_NULL_INDEX) + while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = shapes + shapeId; - if (shape->enlargedAABB == false) + if ( shape->enlargedAABB == false ) { shapeId = shape->nextShapeId; continue; @@ -1925,44 +1928,44 @@ void b2Solve(b2World* world, b2StepContext* stepContext) shape->enlargedAABB = false; int proxyKey = shape->proxyKey; - int proxyId = B2_PROXY_ID(proxyKey); - B2_ASSERT(B2_PROXY_TYPE(proxyKey) == b2_dynamicBody); + int proxyId = B2_PROXY_ID( proxyKey ); + B2_ASSERT( B2_PROXY_TYPE( proxyKey ) == b2_dynamicBody ); // all fast shapes should already be in the move buffer - B2_ASSERT(b2ContainsKey(&broadPhase->moveSet, proxyKey + 1)); + B2_ASSERT( b2ContainsKey( &broadPhase->moveSet, proxyKey + 1 ) ); - b2DynamicTree_EnlargeProxy(dynamicTree, proxyId, shape->fatAABB); + b2DynamicTree_EnlargeProxy( dynamicTree, proxyId, shape->fatAABB ); shapeId = shape->nextShapeId; } } } - b2TracyCZoneEnd(continuous_collision); + b2TracyCZoneEnd( continuous_collision ); - b2FreeStackItem(&world->stackAllocator, stepContext->bulletBodies); + b2FreeStackItem( &world->stackAllocator, stepContext->bulletBodies ); stepContext->bulletBodies = NULL; stepContext->bulletBodyCount = 0; - b2FreeStackItem(&world->stackAllocator, stepContext->fastBodies); + b2FreeStackItem( &world->stackAllocator, stepContext->fastBodies ); stepContext->fastBodies = NULL; stepContext->fastBodyCount = 0; - world->profile.continuous = b2GetMillisecondsAndReset(&timer); + world->profile.continuous = b2GetMillisecondsAndReset( &timer ); // Island sleeping // This must be done last because putting islands to sleep invalidates the enlarged body bits. - if (world->enableSleep == true) + if ( world->enableSleep == true ) { - b2TracyCZoneNC(sleep_islands, "Island Sleep", b2_colorGainsboro, true); + b2TracyCZoneNC( sleep_islands, "Island Sleep", b2_colorGainsboro, true ); // Collect split island candidate for the next time step. No need to split if sleeping is disabled. - B2_ASSERT(world->splitIslandId == B2_NULL_INDEX); + B2_ASSERT( world->splitIslandId == B2_NULL_INDEX ); float splitSleepTimer = 0.0f; - for (int i = 0; i < world->workerCount; ++i) + for ( int i = 0; i < world->workerCount; ++i ) { b2TaskContext* taskContext = world->taskContextArray + i; - if (taskContext->splitIslandId != B2_NULL_INDEX && taskContext->splitSleepTime > splitSleepTimer) + if ( taskContext->splitIslandId != B2_NULL_INDEX && taskContext->splitSleepTime > splitSleepTimer ) { world->splitIslandId = taskContext->splitIslandId; splitSleepTimer = taskContext->splitSleepTime; @@ -1970,17 +1973,17 @@ void b2Solve(b2World* world, b2StepContext* stepContext) } b2BitSet* awakeIslandBitSet = &world->taskContextArray[0].awakeIslandBitSet; - for (int i = 1; i < world->workerCount; ++i) + for ( int i = 1; i < world->workerCount; ++i ) { - b2InPlaceUnion(awakeIslandBitSet, &world->taskContextArray[i].awakeIslandBitSet); + b2InPlaceUnion( awakeIslandBitSet, &world->taskContextArray[i].awakeIslandBitSet ); } // Need to process in reverse because this moves islands to sleeping solver sets. b2IslandSim* islands = awakeSet->islands.data; int count = awakeSet->islands.count; - for (int islandIndex = count - 1; islandIndex >= 0; islandIndex -= 1) + for ( int islandIndex = count - 1; islandIndex >= 0; islandIndex -= 1 ) { - if (b2GetBit(awakeIslandBitSet, islandIndex) == true) + if ( b2GetBit( awakeIslandBitSet, islandIndex ) == true ) { // this island is still awake continue; @@ -1989,14 +1992,14 @@ void b2Solve(b2World* world, b2StepContext* stepContext) b2IslandSim* island = islands + islandIndex; int islandId = island->islandId; - b2TrySleepIsland(world, islandId); + b2TrySleepIsland( world, islandId ); } - b2ValidateSolverSets(world); + b2ValidateSolverSets( world ); - b2TracyCZoneEnd(sleep_islands); + b2TracyCZoneEnd( sleep_islands ); } - world->profile.sleepIslands = b2GetMillisecondsAndReset(&timer); - b2TracyCZoneEnd(solve); + world->profile.sleepIslands = b2GetMillisecondsAndReset( &timer ); + b2TracyCZoneEnd( solve ); } diff --git a/src/solver.h b/src/solver.h index 1a8de395..2de83838 100644 --- a/src/solver.h +++ b/src/solver.h @@ -141,18 +141,18 @@ typedef struct b2StepContext } b2StepContext; -static inline b2Softness b2MakeSoft(float hertz, float zeta, float h) +static inline b2Softness b2MakeSoft( float hertz, float zeta, float h ) { - if (hertz == 0.0f) + if ( hertz == 0.0f ) { - return (b2Softness){0.0f, 1.0f, 0.0f}; + return ( b2Softness ){ 0.0f, 1.0f, 0.0f }; } float omega = 2.0f * b2_pi * hertz; float a1 = 2.0f * zeta + h * omega; float a2 = h * omega * a1; - float a3 = 1.0f / (1.0f + a2); - return (b2Softness){omega / a1, a2 * a3, a3}; + float a3 = 1.0f / ( 1.0f + a2 ); + return ( b2Softness ){ omega / a1, a2 * a3, a3 }; } -void b2Solve(b2World* world, b2StepContext* stepContext); +void b2Solve( b2World* world, b2StepContext* stepContext ); diff --git a/src/solver_set.c b/src/solver_set.c index 865723d8..c0624b94 100644 --- a/src/solver_set.c +++ b/src/solver_set.c @@ -13,16 +13,16 @@ #include -void b2DestroySolverSet(b2World* world, int setIndex) +void b2DestroySolverSet( b2World* world, int setIndex ) { b2SolverSet* set = world->solverSetArray + setIndex; - b2DestroyBodySimArray(&set->sims); - b2DestroyBodyStateArray(&set->states); - b2DestroyContactArray(&set->contacts); - b2DestroyJointArray(&set->joints); - b2DestroyIslandArray(&set->islands); - b2FreeId(&world->solverSetIdPool, setIndex); - *set = (b2SolverSet){0}; + b2DestroyBodySimArray( &set->sims ); + b2DestroyBodyStateArray( &set->states ); + b2DestroyContactArray( &set->contacts ); + b2DestroyJointArray( &set->joints ); + b2DestroyIslandArray( &set->islands ); + b2FreeId( &world->solverSetIdPool, setIndex ); + *set = ( b2SolverSet ){ 0 }; set->setIndex = B2_NULL_INDEX; } @@ -32,10 +32,10 @@ void b2DestroySolverSet(b2World* world, int setIndex) // 2. non-touching contacts already in the awake set // 3. touching contacts in the sleeping set // This handles contact types 1 and 3. Type 2 doesn't need any action. -void b2WakeSolverSet(b2World* world, int setIndex) +void b2WakeSolverSet( b2World* world, int setIndex ) { - B2_ASSERT(setIndex >= b2_firstSleepingSet); - b2CheckIndex(world->solverSetArray, setIndex); + B2_ASSERT( setIndex >= b2_firstSleepingSet ); + b2CheckIndex( world->solverSetArray, setIndex ); b2SolverSet* set = world->solverSetArray + setIndex; b2SolverSet* awakeSet = world->solverSetArray + b2_awakeSet; b2SolverSet* disabledSet = world->solverSetArray + b2_disabledSet; @@ -44,61 +44,61 @@ void b2WakeSolverSet(b2World* world, int setIndex) b2Contact* contacts = world->contactArray; int bodyCount = set->sims.count; - for (int i = 0; i < bodyCount; ++i) + for ( int i = 0; i < bodyCount; ++i ) { b2BodySim* simSrc = set->sims.data + i; b2Body* body = bodies + simSrc->bodyId; - B2_ASSERT(body->setIndex == setIndex); + B2_ASSERT( body->setIndex == setIndex ); body->setIndex = b2_awakeSet; body->localIndex = awakeSet->sims.count; // Reset sleep timer body->sleepTime = 0.0f; - b2BodySim* simDst = b2AddBodySim(&awakeSet->sims); - memcpy(simDst, simSrc, sizeof(b2BodySim)); + b2BodySim* simDst = b2AddBodySim( &awakeSet->sims ); + memcpy( simDst, simSrc, sizeof( b2BodySim ) ); - b2BodyState* state = b2AddBodyState(&awakeSet->states); + b2BodyState* state = b2AddBodyState( &awakeSet->states ); *state = b2_identityBodyState; // move non-touching contacts from disabled set to awake set int contactKey = body->headContactKey; - while (contactKey != B2_NULL_INDEX) + while ( contactKey != B2_NULL_INDEX ) { int edgeIndex = contactKey & 1; int contactId = contactKey >> 1; - b2CheckIndex(contacts, contactId); + b2CheckIndex( contacts, contactId ); b2Contact* contact = contacts + contactId; contactKey = contact->edges[edgeIndex].nextKey; - if (contact->setIndex != b2_disabledSet) + if ( contact->setIndex != b2_disabledSet ) { - B2_ASSERT(contact->setIndex == b2_awakeSet || contact->setIndex == setIndex); + B2_ASSERT( contact->setIndex == b2_awakeSet || contact->setIndex == setIndex ); continue; } int localIndex = contact->localIndex; - B2_ASSERT(0 <= localIndex && localIndex < disabledSet->contacts.count); + B2_ASSERT( 0 <= localIndex && localIndex < disabledSet->contacts.count ); b2ContactSim* contactSim = disabledSet->contacts.data + localIndex; - B2_ASSERT((contact->flags & b2_contactTouchingFlag) == 0 && contactSim->manifold.pointCount == 0); + B2_ASSERT( ( contact->flags & b2_contactTouchingFlag ) == 0 && contactSim->manifold.pointCount == 0 ); contact->setIndex = b2_awakeSet; contact->localIndex = awakeSet->contacts.count; - b2ContactSim* awakeContactSim = b2AddContact(&awakeSet->contacts); - memcpy(awakeContactSim, contactSim, sizeof(b2ContactSim)); + b2ContactSim* awakeContactSim = b2AddContact( &awakeSet->contacts ); + memcpy( awakeContactSim, contactSim, sizeof( b2ContactSim ) ); - int movedLocalIndex = b2RemoveContact(&disabledSet->contacts, localIndex); - if (movedLocalIndex != B2_NULL_INDEX) + int movedLocalIndex = b2RemoveContact( &disabledSet->contacts, localIndex ); + if ( movedLocalIndex != B2_NULL_INDEX ) { // fix moved element b2ContactSim* movedContact = disabledSet->contacts.data + localIndex; int movedId = movedContact->contactId; - b2CheckIndex(contacts, movedId); - B2_ASSERT(contacts[movedId].localIndex == movedLocalIndex); + b2CheckIndex( contacts, movedId ); + B2_ASSERT( contacts[movedId].localIndex == movedLocalIndex ); contacts[movedId].localIndex = localIndex; } } @@ -107,15 +107,15 @@ void b2WakeSolverSet(b2World* world, int setIndex) // transfer touching contacts from sleeping set to contact graph { int contactCount = set->contacts.count; - for (int i = 0; i < contactCount; ++i) + for ( int i = 0; i < contactCount; ++i ) { b2ContactSim* contactSim = set->contacts.data + i; b2Contact* contact = contacts + contactSim->contactId; - B2_ASSERT(contact->flags & b2_contactTouchingFlag); - B2_ASSERT(contactSim->simFlags & b2_simTouchingFlag); - B2_ASSERT(contactSim->manifold.pointCount > 0); - B2_ASSERT(contact->setIndex == setIndex); - b2AddContactToGraph(world, contactSim, contact); + B2_ASSERT( contact->flags & b2_contactTouchingFlag ); + B2_ASSERT( contactSim->simFlags & b2_simTouchingFlag ); + B2_ASSERT( contactSim->manifold.pointCount > 0 ); + B2_ASSERT( contact->setIndex == setIndex ); + b2AddContactToGraph( world, contactSim, contact ); contact->setIndex = b2_awakeSet; } } @@ -124,12 +124,12 @@ void b2WakeSolverSet(b2World* world, int setIndex) { b2Joint* joints = world->jointArray; int jointCount = set->joints.count; - for (int i = 0; i < jointCount; ++i) + for ( int i = 0; i < jointCount; ++i ) { b2JointSim* jointSim = set->joints.data + i; b2Joint* joint = joints + jointSim->jointId; - B2_ASSERT(joint->setIndex == setIndex); - b2AddJointToGraph(world, jointSim, joint); + B2_ASSERT( joint->setIndex == setIndex ); + b2AddJointToGraph( world, jointSim, joint ); joint->setIndex = b2_awakeSet; } } @@ -141,32 +141,32 @@ void b2WakeSolverSet(b2World* world, int setIndex) { b2Island* islands = world->islandArray; int islandCount = set->islands.count; - for (int i = 0; i < islandCount; ++i) + for ( int i = 0; i < islandCount; ++i ) { b2IslandSim* islandSrc = set->islands.data + i; - b2CheckIndex(islands, islandSrc->islandId); + b2CheckIndex( islands, islandSrc->islandId ); b2Island* island = islands + islandSrc->islandId; island->setIndex = b2_awakeSet; island->localIndex = awakeSet->islands.count; - b2IslandSim* islandDst = b2AddIsland(&awakeSet->islands); - memcpy(islandDst, islandSrc, sizeof(b2IslandSim)); + b2IslandSim* islandDst = b2AddIsland( &awakeSet->islands ); + memcpy( islandDst, islandSrc, sizeof( b2IslandSim ) ); } } // destroy the sleeping set - b2DestroySolverSet(world, setIndex); + b2DestroySolverSet( world, setIndex ); - b2ValidateSolverSets(world); + b2ValidateSolverSets( world ); } -void b2TrySleepIsland(b2World* world, int islandId) +void b2TrySleepIsland( b2World* world, int islandId ) { - b2CheckIndex(world->islandArray, islandId); + b2CheckIndex( world->islandArray, islandId ); b2Island* island = world->islandArray + islandId; - B2_ASSERT(island->setIndex == b2_awakeSet); + B2_ASSERT( island->setIndex == b2_awakeSet ); // cannot put an island to sleep while it has a pending split - if (island->constraintRemoveCount > 0) + if ( island->constraintRemoveCount > 0 ) { return; } @@ -179,25 +179,25 @@ void b2TrySleepIsland(b2World* world, int islandId) // - identify non-touching contacts that should move to sleeping solver set or disabled set // - remove old island // - fix island - int sleepSetId = b2AllocId(&world->solverSetIdPool); - if (sleepSetId == b2Array(world->solverSetArray).count) + int sleepSetId = b2AllocId( &world->solverSetIdPool ); + if ( sleepSetId == b2Array( world->solverSetArray ).count ) { - b2SolverSet set = {0}; + b2SolverSet set = { 0 }; set.setIndex = B2_NULL_INDEX; - b2Array_Push(world->solverSetArray, set); + b2Array_Push( world->solverSetArray, set ); } b2SolverSet* sleepSet = world->solverSetArray + sleepSetId; - *sleepSet = (b2SolverSet){0}; + *sleepSet = ( b2SolverSet ){ 0 }; // grab awake set after creating the sleep set because the solver set array may have been resized b2SolverSet* awakeSet = world->solverSetArray + b2_awakeSet; - B2_ASSERT(0 <= island->localIndex && island->localIndex < awakeSet->islands.count); + B2_ASSERT( 0 <= island->localIndex && island->localIndex < awakeSet->islands.count ); sleepSet->setIndex = sleepSetId; - sleepSet->sims = b2CreateBodySimArray(island->bodyCount); - sleepSet->contacts = b2CreateContactArray(island->contactCount); - sleepSet->joints = b2CreateJointArray(island->jointCount); + sleepSet->sims = b2CreateBodySimArray( island->bodyCount ); + sleepSet->contacts = b2CreateContactArray( island->contactCount ); + sleepSet->joints = b2CreateJointArray( island->jointCount ); // move awake bodies to sleeping set // this shuffles around bodies in the awake set @@ -206,48 +206,48 @@ void b2TrySleepIsland(b2World* world, int islandId) b2Body* bodies = world->bodyArray; b2Contact* contacts = world->contactArray; int bodyId = island->headBody; - while (bodyId != B2_NULL_INDEX) + while ( bodyId != B2_NULL_INDEX ) { - b2CheckIndex(bodies, bodyId); + b2CheckIndex( bodies, bodyId ); b2Body* body = bodies + bodyId; - B2_ASSERT(body->setIndex == b2_awakeSet); - B2_ASSERT(body->islandId == islandId); - + B2_ASSERT( body->setIndex == b2_awakeSet ); + B2_ASSERT( body->islandId == islandId ); + // Update the body move event to indicate this body fell asleep // It could happen the body is forced asleep before it ever moves. - if (body->bodyMoveIndex != B2_NULL_INDEX) + if ( body->bodyMoveIndex != B2_NULL_INDEX ) { - b2CheckIndex(moveEvents, body->bodyMoveIndex); - B2_ASSERT(moveEvents[body->bodyMoveIndex].bodyId.index1 - 1 == bodyId); - B2_ASSERT(moveEvents[body->bodyMoveIndex].bodyId.revision == body->revision); + b2CheckIndex( moveEvents, body->bodyMoveIndex ); + B2_ASSERT( moveEvents[body->bodyMoveIndex].bodyId.index1 - 1 == bodyId ); + B2_ASSERT( moveEvents[body->bodyMoveIndex].bodyId.revision == body->revision ); moveEvents[body->bodyMoveIndex].fellAsleep = true; body->bodyMoveIndex = B2_NULL_INDEX; } - + int awakeBodyIndex = body->localIndex; - B2_ASSERT(0 <= awakeBodyIndex && awakeBodyIndex < awakeSet->sims.count); + B2_ASSERT( 0 <= awakeBodyIndex && awakeBodyIndex < awakeSet->sims.count ); b2BodySim* awakeSim = awakeSet->sims.data + awakeBodyIndex; // move body sim to sleep set int sleepBodyIndex = sleepSet->sims.count; - b2BodySim* sleepBodySim = b2AddBodySim(&sleepSet->sims); - memcpy(sleepBodySim, awakeSim, sizeof(b2BodySim)); + b2BodySim* sleepBodySim = b2AddBodySim( &sleepSet->sims ); + memcpy( sleepBodySim, awakeSim, sizeof( b2BodySim ) ); - int movedIndex = b2RemoveBodySim(&awakeSet->sims, awakeBodyIndex); - if (movedIndex != B2_NULL_INDEX) + int movedIndex = b2RemoveBodySim( &awakeSet->sims, awakeBodyIndex ); + if ( movedIndex != B2_NULL_INDEX ) { // fix local index on moved element b2BodySim* movedSim = awakeSet->sims.data + awakeBodyIndex; int movedId = movedSim->bodyId; - b2CheckIndex(bodies, movedId); + b2CheckIndex( bodies, movedId ); b2Body* movedBody = bodies + movedId; - B2_ASSERT(movedBody->localIndex == movedIndex); + B2_ASSERT( movedBody->localIndex == movedIndex ); movedBody->localIndex = awakeBodyIndex; } // destroy state, no need to clone - b2RemoveBodyState(&awakeSet->states, awakeBodyIndex); + b2RemoveBodyState( &awakeSet->states, awakeBodyIndex ); body->setIndex = sleepSetId; body->localIndex = sleepBodyIndex; @@ -255,27 +255,27 @@ void b2TrySleepIsland(b2World* world, int islandId) // Move non-touching contacts to the disabled set. // Non-touching contacts may exist between sleeping islands and there is no clear ownership. int contactKey = body->headContactKey; - while (contactKey != B2_NULL_INDEX) + while ( contactKey != B2_NULL_INDEX ) { int contactId = contactKey >> 1; int edgeIndex = contactKey & 1; - b2CheckIndex(contacts, contactId); + b2CheckIndex( contacts, contactId ); b2Contact* contact = contacts + contactId; - B2_ASSERT(contact->setIndex == b2_awakeSet || contact->setIndex == b2_disabledSet); + B2_ASSERT( contact->setIndex == b2_awakeSet || contact->setIndex == b2_disabledSet ); contactKey = contact->edges[edgeIndex].nextKey; - if (contact->setIndex == b2_disabledSet) + if ( contact->setIndex == b2_disabledSet ) { // already moved to disabled set by another body in the island continue; } - if (contact->colorIndex != B2_NULL_INDEX) + if ( contact->colorIndex != B2_NULL_INDEX ) { // contact is touching and will be moved separately - B2_ASSERT((contact->flags & b2_contactTouchingFlag) != 0); + B2_ASSERT( ( contact->flags & b2_contactTouchingFlag ) != 0 ); continue; } @@ -283,34 +283,34 @@ void b2TrySleepIsland(b2World* world, int islandId) // for moving this contact to the disabled set. int otherEdgeIndex = edgeIndex ^ 1; int otherBodyId = contact->edges[otherEdgeIndex].bodyId; - b2CheckIndex(bodies, otherBodyId); + b2CheckIndex( bodies, otherBodyId ); b2Body* otherBody = bodies + otherBodyId; - if (otherBody->setIndex == b2_awakeSet) + if ( otherBody->setIndex == b2_awakeSet ) { continue; } int localIndex = contact->localIndex; - B2_ASSERT(0 <= localIndex && localIndex < awakeSet->contacts.count); + B2_ASSERT( 0 <= localIndex && localIndex < awakeSet->contacts.count ); b2ContactSim* contactSim = awakeSet->contacts.data + localIndex; - B2_ASSERT(contactSim->manifold.pointCount == 0); - B2_ASSERT((contact->flags & b2_contactTouchingFlag) == 0 || (contact->flags & b2_contactSensorFlag) != 0); + B2_ASSERT( contactSim->manifold.pointCount == 0 ); + B2_ASSERT( ( contact->flags & b2_contactTouchingFlag ) == 0 || ( contact->flags & b2_contactSensorFlag ) != 0 ); // move the non-touching contact to the disabled set contact->setIndex = b2_disabledSet; contact->localIndex = disabledSet->contacts.count; - b2ContactSim* disabledContactSim = b2AddContact(&disabledSet->contacts); - memcpy(disabledContactSim, contactSim, sizeof(b2ContactSim)); + b2ContactSim* disabledContactSim = b2AddContact( &disabledSet->contacts ); + memcpy( disabledContactSim, contactSim, sizeof( b2ContactSim ) ); - int movedContactIndex = b2RemoveContact(&awakeSet->contacts, localIndex); - if (movedContactIndex != B2_NULL_INDEX) + int movedContactIndex = b2RemoveContact( &awakeSet->contacts, localIndex ); + if ( movedContactIndex != B2_NULL_INDEX ) { // fix moved element b2ContactSim* movedContactSim = awakeSet->contacts.data + localIndex; int movedId = movedContactSim->contactId; - b2CheckIndex(contacts, movedId); - B2_ASSERT(contacts[movedId].localIndex == movedContactIndex); + b2CheckIndex( contacts, movedId ); + B2_ASSERT( contacts[movedId].localIndex == movedContactIndex ); contacts[movedId].localIndex = localIndex; } } @@ -324,42 +324,42 @@ void b2TrySleepIsland(b2World* world, int islandId) { b2Contact* contacts = world->contactArray; int contactId = island->headContact; - while (contactId != B2_NULL_INDEX) + while ( contactId != B2_NULL_INDEX ) { - b2CheckIndex(contacts, contactId); + b2CheckIndex( contacts, contactId ); b2Contact* contact = contacts + contactId; - B2_ASSERT(contact->setIndex == b2_awakeSet); - B2_ASSERT(contact->islandId == islandId); + B2_ASSERT( contact->setIndex == b2_awakeSet ); + B2_ASSERT( contact->islandId == islandId ); int colorIndex = contact->colorIndex; - B2_ASSERT(0 <= colorIndex && colorIndex < b2_graphColorCount); + B2_ASSERT( 0 <= colorIndex && colorIndex < b2_graphColorCount ); b2GraphColor* color = world->constraintGraph.colors + colorIndex; // Remove bodies from graph coloring associated with this constraint - if (colorIndex != b2_overflowIndex) + if ( colorIndex != b2_overflowIndex ) { // might clear a bit for a static body, but this has no effect - b2ClearBit(&color->bodySet, contact->edges[0].bodyId); - b2ClearBit(&color->bodySet, contact->edges[1].bodyId); + b2ClearBit( &color->bodySet, contact->edges[0].bodyId ); + b2ClearBit( &color->bodySet, contact->edges[1].bodyId ); } int awakeContactIndex = contact->localIndex; - B2_ASSERT(0 <= awakeContactIndex && awakeContactIndex < color->contacts.count); + B2_ASSERT( 0 <= awakeContactIndex && awakeContactIndex < color->contacts.count ); b2ContactSim* awakeContactSim = color->contacts.data + awakeContactIndex; int sleepContactIndex = sleepSet->contacts.count; - b2ContactSim* sleepContactSim = b2AddContact(&sleepSet->contacts); - memcpy(sleepContactSim, awakeContactSim, sizeof(b2ContactSim)); + b2ContactSim* sleepContactSim = b2AddContact( &sleepSet->contacts ); + memcpy( sleepContactSim, awakeContactSim, sizeof( b2ContactSim ) ); - int movedIndex = b2RemoveContact(&color->contacts, awakeContactIndex); - if (movedIndex != B2_NULL_INDEX) + int movedIndex = b2RemoveContact( &color->contacts, awakeContactIndex ); + if ( movedIndex != B2_NULL_INDEX ) { // fix moved element b2ContactSim* movedContactSim = color->contacts.data + awakeContactIndex; int movedId = movedContactSim->contactId; - b2CheckIndex(contacts, movedId); + b2CheckIndex( contacts, movedId ); b2Contact* movedContact = contacts + movedId; - B2_ASSERT(movedContact->localIndex == movedIndex); + B2_ASSERT( movedContact->localIndex == movedIndex ); movedContact->localIndex = awakeContactIndex; } @@ -376,42 +376,42 @@ void b2TrySleepIsland(b2World* world, int islandId) { b2Joint* joints = world->jointArray; int jointId = island->headJoint; - while (jointId != B2_NULL_INDEX) + while ( jointId != B2_NULL_INDEX ) { - b2CheckIndex(joints, jointId); + b2CheckIndex( joints, jointId ); b2Joint* joint = joints + jointId; - B2_ASSERT(joint->setIndex == b2_awakeSet); - B2_ASSERT(joint->islandId == islandId); + B2_ASSERT( joint->setIndex == b2_awakeSet ); + B2_ASSERT( joint->islandId == islandId ); int colorIndex = joint->colorIndex; int localIndex = joint->localIndex; - B2_ASSERT(0 <= colorIndex && colorIndex < b2_graphColorCount); + B2_ASSERT( 0 <= colorIndex && colorIndex < b2_graphColorCount ); b2GraphColor* color = world->constraintGraph.colors + colorIndex; - B2_ASSERT(0 <= localIndex && localIndex < color->joints.count); + B2_ASSERT( 0 <= localIndex && localIndex < color->joints.count ); b2JointSim* awakeJointSim = color->joints.data + localIndex; - if (colorIndex != b2_overflowIndex) + if ( colorIndex != b2_overflowIndex ) { // might clear a bit for a static body, but this has no effect - b2ClearBit(&color->bodySet, joint->edges[0].bodyId); - b2ClearBit(&color->bodySet, joint->edges[1].bodyId); + b2ClearBit( &color->bodySet, joint->edges[0].bodyId ); + b2ClearBit( &color->bodySet, joint->edges[1].bodyId ); } int sleepJointIndex = sleepSet->joints.count; - b2JointSim* sleepJointSim = b2AddJoint(&sleepSet->joints); - memcpy(sleepJointSim, awakeJointSim, sizeof(b2JointSim)); + b2JointSim* sleepJointSim = b2AddJoint( &sleepSet->joints ); + memcpy( sleepJointSim, awakeJointSim, sizeof( b2JointSim ) ); - int movedIndex = b2RemoveJoint(&color->joints, localIndex); - if (movedIndex != B2_NULL_INDEX) + int movedIndex = b2RemoveJoint( &color->joints, localIndex ); + if ( movedIndex != B2_NULL_INDEX ) { // fix moved element b2JointSim* movedJointSim = color->joints.data + localIndex; int movedId = movedJointSim->jointId; - b2CheckIndex(joints, movedId); + b2CheckIndex( joints, movedId ); b2Joint* movedJoint = joints + movedId; - B2_ASSERT(movedJoint->localIndex == movedIndex); + B2_ASSERT( movedJoint->localIndex == movedIndex ); movedJoint->localIndex = localIndex; } @@ -425,21 +425,21 @@ void b2TrySleepIsland(b2World* world, int islandId) // move island struct { - B2_ASSERT(island->setIndex == b2_awakeSet); + B2_ASSERT( island->setIndex == b2_awakeSet ); int islandIndex = island->localIndex; - b2IslandSim* sleepIsland = b2AddIsland(&sleepSet->islands); + b2IslandSim* sleepIsland = b2AddIsland( &sleepSet->islands ); sleepIsland->islandId = islandId; - int movedIslandIndex = b2RemoveIsland(&awakeSet->islands, islandIndex); - if (movedIslandIndex != B2_NULL_INDEX) + int movedIslandIndex = b2RemoveIsland( &awakeSet->islands, islandIndex ); + if ( movedIslandIndex != B2_NULL_INDEX ) { // fix index on moved element b2IslandSim* movedIslandSim = awakeSet->islands.data + islandIndex; int movedIslandId = movedIslandSim->islandId; - b2CheckIndex(world->islandArray, movedIslandId); + b2CheckIndex( world->islandArray, movedIslandId ); b2Island* movedIsland = world->islandArray + movedIslandId; - B2_ASSERT(movedIsland->localIndex == movedIslandIndex); + B2_ASSERT( movedIsland->localIndex == movedIslandIndex ); movedIsland->localIndex = islandIndex; } @@ -447,23 +447,23 @@ void b2TrySleepIsland(b2World* world, int islandId) island->localIndex = 0; } - b2ValidateSolverSets(world); + b2ValidateSolverSets( world ); } // This is called when joints are created between sets. I want to allow the sets // to continue sleeping if both are asleep. Otherwise one set is waked. // Islands will get merge when the set is waked. -void b2MergeSolverSets(b2World* world, int setId1, int setId2) +void b2MergeSolverSets( b2World* world, int setId1, int setId2 ) { - B2_ASSERT(setId1 >= b2_firstSleepingSet); - B2_ASSERT(setId2 >= b2_firstSleepingSet); - b2CheckIndex(world->solverSetArray, setId1); - b2CheckIndex(world->solverSetArray, setId2); + B2_ASSERT( setId1 >= b2_firstSleepingSet ); + B2_ASSERT( setId2 >= b2_firstSleepingSet ); + b2CheckIndex( world->solverSetArray, setId1 ); + b2CheckIndex( world->solverSetArray, setId2 ); b2SolverSet* set1 = world->solverSetArray + setId1; b2SolverSet* set2 = world->solverSetArray + setId2; // Move the fewest number of bodies - if (set1->sims.count < set2->sims.count) + if ( set1->sims.count < set2->sims.count ) { b2SolverSet* tempSet = set1; set1 = set2; @@ -478,17 +478,17 @@ void b2MergeSolverSets(b2World* world, int setId1, int setId2) { b2Body* bodies = world->bodyArray; int bodyCount = set2->sims.count; - for (int i = 0; i < bodyCount; ++i) + for ( int i = 0; i < bodyCount; ++i ) { b2BodySim* simSrc = set2->sims.data + i; b2Body* body = bodies + simSrc->bodyId; - B2_ASSERT(body->setIndex == setId2); + B2_ASSERT( body->setIndex == setId2 ); body->setIndex = setId1; body->localIndex = set1->sims.count; - b2BodySim* simDst = b2AddBodySim(&set1->sims); - memcpy(simDst, simSrc, sizeof(b2BodySim)); + b2BodySim* simDst = b2AddBodySim( &set1->sims ); + memcpy( simDst, simSrc, sizeof( b2BodySim ) ); } } @@ -496,17 +496,17 @@ void b2MergeSolverSets(b2World* world, int setId1, int setId2) { b2Contact* contacts = world->contactArray; int contactCount = set2->contacts.count; - for (int i = 0; i < contactCount; ++i) + for ( int i = 0; i < contactCount; ++i ) { b2ContactSim* contactSrc = set2->contacts.data + i; b2Contact* contact = contacts + contactSrc->contactId; - B2_ASSERT(contact->setIndex == setId2); + B2_ASSERT( contact->setIndex == setId2 ); contact->setIndex = setId1; contact->localIndex = set1->contacts.count; - b2ContactSim* contactDst = b2AddContact(&set1->contacts); - memcpy(contactDst, contactSrc, sizeof(b2ContactSim)); + b2ContactSim* contactDst = b2AddContact( &set1->contacts ); + memcpy( contactDst, contactSrc, sizeof( b2ContactSim ) ); } } @@ -514,17 +514,17 @@ void b2MergeSolverSets(b2World* world, int setId1, int setId2) { b2Joint* joints = world->jointArray; int jointCount = set2->joints.count; - for (int i = 0; i < jointCount; ++i) + for ( int i = 0; i < jointCount; ++i ) { b2JointSim* jointSrc = set2->joints.data + i; b2Joint* joint = joints + jointSrc->jointId; - B2_ASSERT(joint->setIndex == setId2); + B2_ASSERT( joint->setIndex == setId2 ); joint->setIndex = setId1; joint->localIndex = set1->joints.count; - b2JointSim* jointDst = b2AddJoint(&set1->joints); - memcpy(jointDst, jointSrc, sizeof(b2JointSim)); + b2JointSim* jointDst = b2AddJoint( &set1->joints ); + memcpy( jointDst, jointSrc, sizeof( b2JointSim ) ); } } @@ -532,58 +532,58 @@ void b2MergeSolverSets(b2World* world, int setId1, int setId2) { b2Island* islands = world->islandArray; int islandCount = set2->islands.count; - for (int i = 0; i < islandCount; ++i) + for ( int i = 0; i < islandCount; ++i ) { b2IslandSim* islandSrc = set2->islands.data + i; int islandId = islandSrc->islandId; - b2CheckIndex(islands, islandId); + b2CheckIndex( islands, islandId ); b2Island* island = islands + islandId; island->setIndex = setId1; island->localIndex = set1->islands.count; - b2IslandSim* islandDst = b2AddIsland(&set1->islands); - memcpy(islandDst, islandSrc, sizeof(b2IslandSim)); + b2IslandSim* islandDst = b2AddIsland( &set1->islands ); + memcpy( islandDst, islandSrc, sizeof( b2IslandSim ) ); } } // destroy the merged set - b2DestroySolverSet(world, setId2); + b2DestroySolverSet( world, setId2 ); - b2ValidateSolverSets(world); + b2ValidateSolverSets( world ); } -void b2TransferBody(b2World* world, b2SolverSet* targetSet, b2SolverSet* sourceSet, b2Body* body) +void b2TransferBody( b2World* world, b2SolverSet* targetSet, b2SolverSet* sourceSet, b2Body* body ) { - B2_ASSERT(targetSet != sourceSet); + B2_ASSERT( targetSet != sourceSet ); int sourceIndex = body->localIndex; - B2_ASSERT(0 <= sourceIndex && sourceIndex <= sourceSet->sims.count); + B2_ASSERT( 0 <= sourceIndex && sourceIndex <= sourceSet->sims.count ); b2BodySim* sourceSim = sourceSet->sims.data + sourceIndex; int targetIndex = targetSet->sims.count; - b2BodySim* targetSim = b2AddBodySim(&targetSet->sims); - memcpy(targetSim, sourceSim, sizeof(b2BodySim)); + b2BodySim* targetSim = b2AddBodySim( &targetSet->sims ); + memcpy( targetSim, sourceSim, sizeof( b2BodySim ) ); // Remove body sim from solver set that owns it - int movedIndex = b2RemoveBodySim(&sourceSet->sims, sourceIndex); - if (movedIndex != B2_NULL_INDEX) + int movedIndex = b2RemoveBodySim( &sourceSet->sims, sourceIndex ); + if ( movedIndex != B2_NULL_INDEX ) { // Fix moved body index b2BodySim* movedSim = sourceSet->sims.data + sourceIndex; int movedId = movedSim->bodyId; b2Body* movedBody = world->bodyArray + movedId; - B2_ASSERT(movedBody->localIndex == movedIndex); + B2_ASSERT( movedBody->localIndex == movedIndex ); movedBody->localIndex = sourceIndex; } - if (sourceSet->setIndex == b2_awakeSet) + if ( sourceSet->setIndex == b2_awakeSet ) { - b2RemoveBodyState(&sourceSet->states, sourceIndex); + b2RemoveBodyState( &sourceSet->states, sourceIndex ); } - else if (targetSet->setIndex == b2_awakeSet) + else if ( targetSet->setIndex == b2_awakeSet ) { - b2BodyState* state = b2AddBodyState(&targetSet->states); + b2BodyState* state = b2AddBodyState( &targetSet->states ); *state = b2_identityBodyState; } @@ -591,34 +591,34 @@ void b2TransferBody(b2World* world, b2SolverSet* targetSet, b2SolverSet* sourceS body->localIndex = targetIndex; } -void b2TransferJoint(b2World* world, b2SolverSet* targetSet, b2SolverSet* sourceSet, b2Joint* joint) +void b2TransferJoint( b2World* world, b2SolverSet* targetSet, b2SolverSet* sourceSet, b2Joint* joint ) { - B2_ASSERT(targetSet != sourceSet); + B2_ASSERT( targetSet != sourceSet ); int localIndex = joint->localIndex; int colorIndex = joint->colorIndex; // Retrieve source. b2JointSim* sourceSim; - if (sourceSet->setIndex == b2_awakeSet) + if ( sourceSet->setIndex == b2_awakeSet ) { - B2_ASSERT(0 <= colorIndex && colorIndex < b2_graphColorCount); + B2_ASSERT( 0 <= colorIndex && colorIndex < b2_graphColorCount ); b2GraphColor* color = world->constraintGraph.colors + colorIndex; - B2_ASSERT(0 <= localIndex && localIndex < color->joints.count); + B2_ASSERT( 0 <= localIndex && localIndex < color->joints.count ); sourceSim = color->joints.data + localIndex; } else { - B2_ASSERT(colorIndex == B2_NULL_INDEX); - B2_ASSERT(0 <= localIndex && localIndex < sourceSet->joints.count); + B2_ASSERT( colorIndex == B2_NULL_INDEX ); + B2_ASSERT( 0 <= localIndex && localIndex < sourceSet->joints.count ); sourceSim = sourceSet->joints.data + localIndex; } // Create target and copy. Fix joint. - if (targetSet->setIndex == b2_awakeSet) + if ( targetSet->setIndex == b2_awakeSet ) { - b2AddJointToGraph(world, sourceSim, joint); + b2AddJointToGraph( world, sourceSim, joint ); joint->setIndex = b2_awakeSet; } else @@ -627,24 +627,24 @@ void b2TransferJoint(b2World* world, b2SolverSet* targetSet, b2SolverSet* source joint->localIndex = targetSet->joints.count; joint->colorIndex = B2_NULL_INDEX; - b2JointSim* targetSim = b2AddJoint(&targetSet->joints); - memcpy(targetSim, sourceSim, sizeof(b2JointSim)); + b2JointSim* targetSim = b2AddJoint( &targetSet->joints ); + memcpy( targetSim, sourceSim, sizeof( b2JointSim ) ); } // Destroy source. - if (sourceSet->setIndex == b2_awakeSet) + if ( sourceSet->setIndex == b2_awakeSet ) { - b2RemoveJointFromGraph(world, joint->edges[0].bodyId, joint->edges[1].bodyId, colorIndex, localIndex); + b2RemoveJointFromGraph( world, joint->edges[0].bodyId, joint->edges[1].bodyId, colorIndex, localIndex ); } else { - int movedIndex = b2RemoveJoint(&sourceSet->joints, localIndex); - if (movedIndex != B2_NULL_INDEX) + int movedIndex = b2RemoveJoint( &sourceSet->joints, localIndex ); + if ( movedIndex != B2_NULL_INDEX ) { // fix swapped element b2JointSim* movedJointSim = sourceSet->joints.data + localIndex; int movedId = movedJointSim->jointId; - b2CheckIndex(world->jointArray, movedId); + b2CheckIndex( world->jointArray, movedId ); b2Joint* movedJoint = world->jointArray + movedId; movedJoint->localIndex = localIndex; } diff --git a/src/solver_set.h b/src/solver_set.h index 7e0f3cab..5ed8e838 100644 --- a/src/solver_set.h +++ b/src/solver_set.h @@ -42,14 +42,14 @@ typedef struct b2SolverSet int setIndex; } b2SolverSet; -void b2DestroySolverSet(b2World* world, int setIndex); +void b2DestroySolverSet( b2World* world, int setIndex ); -void b2WakeSolverSet(b2World* world, int setIndex); -void b2TrySleepIsland(b2World* world, int islandId); +void b2WakeSolverSet( b2World* world, int setIndex ); +void b2TrySleepIsland( b2World* world, int islandId ); // Merge set 2 into set 1 then destroy set 2. // Warning: any pointers into these sets will be orphaned. -void b2MergeSolverSets(b2World* world, int setIndex1, int setIndex2); +void b2MergeSolverSets( b2World* world, int setIndex1, int setIndex2 ); -void b2TransferBody(b2World* world, b2SolverSet* targetSet, b2SolverSet* sourceSet, b2Body* body); -void b2TransferJoint(b2World* world, b2SolverSet* targetSet, b2SolverSet* sourceSet, b2Joint* joint); +void b2TransferBody( b2World* world, b2SolverSet* targetSet, b2SolverSet* sourceSet, b2Body* body ); +void b2TransferJoint( b2World* world, b2SolverSet* targetSet, b2SolverSet* sourceSet, b2Joint* joint ); diff --git a/src/stack_allocator.c b/src/stack_allocator.c index 279eb038..c7bb45a3 100644 --- a/src/stack_allocator.c +++ b/src/stack_allocator.c @@ -17,41 +17,40 @@ typedef struct b2StackEntry bool usedMalloc; } b2StackEntry; - -b2StackAllocator b2CreateStackAllocator(int capacity) +b2StackAllocator b2CreateStackAllocator( int capacity ) { - B2_ASSERT(capacity >= 0); - b2StackAllocator allocator = {0}; + B2_ASSERT( capacity >= 0 ); + b2StackAllocator allocator = { 0 }; allocator.capacity = capacity; - allocator.data = b2Alloc(capacity); + allocator.data = b2Alloc( capacity ); allocator.allocation = 0; allocator.maxAllocation = 0; allocator.index = 0; - allocator.entries = b2CreateArray(sizeof(b2StackEntry), 32); + allocator.entries = b2CreateArray( sizeof( b2StackEntry ), 32 ); return allocator; } -void b2DestroyStackAllocator(b2StackAllocator* allocator) +void b2DestroyStackAllocator( b2StackAllocator* allocator ) { - b2DestroyArray(allocator->entries, sizeof(b2StackEntry)); - b2Free(allocator->data, allocator->capacity); + b2DestroyArray( allocator->entries, sizeof( b2StackEntry ) ); + b2Free( allocator->data, allocator->capacity ); } -void* b2AllocateStackItem(b2StackAllocator* alloc, int size, const char* name) +void* b2AllocateStackItem( b2StackAllocator* alloc, int size, const char* name ) { // ensure allocation is 32 byte aligned to support 256-bit SIMD - int size32 = ((size - 1) | 0x1F) + 1; + int size32 = ( ( size - 1 ) | 0x1F ) + 1; b2StackEntry entry; entry.size = size32; entry.name = name; - if (alloc->index + size32 > alloc->capacity) + if ( alloc->index + size32 > alloc->capacity ) { // fall back to the heap (undesirable) - entry.data = b2Alloc(size32); + entry.data = b2Alloc( size32 ); entry.usedMalloc = true; - B2_ASSERT(((uintptr_t)entry.data & 0x1F) == 0); + B2_ASSERT( ( (uintptr_t)entry.data & 0x1F ) == 0 ); } else { @@ -59,61 +58,61 @@ void* b2AllocateStackItem(b2StackAllocator* alloc, int size, const char* name) entry.usedMalloc = false; alloc->index += size32; - B2_ASSERT(((uintptr_t)entry.data & 0x1F) == 0); + B2_ASSERT( ( (uintptr_t)entry.data & 0x1F ) == 0 ); } alloc->allocation += size32; - if (alloc->allocation > alloc->maxAllocation) + if ( alloc->allocation > alloc->maxAllocation ) { alloc->maxAllocation = alloc->allocation; } - b2Array_Push(alloc->entries, entry); + b2Array_Push( alloc->entries, entry ); return entry.data; } -void b2FreeStackItem(b2StackAllocator* alloc, void* mem) +void b2FreeStackItem( b2StackAllocator* alloc, void* mem ) { - int entryCount = b2Array(alloc->entries).count; - B2_ASSERT(entryCount > 0); - b2StackEntry* entry = alloc->entries + (entryCount - 1); - B2_ASSERT(mem == entry->data); - if (entry->usedMalloc) + int entryCount = b2Array( alloc->entries ).count; + B2_ASSERT( entryCount > 0 ); + b2StackEntry* entry = alloc->entries + ( entryCount - 1 ); + B2_ASSERT( mem == entry->data ); + if ( entry->usedMalloc ) { - b2Free(mem, entry->size); + b2Free( mem, entry->size ); } else { alloc->index -= entry->size; } alloc->allocation -= entry->size; - b2Array_Pop(alloc->entries); + b2Array_Pop( alloc->entries ); } -void b2GrowStack(b2StackAllocator* alloc) +void b2GrowStack( b2StackAllocator* alloc ) { // Stack must not be in use - B2_ASSERT(alloc->allocation == 0); + B2_ASSERT( alloc->allocation == 0 ); - if (alloc->maxAllocation > alloc->capacity) + if ( alloc->maxAllocation > alloc->capacity ) { - b2Free(alloc->data, alloc->capacity); + b2Free( alloc->data, alloc->capacity ); alloc->capacity = alloc->maxAllocation + alloc->maxAllocation / 2; - alloc->data = b2Alloc(alloc->capacity); + alloc->data = b2Alloc( alloc->capacity ); } } -int b2GetStackCapacity(b2StackAllocator* alloc) +int b2GetStackCapacity( b2StackAllocator* alloc ) { return alloc->capacity; } -int b2GetStackAllocation(b2StackAllocator* alloc) +int b2GetStackAllocation( b2StackAllocator* alloc ) { return alloc->allocation; } -int b2GetMaxStackAllocation(b2StackAllocator* alloc) +int b2GetMaxStackAllocation( b2StackAllocator* alloc ) { return alloc->maxAllocation; } diff --git a/src/stack_allocator.h b/src/stack_allocator.h index 1777d3ed..7d4fb05f 100644 --- a/src/stack_allocator.h +++ b/src/stack_allocator.h @@ -20,15 +20,15 @@ typedef struct b2StackAllocator struct b2StackEntry* entries; } b2StackAllocator; -b2StackAllocator b2CreateStackAllocator(int capacity); -void b2DestroyStackAllocator(b2StackAllocator* allocator); +b2StackAllocator b2CreateStackAllocator( int capacity ); +void b2DestroyStackAllocator( b2StackAllocator* allocator ); -void* b2AllocateStackItem(b2StackAllocator* alloc, int size, const char* name); -void b2FreeStackItem(b2StackAllocator* alloc, void* mem); +void* b2AllocateStackItem( b2StackAllocator* alloc, int size, const char* name ); +void b2FreeStackItem( b2StackAllocator* alloc, void* mem ); // Grow the stack based on usage -void b2GrowStack(b2StackAllocator* alloc); +void b2GrowStack( b2StackAllocator* alloc ); -int b2GetStackCapacity(b2StackAllocator* alloc); -int b2GetStackAllocation(b2StackAllocator* alloc); -int b2GetMaxStackAllocation(b2StackAllocator* alloc); +int b2GetStackCapacity( b2StackAllocator* alloc ); +int b2GetStackAllocation( b2StackAllocator* alloc ); +int b2GetMaxStackAllocation( b2StackAllocator* alloc ); diff --git a/src/table.c b/src/table.c index 0c395e22..46a22437 100644 --- a/src/table.c +++ b/src/table.c @@ -17,14 +17,14 @@ _Atomic int g_probeCount; // todo compare with https://github.com/skeeto/scratch/blob/master/set32/set32.h -b2HashSet b2CreateSet(int32_t capacity) +b2HashSet b2CreateSet( int32_t capacity ) { - b2HashSet set = {0}; + b2HashSet set = { 0 }; // Capacity must be a power of 2 - if (capacity > 16) + if ( capacity > 16 ) { - set.capacity = b2RoundUpPowerOf2(capacity); + set.capacity = b2RoundUpPowerOf2( capacity ); } else { @@ -32,24 +32,24 @@ b2HashSet b2CreateSet(int32_t capacity) } set.count = 0; - set.items = b2Alloc(capacity * sizeof(b2SetItem)); - memset(set.items, 0, capacity * sizeof(b2SetItem)); + set.items = b2Alloc( capacity * sizeof( b2SetItem ) ); + memset( set.items, 0, capacity * sizeof( b2SetItem ) ); return set; } -void b2DestroySet(b2HashSet* set) +void b2DestroySet( b2HashSet* set ) { - b2Free(set->items, set->capacity * sizeof(b2SetItem)); + b2Free( set->items, set->capacity * sizeof( b2SetItem ) ); set->items = NULL; set->count = 0; set->capacity = 0; } -void b2ClearSet(b2HashSet* set) +void b2ClearSet( b2HashSet* set ) { set->count = 0; - memset(set->items, 0, set->capacity * sizeof(b2SetItem)); + memset( set->items, 0, set->capacity * sizeof( b2SetItem ) ); } // I need a good hash because the keys are built from pairs of increasing integers. @@ -57,7 +57,7 @@ void b2ClearSet(b2HashSet* set) // https://lemire.me/blog/2018/08/15/fast-strongly-universal-64-bit-hashing-everywhere/ // https://preshing.com/20130107/this-hash-set-is-faster-than-a-judy-array/ // TODO_ERIN try: https://www.jandrewrogers.com/2019/02/12/fast-perfect-hashing/ -static inline uint32_t b2KeyHash(uint64_t key) +static inline uint32_t b2KeyHash( uint64_t key ) { uint64_t h = key; h ^= h >> 33; @@ -69,37 +69,37 @@ static inline uint32_t b2KeyHash(uint64_t key) return (uint32_t)h; } -int32_t b2FindSlot(const b2HashSet* set, uint64_t key, uint32_t hash) +int32_t b2FindSlot( const b2HashSet* set, uint64_t key, uint32_t hash ) { uint32_t capacity = set->capacity; - int32_t index = hash & (capacity - 1); + int32_t index = hash & ( capacity - 1 ); const b2SetItem* items = set->items; - while (items[index].hash != 0 && items[index].key != key) + while ( items[index].hash != 0 && items[index].key != key ) { #if B2_DEBUG - atomic_fetch_add(&g_probeCount, 1); + atomic_fetch_add( &g_probeCount, 1 ); #endif - index = (index + 1) & (capacity - 1); + index = ( index + 1 ) & ( capacity - 1 ); } return index; } -static void b2AddKeyHaveCapacity(b2HashSet* set, uint64_t key, uint32_t hash) +static void b2AddKeyHaveCapacity( b2HashSet* set, uint64_t key, uint32_t hash ) { - int32_t index = b2FindSlot(set, key, hash); + int32_t index = b2FindSlot( set, key, hash ); b2SetItem* items = set->items; - B2_ASSERT(items[index].hash == 0); + B2_ASSERT( items[index].hash == 0 ); items[index].key = key; items[index].hash = hash; set->count += 1; } -static void b2GrowTable(b2HashSet* set) +static void b2GrowTable( b2HashSet* set ) { uint32_t oldCount = set->count; - B2_MAYBE_UNUSED(oldCount); + B2_MAYBE_UNUSED( oldCount ); uint32_t oldCapacity = set->capacity; b2SetItem* oldItems = set->items; @@ -107,73 +107,73 @@ static void b2GrowTable(b2HashSet* set) set->count = 0; // Capacity must be a power of 2 set->capacity = 2 * oldCapacity; - set->items = b2Alloc(set->capacity * sizeof(b2SetItem)); - memset(set->items, 0, set->capacity * sizeof(b2SetItem)); + set->items = b2Alloc( set->capacity * sizeof( b2SetItem ) ); + memset( set->items, 0, set->capacity * sizeof( b2SetItem ) ); // Transfer items into new array - for (uint32_t i = 0; i < oldCapacity; ++i) + for ( uint32_t i = 0; i < oldCapacity; ++i ) { b2SetItem* item = oldItems + i; - if (item->hash == 0) + if ( item->hash == 0 ) { // this item was empty continue; } - b2AddKeyHaveCapacity(set, item->key, item->hash); + b2AddKeyHaveCapacity( set, item->key, item->hash ); } - B2_ASSERT(set->count == oldCount); + B2_ASSERT( set->count == oldCount ); - b2Free(oldItems, oldCapacity * sizeof(b2SetItem)); + b2Free( oldItems, oldCapacity * sizeof( b2SetItem ) ); } -bool b2ContainsKey(const b2HashSet* set, uint64_t key) +bool b2ContainsKey( const b2HashSet* set, uint64_t key ) { // key of zero is a sentinel - B2_ASSERT(key != 0); - uint32_t hash = b2KeyHash(key); - int32_t index = b2FindSlot(set, key, hash); + B2_ASSERT( key != 0 ); + uint32_t hash = b2KeyHash( key ); + int32_t index = b2FindSlot( set, key, hash ); return set->items[index].key == key; } -int b2GetHashSetBytes(b2HashSet* set) +int b2GetHashSetBytes( b2HashSet* set ) { - return set->capacity * (int)sizeof(b2SetItem); + return set->capacity * (int)sizeof( b2SetItem ); } -bool b2AddKey(b2HashSet* set, uint64_t key) +bool b2AddKey( b2HashSet* set, uint64_t key ) { // key of zero is a sentinel - B2_ASSERT(key != 0); + B2_ASSERT( key != 0 ); - uint32_t hash = b2KeyHash(key); - B2_ASSERT(hash != 0); + uint32_t hash = b2KeyHash( key ); + B2_ASSERT( hash != 0 ); - int32_t index = b2FindSlot(set, key, hash); - if (set->items[index].hash != 0) + int32_t index = b2FindSlot( set, key, hash ); + if ( set->items[index].hash != 0 ) { // Already in set - B2_ASSERT(set->items[index].hash == hash && set->items[index].key == key); + B2_ASSERT( set->items[index].hash == hash && set->items[index].key == key ); return true; } - if (2 * set->count >= set->capacity) + if ( 2 * set->count >= set->capacity ) { - b2GrowTable(set); + b2GrowTable( set ); } - b2AddKeyHaveCapacity(set, key, hash); + b2AddKeyHaveCapacity( set, key, hash ); return false; } // See https://en.wikipedia.org/wiki/Open_addressing -bool b2RemoveKey(b2HashSet* set, uint64_t key) +bool b2RemoveKey( b2HashSet* set, uint64_t key ) { - uint32_t hash = b2KeyHash(key); - int32_t i = b2FindSlot(set, key, hash); + uint32_t hash = b2KeyHash( key ); + int32_t i = b2FindSlot( set, key, hash ); b2SetItem* items = set->items; - if (items[i].hash == 0) + if ( items[i].hash == 0 ) { // Not in set return false; @@ -183,36 +183,36 @@ bool b2RemoveKey(b2HashSet* set, uint64_t key) items[i].key = 0; items[i].hash = 0; - B2_ASSERT(set->count > 0); + B2_ASSERT( set->count > 0 ); set->count -= 1; // Attempt to fill item i int32_t j = i; uint32_t capacity = set->capacity; - for (;;) + for ( ;; ) { - j = (j + 1) & (capacity - 1); - if (items[j].hash == 0) + j = ( j + 1 ) & ( capacity - 1 ); + if ( items[j].hash == 0 ) { break; } // k is the first item for the hash of j - int32_t k = items[j].hash & (capacity - 1); + int32_t k = items[j].hash & ( capacity - 1 ); // determine if k lies cyclically in (i,j] // i <= j: | i..k..j | // i > j: |.k..j i....| or |....j i..k.| - if (i <= j) + if ( i <= j ) { - if (i < k && k <= j) + if ( i < k && k <= j ) { continue; } } else { - if (i < k || k <= j) + if ( i < k || k <= j ) { continue; } diff --git a/src/table.h b/src/table.h index 9a3ba96b..04949949 100644 --- a/src/table.h +++ b/src/table.h @@ -6,7 +6,7 @@ #include #include -#define B2_SHAPE_PAIR_KEY(K1, K2) K1 < K2 ? (uint64_t)K1 << 32 | (uint64_t)K2 : (uint64_t)K2 << 32 | (uint64_t)K1 +#define B2_SHAPE_PAIR_KEY( K1, K2 ) K1 < K2 ? (uint64_t)K1 << 32 | (uint64_t)K2 : (uint64_t)K2 << 32 | (uint64_t)K1 typedef struct b2SetItem { @@ -21,17 +21,17 @@ typedef struct b2HashSet uint32_t count; } b2HashSet; -b2HashSet b2CreateSet(int32_t capacity); -void b2DestroySet(b2HashSet* set); +b2HashSet b2CreateSet( int32_t capacity ); +void b2DestroySet( b2HashSet* set ); -void b2ClearSet(b2HashSet* set); +void b2ClearSet( b2HashSet* set ); // Returns true if key was already in set -bool b2AddKey(b2HashSet* set, uint64_t key); +bool b2AddKey( b2HashSet* set, uint64_t key ); // Returns true if the key was found -bool b2RemoveKey(b2HashSet* set, uint64_t key); +bool b2RemoveKey( b2HashSet* set, uint64_t key ); -bool b2ContainsKey(const b2HashSet* set, uint64_t key); +bool b2ContainsKey( const b2HashSet* set, uint64_t key ); -int b2GetHashSetBytes(b2HashSet* set); +int b2GetHashSetBytes( b2HashSet* set ); diff --git a/src/timer.c b/src/timer.c index 05758fba..df2420ab 100644 --- a/src/timer.c +++ b/src/timer.c @@ -3,70 +3,70 @@ #include "box2d/base.h" -#if defined(_WIN32) +#if defined( _WIN32 ) -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif -#include + #include static double s_invFrequency = 0.0; -b2Timer b2CreateTimer(void) +b2Timer b2CreateTimer( void ) { LARGE_INTEGER largeInteger; - if (s_invFrequency == 0.0) + if ( s_invFrequency == 0.0 ) { - QueryPerformanceFrequency(&largeInteger); + QueryPerformanceFrequency( &largeInteger ); s_invFrequency = (double)largeInteger.QuadPart; - if (s_invFrequency > 0.0) + if ( s_invFrequency > 0.0 ) { s_invFrequency = 1000.0 / s_invFrequency; } } - QueryPerformanceCounter(&largeInteger); + QueryPerformanceCounter( &largeInteger ); b2Timer timer; timer.start = largeInteger.QuadPart; return timer; } -int64_t b2GetTicks(b2Timer* timer) +int64_t b2GetTicks( b2Timer* timer ) { LARGE_INTEGER largeInteger; - QueryPerformanceCounter(&largeInteger); + QueryPerformanceCounter( &largeInteger ); int64_t ticks = largeInteger.QuadPart; int64_t count = ticks - timer->start; timer->start = ticks; return count; } -float b2GetMilliseconds(const b2Timer* timer) +float b2GetMilliseconds( const b2Timer* timer ) { LARGE_INTEGER largeInteger; - QueryPerformanceCounter(&largeInteger); + QueryPerformanceCounter( &largeInteger ); int64_t count = largeInteger.QuadPart; - float ms = (float)(s_invFrequency * (count - timer->start)); + float ms = (float)( s_invFrequency * ( count - timer->start ) ); return ms; } -float b2GetMillisecondsAndReset(b2Timer* timer) +float b2GetMillisecondsAndReset( b2Timer* timer ) { LARGE_INTEGER largeInteger; - QueryPerformanceCounter(&largeInteger); + QueryPerformanceCounter( &largeInteger ); int64_t count = largeInteger.QuadPart; - float ms = (float)(s_invFrequency * (count - timer->start)); + float ms = (float)( s_invFrequency * ( count - timer->start ) ); timer->start = count; return ms; } -void b2SleepMilliseconds(int milliseconds) +void b2SleepMilliseconds( int milliseconds ) { // also SwitchToThread() - Sleep((DWORD)milliseconds); + Sleep( (DWORD)milliseconds ); } void b2Yield() @@ -74,80 +74,80 @@ void b2Yield() SwitchToThread(); } -#elif defined(__linux__) || defined (__APPLE__) +#elif defined( __linux__ ) || defined( __APPLE__ ) -#include -#include -#include + #include + #include + #include -b2Timer b2CreateTimer(void) +b2Timer b2CreateTimer( void ) { b2Timer timer; struct timeval t; - gettimeofday(&t, 0); + gettimeofday( &t, 0 ); timer.start_sec = t.tv_sec; timer.start_usec = t.tv_usec; return timer; } -float b2GetMilliseconds(const b2Timer* timer) +float b2GetMilliseconds( const b2Timer* timer ) { struct timeval t; - gettimeofday(&t, 0); + gettimeofday( &t, 0 ); time_t start_sec = timer->start_sec; suseconds_t start_usec = (suseconds_t)timer->start_usec; - + // http://www.gnu.org/software/libc/manual/html_node/Elapsed-Time.html - if (t.tv_usec < start_usec) + if ( t.tv_usec < start_usec ) { - int nsec = (start_usec - t.tv_usec) / 1000000 + 1; + int nsec = ( start_usec - t.tv_usec ) / 1000000 + 1; start_usec -= 1000000 * nsec; start_sec += nsec; } - - if (t.tv_usec - start_usec > 1000000) + + if ( t.tv_usec - start_usec > 1000000 ) { - int nsec = (t.tv_usec - start_usec) / 1000000; + int nsec = ( t.tv_usec - start_usec ) / 1000000; start_usec += 1000000 * nsec; start_sec -= nsec; } - return 1000.0f * (t.tv_sec - start_sec) + 0.001f * (t.tv_usec - start_usec); + return 1000.0f * ( t.tv_sec - start_sec ) + 0.001f * ( t.tv_usec - start_usec ); } -float b2GetMillisecondsAndReset(b2Timer* timer) +float b2GetMillisecondsAndReset( b2Timer* timer ) { struct timeval t; - gettimeofday(&t, 0); + gettimeofday( &t, 0 ); time_t start_sec = timer->start_sec; suseconds_t start_usec = (suseconds_t)timer->start_usec; // http://www.gnu.org/software/libc/manual/html_node/Elapsed-Time.html - if (t.tv_usec < start_usec) + if ( t.tv_usec < start_usec ) { - int nsec = (start_usec - t.tv_usec) / 1000000 + 1; + int nsec = ( start_usec - t.tv_usec ) / 1000000 + 1; start_usec -= 1000000 * nsec; start_sec += nsec; } - if (t.tv_usec - start_usec > 1000000) + if ( t.tv_usec - start_usec > 1000000 ) { - int nsec = (t.tv_usec - start_usec) / 1000000; + int nsec = ( t.tv_usec - start_usec ) / 1000000; start_usec += 1000000 * nsec; start_sec -= nsec; } - + timer->start_sec = t.tv_sec; timer->start_usec = t.tv_usec; - return 1000.0f * (t.tv_sec - start_sec) + 0.001f * (t.tv_usec - start_usec); + return 1000.0f * ( t.tv_sec - start_sec ) + 0.001f * ( t.tv_usec - start_usec ); } -void b2SleepMilliseconds(int milliseconds) +void b2SleepMilliseconds( int milliseconds ) { struct timespec ts; ts.tv_sec = milliseconds / 1000; - ts.tv_nsec = (milliseconds % 1000) * 1000000; - nanosleep(&ts, NULL); + ts.tv_nsec = ( milliseconds % 1000 ) * 1000000; + nanosleep( &ts, NULL ); } void b2Yield() @@ -157,27 +157,27 @@ void b2Yield() #else -b2Timer b2CreateTimer(void) +b2Timer b2CreateTimer( void ) { - b2Timer timer = {0}; + b2Timer timer = { 0 }; return timer; } -float b2GetMilliseconds(const b2Timer* timer) +float b2GetMilliseconds( const b2Timer* timer ) { - ((void)(timer)); + ( (void)( timer ) ); return 0.0f; } -float b2GetMillisecondsAndReset(b2Timer* timer) +float b2GetMillisecondsAndReset( b2Timer* timer ) { - ((void)(timer)); + ( (void)( timer ) ); return 0.0f; } -void b2SleepMilliseconds(int milliseconds) +void b2SleepMilliseconds( int milliseconds ) { - ((void)(milliseconds)); + ( (void)( milliseconds ) ); } void b2Yield() diff --git a/src/types.c b/src/types.c index 514e2428..7d54d6d4 100644 --- a/src/types.c +++ b/src/types.c @@ -1,13 +1,13 @@ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT -#include "core.h" - #include "box2d/types.h" -b2WorldDef b2DefaultWorldDef(void) +#include "core.h" + +b2WorldDef b2DefaultWorldDef( void ) { - b2WorldDef def = {0}; + b2WorldDef def = { 0 }; def.gravity.x = 0.0f; def.gravity.y = -10.0f; def.hitEventThreshold = 1.0f * b2_lengthUnitsPerMeter; @@ -23,9 +23,9 @@ b2WorldDef b2DefaultWorldDef(void) return def; } -b2BodyDef b2DefaultBodyDef(void) +b2BodyDef b2DefaultBodyDef( void ) { - b2BodyDef def = {0}; + b2BodyDef def = { 0 }; def.type = b2_staticBody; def.rotation = b2Rot_identity; def.sleepThreshold = 0.05f * b2_lengthUnitsPerMeter; @@ -38,21 +38,21 @@ b2BodyDef b2DefaultBodyDef(void) return def; } -b2Filter b2DefaultFilter(void) +b2Filter b2DefaultFilter( void ) { - b2Filter filter = {0x00000001, 0xFFFFFFFF, 0}; + b2Filter filter = { 0x00000001, 0xFFFFFFFF, 0 }; return filter; } -b2QueryFilter b2DefaultQueryFilter(void) +b2QueryFilter b2DefaultQueryFilter( void ) { - b2QueryFilter filter = {0x00000001, 0xFFFFFFFF}; + b2QueryFilter filter = { 0x00000001, 0xFFFFFFFF }; return filter; } -b2ShapeDef b2DefaultShapeDef(void) +b2ShapeDef b2DefaultShapeDef( void ) { - b2ShapeDef def = {0}; + b2ShapeDef def = { 0 }; def.friction = 0.6f; def.density = 1.0f; def.filter = b2DefaultFilter(); @@ -62,9 +62,9 @@ b2ShapeDef b2DefaultShapeDef(void) return def; } -b2ChainDef b2DefaultChainDef(void) +b2ChainDef b2DefaultChainDef( void ) { - b2ChainDef def = {0}; + b2ChainDef def = { 0 }; def.friction = 0.6f; def.filter = b2DefaultFilter(); def.internalValue = B2_SECRET_COOKIE; diff --git a/src/weld_joint.c b/src/weld_joint.c index bab9d393..11e9265f 100644 --- a/src/weld_joint.c +++ b/src/weld_joint.c @@ -11,65 +11,65 @@ // needed for dll export #include "box2d/box2d.h" -void b2WeldJoint_SetLinearHertz(b2JointId jointId, float hertz) +void b2WeldJoint_SetLinearHertz( b2JointId jointId, float hertz ) { - B2_ASSERT(b2IsValid(hertz) && hertz >= 0.0f); - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_weldJoint); + B2_ASSERT( b2IsValid( hertz ) && hertz >= 0.0f ); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_weldJoint ); joint->weldJoint.linearHertz = hertz; } -float b2WeldJoint_GetLinearHertz(b2JointId jointId) +float b2WeldJoint_GetLinearHertz( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_weldJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_weldJoint ); return joint->weldJoint.linearHertz; } -void b2WeldJoint_SetLinearDampingRatio(b2JointId jointId, float dampingRatio) +void b2WeldJoint_SetLinearDampingRatio( b2JointId jointId, float dampingRatio ) { - B2_ASSERT(b2IsValid(dampingRatio) && dampingRatio >= 0.0f); - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_weldJoint); + B2_ASSERT( b2IsValid( dampingRatio ) && dampingRatio >= 0.0f ); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_weldJoint ); joint->weldJoint.linearDampingRatio = dampingRatio; } -float b2WeldJoint_GetLinearDampingRatio(b2JointId jointId) +float b2WeldJoint_GetLinearDampingRatio( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_weldJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_weldJoint ); return joint->weldJoint.linearDampingRatio; } -void b2WeldJoint_SetAngularHertz(b2JointId jointId, float hertz) +void b2WeldJoint_SetAngularHertz( b2JointId jointId, float hertz ) { - B2_ASSERT(b2IsValid(hertz) && hertz >= 0.0f); - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_weldJoint); + B2_ASSERT( b2IsValid( hertz ) && hertz >= 0.0f ); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_weldJoint ); joint->weldJoint.angularHertz = hertz; } -float b2WeldJoint_GetAngularHertz(b2JointId jointId) +float b2WeldJoint_GetAngularHertz( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_weldJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_weldJoint ); return joint->weldJoint.angularHertz; } -void b2WeldJoint_SetAngularDampingRatio(b2JointId jointId, float dampingRatio) +void b2WeldJoint_SetAngularDampingRatio( b2JointId jointId, float dampingRatio ) { - B2_ASSERT(b2IsValid(dampingRatio) && dampingRatio >= 0.0f); - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_weldJoint); + B2_ASSERT( b2IsValid( dampingRatio ) && dampingRatio >= 0.0f ); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_weldJoint ); joint->weldJoint.angularDampingRatio = dampingRatio; } -float b2WeldJoint_GetAngularDampingRatio(b2JointId jointId) +float b2WeldJoint_GetAngularDampingRatio( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_weldJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_weldJoint ); return joint->weldJoint.angularDampingRatio; } -b2Vec2 b2GetWeldJointForce(b2World* world, b2JointSim* base) +b2Vec2 b2GetWeldJointForce( b2World* world, b2JointSim* base ) { - b2Vec2 force = b2MulSV(world->inv_h, base->weldJoint.linearImpulse); + b2Vec2 force = b2MulSV( world->inv_h, base->weldJoint.linearImpulse ); return force; } -float b2GetWeldJointTorque(b2World* world, b2JointSim* base) +float b2GetWeldJointTorque( b2World* world, b2JointSim* base ) { return world->inv_h * base->weldJoint.angularImpulse; } @@ -88,9 +88,9 @@ float b2GetWeldJointTorque(b2World* world, b2JointSim* base) // J = [0 0 -1 0 0 1] // K = invI1 + invI2 -void b2PrepareWeldJoint(b2JointSim* base, b2StepContext* context) +void b2PrepareWeldJoint( b2JointSim* base, b2StepContext* context ) { - B2_ASSERT(base->type == b2_weldJoint); + B2_ASSERT( base->type == b2_weldJoint ); // chase body id to the solver set where the body lives int idA = base->bodyIdA; @@ -99,15 +99,15 @@ void b2PrepareWeldJoint(b2JointSim* base, b2StepContext* context) b2World* world = context->world; b2Body* bodies = world->bodyArray; - b2CheckIndex(bodies, idA); - b2CheckIndex(bodies, idB); + b2CheckIndex( bodies, idA ); + b2CheckIndex( bodies, idB ); b2Body* bodyA = bodies + idA; b2Body* bodyB = bodies + idB; - B2_ASSERT(bodyA->setIndex == b2_awakeSet || bodyB->setIndex == b2_awakeSet); - b2CheckIndex(world->solverSetArray, bodyA->setIndex); - b2CheckIndex(world->solverSetArray, bodyB->setIndex); + B2_ASSERT( bodyA->setIndex == b2_awakeSet || bodyB->setIndex == b2_awakeSet ); + b2CheckIndex( world->solverSetArray, bodyA->setIndex ); + b2CheckIndex( world->solverSetArray, bodyB->setIndex ); b2SolverSet* setA = world->solverSetArray + bodyA->setIndex; b2SolverSet* setB = world->solverSetArray + bodyB->setIndex; @@ -115,8 +115,8 @@ void b2PrepareWeldJoint(b2JointSim* base, b2StepContext* context) int localIndexA = bodyA->localIndex; int localIndexB = bodyB->localIndex; - B2_ASSERT(0 <= localIndexA && localIndexA <= setA->sims.count); - B2_ASSERT(0 <= localIndexB && localIndexB <= setB->sims.count); + B2_ASSERT( 0 <= localIndexA && localIndexA <= setA->sims.count ); + B2_ASSERT( 0 <= localIndexB && localIndexB <= setB->sims.count ); b2BodySim* bodySimA = setA->sims.data + bodyA->localIndex; b2BodySim* bodySimB = setB->sims.data + bodyB->localIndex; @@ -138,42 +138,42 @@ void b2PrepareWeldJoint(b2JointSim* base, b2StepContext* context) b2Rot qA = bodySimA->transform.q; b2Rot qB = bodySimB->transform.q; - joint->anchorA = b2RotateVector(qA, b2Sub(base->localOriginAnchorA, bodySimA->localCenter)); - joint->anchorB = b2RotateVector(qB, b2Sub(base->localOriginAnchorB, bodySimB->localCenter)); - joint->deltaCenter = b2Sub(bodySimB->center, bodySimA->center); - joint->deltaAngle = b2RelativeAngle(qB, qA) - joint->referenceAngle; + joint->anchorA = b2RotateVector( qA, b2Sub( base->localOriginAnchorA, bodySimA->localCenter ) ); + joint->anchorB = b2RotateVector( qB, b2Sub( base->localOriginAnchorB, bodySimB->localCenter ) ); + joint->deltaCenter = b2Sub( bodySimB->center, bodySimA->center ); + joint->deltaAngle = b2RelativeAngle( qB, qA ) - joint->referenceAngle; float ka = iA + iB; joint->axialMass = ka > 0.0f ? 1.0f / ka : 0.0f; const float h = context->dt; - if (joint->linearHertz == 0.0f) + if ( joint->linearHertz == 0.0f ) { joint->linearSoftness = context->jointSoftness; } else { - joint->linearSoftness = b2MakeSoft(joint->linearHertz, joint->linearDampingRatio, context->h); + joint->linearSoftness = b2MakeSoft( joint->linearHertz, joint->linearDampingRatio, context->h ); } - if (joint->angularHertz == 0.0f) + if ( joint->angularHertz == 0.0f ) { joint->angularSoftness = context->jointSoftness; } else { - joint->angularSoftness = b2MakeSoft(joint->angularHertz, joint->angularDampingRatio, context->h); + joint->angularSoftness = b2MakeSoft( joint->angularHertz, joint->angularDampingRatio, context->h ); } - if (context->enableWarmStarting == false) + if ( context->enableWarmStarting == false ) { joint->linearImpulse = b2Vec2_zero; joint->angularImpulse = 0.0f; } } -void b2WarmStartWeldJoint(b2JointSim* base, b2StepContext* context) +void b2WarmStartWeldJoint( b2JointSim* base, b2StepContext* context ) { float mA = base->invMassA; float mB = base->invMassB; @@ -188,19 +188,19 @@ void b2WarmStartWeldJoint(b2JointSim* base, b2StepContext* context) b2BodyState* stateA = joint->indexA == B2_NULL_INDEX ? &dummyState : context->states + joint->indexA; b2BodyState* stateB = joint->indexB == B2_NULL_INDEX ? &dummyState : context->states + joint->indexB; - b2Vec2 rA = b2RotateVector(stateA->deltaRotation, joint->anchorA); - b2Vec2 rB = b2RotateVector(stateB->deltaRotation, joint->anchorB); + b2Vec2 rA = b2RotateVector( stateA->deltaRotation, joint->anchorA ); + b2Vec2 rB = b2RotateVector( stateB->deltaRotation, joint->anchorB ); - stateA->linearVelocity = b2MulSub(stateA->linearVelocity, mA, joint->linearImpulse); - stateA->angularVelocity -= iA * (b2Cross(rA, joint->linearImpulse) + joint->angularImpulse); + stateA->linearVelocity = b2MulSub( stateA->linearVelocity, mA, joint->linearImpulse ); + stateA->angularVelocity -= iA * ( b2Cross( rA, joint->linearImpulse ) + joint->angularImpulse ); - stateB->linearVelocity = b2MulAdd(stateB->linearVelocity, mB, joint->linearImpulse); - stateB->angularVelocity += iB * (b2Cross(rB, joint->linearImpulse) + joint->angularImpulse); + stateB->linearVelocity = b2MulAdd( stateB->linearVelocity, mB, joint->linearImpulse ); + stateB->angularVelocity += iB * ( b2Cross( rB, joint->linearImpulse ) + joint->angularImpulse ); } -void b2SolveWeldJoint(b2JointSim* base, const b2StepContext* context, bool useBias) +void b2SolveWeldJoint( b2JointSim* base, b2StepContext* context, bool useBias ) { - B2_ASSERT(base->type == b2_weldJoint); + B2_ASSERT( base->type == b2_weldJoint ); float mA = base->invMassA; float mB = base->invMassB; @@ -225,16 +225,16 @@ void b2SolveWeldJoint(b2JointSim* base, const b2StepContext* context, bool useBi float bias = 0.0f; float massScale = 1.0f; float impulseScale = 0.0f; - if (useBias || joint->angularHertz > 0.0f) + if ( useBias || joint->angularHertz > 0.0f ) { - float C = b2RelativeAngle(stateB->deltaRotation, stateA->deltaRotation) + joint->deltaAngle; + float C = b2RelativeAngle( stateB->deltaRotation, stateA->deltaRotation ) + joint->deltaAngle; bias = joint->angularSoftness.biasRate * C; massScale = joint->angularSoftness.massScale; impulseScale = joint->angularSoftness.impulseScale; } float Cdot = wB - wA; - float impulse = -massScale * joint->axialMass * (Cdot + bias) - impulseScale * joint->angularImpulse; + float impulse = -massScale * joint->axialMass * ( Cdot + bias ) - impulseScale * joint->angularImpulse; joint->angularImpulse += impulse; wA -= iA * impulse; @@ -243,43 +243,43 @@ void b2SolveWeldJoint(b2JointSim* base, const b2StepContext* context, bool useBi // linear constraint { - b2Vec2 rA = b2RotateVector(stateA->deltaRotation, joint->anchorA); - b2Vec2 rB = b2RotateVector(stateB->deltaRotation, joint->anchorB); + b2Vec2 rA = b2RotateVector( stateA->deltaRotation, joint->anchorA ); + b2Vec2 rB = b2RotateVector( stateB->deltaRotation, joint->anchorB ); b2Vec2 bias = b2Vec2_zero; float massScale = 1.0f; float impulseScale = 0.0f; - if (useBias || joint->linearHertz > 0.0f) + if ( useBias || joint->linearHertz > 0.0f ) { b2Vec2 dcA = stateA->deltaPosition; b2Vec2 dcB = stateB->deltaPosition; - b2Vec2 C = b2Add(b2Add(b2Sub(dcB, dcA), b2Sub(rB, rA)), joint->deltaCenter); + b2Vec2 C = b2Add( b2Add( b2Sub( dcB, dcA ), b2Sub( rB, rA ) ), joint->deltaCenter ); - bias = b2MulSV(joint->linearSoftness.biasRate, C); + bias = b2MulSV( joint->linearSoftness.biasRate, C ); massScale = joint->linearSoftness.massScale; impulseScale = joint->linearSoftness.impulseScale; } - b2Vec2 Cdot = b2Sub(b2Add(vB, b2CrossSV(wB, rB)), b2Add(vA, b2CrossSV(wA, rA))); + b2Vec2 Cdot = b2Sub( b2Add( vB, b2CrossSV( wB, rB ) ), b2Add( vA, b2CrossSV( wA, rA ) ) ); b2Mat22 K; K.cx.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; K.cy.x = -rA.y * rA.x * iA - rB.y * rB.x * iB; K.cx.y = K.cy.x; K.cy.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; - b2Vec2 b = b2Solve22(K, b2Add(Cdot, bias)); + b2Vec2 b = b2Solve22( K, b2Add( Cdot, bias ) ); b2Vec2 impulse = { -massScale * b.x - impulseScale * joint->linearImpulse.x, -massScale * b.y - impulseScale * joint->linearImpulse.y, }; - joint->linearImpulse = b2Add(joint->linearImpulse, impulse); + joint->linearImpulse = b2Add( joint->linearImpulse, impulse ); - vA = b2MulSub(vA, mA, impulse); - wA -= iA * b2Cross(rA, impulse); - vB = b2MulAdd(vB, mB, impulse); - wB += iB * b2Cross(rB, impulse); + vA = b2MulSub( vA, mA, impulse ); + wA -= iA * b2Cross( rA, impulse ); + vB = b2MulAdd( vB, mB, impulse ); + wB += iB * b2Cross( rB, impulse ); } stateA->linearVelocity = vA; diff --git a/src/wheel_joint.c b/src/wheel_joint.c index a326199d..a2c2c311 100644 --- a/src/wheel_joint.c +++ b/src/wheel_joint.c @@ -13,51 +13,51 @@ #include -void b2WheelJoint_EnableSpring(b2JointId jointId, bool enableSpring) +void b2WheelJoint_EnableSpring( b2JointId jointId, bool enableSpring ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_wheelJoint); - - if (enableSpring != joint->wheelJoint.enableSpring) + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); + + if ( enableSpring != joint->wheelJoint.enableSpring ) { joint->wheelJoint.enableSpring = enableSpring; joint->wheelJoint.springImpulse = 0.0f; } } -bool b2WheelJoint_IsSpringEnabled(b2JointId jointId) +bool b2WheelJoint_IsSpringEnabled( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_wheelJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); return joint->wheelJoint.enableSpring; } -void b2WheelJoint_SetSpringHertz(b2JointId jointId, float hertz) +void b2WheelJoint_SetSpringHertz( b2JointId jointId, float hertz ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_wheelJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); joint->wheelJoint.hertz = hertz; } -float b2WheelJoint_GetSpringHertz(b2JointId jointId) +float b2WheelJoint_GetSpringHertz( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_wheelJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); return joint->wheelJoint.hertz; } -void b2WheelJoint_SetSpringDampingRatio(b2JointId jointId, float dampingRatio) +void b2WheelJoint_SetSpringDampingRatio( b2JointId jointId, float dampingRatio ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_wheelJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); joint->wheelJoint.dampingRatio = dampingRatio; } -float b2WheelJoint_GetSpringDampingRatio(b2JointId jointId) +float b2WheelJoint_GetSpringDampingRatio( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_wheelJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); return joint->wheelJoint.dampingRatio; } -void b2WheelJoint_EnableLimit(b2JointId jointId, bool enableLimit) +void b2WheelJoint_EnableLimit( b2JointId jointId, bool enableLimit ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_wheelJoint); - if (joint->wheelJoint.enableLimit != enableLimit) + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); + if ( joint->wheelJoint.enableLimit != enableLimit ) { joint->wheelJoint.lowerImpulse = 0.0f; joint->wheelJoint.upperImpulse = 0.0f; @@ -65,99 +65,99 @@ void b2WheelJoint_EnableLimit(b2JointId jointId, bool enableLimit) } } -bool b2WheelJoint_IsLimitEnabled(b2JointId jointId) +bool b2WheelJoint_IsLimitEnabled( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_wheelJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); return joint->wheelJoint.enableLimit; } -float b2WheelJoint_GetLowerLimit(b2JointId jointId) +float b2WheelJoint_GetLowerLimit( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_wheelJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); return joint->wheelJoint.lowerTranslation; } -float b2WheelJoint_GetUpperLimit(b2JointId jointId) +float b2WheelJoint_GetUpperLimit( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_wheelJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); return joint->wheelJoint.upperTranslation; } -void b2WheelJoint_SetLimits(b2JointId jointId, float lower, float upper) +void b2WheelJoint_SetLimits( b2JointId jointId, float lower, float upper ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_wheelJoint); - if (lower != joint->wheelJoint.lowerTranslation || upper != joint->wheelJoint.upperTranslation) + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); + if ( lower != joint->wheelJoint.lowerTranslation || upper != joint->wheelJoint.upperTranslation ) { - joint->wheelJoint.lowerTranslation = b2MinFloat(lower, upper); - joint->wheelJoint.upperTranslation = b2MaxFloat(lower, upper); + joint->wheelJoint.lowerTranslation = b2MinFloat( lower, upper ); + joint->wheelJoint.upperTranslation = b2MaxFloat( lower, upper ); joint->wheelJoint.lowerImpulse = 0.0f; joint->wheelJoint.upperImpulse = 0.0f; } } -void b2WheelJoint_EnableMotor(b2JointId jointId, bool enableMotor) +void b2WheelJoint_EnableMotor( b2JointId jointId, bool enableMotor ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_wheelJoint); - if (joint->wheelJoint.enableMotor != enableMotor) + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); + if ( joint->wheelJoint.enableMotor != enableMotor ) { joint->wheelJoint.motorImpulse = 0.0f; joint->wheelJoint.enableMotor = enableMotor; } } -bool b2WheelJoint_IsMotorEnabled(b2JointId jointId) +bool b2WheelJoint_IsMotorEnabled( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_wheelJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); return joint->wheelJoint.enableMotor; } -void b2WheelJoint_SetMotorSpeed(b2JointId jointId, float motorSpeed) +void b2WheelJoint_SetMotorSpeed( b2JointId jointId, float motorSpeed ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_wheelJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); joint->wheelJoint.motorSpeed = motorSpeed; } -float b2WheelJoint_GetMotorSpeed(b2JointId jointId) +float b2WheelJoint_GetMotorSpeed( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_wheelJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); return joint->wheelJoint.motorSpeed; } -float b2WheelJoint_GetMotorTorque(b2JointId jointId) +float b2WheelJoint_GetMotorTorque( b2JointId jointId ) { - b2World* world = b2GetWorld(jointId.world0); - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_wheelJoint); + b2World* world = b2GetWorld( jointId.world0 ); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); return world->inv_h * joint->wheelJoint.motorImpulse; } -void b2WheelJoint_SetMaxMotorTorque(b2JointId jointId, float torque) +void b2WheelJoint_SetMaxMotorTorque( b2JointId jointId, float torque ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_wheelJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); joint->wheelJoint.maxMotorTorque = torque; } -float b2WheelJoint_GetMaxMotorTorque(b2JointId jointId) +float b2WheelJoint_GetMaxMotorTorque( b2JointId jointId ) { - b2JointSim* joint = b2GetJointSimCheckType(jointId, b2_wheelJoint); + b2JointSim* joint = b2GetJointSimCheckType( jointId, b2_wheelJoint ); return joint->wheelJoint.maxMotorTorque; } -b2Vec2 b2GetWheelJointForce(b2World* world, b2JointSim* base) +b2Vec2 b2GetWheelJointForce( b2World* world, b2JointSim* base ) { b2WheelJoint* joint = &base->wheelJoint; // This is a frame behind b2Vec2 axisA = joint->axisA; - b2Vec2 perpA = b2LeftPerp(axisA); + b2Vec2 perpA = b2LeftPerp( axisA ); float perpForce = world->inv_h * joint->perpImpulse; - float axialForce = world->inv_h * (joint->springImpulse + joint->lowerImpulse - joint->upperImpulse); + float axialForce = world->inv_h * ( joint->springImpulse + joint->lowerImpulse - joint->upperImpulse ); - b2Vec2 force = b2Add(b2MulSV(perpForce, perpA), b2MulSV(axialForce, axisA)); + b2Vec2 force = b2Add( b2MulSV( perpForce, perpA ), b2MulSV( axialForce, axisA ) ); return force; } -float b2GetWheelJointTorque(b2World* world, b2JointSim* base) +float b2GetWheelJointTorque( b2World* world, b2JointSim* base ) { return world->inv_h * base->wheelJoint.motorImpulse; } @@ -178,9 +178,9 @@ float b2GetWheelJointTorque(b2World* world, b2JointSim* base) // Cdot = wB - wA // J = [0 0 -1 0 0 1] -void b2PrepareWheelJoint(b2JointSim* base, b2StepContext* context) +void b2PrepareWheelJoint( b2JointSim* base, b2StepContext* context ) { - B2_ASSERT(base->type == b2_wheelJoint); + B2_ASSERT( base->type == b2_wheelJoint ); // chase body id to the solver set where the body lives int idA = base->bodyIdA; @@ -189,15 +189,15 @@ void b2PrepareWheelJoint(b2JointSim* base, b2StepContext* context) b2World* world = context->world; b2Body* bodies = world->bodyArray; - b2CheckIndex(bodies, idA); - b2CheckIndex(bodies, idB); + b2CheckIndex( bodies, idA ); + b2CheckIndex( bodies, idB ); b2Body* bodyA = bodies + idA; b2Body* bodyB = bodies + idB; - B2_ASSERT(bodyA->setIndex == b2_awakeSet || bodyB->setIndex == b2_awakeSet); - b2CheckIndex(world->solverSetArray, bodyA->setIndex); - b2CheckIndex(world->solverSetArray, bodyB->setIndex); + B2_ASSERT( bodyA->setIndex == b2_awakeSet || bodyB->setIndex == b2_awakeSet ); + b2CheckIndex( world->solverSetArray, bodyA->setIndex ); + b2CheckIndex( world->solverSetArray, bodyB->setIndex ); b2SolverSet* setA = world->solverSetArray + bodyA->setIndex; b2SolverSet* setB = world->solverSetArray + bodyB->setIndex; @@ -205,8 +205,8 @@ void b2PrepareWheelJoint(b2JointSim* base, b2StepContext* context) int localIndexA = bodyA->localIndex; int localIndexB = bodyB->localIndex; - B2_ASSERT(0 <= localIndexA && localIndexA <= setA->sims.count); - B2_ASSERT(0 <= localIndexB && localIndexB <= setB->sims.count); + B2_ASSERT( 0 <= localIndexA && localIndexA <= setA->sims.count ); + B2_ASSERT( 0 <= localIndexB && localIndexB <= setB->sims.count ); b2BodySim* bodySimA = setA->sims.data + bodyA->localIndex; b2BodySim* bodySimB = setB->sims.data + bodyB->localIndex; @@ -229,38 +229,38 @@ void b2PrepareWheelJoint(b2JointSim* base, b2StepContext* context) b2Rot qA = bodySimA->transform.q; b2Rot qB = bodySimB->transform.q; - joint->anchorA = b2RotateVector(qA, b2Sub(base->localOriginAnchorA, bodySimA->localCenter)); - joint->anchorB = b2RotateVector(qB, b2Sub(base->localOriginAnchorB, bodySimB->localCenter)); - joint->axisA = b2RotateVector(qA, joint->localAxisA); - joint->deltaCenter = b2Sub(bodySimB->center, bodySimA->center); + joint->anchorA = b2RotateVector( qA, b2Sub( base->localOriginAnchorA, bodySimA->localCenter ) ); + joint->anchorB = b2RotateVector( qB, b2Sub( base->localOriginAnchorB, bodySimB->localCenter ) ); + joint->axisA = b2RotateVector( qA, joint->localAxisA ); + joint->deltaCenter = b2Sub( bodySimB->center, bodySimA->center ); b2Vec2 rA = joint->anchorA; b2Vec2 rB = joint->anchorB; - b2Vec2 d = b2Add(joint->deltaCenter, b2Sub(rB, rA)); + b2Vec2 d = b2Add( joint->deltaCenter, b2Sub( rB, rA ) ); b2Vec2 axisA = joint->axisA; - b2Vec2 perpA = b2LeftPerp(axisA); + b2Vec2 perpA = b2LeftPerp( axisA ); // perpendicular constraint (keep wheel on line) - float s1 = b2Cross(b2Add(d, rA), perpA); - float s2 = b2Cross(rB, perpA); - + float s1 = b2Cross( b2Add( d, rA ), perpA ); + float s2 = b2Cross( rB, perpA ); + float kp = mA + mB + iA * s1 * s1 + iB * s2 * s2; joint->perpMass = kp > 0.0f ? 1.0f / kp : 0.0f; // spring constraint - float a1 = b2Cross(b2Add(d, rA), axisA); - float a2 = b2Cross(rB, axisA); + float a1 = b2Cross( b2Add( d, rA ), axisA ); + float a2 = b2Cross( rB, axisA ); float ka = mA + mB + iA * a1 * a1 + iB * a2 * a2; joint->axialMass = ka > 0.0f ? 1.0f / ka : 0.0f; - joint->springSoftness = b2MakeSoft(joint->hertz, joint->dampingRatio, context->h); + joint->springSoftness = b2MakeSoft( joint->hertz, joint->dampingRatio, context->h ); float km = iA + iB; joint->motorMass = km > 0.0f ? 1.0f / km : 0.0f; - if (context->enableWarmStarting == false) + if ( context->enableWarmStarting == false ) { joint->perpImpulse = 0.0f; joint->springImpulse = 0.0f; @@ -270,9 +270,9 @@ void b2PrepareWheelJoint(b2JointSim* base, b2StepContext* context) } } -void b2WarmStartWheelJoint(b2JointSim* base, b2StepContext* context) +void b2WarmStartWheelJoint( b2JointSim* base, b2StepContext* context ) { - B2_ASSERT(base->type == b2_wheelJoint); + B2_ASSERT( base->type == b2_wheelJoint ); float mA = base->invMassA; float mB = base->invMassB; @@ -287,33 +287,33 @@ void b2WarmStartWheelJoint(b2JointSim* base, b2StepContext* context) b2BodyState* stateA = joint->indexA == B2_NULL_INDEX ? &dummyState : context->states + joint->indexA; b2BodyState* stateB = joint->indexB == B2_NULL_INDEX ? &dummyState : context->states + joint->indexB; - b2Vec2 rA = b2RotateVector(stateA->deltaRotation, joint->anchorA); - b2Vec2 rB = b2RotateVector(stateB->deltaRotation, joint->anchorB); + b2Vec2 rA = b2RotateVector( stateA->deltaRotation, joint->anchorA ); + b2Vec2 rB = b2RotateVector( stateB->deltaRotation, joint->anchorB ); - b2Vec2 d = b2Add(b2Add(b2Sub(stateB->deltaPosition, stateA->deltaPosition), joint->deltaCenter), b2Sub(rB, rA)); - b2Vec2 axisA = b2RotateVector(stateA->deltaRotation, joint->axisA); - b2Vec2 perpA = b2LeftPerp(axisA); + b2Vec2 d = b2Add( b2Add( b2Sub( stateB->deltaPosition, stateA->deltaPosition ), joint->deltaCenter ), b2Sub( rB, rA ) ); + b2Vec2 axisA = b2RotateVector( stateA->deltaRotation, joint->axisA ); + b2Vec2 perpA = b2LeftPerp( axisA ); - float a1 = b2Cross(b2Add(d, rA), axisA); - float a2 = b2Cross(rB, axisA); - float s1 = b2Cross(b2Add(d, rA), perpA); - float s2 = b2Cross(rB, perpA); + float a1 = b2Cross( b2Add( d, rA ), axisA ); + float a2 = b2Cross( rB, axisA ); + float s1 = b2Cross( b2Add( d, rA ), perpA ); + float s2 = b2Cross( rB, perpA ); float axialImpulse = joint->springImpulse + joint->lowerImpulse - joint->upperImpulse; - - b2Vec2 P = b2Add(b2MulSV(axialImpulse, axisA), b2MulSV(joint->perpImpulse, perpA)); + + b2Vec2 P = b2Add( b2MulSV( axialImpulse, axisA ), b2MulSV( joint->perpImpulse, perpA ) ); float LA = axialImpulse * a1 + joint->perpImpulse * s1 + joint->motorImpulse; float LB = axialImpulse * a2 + joint->perpImpulse * s2 + joint->motorImpulse; - stateA->linearVelocity = b2MulSub(stateA->linearVelocity, mA, P); + stateA->linearVelocity = b2MulSub( stateA->linearVelocity, mA, P ); stateA->angularVelocity -= iA * LA; - stateB->linearVelocity = b2MulAdd(stateB->linearVelocity, mB, P); + stateB->linearVelocity = b2MulAdd( stateB->linearVelocity, mB, P ); stateB->angularVelocity += iB * LB; } -void b2SolveWheelJoint(b2JointSim* base, b2StepContext* context, bool useBias) +void b2SolveWheelJoint( b2JointSim* base, b2StepContext* context, bool useBias ) { - B2_ASSERT(base->type == b2_wheelJoint); + B2_ASSERT( base->type == b2_wheelJoint ); float mA = base->invMassA; float mB = base->invMassB; @@ -326,7 +326,7 @@ void b2SolveWheelJoint(b2JointSim* base, b2StepContext* context, bool useBias) b2WheelJoint* joint = &base->wheelJoint; // This is a dummy body to represent a static body since static bodies don't have a solver body. - b2BodyState dummyBody = {0}; + b2BodyState dummyBody = { 0 }; b2BodyState* stateA = joint->indexA == B2_NULL_INDEX ? &dummyState : context->states + joint->indexA; b2BodyState* stateB = joint->indexB == B2_NULL_INDEX ? &dummyState : context->states + joint->indexB; @@ -336,27 +336,27 @@ void b2SolveWheelJoint(b2JointSim* base, b2StepContext* context, bool useBias) b2Vec2 vB = stateB->linearVelocity; float wB = stateB->angularVelocity; - bool fixedRotation = (iA + iB == 0.0f); + bool fixedRotation = ( iA + iB == 0.0f ); // current anchors - b2Vec2 rA = b2RotateVector(stateA->deltaRotation, joint->anchorA); - b2Vec2 rB = b2RotateVector(stateB->deltaRotation, joint->anchorB); + b2Vec2 rA = b2RotateVector( stateA->deltaRotation, joint->anchorA ); + b2Vec2 rB = b2RotateVector( stateB->deltaRotation, joint->anchorB ); - b2Vec2 d = b2Add(b2Add(b2Sub(stateB->deltaPosition, stateA->deltaPosition), joint->deltaCenter), b2Sub(rB, rA)); - b2Vec2 axisA = b2RotateVector(stateA->deltaRotation, joint->axisA); - float translation = b2Dot(axisA, d); + b2Vec2 d = b2Add( b2Add( b2Sub( stateB->deltaPosition, stateA->deltaPosition ), joint->deltaCenter ), b2Sub( rB, rA ) ); + b2Vec2 axisA = b2RotateVector( stateA->deltaRotation, joint->axisA ); + float translation = b2Dot( axisA, d ); - float a1 = b2Cross(b2Add(d, rA), axisA); - float a2 = b2Cross(rB, axisA); + float a1 = b2Cross( b2Add( d, rA ), axisA ); + float a2 = b2Cross( rB, axisA ); // motor constraint - if (joint->enableMotor && fixedRotation == false) + if ( joint->enableMotor && fixedRotation == false ) { float Cdot = wB - wA - joint->motorSpeed; float impulse = -joint->motorMass * Cdot; float oldImpulse = joint->motorImpulse; float maxImpulse = context->h * joint->maxMotorTorque; - joint->motorImpulse = b2ClampFloat(joint->motorImpulse + impulse, -maxImpulse, maxImpulse); + joint->motorImpulse = b2ClampFloat( joint->motorImpulse + impulse, -maxImpulse, maxImpulse ); impulse = joint->motorImpulse - oldImpulse; wA -= iA * impulse; @@ -364,7 +364,7 @@ void b2SolveWheelJoint(b2JointSim* base, b2StepContext* context, bool useBias) } // spring constraint - if (joint->enableSpring) + if ( joint->enableSpring ) { // This is a real spring and should be applied even during relax float C = translation; @@ -372,23 +372,23 @@ void b2SolveWheelJoint(b2JointSim* base, b2StepContext* context, bool useBias) float massScale = joint->springSoftness.massScale; float impulseScale = joint->springSoftness.impulseScale; - float Cdot = b2Dot(axisA, b2Sub(vB, vA)) + a2 * wB - a1 * wA; - float impulse = -massScale * joint->axialMass * (Cdot + bias) - impulseScale * joint->springImpulse; + float Cdot = b2Dot( axisA, b2Sub( vB, vA ) ) + a2 * wB - a1 * wA; + float impulse = -massScale * joint->axialMass * ( Cdot + bias ) - impulseScale * joint->springImpulse; joint->springImpulse += impulse; - b2Vec2 P = b2MulSV(impulse, axisA); + b2Vec2 P = b2MulSV( impulse, axisA ); float LA = impulse * a1; float LB = impulse * a2; - vA = b2MulSub(vA, mA, P); + vA = b2MulSub( vA, mA, P ); wA -= iA * LA; - vB = b2MulAdd(vB, mB, P); + vB = b2MulAdd( vB, mB, P ); wB += iB * LB; } - if (joint->enableLimit) + if ( joint->enableLimit ) { - float translation = b2Dot(axisA, d); + float translation = b2Dot( axisA, d ); // Lower limit { @@ -397,31 +397,31 @@ void b2SolveWheelJoint(b2JointSim* base, b2StepContext* context, bool useBias) float massScale = 1.0f; float impulseScale = 0.0f; - if (C > 0.0f) + if ( C > 0.0f ) { // speculation bias = C * context->inv_h; } - else if (useBias) + else if ( useBias ) { bias = context->jointSoftness.biasRate * C; massScale = context->jointSoftness.massScale; impulseScale = context->jointSoftness.impulseScale; } - float Cdot = b2Dot(axisA, b2Sub(vB, vA)) + a2 * wB - a1 * wA; - float impulse = -massScale * joint->axialMass * (Cdot + bias) - impulseScale * joint->lowerImpulse; + float Cdot = b2Dot( axisA, b2Sub( vB, vA ) ) + a2 * wB - a1 * wA; + float impulse = -massScale * joint->axialMass * ( Cdot + bias ) - impulseScale * joint->lowerImpulse; float oldImpulse = joint->lowerImpulse; - joint->lowerImpulse = b2MaxFloat(oldImpulse + impulse, 0.0f); + joint->lowerImpulse = b2MaxFloat( oldImpulse + impulse, 0.0f ); impulse = joint->lowerImpulse - oldImpulse; - b2Vec2 P = b2MulSV(impulse, axisA); + b2Vec2 P = b2MulSV( impulse, axisA ); float LA = impulse * a1; float LB = impulse * a2; - vA = b2MulSub(vA, mA, P); + vA = b2MulSub( vA, mA, P ); wA -= iA * LA; - vB = b2MulAdd(vB, mB, P); + vB = b2MulAdd( vB, mB, P ); wB += iB * LB; } @@ -435,12 +435,12 @@ void b2SolveWheelJoint(b2JointSim* base, b2StepContext* context, bool useBias) float massScale = 1.0f; float impulseScale = 0.0f; - if (C > 0.0f) + if ( C > 0.0f ) { // speculation bias = C * context->inv_h; } - else if (useBias) + else if ( useBias ) { bias = context->jointSoftness.biasRate * C; massScale = context->jointSoftness.massScale; @@ -448,53 +448,53 @@ void b2SolveWheelJoint(b2JointSim* base, b2StepContext* context, bool useBias) } // sign flipped on Cdot - float Cdot = b2Dot(axisA, b2Sub(vA, vB)) + a1 * wA - a2 * wB; - float impulse = -massScale * joint->axialMass * (Cdot + bias) - impulseScale * joint->upperImpulse; + float Cdot = b2Dot( axisA, b2Sub( vA, vB ) ) + a1 * wA - a2 * wB; + float impulse = -massScale * joint->axialMass * ( Cdot + bias ) - impulseScale * joint->upperImpulse; float oldImpulse = joint->upperImpulse; - joint->upperImpulse = b2MaxFloat(oldImpulse + impulse, 0.0f); + joint->upperImpulse = b2MaxFloat( oldImpulse + impulse, 0.0f ); impulse = joint->upperImpulse - oldImpulse; - b2Vec2 P = b2MulSV(impulse, axisA); + b2Vec2 P = b2MulSV( impulse, axisA ); float LA = impulse * a1; float LB = impulse * a2; // sign flipped on applied impulse - vA = b2MulAdd(vA, mA, P); + vA = b2MulAdd( vA, mA, P ); wA += iA * LA; - vB = b2MulSub(vB, mB, P); + vB = b2MulSub( vB, mB, P ); wB -= iB * LB; } } // point to line constraint { - b2Vec2 perpA = b2LeftPerp(axisA); + b2Vec2 perpA = b2LeftPerp( axisA ); float bias = 0.0f; float massScale = 1.0f; float impulseScale = 0.0f; - if (useBias) + if ( useBias ) { - float C = b2Dot(perpA, d); + float C = b2Dot( perpA, d ); bias = context->jointSoftness.biasRate * C; massScale = context->jointSoftness.massScale; impulseScale = context->jointSoftness.impulseScale; } - float s1 = b2Cross(b2Add(d, rA), perpA); - float s2 = b2Cross(rB, perpA); - float Cdot = b2Dot(perpA, b2Sub(vB, vA)) + s2 * wB - s1 * wA; + float s1 = b2Cross( b2Add( d, rA ), perpA ); + float s2 = b2Cross( rB, perpA ); + float Cdot = b2Dot( perpA, b2Sub( vB, vA ) ) + s2 * wB - s1 * wA; - float impulse = -massScale * joint->perpMass * (Cdot + bias) - impulseScale * joint->perpImpulse; + float impulse = -massScale * joint->perpMass * ( Cdot + bias ) - impulseScale * joint->perpImpulse; joint->perpImpulse += impulse; - b2Vec2 P = b2MulSV(impulse, perpA); + b2Vec2 P = b2MulSV( impulse, perpA ); float LA = impulse * s1; float LB = impulse * s2; - vA = b2MulSub(vA, mA, P); + vA = b2MulSub( vA, mA, P ); wA -= iA * LA; - vB = b2MulAdd(vB, mB, P); + vB = b2MulAdd( vB, mB, P ); wB += iB * LB; } @@ -527,15 +527,15 @@ void b2WheelJoint_Dump() } #endif -void b2DrawWheelJoint(b2DebugDraw* draw, b2JointSim* base, b2Transform transformA, b2Transform transformB) +void b2DrawWheelJoint( b2DebugDraw* draw, b2JointSim* base, b2Transform transformA, b2Transform transformB ) { - B2_ASSERT(base->type == b2_wheelJoint); + B2_ASSERT( base->type == b2_wheelJoint ); b2WheelJoint* joint = &base->wheelJoint; - b2Vec2 pA = b2TransformPoint(transformA, base->localOriginAnchorA); - b2Vec2 pB = b2TransformPoint(transformB, base->localOriginAnchorB); - b2Vec2 axis = b2RotateVector(transformA.q, joint->localAxisA); + b2Vec2 pA = b2TransformPoint( transformA, base->localOriginAnchorA ); + b2Vec2 pB = b2TransformPoint( transformB, base->localOriginAnchorB ); + b2Vec2 axis = b2RotateVector( transformA.q, joint->localAxisA ); b2HexColor c1 = b2_colorGray7; b2HexColor c2 = b2_colorGreen; @@ -543,22 +543,22 @@ void b2DrawWheelJoint(b2DebugDraw* draw, b2JointSim* base, b2Transform transform b2HexColor c4 = b2_colorGray4; b2HexColor c5 = b2_colorBlue; - draw->DrawSegment(pA, pB, c5, draw->context); + draw->DrawSegment( pA, pB, c5, draw->context ); - if (joint->enableLimit) + if ( joint->enableLimit ) { - b2Vec2 lower = b2MulAdd(pA, joint->lowerTranslation, axis); - b2Vec2 upper = b2MulAdd(pA, joint->upperTranslation, axis); - b2Vec2 perp = b2LeftPerp(axis); - draw->DrawSegment(lower, upper, c1, draw->context); - draw->DrawSegment(b2MulSub(lower, 0.1f, perp), b2MulAdd(lower, 0.1f, perp), c2, draw->context); - draw->DrawSegment(b2MulSub(upper, 0.1f, perp), b2MulAdd(upper, 0.1f, perp), c3, draw->context); + b2Vec2 lower = b2MulAdd( pA, joint->lowerTranslation, axis ); + b2Vec2 upper = b2MulAdd( pA, joint->upperTranslation, axis ); + b2Vec2 perp = b2LeftPerp( axis ); + draw->DrawSegment( lower, upper, c1, draw->context ); + draw->DrawSegment( b2MulSub( lower, 0.1f, perp ), b2MulAdd( lower, 0.1f, perp ), c2, draw->context ); + draw->DrawSegment( b2MulSub( upper, 0.1f, perp ), b2MulAdd( upper, 0.1f, perp ), c3, draw->context ); } else { - draw->DrawSegment(b2MulSub(pA, 1.0f, axis), b2MulAdd(pA, 1.0f, axis), c1, draw->context); + draw->DrawSegment( b2MulSub( pA, 1.0f, axis ), b2MulAdd( pA, 1.0f, axis ), c1, draw->context ); } - draw->DrawPoint(pA, 5.0f, c1, draw->context); - draw->DrawPoint(pB, 5.0f, c4, draw->context); + draw->DrawPoint( pA, 5.0f, c1, draw->context ); + draw->DrawPoint( pB, 5.0f, c4, draw->context ); } diff --git a/src/world.c b/src/world.c index 6aa78341..58dcd8a8 100644 --- a/src/world.c +++ b/src/world.c @@ -23,78 +23,78 @@ #include "solver_set.h" #include "stack_allocator.h" +#include "box2d/box2d.h" + #include #include #include -#include "box2d/box2d.h" - -_Static_assert(b2_maxWorlds > 0, "must be 1 or more"); +_Static_assert( b2_maxWorlds > 0, "must be 1 or more" ); b2World b2_worlds[b2_maxWorlds]; -b2World* b2GetWorldFromId(b2WorldId id) +b2World* b2GetWorldFromId( b2WorldId id ) { - B2_ASSERT(1 <= id.index1 && id.index1 <= b2_maxWorlds); - b2World* world = b2_worlds + (id.index1 - 1); - B2_ASSERT(id.index1 == world->worldId + 1); - B2_ASSERT(id.revision == world->revision); + B2_ASSERT( 1 <= id.index1 && id.index1 <= b2_maxWorlds ); + b2World* world = b2_worlds + ( id.index1 - 1 ); + B2_ASSERT( id.index1 == world->worldId + 1 ); + B2_ASSERT( id.revision == world->revision ); return world; } -b2World* b2GetWorld(int index) +b2World* b2GetWorld( int index ) { - B2_ASSERT(0 <= index && index < b2_maxWorlds); + B2_ASSERT( 0 <= index && index < b2_maxWorlds ); b2World* world = b2_worlds + index; - B2_ASSERT(world->worldId == index); + B2_ASSERT( world->worldId == index ); return world; } -b2World* b2GetWorldLocked(int index) +b2World* b2GetWorldLocked( int index ) { - B2_ASSERT(0 <= index && index < b2_maxWorlds); + B2_ASSERT( 0 <= index && index < b2_maxWorlds ); b2World* world = b2_worlds + index; - B2_ASSERT(world->worldId == index); - if (world->locked) + B2_ASSERT( world->worldId == index ); + if ( world->locked ) { - B2_ASSERT(false); + B2_ASSERT( false ); return NULL; } return world; } -static void* b2DefaultAddTaskFcn(b2TaskCallback* task, int count, int minRange, void* taskContext, void* userContext) +static void* b2DefaultAddTaskFcn( b2TaskCallback* task, int count, int minRange, void* taskContext, void* userContext ) { - B2_MAYBE_UNUSED(minRange); - B2_MAYBE_UNUSED(userContext); - task(0, count, 0, taskContext); + B2_MAYBE_UNUSED( minRange ); + B2_MAYBE_UNUSED( userContext ); + task( 0, count, 0, taskContext ); return NULL; } -static void b2DefaultFinishTaskFcn(void* userTask, void* userContext) +static void b2DefaultFinishTaskFcn( void* userTask, void* userContext ) { - B2_MAYBE_UNUSED(userTask); - B2_MAYBE_UNUSED(userContext); + B2_MAYBE_UNUSED( userTask ); + B2_MAYBE_UNUSED( userContext ); } -b2WorldId b2CreateWorld(const b2WorldDef* def) +b2WorldId b2CreateWorld( const b2WorldDef* def ) { - _Static_assert(b2_maxWorlds < UINT16_MAX, "b2_maxWorlds limit exceeded"); - b2CheckDef(def); + _Static_assert( b2_maxWorlds < UINT16_MAX, "b2_maxWorlds limit exceeded" ); + b2CheckDef( def ); int worldId = B2_NULL_INDEX; - for (int i = 0; i < b2_maxWorlds; ++i) + for ( int i = 0; i < b2_maxWorlds; ++i ) { - if (b2_worlds[i].inUse == false) + if ( b2_worlds[i].inUse == false ) { worldId = i; break; } } - if (worldId == B2_NULL_INDEX) + if ( worldId == B2_NULL_INDEX ) { - return (b2WorldId){0}; + return ( b2WorldId ){ 0 }; } b2InitializeContactRegisters(); @@ -102,61 +102,61 @@ b2WorldId b2CreateWorld(const b2WorldDef* def) b2World* world = b2_worlds + worldId; uint16_t revision = world->revision; - *world = (b2World){0}; + *world = ( b2World ){ 0 }; world->worldId = (uint16_t)worldId; world->revision = revision; world->inUse = true; - world->stackAllocator = b2CreateStackAllocator(2048); - b2CreateBroadPhase(&world->broadPhase); - b2CreateGraph(&world->constraintGraph, 16); + world->stackAllocator = b2CreateStackAllocator( 2048 ); + b2CreateBroadPhase( &world->broadPhase ); + b2CreateGraph( &world->constraintGraph, 16 ); // pools world->bodyIdPool = b2CreateIdPool(); - world->bodyArray = b2CreateArray(sizeof(b2Body), 16); - world->solverSetArray = b2CreateArray(sizeof(b2SolverSet), 8); + world->bodyArray = b2CreateArray( sizeof( b2Body ), 16 ); + world->solverSetArray = b2CreateArray( sizeof( b2SolverSet ), 8 ); // add empty static, active, and disabled body sets world->solverSetIdPool = b2CreateIdPool(); - b2SolverSet set = {0}; + b2SolverSet set = { 0 }; // static set - set.setIndex = b2AllocId(&world->solverSetIdPool); - b2Array_Push(world->solverSetArray, set); - B2_ASSERT(world->solverSetArray[b2_staticSet].setIndex == b2_staticSet); + set.setIndex = b2AllocId( &world->solverSetIdPool ); + b2Array_Push( world->solverSetArray, set ); + B2_ASSERT( world->solverSetArray[b2_staticSet].setIndex == b2_staticSet ); // disabled set - set.setIndex = b2AllocId(&world->solverSetIdPool); - b2Array_Push(world->solverSetArray, set); - B2_ASSERT(world->solverSetArray[b2_disabledSet].setIndex == b2_disabledSet); + set.setIndex = b2AllocId( &world->solverSetIdPool ); + b2Array_Push( world->solverSetArray, set ); + B2_ASSERT( world->solverSetArray[b2_disabledSet].setIndex == b2_disabledSet ); // awake set - set.setIndex = b2AllocId(&world->solverSetIdPool); - b2Array_Push(world->solverSetArray, set); - B2_ASSERT(world->solverSetArray[b2_awakeSet].setIndex == b2_awakeSet); + set.setIndex = b2AllocId( &world->solverSetIdPool ); + b2Array_Push( world->solverSetArray, set ); + B2_ASSERT( world->solverSetArray[b2_awakeSet].setIndex == b2_awakeSet ); world->shapeIdPool = b2CreateIdPool(); - world->shapeArray = b2CreateArray(sizeof(b2Shape), 16); + world->shapeArray = b2CreateArray( sizeof( b2Shape ), 16 ); world->chainIdPool = b2CreateIdPool(); - world->chainArray = b2CreateArray(sizeof(b2ChainShape), 4); + world->chainArray = b2CreateArray( sizeof( b2ChainShape ), 4 ); world->contactIdPool = b2CreateIdPool(); - world->contactArray = b2CreateArray(sizeof(b2Contact), 16); + world->contactArray = b2CreateArray( sizeof( b2Contact ), 16 ); world->jointIdPool = b2CreateIdPool(); - world->jointArray = b2CreateArray(sizeof(b2Joint), 16); + world->jointArray = b2CreateArray( sizeof( b2Joint ), 16 ); world->islandIdPool = b2CreateIdPool(); - world->islandArray = b2CreateArray(sizeof(b2Island), 8); + world->islandArray = b2CreateArray( sizeof( b2Island ), 8 ); - world->bodyMoveEventArray = b2CreateArray(sizeof(b2BodyMoveEvent), 4); - world->sensorBeginEventArray = b2CreateArray(sizeof(b2SensorBeginTouchEvent), 4); - world->sensorEndEventArray = b2CreateArray(sizeof(b2SensorEndTouchEvent), 4); - world->contactBeginArray = b2CreateArray(sizeof(b2ContactBeginTouchEvent), 4); - world->contactEndArray = b2CreateArray(sizeof(b2ContactEndTouchEvent), 4); - world->contactHitArray = b2CreateArray(sizeof(b2ContactHitEvent), 4); + world->bodyMoveEventArray = b2CreateArray( sizeof( b2BodyMoveEvent ), 4 ); + world->sensorBeginEventArray = b2CreateArray( sizeof( b2SensorBeginTouchEvent ), 4 ); + world->sensorEndEventArray = b2CreateArray( sizeof( b2SensorEndTouchEvent ), 4 ); + world->contactBeginArray = b2CreateArray( sizeof( b2ContactBeginTouchEvent ), 4 ); + world->contactEndArray = b2CreateArray( sizeof( b2ContactEndTouchEvent ), 4 ); + world->contactHitArray = b2CreateArray( sizeof( b2ContactHitEvent ), 4 ); world->stepIndex = 0; world->splitIslandId = B2_NULL_INDEX; @@ -176,9 +176,9 @@ b2WorldId b2CreateWorld(const b2WorldDef* def) world->enableContinuous = def->enableContinous; world->userTreeTask = NULL; - if (def->workerCount > 0 && def->enqueueTask != NULL && def->finishTask != NULL) + if ( def->workerCount > 0 && def->enqueueTask != NULL && def->finishTask != NULL ) { - world->workerCount = b2MinInt(def->workerCount, b2_maxWorkers); + world->workerCount = b2MinInt( def->workerCount, b2_maxWorkers ); world->enqueueTaskFcn = def->enqueueTask; world->finishTaskFcn = def->finishTask; world->userTaskContext = def->userTaskContext; @@ -191,117 +191,117 @@ b2WorldId b2CreateWorld(const b2WorldDef* def) world->userTaskContext = NULL; } - world->taskContextArray = b2CreateArray(sizeof(b2TaskContext), world->workerCount); - for (int i = 0; i < world->workerCount; ++i) + world->taskContextArray = b2CreateArray( sizeof( b2TaskContext ), world->workerCount ); + for ( int i = 0; i < world->workerCount; ++i ) { - world->taskContextArray[i].contactStateBitSet = b2CreateBitSet(1024); - world->taskContextArray[i].enlargedSimBitSet = b2CreateBitSet(256); - world->taskContextArray[i].awakeIslandBitSet = b2CreateBitSet(256); + world->taskContextArray[i].contactStateBitSet = b2CreateBitSet( 1024 ); + world->taskContextArray[i].enlargedSimBitSet = b2CreateBitSet( 256 ); + world->taskContextArray[i].awakeIslandBitSet = b2CreateBitSet( 256 ); } - world->debugBodySet = b2CreateBitSet(256); - world->debugJointSet = b2CreateBitSet(256); - world->debugContactSet = b2CreateBitSet(256); + world->debugBodySet = b2CreateBitSet( 256 ); + world->debugJointSet = b2CreateBitSet( 256 ); + world->debugContactSet = b2CreateBitSet( 256 ); // add one to worldId so that 0 represents a null b2WorldId - return (b2WorldId){(uint16_t)(worldId + 1), world->revision}; + return ( b2WorldId ){ (uint16_t)( worldId + 1 ), world->revision }; } -void b2DestroyWorld(b2WorldId worldId) +void b2DestroyWorld( b2WorldId worldId ) { - b2World* world = b2GetWorldFromId(worldId); + b2World* world = b2GetWorldFromId( worldId ); - b2DestroyBitSet(&world->debugBodySet); - b2DestroyBitSet(&world->debugJointSet); - b2DestroyBitSet(&world->debugContactSet); + b2DestroyBitSet( &world->debugBodySet ); + b2DestroyBitSet( &world->debugJointSet ); + b2DestroyBitSet( &world->debugContactSet ); - for (int i = 0; i < world->workerCount; ++i) + for ( int i = 0; i < world->workerCount; ++i ) { - b2DestroyBitSet(&world->taskContextArray[i].contactStateBitSet); - b2DestroyBitSet(&world->taskContextArray[i].enlargedSimBitSet); - b2DestroyBitSet(&world->taskContextArray[i].awakeIslandBitSet); + b2DestroyBitSet( &world->taskContextArray[i].contactStateBitSet ); + b2DestroyBitSet( &world->taskContextArray[i].enlargedSimBitSet ); + b2DestroyBitSet( &world->taskContextArray[i].awakeIslandBitSet ); } - b2DestroyArray(world->taskContextArray, sizeof(b2TaskContext)); + b2DestroyArray( world->taskContextArray, sizeof( b2TaskContext ) ); - b2DestroyArray(world->bodyMoveEventArray, sizeof(b2BodyMoveEvent)); - b2DestroyArray(world->sensorBeginEventArray, sizeof(b2SensorBeginTouchEvent)); - b2DestroyArray(world->sensorEndEventArray, sizeof(b2SensorEndTouchEvent)); - b2DestroyArray(world->contactBeginArray, sizeof(b2ContactBeginTouchEvent)); - b2DestroyArray(world->contactEndArray, sizeof(b2ContactEndTouchEvent)); - b2DestroyArray(world->contactHitArray, sizeof(b2ContactHitEvent)); + b2DestroyArray( world->bodyMoveEventArray, sizeof( b2BodyMoveEvent ) ); + b2DestroyArray( world->sensorBeginEventArray, sizeof( b2SensorBeginTouchEvent ) ); + b2DestroyArray( world->sensorEndEventArray, sizeof( b2SensorEndTouchEvent ) ); + b2DestroyArray( world->contactBeginArray, sizeof( b2ContactBeginTouchEvent ) ); + b2DestroyArray( world->contactEndArray, sizeof( b2ContactEndTouchEvent ) ); + b2DestroyArray( world->contactHitArray, sizeof( b2ContactHitEvent ) ); - int chainCapacity = b2Array(world->chainArray).count; - for (int i = 0; i < chainCapacity; ++i) + int chainCapacity = b2Array( world->chainArray ).count; + for ( int i = 0; i < chainCapacity; ++i ) { b2ChainShape* chain = world->chainArray + i; - if (chain->id != B2_NULL_INDEX) + if ( chain->id != B2_NULL_INDEX ) { - b2Free(chain->shapeIndices, chain->count * sizeof(int)); + b2Free( chain->shapeIndices, chain->count * sizeof( int ) ); } else { - B2_ASSERT(chain->shapeIndices == NULL); + B2_ASSERT( chain->shapeIndices == NULL ); } } - b2DestroyArray(world->bodyArray, sizeof(b2Body)); - b2DestroyArray(world->shapeArray, sizeof(b2Shape)); - b2DestroyArray(world->chainArray, sizeof(b2ChainShape)); - b2DestroyArray(world->contactArray, sizeof(b2Contact)); - b2DestroyArray(world->jointArray, sizeof(b2Joint)); - b2DestroyArray(world->islandArray, sizeof(b2Island)); + b2DestroyArray( world->bodyArray, sizeof( b2Body ) ); + b2DestroyArray( world->shapeArray, sizeof( b2Shape ) ); + b2DestroyArray( world->chainArray, sizeof( b2ChainShape ) ); + b2DestroyArray( world->contactArray, sizeof( b2Contact ) ); + b2DestroyArray( world->jointArray, sizeof( b2Joint ) ); + b2DestroyArray( world->islandArray, sizeof( b2Island ) ); // The data in the solvers sets all comes from the block allocator so no // need to destroy the set contents. // todo testing - int setCapacity = b2Array(world->solverSetArray).count; - for (int i = 0; i < setCapacity; ++i) + int setCapacity = b2Array( world->solverSetArray ).count; + for ( int i = 0; i < setCapacity; ++i ) { b2SolverSet* set = world->solverSetArray + i; - if (set->setIndex != B2_NULL_INDEX) + if ( set->setIndex != B2_NULL_INDEX ) { - b2DestroySolverSet(world, i); + b2DestroySolverSet( world, i ); } } - b2DestroyArray(world->solverSetArray, sizeof(b2SolverSet)); + b2DestroyArray( world->solverSetArray, sizeof( b2SolverSet ) ); - b2DestroyGraph(&world->constraintGraph); - b2DestroyBroadPhase(&world->broadPhase); + b2DestroyGraph( &world->constraintGraph ); + b2DestroyBroadPhase( &world->broadPhase ); - b2DestroyIdPool(&world->bodyIdPool); - b2DestroyIdPool(&world->shapeIdPool); - b2DestroyIdPool(&world->chainIdPool); - b2DestroyIdPool(&world->contactIdPool); - b2DestroyIdPool(&world->jointIdPool); - b2DestroyIdPool(&world->islandIdPool); - b2DestroyIdPool(&world->solverSetIdPool); + b2DestroyIdPool( &world->bodyIdPool ); + b2DestroyIdPool( &world->shapeIdPool ); + b2DestroyIdPool( &world->chainIdPool ); + b2DestroyIdPool( &world->contactIdPool ); + b2DestroyIdPool( &world->jointIdPool ); + b2DestroyIdPool( &world->islandIdPool ); + b2DestroyIdPool( &world->solverSetIdPool ); - b2DestroyStackAllocator(&world->stackAllocator); + b2DestroyStackAllocator( &world->stackAllocator ); // Wipe world but preserve revision uint16_t revision = world->revision; - *world = (b2World){0}; + *world = ( b2World ){ 0 }; world->worldId = B2_NULL_INDEX; world->revision = revision + 1; } -static void b2CollideTask(int startIndex, int endIndex, uint32_t threadIndex, void* context) +static void b2CollideTask( int startIndex, int endIndex, uint32_t threadIndex, void* context ) { - b2TracyCZoneNC(collide_task, "Collide Task", b2_colorDodgerBlue1, true); + b2TracyCZoneNC( collide_task, "Collide Task", b2_colorDodgerBlue, true ); b2StepContext* stepContext = context; b2World* world = stepContext->world; - B2_ASSERT(threadIndex < world->workerCount); + B2_ASSERT( threadIndex < world->workerCount ); b2TaskContext* taskContext = world->taskContextArray + threadIndex; b2ContactSim** contactSims = stepContext->contacts; b2Shape* shapes = world->shapeArray; b2Body* bodies = world->bodyArray; - B2_ASSERT(startIndex < endIndex); + B2_ASSERT( startIndex < endIndex ); - for (int i = startIndex; i < endIndex; ++i) + for ( int i = startIndex; i < endIndex; ++i ) { b2ContactSim* contactSim = contactSims[i]; @@ -311,22 +311,22 @@ static void b2CollideTask(int startIndex, int endIndex, uint32_t threadIndex, vo b2Shape* shapeB = shapes + contactSim->shapeIdB; // Do proxies still overlap? - bool overlap = b2AABB_Overlaps(shapeA->fatAABB, shapeB->fatAABB); - if (overlap == false) + bool overlap = b2AABB_Overlaps( shapeA->fatAABB, shapeB->fatAABB ); + if ( overlap == false ) { contactSim->simFlags |= b2_simDisjoint; contactSim->simFlags &= ~b2_simTouchingFlag; - b2SetBit(&taskContext->contactStateBitSet, contactId); + b2SetBit( &taskContext->contactStateBitSet, contactId ); } else { - bool wasTouching = (contactSim->simFlags & b2_simTouchingFlag); + bool wasTouching = ( contactSim->simFlags & b2_simTouchingFlag ); // Update contact respecting shape/body order (A,B) b2Body* bodyA = bodies + shapeA->bodyId; b2Body* bodyB = bodies + shapeB->bodyId; - b2BodySim* bodySimA = b2GetBodySim(world, bodyA); - b2BodySim* bodySimB = b2GetBodySim(world, bodyB); + b2BodySim* bodySimA = b2GetBodySim( world, bodyA ); + b2BodySim* bodySimB = b2GetBodySim( world, bodyB ); // avoid cache misses in b2PrepareContactsTask contactSim->bodySimIndexA = bodyA->setIndex == b2_awakeSet ? bodyA->localIndex : B2_NULL_INDEX; @@ -340,91 +340,91 @@ static void b2CollideTask(int startIndex, int endIndex, uint32_t threadIndex, vo b2Transform transformA = bodySimA->transform; b2Transform transformB = bodySimB->transform; - b2Vec2 centerOffsetA = b2RotateVector(transformA.q, bodySimA->localCenter); - b2Vec2 centerOffsetB = b2RotateVector(transformB.q, bodySimB->localCenter); + b2Vec2 centerOffsetA = b2RotateVector( transformA.q, bodySimA->localCenter ); + b2Vec2 centerOffsetB = b2RotateVector( transformB.q, bodySimB->localCenter ); // This updates solid contacts and sensors bool touching = - b2UpdateContact(world, contactSim, shapeA, transformA, centerOffsetA, shapeB, transformB, centerOffsetB); + b2UpdateContact( world, contactSim, shapeA, transformA, centerOffsetA, shapeB, transformB, centerOffsetB ); // State changes that affect island connectivity. Also contact and sensor events. - if (touching == true && wasTouching == false) + if ( touching == true && wasTouching == false ) { contactSim->simFlags |= b2_simStartedTouching; - b2SetBit(&taskContext->contactStateBitSet, contactId); + b2SetBit( &taskContext->contactStateBitSet, contactId ); } - else if (touching == false && wasTouching == true) + else if ( touching == false && wasTouching == true ) { contactSim->simFlags |= b2_simStoppedTouching; - b2SetBit(&taskContext->contactStateBitSet, contactId); + b2SetBit( &taskContext->contactStateBitSet, contactId ); } } } - b2TracyCZoneEnd(collide_task); + b2TracyCZoneEnd( collide_task ); } -static void b2UpdateTreesTask(int startIndex, int endIndex, uint32_t threadIndex, void* context) +static void b2UpdateTreesTask( int startIndex, int endIndex, uint32_t threadIndex, void* context ) { - B2_MAYBE_UNUSED(startIndex); - B2_MAYBE_UNUSED(endIndex); - B2_MAYBE_UNUSED(threadIndex); + B2_MAYBE_UNUSED( startIndex ); + B2_MAYBE_UNUSED( endIndex ); + B2_MAYBE_UNUSED( threadIndex ); - b2TracyCZoneNC(tree_task, "Rebuild Trees", b2_colorSnow1, true); + b2TracyCZoneNC( tree_task, "Rebuild Trees", b2_colorSnow, true ); b2World* world = context; - b2BroadPhase_RebuildTrees(&world->broadPhase); + b2BroadPhase_RebuildTrees( &world->broadPhase ); - b2TracyCZoneEnd(tree_task); + b2TracyCZoneEnd( tree_task ); } -static void b2AddNonTouchingContact(b2World* world, b2Contact* contact, b2ContactSim* contactSim) +static void b2AddNonTouchingContact( b2World* world, b2Contact* contact, b2ContactSim* contactSim ) { - B2_ASSERT(contact->setIndex == b2_awakeSet); + B2_ASSERT( contact->setIndex == b2_awakeSet ); b2SolverSet* set = world->solverSetArray + b2_awakeSet; contact->colorIndex = B2_NULL_INDEX; contact->localIndex = set->contacts.count; - b2ContactSim* newContactSim = b2AddContact(&set->contacts); - memcpy(newContactSim, contactSim, sizeof(b2ContactSim)); + b2ContactSim* newContactSim = b2AddContact( &set->contacts ); + memcpy( newContactSim, contactSim, sizeof( b2ContactSim ) ); } -static void b2RemoveNonTouchingContact(b2World* world, int setIndex, int localIndex) +static void b2RemoveNonTouchingContact( b2World* world, int setIndex, int localIndex ) { - b2CheckIndex(world->solverSetArray, setIndex); + b2CheckIndex( world->solverSetArray, setIndex ); b2SolverSet* set = world->solverSetArray + setIndex; - int movedIndex = b2RemoveContact(&set->contacts, localIndex); - if (movedIndex != B2_NULL_INDEX) + int movedIndex = b2RemoveContact( &set->contacts, localIndex ); + if ( movedIndex != B2_NULL_INDEX ) { b2ContactSim* movedContactSim = set->contacts.data + localIndex; - b2CheckIndex(world->contactArray, movedContactSim->contactId); + b2CheckIndex( world->contactArray, movedContactSim->contactId ); b2Contact* movedContact = world->contactArray + movedContactSim->contactId; - B2_ASSERT(movedContact->setIndex == setIndex); - B2_ASSERT(movedContact->localIndex == movedIndex); - B2_ASSERT(movedContact->colorIndex == B2_NULL_INDEX); + B2_ASSERT( movedContact->setIndex == setIndex ); + B2_ASSERT( movedContact->localIndex == movedIndex ); + B2_ASSERT( movedContact->colorIndex == B2_NULL_INDEX ); movedContact->localIndex = localIndex; } } // Narrow-phase collision -static void b2Collide(b2StepContext* context) +static void b2Collide( b2StepContext* context ) { b2World* world = context->world; - B2_ASSERT(world->workerCount > 0); + B2_ASSERT( world->workerCount > 0 ); - b2TracyCZoneNC(collide, "Collide", b2_colorDarkOrchid, true); + b2TracyCZoneNC( collide, "Collide", b2_colorDarkOrchid, true ); // Tasks 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 - world->userTreeTask = world->enqueueTaskFcn(&b2UpdateTreesTask, 1, 1, world, world->userTaskContext); + world->userTreeTask = world->enqueueTaskFcn( &b2UpdateTreesTask, 1, 1, world, world->userTaskContext ); world->taskCount += 1; world->activeTaskCount += world->userTreeTask == NULL ? 0 : 1; // gather contacts into a single array for easier parallel-for int contactCount = 0; b2GraphColor* graphColors = world->constraintGraph.colors; - for (int i = 0; i < b2_graphColorCount; ++i) + for ( int i = 0; i < b2_graphColorCount; ++i ) { contactCount += graphColors[i].contacts.count; } @@ -432,21 +432,21 @@ static void b2Collide(b2StepContext* context) int nonTouchingCount = world->solverSetArray[b2_awakeSet].contacts.count; contactCount += nonTouchingCount; - if (contactCount == 0) + if ( contactCount == 0 ) { - b2TracyCZoneEnd(collide); + b2TracyCZoneEnd( collide ); return; } - b2ContactSim** contactSims = b2AllocateStackItem(&world->stackAllocator, contactCount * sizeof(b2ContactSim), "contacts"); + b2ContactSim** contactSims = b2AllocateStackItem( &world->stackAllocator, contactCount * sizeof( b2ContactSim ), "contacts" ); int contactIndex = 0; - for (int i = 0; i < b2_graphColorCount; ++i) + for ( int i = 0; i < b2_graphColorCount; ++i ) { b2GraphColor* color = graphColors + i; int count = color->contacts.count; b2ContactSim* base = color->contacts.data; - for (int j = 0; j < count; ++j) + for ( int j = 0; j < count; ++j ) { contactSims[contactIndex] = base + j; contactIndex += 1; @@ -455,45 +455,45 @@ static void b2Collide(b2StepContext* context) { b2ContactSim* base = world->solverSetArray[b2_awakeSet].contacts.data; - for (int i = 0; i < nonTouchingCount; ++i) + for ( int i = 0; i < nonTouchingCount; ++i ) { contactSims[contactIndex] = base + i; contactIndex += 1; } } - B2_ASSERT(contactIndex == contactCount); + B2_ASSERT( contactIndex == contactCount ); context->contacts = contactSims; // Contact bit set on ids because contact pointers are unstable as they move between touching and not touching. - int contactIdCapacity = b2GetIdCapacity(&world->contactIdPool); - for (int i = 0; i < world->workerCount; ++i) + int contactIdCapacity = b2GetIdCapacity( &world->contactIdPool ); + for ( int i = 0; i < world->workerCount; ++i ) { - b2SetBitCountAndClear(&world->taskContextArray[i].contactStateBitSet, contactIdCapacity); + b2SetBitCountAndClear( &world->taskContextArray[i].contactStateBitSet, contactIdCapacity ); } // Task should take at least 40us on a 4GHz CPU (10K cycles) int minRange = 64; - void* userCollideTask = world->enqueueTaskFcn(&b2CollideTask, contactCount, minRange, context, world->userTaskContext); + void* userCollideTask = world->enqueueTaskFcn( &b2CollideTask, contactCount, minRange, context, world->userTaskContext ); world->taskCount += 1; - if (userCollideTask != NULL) + if ( userCollideTask != NULL ) { - world->finishTaskFcn(userCollideTask, world->userTaskContext); + world->finishTaskFcn( userCollideTask, world->userTaskContext ); } - b2FreeStackItem(&world->stackAllocator, contactSims); + b2FreeStackItem( &world->stackAllocator, contactSims ); context->contacts = NULL; contactSims = NULL; // Serially update contact state - b2TracyCZoneNC(contact_state, "Contact State", b2_colorCoral, true); + b2TracyCZoneNC( contact_state, "Contact State", b2_colorCoral, true ); // Bitwise OR all contact bits b2BitSet* bitSet = &world->taskContextArray[0].contactStateBitSet; - for (int i = 1; i < world->workerCount; ++i) + for ( int i = 1; i < world->workerCount; ++i ) { - b2InPlaceUnion(bitSet, &world->taskContextArray[i].contactStateBitSet); + b2InPlaceUnion( bitSet, &world->taskContextArray[i].contactStateBitSet ); } b2Contact* contacts = world->contactArray; @@ -503,77 +503,77 @@ static void b2Collide(b2StepContext* context) int16_t worldId = world->worldId; // Process contact state changes. Iterate over set bits - for (uint32_t k = 0; k < bitSet->blockCount; ++k) + for ( uint32_t k = 0; k < bitSet->blockCount; ++k ) { uint64_t bits = bitSet->bits[k]; - while (bits != 0) + while ( bits != 0 ) { - uint32_t ctz = b2CTZ64(bits); - int contactId = (int)(64 * k + ctz); + uint32_t ctz = b2CTZ64( bits ); + int contactId = (int)( 64 * k + ctz ); - b2CheckIndex(contacts, contactId); + b2CheckIndex( contacts, contactId ); b2Contact* contact = contacts + contactId; - B2_ASSERT(contact->setIndex == b2_awakeSet); + B2_ASSERT( contact->setIndex == b2_awakeSet ); int colorIndex = contact->colorIndex; int localIndex = contact->localIndex; b2ContactSim* contactSim = NULL; - if (colorIndex != B2_NULL_INDEX) + if ( colorIndex != B2_NULL_INDEX ) { // contact lives in constraint graph - B2_ASSERT(0 <= colorIndex && colorIndex < b2_graphColorCount); + B2_ASSERT( 0 <= colorIndex && colorIndex < b2_graphColorCount ); b2GraphColor* color = graphColors + colorIndex; - B2_ASSERT(0 <= localIndex && localIndex < color->contacts.count); + B2_ASSERT( 0 <= localIndex && localIndex < color->contacts.count ); contactSim = color->contacts.data + localIndex; } else { - B2_ASSERT(0 <= localIndex && localIndex < awakeSet->contacts.count); + B2_ASSERT( 0 <= localIndex && localIndex < awakeSet->contacts.count ); contactSim = awakeSet->contacts.data + localIndex; } const b2Shape* shapeA = shapes + contact->shapeIdA; const b2Shape* shapeB = shapes + contact->shapeIdB; - b2ShapeId shapeIdA = {shapeA->id + 1, worldId, shapeA->revision}; - b2ShapeId shapeIdB = {shapeB->id + 1, worldId, shapeB->revision}; + b2ShapeId shapeIdA = { shapeA->id + 1, worldId, shapeA->revision }; + b2ShapeId shapeIdB = { shapeB->id + 1, worldId, shapeB->revision }; uint32_t flags = contact->flags; uint32_t simFlags = contactSim->simFlags; - if (simFlags & b2_simDisjoint) + if ( simFlags & b2_simDisjoint ) { // Was touching? - if ((flags & b2_contactTouchingFlag) != 0 && (flags & b2_contactEnableContactEvents) != 0) + if ( ( flags & b2_contactTouchingFlag ) != 0 && ( flags & b2_contactEnableContactEvents ) != 0 ) { - b2ContactEndTouchEvent event = {shapeIdA, shapeIdB}; - b2Array_Push(world->contactEndArray, event); + b2ContactEndTouchEvent event = { shapeIdA, shapeIdB }; + b2Array_Push( world->contactEndArray, event ); } // Bounding boxes no longer overlap contact->flags &= ~b2_contactTouchingFlag; - b2DestroyContact(world, contact, false); + b2DestroyContact( world, contact, false ); contact = NULL; contactSim = NULL; } - else if (simFlags & b2_simStartedTouching) + else if ( simFlags & b2_simStartedTouching ) { - B2_ASSERT(contact->islandId == B2_NULL_INDEX); - if ((flags & b2_contactSensorFlag) != 0) + B2_ASSERT( contact->islandId == B2_NULL_INDEX ); + if ( ( flags & b2_contactSensorFlag ) != 0 ) { // Contact is a sensor - if ((flags & b2_contactEnableSensorEvents) != 0) + if ( ( flags & b2_contactEnableSensorEvents ) != 0 ) { - if (shapeA->isSensor) + if ( shapeA->isSensor ) { - b2SensorBeginTouchEvent event = {shapeIdA, shapeIdB}; - b2Array_Push(world->sensorBeginEventArray, event); + b2SensorBeginTouchEvent event = { shapeIdA, shapeIdB }; + b2Array_Push( world->sensorBeginEventArray, event ); } - if (shapeB->isSensor) + if ( shapeB->isSensor ) { - b2SensorBeginTouchEvent event = {shapeIdB, shapeIdA}; - b2Array_Push(world->sensorBeginEventArray, event); + b2SensorBeginTouchEvent event = { shapeIdB, shapeIdA }; + b2Array_Push( world->sensorBeginEventArray, event ); } } @@ -583,124 +583,123 @@ static void b2Collide(b2StepContext* context) else { // Contact is solid - if (flags & b2_contactEnableContactEvents) + if ( flags & b2_contactEnableContactEvents ) { - b2ContactBeginTouchEvent event = {shapeIdA, shapeIdB}; - b2Array_Push(world->contactBeginArray, event); + b2ContactBeginTouchEvent event = { shapeIdA, shapeIdB }; + b2Array_Push( world->contactBeginArray, event ); } - B2_ASSERT(contactSim->manifold.pointCount > 0); - B2_ASSERT(contact->setIndex == b2_awakeSet); + B2_ASSERT( contactSim->manifold.pointCount > 0 ); + B2_ASSERT( contact->setIndex == b2_awakeSet ); // Link first because this wakes colliding bodies and ensures the body sims // are in the correct place. contact->flags |= b2_contactTouchingFlag; - b2LinkContact(world, contact); + b2LinkContact( world, contact ); // Make sure these didn't change - B2_ASSERT(contact->colorIndex == B2_NULL_INDEX); - B2_ASSERT(contact->localIndex == localIndex); + B2_ASSERT( contact->colorIndex == B2_NULL_INDEX ); + B2_ASSERT( contact->localIndex == localIndex ); // Contact sim pointer may have become orphaned due to awake set growth, // so I just need to refresh it. - B2_ASSERT(0 <= localIndex && localIndex < awakeSet->contacts.count); + B2_ASSERT( 0 <= localIndex && localIndex < awakeSet->contacts.count ); contactSim = awakeSet->contacts.data + localIndex; contactSim->simFlags &= ~b2_simStartedTouching; - b2AddContactToGraph(world, contactSim, contact); - b2RemoveNonTouchingContact(world, b2_awakeSet, localIndex); + b2AddContactToGraph( world, contactSim, contact ); + b2RemoveNonTouchingContact( world, b2_awakeSet, localIndex ); contactSim = NULL; } } - else if (simFlags & b2_simStoppedTouching) + else if ( simFlags & b2_simStoppedTouching ) { contactSim->simFlags &= ~b2_simStoppedTouching; - if ((flags & b2_contactSensorFlag) != 0) + if ( ( flags & b2_contactSensorFlag ) != 0 ) { // Contact is a sensor contact->flags &= ~b2_contactSensorTouchingFlag; - if ((flags & b2_contactEnableSensorEvents) != 0) + if ( ( flags & b2_contactEnableSensorEvents ) != 0 ) { - if (shapeA->isSensor) + if ( shapeA->isSensor ) { - b2SensorEndTouchEvent event = {shapeIdA, shapeIdB}; - b2Array_Push(world->sensorEndEventArray, event); + b2SensorEndTouchEvent event = { shapeIdA, shapeIdB }; + b2Array_Push( world->sensorEndEventArray, event ); } - if (shapeB->isSensor) + if ( shapeB->isSensor ) { - b2SensorEndTouchEvent event = {shapeIdB, shapeIdA}; - b2Array_Push(world->sensorEndEventArray, event); + b2SensorEndTouchEvent event = { shapeIdB, shapeIdA }; + b2Array_Push( world->sensorEndEventArray, event ); } } - } else { // Contact is solid contact->flags &= ~b2_contactTouchingFlag; - if (contact->flags & b2_contactEnableContactEvents) + if ( contact->flags & b2_contactEnableContactEvents ) { - b2ContactEndTouchEvent event = {shapeIdA, shapeIdB}; - b2Array_Push(world->contactEndArray, event); + b2ContactEndTouchEvent event = { shapeIdA, shapeIdB }; + b2Array_Push( world->contactEndArray, event ); } - B2_ASSERT(contactSim->manifold.pointCount == 0); + B2_ASSERT( contactSim->manifold.pointCount == 0 ); - b2UnlinkContact(world, contact); + b2UnlinkContact( world, contact ); int bodyIdA = contact->edges[0].bodyId; int bodyIdB = contact->edges[1].bodyId; - b2AddNonTouchingContact(world, contact, contactSim); - b2RemoveContactFromGraph(world, bodyIdA, bodyIdB, colorIndex, localIndex); + b2AddNonTouchingContact( world, contact, contactSim ); + b2RemoveContactFromGraph( world, bodyIdA, bodyIdB, colorIndex, localIndex ); contact = NULL; contactSim = NULL; } } // Clear the smallest set bit - bits = bits & (bits - 1); + bits = bits & ( bits - 1 ); } } - b2ValidateSolverSets(world); - b2ValidateContacts(world); + b2ValidateSolverSets( world ); + b2ValidateContacts( world ); - b2TracyCZoneEnd(contact_state); - b2TracyCZoneEnd(collide); + b2TracyCZoneEnd( contact_state ); + b2TracyCZoneEnd( collide ); } -void b2World_Step(b2WorldId worldId, float timeStep, int subStepCount) +void b2World_Step( b2WorldId worldId, float timeStep, int subStepCount ) { - b2World* world = b2GetWorldFromId(worldId); - B2_ASSERT(world->locked == false); - if (world->locked) + b2World* world = b2GetWorldFromId( worldId ); + B2_ASSERT( world->locked == false ); + if ( world->locked ) { return; } // Prepare to capture events // Ensure user does not access stale data if there is an early return - b2Array_Clear(world->bodyMoveEventArray); - b2Array_Clear(world->sensorBeginEventArray); - b2Array_Clear(world->sensorEndEventArray); - b2Array_Clear(world->contactBeginArray); - b2Array_Clear(world->contactEndArray); - b2Array_Clear(world->contactHitArray); + b2Array_Clear( world->bodyMoveEventArray ); + b2Array_Clear( world->sensorBeginEventArray ); + b2Array_Clear( world->sensorEndEventArray ); + b2Array_Clear( world->contactBeginArray ); + b2Array_Clear( world->contactEndArray ); + b2Array_Clear( world->contactHitArray ); - world->profile = (b2Profile){0}; + world->profile = ( b2Profile ){ 0 }; - if (timeStep == 0.0f) + if ( timeStep == 0.0f ) { // todo would be useful to still process collision while paused return; } - b2TracyCZoneNC(world_step, "Step", b2_colorChartreuse, true); + b2TracyCZoneNC( world_step, "Step", b2_colorChartreuse, true ); world->locked = true; world->activeTaskCount = 0; @@ -711,16 +710,16 @@ void b2World_Step(b2WorldId worldId, float timeStep, int subStepCount) // Update collision pairs and create contacts { b2Timer timer = b2CreateTimer(); - b2UpdateBroadPhasePairs(world); - world->profile.pairs = b2GetMilliseconds(&timer); + b2UpdateBroadPhasePairs( world ); + world->profile.pairs = b2GetMilliseconds( &timer ); } - b2StepContext context = {0}; + b2StepContext context = { 0 }; context.world = world; context.dt = timeStep; - context.subStepCount = b2MaxInt(1, subStepCount); + context.subStepCount = b2MaxInt( 1, subStepCount ); - if (timeStep > 0.0f) + if ( timeStep > 0.0f ) { context.inv_dt = 1.0f / timeStep; context.h = timeStep / context.subStepCount; @@ -736,12 +735,12 @@ void b2World_Step(b2WorldId worldId, float timeStep, int subStepCount) world->inv_h = context.inv_h; // Hertz values get reduced for large time steps - float contactHertz = b2MinFloat(world->contactHertz, 0.25f * context.inv_h); - float jointHertz = b2MinFloat(world->jointHertz, 0.125f * context.inv_h); + float contactHertz = b2MinFloat( world->contactHertz, 0.25f * context.inv_h ); + float jointHertz = b2MinFloat( world->jointHertz, 0.125f * context.inv_h ); - context.contactSoftness = b2MakeSoft(contactHertz, world->contactDampingRatio, context.h); - context.staticSoftness = b2MakeSoft(2.0f * contactHertz, world->contactDampingRatio, context.h); - context.jointSoftness = b2MakeSoft(jointHertz, world->jointDampingRatio, context.h); + context.contactSoftness = b2MakeSoft( contactHertz, world->contactDampingRatio, context.h ); + context.staticSoftness = b2MakeSoft( 2.0f * contactHertz, world->contactDampingRatio, context.h ); + context.jointSoftness = b2MakeSoft( jointHertz, world->jointDampingRatio, context.h ); context.restitutionThreshold = world->restitutionThreshold; context.enableWarmStarting = world->enableWarmStarting; @@ -749,78 +748,78 @@ void b2World_Step(b2WorldId worldId, float timeStep, int subStepCount) // Update contacts { b2Timer timer = b2CreateTimer(); - b2Collide(&context); - world->profile.collide = b2GetMilliseconds(&timer); + b2Collide( &context ); + world->profile.collide = b2GetMilliseconds( &timer ); } // Integrate velocities, solve velocity constraints, and integrate positions. - if (context.dt > 0.0f) + if ( context.dt > 0.0f ) { b2Timer timer = b2CreateTimer(); - b2Solve(world, &context); - world->profile.solve = b2GetMilliseconds(&timer); + b2Solve( world, &context ); + world->profile.solve = b2GetMilliseconds( &timer ); } world->locked = false; - world->profile.step = b2GetMilliseconds(&stepTimer); + world->profile.step = b2GetMilliseconds( &stepTimer ); - B2_ASSERT(b2GetStackAllocation(&world->stackAllocator) == 0); + B2_ASSERT( b2GetStackAllocation( &world->stackAllocator ) == 0 ); // Ensure stack is large enough - b2GrowStack(&world->stackAllocator); + b2GrowStack( &world->stackAllocator ); // Make sure all tasks that were started were also finished - B2_ASSERT(world->activeTaskCount == 0); + B2_ASSERT( world->activeTaskCount == 0 ); - b2TracyCZoneEnd(world_step); + b2TracyCZoneEnd( world_step ); } -static void b2DrawShape(b2DebugDraw* draw, b2Shape* shape, b2Transform xf, b2HexColor color) +static void b2DrawShape( b2DebugDraw* draw, b2Shape* shape, b2Transform xf, b2HexColor color ) { - switch (shape->type) + switch ( shape->type ) { case b2_capsuleShape: { b2Capsule* capsule = &shape->capsule; - b2Vec2 p1 = b2TransformPoint(xf, capsule->center1); - b2Vec2 p2 = b2TransformPoint(xf, capsule->center2); - draw->DrawSolidCapsule(p1, p2, capsule->radius, color, draw->context); + b2Vec2 p1 = b2TransformPoint( xf, capsule->center1 ); + b2Vec2 p2 = b2TransformPoint( xf, capsule->center2 ); + draw->DrawSolidCapsule( p1, p2, capsule->radius, color, draw->context ); } break; case b2_circleShape: { b2Circle* circle = &shape->circle; - xf.p = b2TransformPoint(xf, circle->center); - draw->DrawSolidCircle(xf, circle->radius, color, draw->context); + xf.p = b2TransformPoint( xf, circle->center ); + draw->DrawSolidCircle( xf, circle->radius, color, draw->context ); } break; case b2_polygonShape: { b2Polygon* poly = &shape->polygon; - draw->DrawSolidPolygon(xf, poly->vertices, poly->count, poly->radius, color, draw->context); + draw->DrawSolidPolygon( xf, poly->vertices, poly->count, poly->radius, color, draw->context ); } break; case b2_segmentShape: { b2Segment* segment = &shape->segment; - b2Vec2 p1 = b2TransformPoint(xf, segment->point1); - b2Vec2 p2 = b2TransformPoint(xf, segment->point2); - draw->DrawSegment(p1, p2, color, draw->context); + b2Vec2 p1 = b2TransformPoint( xf, segment->point1 ); + b2Vec2 p2 = b2TransformPoint( xf, segment->point2 ); + draw->DrawSegment( p1, p2, color, draw->context ); } break; case b2_smoothSegmentShape: { b2Segment* segment = &shape->smoothSegment.segment; - b2Vec2 p1 = b2TransformPoint(xf, segment->point1); - b2Vec2 p2 = b2TransformPoint(xf, segment->point2); - draw->DrawSegment(p1, p2, color, draw->context); - draw->DrawPoint(p2, 4.0f, color, draw->context); - draw->DrawSegment(p1, b2Lerp(p1, p2, 0.1f), b2_colorPaleGreen, draw->context); + b2Vec2 p1 = b2TransformPoint( xf, segment->point1 ); + b2Vec2 p2 = b2TransformPoint( xf, segment->point2 ); + draw->DrawSegment( p1, p2, color, draw->context ); + draw->DrawPoint( p2, 4.0f, color, draw->context ); + draw->DrawSegment( p1, b2Lerp( p1, p2, 0.1f ), b2_colorPaleGreen, draw->context ); } break; @@ -835,61 +834,65 @@ struct DrawContext b2DebugDraw* draw; }; -static bool DrawQueryCallback(int proxyId, int shapeId, void* context) +static bool DrawQueryCallback( int proxyId, int shapeId, void* context ) { - B2_MAYBE_UNUSED(proxyId); + B2_MAYBE_UNUSED( proxyId ); struct DrawContext* drawContext = context; b2World* world = drawContext->world; b2DebugDraw* draw = drawContext->draw; - b2CheckId(world->shapeArray, shapeId); + b2CheckId( world->shapeArray, shapeId ); b2Shape* shape = world->shapeArray + shapeId; - b2SetBit(&world->debugBodySet, shape->bodyId); + b2SetBit( &world->debugBodySet, shape->bodyId ); - if (draw->drawShapes) + if ( draw->drawShapes ) { - b2CheckId(world->bodyArray, shape->bodyId); + b2CheckId( world->bodyArray, shape->bodyId ); b2Body* body = world->bodyArray + shape->bodyId; - b2BodySim* bodySim = b2GetBodySim(world, body); + b2BodySim* bodySim = b2GetBodySim( world, body ); b2HexColor color; - if (body->type == b2_dynamicBody && bodySim->mass == 0.0f) + if ( shape->customColor != 0 ) + { + color = shape->customColor; + } + else if ( body->type == b2_dynamicBody && bodySim->mass == 0.0f ) { // Bad body color = b2_colorRed; } - else if (body->setIndex == b2_disabledSet) + else if ( body->setIndex == b2_disabledSet ) { color = b2_colorSlateGray; } - else if (shape->isSensor) + else if ( shape->isSensor ) { color = b2_colorWheat; } - else if (bodySim->isBullet && body->setIndex == b2_awakeSet) + else if ( bodySim->isBullet && body->setIndex == b2_awakeSet ) { color = b2_colorTurquoise; } - else if (body->isSpeedCapped) + else if ( body->isSpeedCapped ) { color = b2_colorYellow; } - else if (bodySim->isFast) + else if ( bodySim->isFast ) { color = b2_colorSalmon; } - else if (body->type == b2_staticBody) + else if ( body->type == b2_staticBody ) { color = b2_colorPaleGreen; } - else if (body->type == b2_kinematicBody) + else if ( body->type == b2_kinematicBody ) { color = b2_colorRoyalBlue; } - else if (body->setIndex == b2_awakeSet) + else if ( body->setIndex == b2_awakeSet ) { color = b2_colorPink; } @@ -898,19 +901,19 @@ static bool DrawQueryCallback(int proxyId, int shapeId, void* context) color = b2_colorGray; } - b2DrawShape(draw, shape, bodySim->transform, color); + b2DrawShape( draw, shape, bodySim->transform, color ); } - if (draw->drawAABBs) + if ( draw->drawAABBs ) { b2AABB aabb = shape->fatAABB; - b2Vec2 vs[4] = {{aabb.lowerBound.x, aabb.lowerBound.y}, - {aabb.upperBound.x, aabb.lowerBound.y}, - {aabb.upperBound.x, aabb.upperBound.y}, - {aabb.lowerBound.x, aabb.upperBound.y}}; + b2Vec2 vs[4] = { { aabb.lowerBound.x, aabb.lowerBound.y }, + { aabb.upperBound.x, aabb.lowerBound.y }, + { aabb.upperBound.x, aabb.upperBound.y }, + { aabb.lowerBound.x, aabb.upperBound.y } }; - draw->DrawPolygon(vs, 4, b2_colorGold, draw->context); + draw->DrawPolygon( vs, 4, b2_colorGold, draw->context ); } return true; @@ -918,9 +921,9 @@ static bool DrawQueryCallback(int proxyId, int shapeId, void* context) // todo this has varying order for moving shapes, causing flicker when overlapping shapes are moving // solution: display order by shape id modulus 3, keep 3 buckets in GLSolid* and flush in 3 passes. -static void b2DrawWithBounds(b2World* world, b2DebugDraw* draw) +static void b2DrawWithBounds( b2World* world, b2DebugDraw* draw ) { - B2_ASSERT(b2AABB_IsValid(draw->drawingBounds)); + B2_ASSERT( b2AABB_IsValid( draw->drawingBounds ) ); const float k_impulseScale = 1.0f; const float k_axisScale = 0.3f; @@ -931,68 +934,69 @@ static void b2DrawWithBounds(b2World* world, b2DebugDraw* draw) b2HexColor impulseColor = b2_colorMagenta; b2HexColor frictionColor = b2_colorYellow; - b2HexColor graphColors[b2_graphColorCount] = {b2_colorRed, b2_colorOrange, b2_colorYellow, b2_colorGreen, - b2_colorCyan, b2_colorBlue, b2_colorViolet, b2_colorPink, - b2_colorChocolate, b2_colorGoldenrod, b2_colorCoral, b2_colorBlack}; + b2HexColor graphColors[b2_graphColorCount] = { b2_colorRed, b2_colorOrange, b2_colorYellow, b2_colorGreen, + b2_colorCyan, b2_colorBlue, b2_colorViolet, b2_colorPink, + b2_colorChocolate, b2_colorGoldenrod, b2_colorCoral, b2_colorBlack }; - int bodyCapacity = b2GetIdCapacity(&world->bodyIdPool); - b2SetBitCountAndClear(&world->debugBodySet, bodyCapacity); + int bodyCapacity = b2GetIdCapacity( &world->bodyIdPool ); + b2SetBitCountAndClear( &world->debugBodySet, bodyCapacity ); - int jointCapacity = b2GetIdCapacity(&world->jointIdPool); - b2SetBitCountAndClear(&world->debugJointSet, jointCapacity); + int jointCapacity = b2GetIdCapacity( &world->jointIdPool ); + b2SetBitCountAndClear( &world->debugJointSet, jointCapacity ); - int contactCapacity = b2GetIdCapacity(&world->contactIdPool); - b2SetBitCountAndClear(&world->debugContactSet, contactCapacity); + int contactCapacity = b2GetIdCapacity( &world->contactIdPool ); + b2SetBitCountAndClear( &world->debugContactSet, contactCapacity ); - struct DrawContext drawContext = {world, draw}; + struct DrawContext drawContext = { world, draw }; - for (int i = 0; i < b2_bodyTypeCount; ++i) + for ( int i = 0; i < b2_bodyTypeCount; ++i ) { - b2DynamicTree_Query(world->broadPhase.trees + i, draw->drawingBounds, b2_defaultMaskBits, DrawQueryCallback, &drawContext); + b2DynamicTree_Query( world->broadPhase.trees + i, draw->drawingBounds, b2_defaultMaskBits, DrawQueryCallback, + &drawContext ); } uint32_t wordCount = world->debugBodySet.blockCount; uint64_t* bits = world->debugBodySet.bits; - for (uint32_t k = 0; k < wordCount; ++k) + for ( uint32_t k = 0; k < wordCount; ++k ) { uint64_t word = bits[k]; - while (word != 0) + while ( word != 0 ) { - uint32_t ctz = b2CTZ64(word); + uint32_t ctz = b2CTZ64( word ); uint32_t bodyId = 64 * k + ctz; - b2CheckId(world->bodyArray, bodyId); + b2CheckId( world->bodyArray, bodyId ); b2Body* body = world->bodyArray + bodyId; - if (draw->drawMass && body->type == b2_dynamicBody) + if ( draw->drawMass && body->type == b2_dynamicBody ) { - b2Vec2 offset = {0.1f, 0.1f}; - b2BodySim* bodySim = b2GetBodySim(world, body); + b2Vec2 offset = { 0.1f, 0.1f }; + b2BodySim* bodySim = b2GetBodySim( world, body ); - b2Transform transform = {bodySim->center, bodySim->transform.q}; - draw->DrawTransform(transform, draw->context); + b2Transform transform = { bodySim->center, bodySim->transform.q }; + draw->DrawTransform( transform, draw->context ); - b2Vec2 p = b2TransformPoint(transform, offset); + b2Vec2 p = b2TransformPoint( transform, offset ); char buffer[32]; - snprintf(buffer, 32, " %.2f", bodySim->mass); - draw->DrawString(p, buffer, draw->context); + snprintf( buffer, 32, " %.2f", bodySim->mass ); + draw->DrawString( p, buffer, draw->context ); } - if (draw->drawJoints) + if ( draw->drawJoints ) { int jointKey = body->headJointKey; - while (jointKey != B2_NULL_INDEX) + while ( jointKey != B2_NULL_INDEX ) { int jointId = jointKey >> 1; int edgeIndex = jointKey & 1; b2Joint* joint = world->jointArray + jointId; // avoid double draw - if (b2GetBit(&world->debugJointSet, jointId) == false) + if ( b2GetBit( &world->debugJointSet, jointId ) == false ) { - b2DrawJoint(draw, world, joint); - b2SetBit(&world->debugJointSet, jointId); + b2DrawJoint( draw, world, joint ); + b2SetBit( &world->debugJointSet, jointId ); } else { @@ -1005,88 +1009,88 @@ static void b2DrawWithBounds(b2World* world, b2DebugDraw* draw) } const float linearSlop = b2_linearSlop; - if (draw->drawContacts && body->type == b2_dynamicBody && body->setIndex == b2_awakeSet) + if ( draw->drawContacts && body->type == b2_dynamicBody && body->setIndex == b2_awakeSet ) { int contactKey = body->headContactKey; - while (contactKey != B2_NULL_INDEX) + while ( contactKey != B2_NULL_INDEX ) { int contactId = contactKey >> 1; int edgeIndex = contactKey & 1; b2Contact* contact = world->contactArray + contactId; contactKey = contact->edges[edgeIndex].nextKey; - if (contact->setIndex != b2_awakeSet || contact->colorIndex == B2_NULL_INDEX) + if ( contact->setIndex != b2_awakeSet || contact->colorIndex == B2_NULL_INDEX ) { continue; } // avoid double draw - if (b2GetBit(&world->debugContactSet, contactId) == false) + if ( b2GetBit( &world->debugContactSet, contactId ) == false ) { - B2_ASSERT(0 <= contact->colorIndex && contact->colorIndex < b2_graphColorCount); + B2_ASSERT( 0 <= contact->colorIndex && contact->colorIndex < b2_graphColorCount ); b2GraphColor* gc = world->constraintGraph.colors + contact->colorIndex; - B2_ASSERT(0 <= contact->localIndex && contact->localIndex < gc->contacts.count); + B2_ASSERT( 0 <= contact->localIndex && contact->localIndex < gc->contacts.count ); b2ContactSim* contactSim = gc->contacts.data + contact->localIndex; int pointCount = contactSim->manifold.pointCount; b2Vec2 normal = contactSim->manifold.normal; char buffer[32]; - for (int j = 0; j < pointCount; ++j) + for ( int j = 0; j < pointCount; ++j ) { b2ManifoldPoint* point = contactSim->manifold.points + j; - if (draw->drawGraphColors) + if ( draw->drawGraphColors ) { // graph color float pointSize = contact->colorIndex == b2_overflowIndex ? 7.5f : 5.0f; - draw->DrawPoint(point->point, pointSize, graphColors[contact->colorIndex], draw->context); + draw->DrawPoint( point->point, pointSize, graphColors[contact->colorIndex], draw->context ); // g_draw.DrawString(point->position, "%d", point->color); } - else if (point->separation > linearSlop) + else if ( point->separation > linearSlop ) { // Speculative - draw->DrawPoint(point->point, 5.0f, speculativeColor, draw->context); + draw->DrawPoint( point->point, 5.0f, speculativeColor, draw->context ); } - else if (point->persisted == false) + else if ( point->persisted == false ) { // Add - draw->DrawPoint(point->point, 10.0f, addColor, draw->context); + draw->DrawPoint( point->point, 10.0f, addColor, draw->context ); } - else if (point->persisted == true) + else if ( point->persisted == true ) { // Persist - draw->DrawPoint(point->point, 5.0f, persistColor, draw->context); + draw->DrawPoint( point->point, 5.0f, persistColor, draw->context ); } - if (draw->drawContactNormals) + if ( draw->drawContactNormals ) { b2Vec2 p1 = point->point; - b2Vec2 p2 = b2MulAdd(p1, k_axisScale, normal); - draw->DrawSegment(p1, p2, normalColor, draw->context); + b2Vec2 p2 = b2MulAdd( p1, k_axisScale, normal ); + draw->DrawSegment( p1, p2, normalColor, draw->context ); } - else if (draw->drawContactImpulses) + else if ( draw->drawContactImpulses ) { b2Vec2 p1 = point->point; - b2Vec2 p2 = b2MulAdd(p1, k_impulseScale * point->normalImpulse, normal); - draw->DrawSegment(p1, p2, impulseColor, draw->context); - snprintf(buffer, B2_ARRAY_COUNT(buffer), "%.1f", 1000.0f * point->normalImpulse); - draw->DrawString(p1, buffer, draw->context); + b2Vec2 p2 = b2MulAdd( p1, k_impulseScale * point->normalImpulse, normal ); + draw->DrawSegment( p1, p2, impulseColor, draw->context ); + snprintf( buffer, B2_ARRAY_COUNT( buffer ), "%.1f", 1000.0f * point->normalImpulse ); + draw->DrawString( p1, buffer, draw->context ); } - if (draw->drawFrictionImpulses) + if ( draw->drawFrictionImpulses ) { - b2Vec2 tangent = b2RightPerp(normal); + b2Vec2 tangent = b2RightPerp( normal ); b2Vec2 p1 = point->point; - b2Vec2 p2 = b2MulAdd(p1, k_impulseScale * point->tangentImpulse, tangent); - draw->DrawSegment(p1, p2, frictionColor, draw->context); - snprintf(buffer, B2_ARRAY_COUNT(buffer), "%.1f", 1000.0f * point->tangentImpulse); - draw->DrawString(p1, buffer, draw->context); + b2Vec2 p2 = b2MulAdd( p1, k_impulseScale * point->tangentImpulse, tangent ); + draw->DrawSegment( p1, p2, frictionColor, draw->context ); + snprintf( buffer, B2_ARRAY_COUNT( buffer ), "%.1f", 1000.0f * point->tangentImpulse ); + draw->DrawString( p1, buffer, draw->context ); } } - b2SetBit(&world->debugContactSet, contactId); + b2SetBit( &world->debugContactSet, contactId ); } else { @@ -1099,82 +1103,86 @@ static void b2DrawWithBounds(b2World* world, b2DebugDraw* draw) } // Clear the smallest set bit - word = word & (word - 1); + word = word & ( word - 1 ); } } } -void b2World_Draw(b2WorldId worldId, b2DebugDraw* draw) +void b2World_Draw( b2WorldId worldId, b2DebugDraw* draw ) { - b2World* world = b2GetWorldFromId(worldId); - B2_ASSERT(world->locked == false); - if (world->locked) + b2World* world = b2GetWorldFromId( worldId ); + B2_ASSERT( world->locked == false ); + if ( world->locked ) { return; } // todo it seems bounds drawing is fast enough for regular usage - if (draw->useDrawingBounds) + if ( draw->useDrawingBounds ) { - b2DrawWithBounds(world, draw); + b2DrawWithBounds( world, draw ); return; } - if (draw->drawShapes) + if ( draw->drawShapes ) { - int setCount = b2Array(world->solverSetArray).count; - for (int setIndex = 0; setIndex < setCount; ++setIndex) + int setCount = b2Array( world->solverSetArray ).count; + for ( int setIndex = 0; setIndex < setCount; ++setIndex ) { b2SolverSet* set = world->solverSetArray + setIndex; int bodyCount = set->sims.count; - for (int bodyIndex = 0; bodyIndex < bodyCount; ++bodyIndex) + for ( int bodyIndex = 0; bodyIndex < bodyCount; ++bodyIndex ) { b2BodySim* bodySim = set->sims.data + bodyIndex; - b2CheckIndex(world->bodyArray, bodySim->bodyId); + b2CheckIndex( world->bodyArray, bodySim->bodyId ); b2Body* body = world->bodyArray + bodySim->bodyId; - B2_ASSERT(body->setIndex == setIndex); + B2_ASSERT( body->setIndex == setIndex ); b2Transform xf = bodySim->transform; int shapeId = body->headShapeId; - while (shapeId != B2_NULL_INDEX) + while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = world->shapeArray + shapeId; b2HexColor color; - if (body->type == b2_dynamicBody && bodySim->mass == 0.0f) + if ( shape->customColor != 0 ) + { + color = shape->customColor; + } + else if ( body->type == b2_dynamicBody && bodySim->mass == 0.0f ) { // Bad body color = b2_colorRed; } - else if (body->setIndex == b2_disabledSet) + else if ( body->setIndex == b2_disabledSet ) { color = b2_colorSlateGray; } - else if (shape->isSensor) + else if ( shape->isSensor ) { color = b2_colorWheat; } - else if (bodySim->isBullet && body->setIndex == b2_awakeSet) + else if ( bodySim->isBullet && body->setIndex == b2_awakeSet ) { color = b2_colorTurquoise; } - else if (body->isSpeedCapped) + else if ( body->isSpeedCapped ) { color = b2_colorYellow; } - else if (bodySim->isFast) + else if ( bodySim->isFast ) { color = b2_colorSalmon; } - else if (body->type == b2_staticBody) + else if ( body->type == b2_staticBody ) { color = b2_colorPaleGreen; } - else if (body->type == b2_kinematicBody) + else if ( body->type == b2_kinematicBody ) { color = b2_colorRoyalBlue; } - else if (body->setIndex == b2_awakeSet) + else if ( body->setIndex == b2_awakeSet ) { color = b2_colorPink; } @@ -1183,61 +1191,61 @@ void b2World_Draw(b2WorldId worldId, b2DebugDraw* draw) color = b2_colorGray; } - b2DrawShape(draw, shape, xf, color); + b2DrawShape( draw, shape, xf, color ); shapeId = shape->nextShapeId; } } } } - if (draw->drawJoints) + if ( draw->drawJoints ) { - int count = b2Array(world->jointArray).count; - for (int i = 0; i < count; ++i) + int count = b2Array( world->jointArray ).count; + for ( int i = 0; i < count; ++i ) { b2Joint* joint = world->jointArray + i; - if (joint->setIndex == B2_NULL_INDEX) + if ( joint->setIndex == B2_NULL_INDEX ) { continue; } - b2DrawJoint(draw, world, joint); + b2DrawJoint( draw, world, joint ); } } - if (draw->drawAABBs) + if ( draw->drawAABBs ) { b2HexColor color = b2_colorGold; - int setCount = b2Array(world->solverSetArray).count; - for (int setIndex = 0; setIndex < setCount; ++setIndex) + int setCount = b2Array( world->solverSetArray ).count; + for ( int setIndex = 0; setIndex < setCount; ++setIndex ) { b2SolverSet* set = world->solverSetArray + setIndex; int bodyCount = set->sims.count; - for (int bodyIndex = 0; bodyIndex < bodyCount; ++bodyIndex) + for ( int bodyIndex = 0; bodyIndex < bodyCount; ++bodyIndex ) { b2BodySim* bodySim = set->sims.data + bodyIndex; char buffer[32]; - snprintf(buffer, 32, "%d", bodySim->bodyId); - draw->DrawString(bodySim->center, buffer, draw->context); + snprintf( buffer, 32, "%d", bodySim->bodyId ); + draw->DrawString( bodySim->center, buffer, draw->context ); - b2CheckIndex(world->bodyArray, bodySim->bodyId); + b2CheckIndex( world->bodyArray, bodySim->bodyId ); b2Body* body = world->bodyArray + bodySim->bodyId; - B2_ASSERT(body->setIndex == setIndex); + B2_ASSERT( body->setIndex == setIndex ); int shapeId = body->headShapeId; - while (shapeId != B2_NULL_INDEX) + while ( shapeId != B2_NULL_INDEX ) { b2Shape* shape = world->shapeArray + shapeId; b2AABB aabb = shape->fatAABB; - b2Vec2 vs[4] = {{aabb.lowerBound.x, aabb.lowerBound.y}, - {aabb.upperBound.x, aabb.lowerBound.y}, - {aabb.upperBound.x, aabb.upperBound.y}, - {aabb.lowerBound.x, aabb.upperBound.y}}; + b2Vec2 vs[4] = { { aabb.lowerBound.x, aabb.lowerBound.y }, + { aabb.upperBound.x, aabb.lowerBound.y }, + { aabb.upperBound.x, aabb.upperBound.y }, + { aabb.lowerBound.x, aabb.upperBound.y } }; - draw->DrawPolygon(vs, 4, color, draw->context); + draw->DrawPolygon( vs, 4, color, draw->context ); shapeId = shape->nextShapeId; } @@ -1245,31 +1253,31 @@ void b2World_Draw(b2WorldId worldId, b2DebugDraw* draw) } } - if (draw->drawMass) + if ( draw->drawMass ) { - b2Vec2 offset = {0.1f, 0.1f}; - int setCount = b2Array(world->solverSetArray).count; - for (int setIndex = 0; setIndex < setCount; ++setIndex) + b2Vec2 offset = { 0.1f, 0.1f }; + int setCount = b2Array( world->solverSetArray ).count; + for ( int setIndex = 0; setIndex < setCount; ++setIndex ) { b2SolverSet* set = world->solverSetArray + setIndex; int bodyCount = set->sims.count; - for (int bodyIndex = 0; bodyIndex < bodyCount; ++bodyIndex) + for ( int bodyIndex = 0; bodyIndex < bodyCount; ++bodyIndex ) { b2BodySim* bodySim = set->sims.data + bodyIndex; - b2Transform transform = {bodySim->center, bodySim->transform.q}; - draw->DrawTransform(transform, draw->context); + b2Transform transform = { bodySim->center, bodySim->transform.q }; + draw->DrawTransform( transform, draw->context ); - b2Vec2 p = b2TransformPoint(transform, offset); + b2Vec2 p = b2TransformPoint( transform, offset ); char buffer[32]; - snprintf(buffer, 32, " %.2f", bodySim->mass); - draw->DrawString(p, buffer, draw->context); + snprintf( buffer, 32, " %.2f", bodySim->mass ); + draw->DrawString( p, buffer, draw->context ); } } } - if (draw->drawContacts) + if ( draw->drawContacts ) { const float k_impulseScale = 1.0f; const float k_axisScale = 0.3f; @@ -1282,72 +1290,72 @@ void b2World_Draw(b2WorldId worldId, b2DebugDraw* draw) b2HexColor impulseColor = b2_colorMagenta; b2HexColor frictionColor = b2_colorYellow; - b2HexColor colors[b2_graphColorCount] = {b2_colorRed, b2_colorOrange, b2_colorYellow, b2_colorGreen, - b2_colorCyan, b2_colorBlue, b2_colorViolet, b2_colorPink, - b2_colorChocolate, b2_colorGoldenrod, b2_colorCoral, b2_colorBlack}; + b2HexColor colors[b2_graphColorCount] = { b2_colorRed, b2_colorOrange, b2_colorYellow, b2_colorGreen, + b2_colorCyan, b2_colorBlue, b2_colorViolet, b2_colorPink, + b2_colorChocolate, b2_colorGoldenrod, b2_colorCoral, b2_colorBlack }; - for (int colorIndex = 0; colorIndex < b2_graphColorCount; ++colorIndex) + for ( int colorIndex = 0; colorIndex < b2_graphColorCount; ++colorIndex ) { b2GraphColor* graphColor = world->constraintGraph.colors + colorIndex; int contactCount = graphColor->contacts.count; - for (int contactIndex = 0; contactIndex < contactCount; ++contactIndex) + for ( int contactIndex = 0; contactIndex < contactCount; ++contactIndex ) { b2ContactSim* contact = graphColor->contacts.data + contactIndex; int pointCount = contact->manifold.pointCount; b2Vec2 normal = contact->manifold.normal; char buffer[32]; - for (int j = 0; j < pointCount; ++j) + for ( int j = 0; j < pointCount; ++j ) { b2ManifoldPoint* point = contact->manifold.points + j; - if (draw->drawGraphColors && 0 <= colorIndex && colorIndex <= b2_graphColorCount) + if ( draw->drawGraphColors && 0 <= colorIndex && colorIndex <= b2_graphColorCount ) { // graph color float pointSize = colorIndex == b2_overflowIndex ? 7.5f : 5.0f; - draw->DrawPoint(point->point, pointSize, colors[colorIndex], draw->context); + draw->DrawPoint( point->point, pointSize, colors[colorIndex], draw->context ); // g_draw.DrawString(point->position, "%d", point->color); } - else if (point->separation > linearSlop) + else if ( point->separation > linearSlop ) { // Speculative - draw->DrawPoint(point->point, 5.0f, speculativeColor, draw->context); + draw->DrawPoint( point->point, 5.0f, speculativeColor, draw->context ); } - else if (point->persisted == false) + else if ( point->persisted == false ) { // Add - draw->DrawPoint(point->point, 10.0f, addColor, draw->context); + draw->DrawPoint( point->point, 10.0f, addColor, draw->context ); } - else if (point->persisted == true) + else if ( point->persisted == true ) { // Persist - draw->DrawPoint(point->point, 5.0f, persistColor, draw->context); + draw->DrawPoint( point->point, 5.0f, persistColor, draw->context ); } - if (draw->drawContactNormals) + if ( draw->drawContactNormals ) { b2Vec2 p1 = point->point; - b2Vec2 p2 = b2MulAdd(p1, k_axisScale, normal); - draw->DrawSegment(p1, p2, normalColor, draw->context); + b2Vec2 p2 = b2MulAdd( p1, k_axisScale, normal ); + draw->DrawSegment( p1, p2, normalColor, draw->context ); } - else if (draw->drawContactImpulses) + else if ( draw->drawContactImpulses ) { b2Vec2 p1 = point->point; - b2Vec2 p2 = b2MulAdd(p1, k_impulseScale * point->normalImpulse, normal); - draw->DrawSegment(p1, p2, impulseColor, draw->context); - snprintf(buffer, B2_ARRAY_COUNT(buffer), "%.2f", 1000.0f * point->normalImpulse); - draw->DrawString(p1, buffer, draw->context); + b2Vec2 p2 = b2MulAdd( p1, k_impulseScale * point->normalImpulse, normal ); + draw->DrawSegment( p1, p2, impulseColor, draw->context ); + snprintf( buffer, B2_ARRAY_COUNT( buffer ), "%.2f", 1000.0f * point->normalImpulse ); + draw->DrawString( p1, buffer, draw->context ); } - if (draw->drawFrictionImpulses) + if ( draw->drawFrictionImpulses ) { - b2Vec2 tangent = b2RightPerp(normal); + b2Vec2 tangent = b2RightPerp( normal ); b2Vec2 p1 = point->point; - b2Vec2 p2 = b2MulAdd(p1, k_impulseScale * point->tangentImpulse, tangent); - draw->DrawSegment(p1, p2, frictionColor, draw->context); - snprintf(buffer, B2_ARRAY_COUNT(buffer), "%.2f", point->normalImpulse); - draw->DrawString(p1, buffer, draw->context); + b2Vec2 p2 = b2MulAdd( p1, k_impulseScale * point->tangentImpulse, tangent ); + draw->DrawSegment( p1, p2, frictionColor, draw->context ); + snprintf( buffer, B2_ARRAY_COUNT( buffer ), "%.2f", point->normalImpulse ); + draw->DrawString( p1, buffer, draw->context ); } } } @@ -1355,65 +1363,65 @@ void b2World_Draw(b2WorldId worldId, b2DebugDraw* draw) } } -b2BodyEvents b2World_GetBodyEvents(b2WorldId worldId) +b2BodyEvents b2World_GetBodyEvents( b2WorldId worldId ) { - b2World* world = b2GetWorldFromId(worldId); - B2_ASSERT(world->locked == false); - if (world->locked) + b2World* world = b2GetWorldFromId( worldId ); + B2_ASSERT( world->locked == false ); + if ( world->locked ) { - return (b2BodyEvents){0}; + return ( b2BodyEvents ){ 0 }; } - int count = b2Array(world->bodyMoveEventArray).count; - b2BodyEvents events = {world->bodyMoveEventArray, count}; + int count = b2Array( world->bodyMoveEventArray ).count; + b2BodyEvents events = { world->bodyMoveEventArray, count }; return events; } -b2SensorEvents b2World_GetSensorEvents(b2WorldId worldId) +b2SensorEvents b2World_GetSensorEvents( b2WorldId worldId ) { - b2World* world = b2GetWorldFromId(worldId); - B2_ASSERT(world->locked == false); - if (world->locked) + b2World* world = b2GetWorldFromId( worldId ); + B2_ASSERT( world->locked == false ); + if ( world->locked ) { - return (b2SensorEvents){0}; + return ( b2SensorEvents ){ 0 }; } - int beginCount = b2Array(world->sensorBeginEventArray).count; - int endCount = b2Array(world->sensorEndEventArray).count; + int beginCount = b2Array( world->sensorBeginEventArray ).count; + int endCount = b2Array( world->sensorEndEventArray ).count; - b2SensorEvents events = {world->sensorBeginEventArray, world->sensorEndEventArray, beginCount, endCount}; + b2SensorEvents events = { world->sensorBeginEventArray, world->sensorEndEventArray, beginCount, endCount }; return events; } -b2ContactEvents b2World_GetContactEvents(b2WorldId worldId) +b2ContactEvents b2World_GetContactEvents( b2WorldId worldId ) { - b2World* world = b2GetWorldFromId(worldId); - B2_ASSERT(world->locked == false); - if (world->locked) + b2World* world = b2GetWorldFromId( worldId ); + B2_ASSERT( world->locked == false ); + if ( world->locked ) { - return (b2ContactEvents){0}; + return ( b2ContactEvents ){ 0 }; } - int beginCount = b2Array(world->contactBeginArray).count; - int endCount = b2Array(world->contactEndArray).count; - int hitCount = b2Array(world->contactHitArray).count; + int beginCount = b2Array( world->contactBeginArray ).count; + int endCount = b2Array( world->contactEndArray ).count; + int hitCount = b2Array( world->contactHitArray ).count; b2ContactEvents events = { - world->contactBeginArray, world->contactEndArray, world->contactHitArray, beginCount, endCount, hitCount}; + world->contactBeginArray, world->contactEndArray, world->contactHitArray, beginCount, endCount, hitCount }; return events; } -bool b2World_IsValid(b2WorldId id) +bool b2World_IsValid( b2WorldId id ) { - if (id.index1 < 1 || b2_maxWorlds < id.index1) + if ( id.index1 < 1 || b2_maxWorlds < id.index1 ) { return false; } - b2World* world = b2_worlds + (id.index1 - 1); + b2World* world = b2_worlds + ( id.index1 - 1 ); - if (world->worldId != id.index1 - 1) + if ( world->worldId != id.index1 - 1 ) { // world is not allocated return false; @@ -1422,37 +1430,37 @@ bool b2World_IsValid(b2WorldId id) return id.revision == world->revision; } -bool b2Body_IsValid(b2BodyId id) +bool b2Body_IsValid( b2BodyId id ) { - if (id.world0 < 0 || b2_maxWorlds <= id.world0) + if ( id.world0 < 0 || b2_maxWorlds <= id.world0 ) { // invalid world return false; } b2World* world = b2_worlds + id.world0; - if (world->worldId != id.world0) + if ( world->worldId != id.world0 ) { // world is free return false; } - if (id.index1 < 1 || b2Array(world->bodyArray).count < id.index1) + if ( id.index1 < 1 || b2Array( world->bodyArray ).count < id.index1 ) { // invalid index return false; } - b2Body* body = world->bodyArray + (id.index1 - 1); - if (body->setIndex == B2_NULL_INDEX) + b2Body* body = world->bodyArray + ( id.index1 - 1 ); + if ( body->setIndex == B2_NULL_INDEX ) { // this was freed return false; } - B2_ASSERT(body->localIndex != B2_NULL_INDEX); + B2_ASSERT( body->localIndex != B2_NULL_INDEX ); - if (body->revision != id.revision) + if ( body->revision != id.revision ) { // this id is orphaned return false; @@ -1461,137 +1469,137 @@ bool b2Body_IsValid(b2BodyId id) return true; } -bool b2Shape_IsValid(b2ShapeId id) +bool b2Shape_IsValid( b2ShapeId id ) { - if (b2_maxWorlds <= id.world0) + if ( b2_maxWorlds <= id.world0 ) { return false; } b2World* world = b2_worlds + id.world0; - if (world->worldId != id.world0) + if ( world->worldId != id.world0 ) { // world is free return false; } int shapeId = id.index1 - 1; - if (shapeId < 0 || b2Array(world->shapeArray).count <= shapeId) + if ( shapeId < 0 || b2Array( world->shapeArray ).count <= shapeId ) { return false; } b2Shape* shape = world->shapeArray + shapeId; - if (shape->id == B2_NULL_INDEX) + if ( shape->id == B2_NULL_INDEX ) { // shape is free return false; } - B2_ASSERT(shape->id == shapeId); + B2_ASSERT( shape->id == shapeId ); return id.revision == shape->revision; } -bool b2Chain_IsValid(b2ChainId id) +bool b2Chain_IsValid( b2ChainId id ) { - if (id.world0 < 0 || b2_maxWorlds <= id.world0) + if ( id.world0 < 0 || b2_maxWorlds <= id.world0 ) { return false; } b2World* world = b2_worlds + id.world0; - if (world->worldId != id.world0) + if ( world->worldId != id.world0 ) { // world is free return false; } int chainId = id.index1 - 1; - if (chainId < 0 || b2Array(world->chainArray).count <= chainId) + if ( chainId < 0 || b2Array( world->chainArray ).count <= chainId ) { return false; } b2ChainShape* chain = world->chainArray + chainId; - if (chain->id == B2_NULL_INDEX) + if ( chain->id == B2_NULL_INDEX ) { // chain is free return false; } - B2_ASSERT(chain->id == chainId); + B2_ASSERT( chain->id == chainId ); return id.revision == chain->revision; } -bool b2Joint_IsValid(b2JointId id) +bool b2Joint_IsValid( b2JointId id ) { - if (id.world0 < 0 || b2_maxWorlds <= id.world0) + if ( id.world0 < 0 || b2_maxWorlds <= id.world0 ) { return false; } b2World* world = b2_worlds + id.world0; - if (world->worldId != id.world0) + if ( world->worldId != id.world0 ) { // world is free return false; } int jointId = id.index1 - 1; - if (jointId < 0 || b2Array(world->jointArray).count <= jointId) + if ( jointId < 0 || b2Array( world->jointArray ).count <= jointId ) { return false; } b2Joint* joint = world->jointArray + jointId; - if (joint->jointId == B2_NULL_INDEX) + if ( joint->jointId == B2_NULL_INDEX ) { // joint is free return false; } - B2_ASSERT(joint->jointId == jointId); + B2_ASSERT( joint->jointId == jointId ); return id.revision == joint->revision; } -void b2World_EnableSleeping(b2WorldId worldId, bool flag) +void b2World_EnableSleeping( b2WorldId worldId, bool flag ) { - b2World* world = b2GetWorldFromId(worldId); - B2_ASSERT(world->locked == false); - if (world->locked) + b2World* world = b2GetWorldFromId( worldId ); + B2_ASSERT( world->locked == false ); + if ( world->locked ) { return; } - if (flag == world->enableSleep) + if ( flag == world->enableSleep ) { return; } world->enableSleep = flag; - if (flag == false) + if ( flag == false ) { - int setCount = b2Array(world->solverSetArray).count; - for (int i = b2_firstSleepingSet; i < setCount; ++i) + int setCount = b2Array( world->solverSetArray ).count; + for ( int i = b2_firstSleepingSet; i < setCount; ++i ) { b2SolverSet* set = world->solverSetArray + i; - if (set->sims.count > 0) + if ( set->sims.count > 0 ) { - b2WakeSolverSet(world, i); + b2WakeSolverSet( world, i ); } } } } -void b2World_EnableWarmStarting(b2WorldId worldId, bool flag) +void b2World_EnableWarmStarting( b2WorldId worldId, bool flag ) { - b2World* world = b2GetWorldFromId(worldId); - B2_ASSERT(world->locked == false); - if (world->locked) + b2World* world = b2GetWorldFromId( worldId ); + B2_ASSERT( world->locked == false ); + if ( world->locked ) { return; } @@ -1599,11 +1607,11 @@ void b2World_EnableWarmStarting(b2WorldId worldId, bool flag) world->enableWarmStarting = flag; } -void b2World_EnableContinuous(b2WorldId worldId, bool flag) +void b2World_EnableContinuous( b2WorldId worldId, bool flag ) { - b2World* world = b2GetWorldFromId(worldId); - B2_ASSERT(world->locked == false); - if (world->locked) + b2World* world = b2GetWorldFromId( worldId ); + B2_ASSERT( world->locked == false ); + if ( world->locked ) { return; } @@ -1611,121 +1619,121 @@ void b2World_EnableContinuous(b2WorldId worldId, bool flag) world->enableContinuous = flag; } -void b2World_SetRestitutionThreshold(b2WorldId worldId, float value) +void b2World_SetRestitutionThreshold( b2WorldId worldId, float value ) { - b2World* world = b2GetWorldFromId(worldId); - B2_ASSERT(world->locked == false); - if (world->locked) + b2World* world = b2GetWorldFromId( worldId ); + B2_ASSERT( world->locked == false ); + if ( world->locked ) { return; } - world->restitutionThreshold = b2ClampFloat(value, 0.0f, FLT_MAX); + world->restitutionThreshold = b2ClampFloat( value, 0.0f, FLT_MAX ); } -void b2World_SetHitEventThreshold(b2WorldId worldId, float value) +void b2World_SetHitEventThreshold( b2WorldId worldId, float value ) { - b2World* world = b2GetWorldFromId(worldId); - B2_ASSERT(world->locked == false); - if (world->locked) + b2World* world = b2GetWorldFromId( worldId ); + B2_ASSERT( world->locked == false ); + if ( world->locked ) { return; } - world->hitEventThreshold = b2ClampFloat(value, 0.0f, FLT_MAX); + world->hitEventThreshold = b2ClampFloat( value, 0.0f, FLT_MAX ); } -void b2World_SetContactTuning(b2WorldId worldId, float hertz, float dampingRatio, float pushOut) +void b2World_SetContactTuning( b2WorldId worldId, float hertz, float dampingRatio, float pushOut ) { - b2World* world = b2GetWorldFromId(worldId); - B2_ASSERT(world->locked == false); - if (world->locked) + b2World* world = b2GetWorldFromId( worldId ); + B2_ASSERT( world->locked == false ); + if ( world->locked ) { return; } - world->contactHertz = b2ClampFloat(hertz, 0.0f, FLT_MAX); - world->contactDampingRatio = b2ClampFloat(dampingRatio, 0.0f, FLT_MAX); - world->contactPushoutVelocity = b2ClampFloat(pushOut, 0.0f, FLT_MAX); + world->contactHertz = b2ClampFloat( hertz, 0.0f, FLT_MAX ); + world->contactDampingRatio = b2ClampFloat( dampingRatio, 0.0f, FLT_MAX ); + world->contactPushoutVelocity = b2ClampFloat( pushOut, 0.0f, FLT_MAX ); } -b2Profile b2World_GetProfile(b2WorldId worldId) +b2Profile b2World_GetProfile( b2WorldId worldId ) { - b2World* world = b2GetWorldFromId(worldId); + b2World* world = b2GetWorldFromId( worldId ); return world->profile; } -b2Counters b2World_GetCounters(b2WorldId worldId) +b2Counters b2World_GetCounters( b2WorldId worldId ) { - b2World* world = b2GetWorldFromId(worldId); - b2Counters s = {0}; - s.bodyCount = b2GetIdCount(&world->bodyIdPool); - s.shapeCount = b2GetIdCount(&world->shapeIdPool); - s.contactCount = b2GetIdCount(&world->contactIdPool); - s.jointCount = b2GetIdCount(&world->jointIdPool); - s.islandCount = b2GetIdCount(&world->islandIdPool); + b2World* world = b2GetWorldFromId( worldId ); + b2Counters s = { 0 }; + s.bodyCount = b2GetIdCount( &world->bodyIdPool ); + s.shapeCount = b2GetIdCount( &world->shapeIdPool ); + s.contactCount = b2GetIdCount( &world->contactIdPool ); + s.jointCount = b2GetIdCount( &world->jointIdPool ); + s.islandCount = b2GetIdCount( &world->islandIdPool ); b2DynamicTree* staticTree = world->broadPhase.trees + b2_staticBody; - s.staticTreeHeight = b2DynamicTree_GetHeight(staticTree); + s.staticTreeHeight = b2DynamicTree_GetHeight( staticTree ); b2DynamicTree* dynamicTree = world->broadPhase.trees + b2_dynamicBody; b2DynamicTree* kinematicTree = world->broadPhase.trees + b2_kinematicBody; - s.treeHeight = b2MaxInt(b2DynamicTree_GetHeight(dynamicTree), b2DynamicTree_GetHeight(kinematicTree)); + s.treeHeight = b2MaxInt( b2DynamicTree_GetHeight( dynamicTree ), b2DynamicTree_GetHeight( kinematicTree ) ); - s.stackUsed = b2GetMaxStackAllocation(&world->stackAllocator); + s.stackUsed = b2GetMaxStackAllocation( &world->stackAllocator ); s.byteCount = b2GetByteCount(); s.taskCount = world->taskCount; - for (int i = 0; i < b2_graphColorCount; ++i) + for ( int i = 0; i < b2_graphColorCount; ++i ) { s.colorCounts[i] = world->constraintGraph.colors[i].contacts.count + world->constraintGraph.colors[i].joints.count; } return s; } -void b2World_DumpMemoryStats(b2WorldId worldId) +void b2World_DumpMemoryStats( b2WorldId worldId ) { - FILE* file = fopen("box2d_memory.txt", "w"); - if (file == NULL) + FILE* file = fopen( "box2d_memory.txt", "w" ); + if ( file == NULL ) { return; } - b2World* world = b2GetWorldFromId(worldId); + b2World* world = b2GetWorldFromId( worldId ); // id pools - fprintf(file, "id pools\n"); - fprintf(file, "body ids: %d\n", b2GetIdBytes(&world->bodyIdPool)); - fprintf(file, "solver set ids: %d\n", b2GetIdBytes(&world->solverSetIdPool)); - fprintf(file, "joint ids: %d\n", b2GetIdBytes(&world->jointIdPool)); - fprintf(file, "contact ids: %d\n", b2GetIdBytes(&world->contactIdPool)); - fprintf(file, "island ids: %d\n", b2GetIdBytes(&world->islandIdPool)); - fprintf(file, "shape ids: %d\n", b2GetIdBytes(&world->shapeIdPool)); - fprintf(file, "chain ids: %d\n", b2GetIdBytes(&world->chainIdPool)); - fprintf(file, "\n"); + fprintf( file, "id pools\n" ); + fprintf( file, "body ids: %d\n", b2GetIdBytes( &world->bodyIdPool ) ); + fprintf( file, "solver set ids: %d\n", b2GetIdBytes( &world->solverSetIdPool ) ); + fprintf( file, "joint ids: %d\n", b2GetIdBytes( &world->jointIdPool ) ); + fprintf( file, "contact ids: %d\n", b2GetIdBytes( &world->contactIdPool ) ); + fprintf( file, "island ids: %d\n", b2GetIdBytes( &world->islandIdPool ) ); + fprintf( file, "shape ids: %d\n", b2GetIdBytes( &world->shapeIdPool ) ); + fprintf( file, "chain ids: %d\n", b2GetIdBytes( &world->chainIdPool ) ); + fprintf( file, "\n" ); // world arrays - fprintf(file, "world arrays\n"); - fprintf(file, "bodies: %d\n", b2GetArrayBytes(world->bodyArray, sizeof(b2Body))); - fprintf(file, "solver sets: %d\n", b2GetArrayBytes(world->solverSetArray, sizeof(b2SolverSet))); - fprintf(file, "joints: %d\n", b2GetArrayBytes(world->jointArray, sizeof(b2Joint))); - fprintf(file, "contacts: %d\n", b2GetArrayBytes(world->contactArray, sizeof(b2Contact))); - fprintf(file, "islands: %d\n", b2GetArrayBytes(world->islandArray, sizeof(b2Island))); - fprintf(file, "shapes: %d\n", b2GetArrayBytes(world->shapeArray, sizeof(b2Shape))); - fprintf(file, "chains: %d\n", b2GetArrayBytes(world->chainArray, sizeof(b2ChainShape))); - fprintf(file, "\n"); + fprintf( file, "world arrays\n" ); + fprintf( file, "bodies: %d\n", b2GetArrayBytes( world->bodyArray, sizeof( b2Body ) ) ); + fprintf( file, "solver sets: %d\n", b2GetArrayBytes( world->solverSetArray, sizeof( b2SolverSet ) ) ); + fprintf( file, "joints: %d\n", b2GetArrayBytes( world->jointArray, sizeof( b2Joint ) ) ); + fprintf( file, "contacts: %d\n", b2GetArrayBytes( world->contactArray, sizeof( b2Contact ) ) ); + fprintf( file, "islands: %d\n", b2GetArrayBytes( world->islandArray, sizeof( b2Island ) ) ); + fprintf( file, "shapes: %d\n", b2GetArrayBytes( world->shapeArray, sizeof( b2Shape ) ) ); + fprintf( file, "chains: %d\n", b2GetArrayBytes( world->chainArray, sizeof( b2ChainShape ) ) ); + fprintf( file, "\n" ); // broad-phase - fprintf(file, "broad-phase\n"); - fprintf(file, "static tree: %d\n", b2DynamicTree_GetByteCount(world->broadPhase.trees + b2_staticBody)); - fprintf(file, "kinematic tree: %d\n", b2DynamicTree_GetByteCount(world->broadPhase.trees + b2_kinematicBody)); - fprintf(file, "dynamic tree: %d\n", b2DynamicTree_GetByteCount(world->broadPhase.trees + b2_dynamicBody)); + fprintf( file, "broad-phase\n" ); + fprintf( file, "static tree: %d\n", b2DynamicTree_GetByteCount( world->broadPhase.trees + b2_staticBody ) ); + fprintf( file, "kinematic tree: %d\n", b2DynamicTree_GetByteCount( world->broadPhase.trees + b2_kinematicBody ) ); + fprintf( file, "dynamic tree: %d\n", b2DynamicTree_GetByteCount( world->broadPhase.trees + b2_dynamicBody ) ); b2HashSet* moveSet = &world->broadPhase.moveSet; - fprintf(file, "moveSet: %d (%d, %d)\n", b2GetHashSetBytes(moveSet), moveSet->count, moveSet->capacity); - fprintf(file, "moveArray: %d\n", b2GetArrayBytes(world->broadPhase.moveArray, sizeof(int))); + fprintf( file, "moveSet: %d (%d, %d)\n", b2GetHashSetBytes( moveSet ), moveSet->count, moveSet->capacity ); + fprintf( file, "moveArray: %d\n", b2GetArrayBytes( world->broadPhase.moveArray, sizeof( int ) ) ); b2HashSet* pairSet = &world->broadPhase.pairSet; - fprintf(file, "pairSet: %d (%d, %d)\n", b2GetHashSetBytes(pairSet), pairSet->count, pairSet->capacity); - fprintf(file, "\n"); + fprintf( file, "pairSet: %d (%d, %d)\n", b2GetHashSetBytes( pairSet ), pairSet->count, pairSet->capacity ); + fprintf( file, "\n" ); // solver sets int bodySimCapacity = 0; @@ -1733,11 +1741,11 @@ void b2World_DumpMemoryStats(b2WorldId worldId) int jointSimCapacity = 0; int contactSimCapacity = 0; int islandSimCapacity = 0; - int solverSetCapacity = b2Array(world->solverSetArray).count; - for (int i = 0; i < solverSetCapacity; ++i) + int solverSetCapacity = b2Array( world->solverSetArray ).count; + for ( int i = 0; i < solverSetCapacity; ++i ) { b2SolverSet* set = world->solverSetArray + i; - if (set->setIndex == B2_NULL_INDEX) + if ( set->setIndex == B2_NULL_INDEX ) { continue; } @@ -1749,39 +1757,39 @@ void b2World_DumpMemoryStats(b2WorldId worldId) islandSimCapacity += set->islands.capacity; } - fprintf(file, "solver sets\n"); - fprintf(file, "body sim: %d\n", bodySimCapacity * (int)sizeof(b2BodySim)); - fprintf(file, "body state: %d\n", bodyStateCapacity * (int)sizeof(b2BodyState)); - fprintf(file, "joint sim: %d\n", jointSimCapacity * (int)sizeof(b2JointSim)); - fprintf(file, "contact sim: %d\n", contactSimCapacity * (int)sizeof(b2ContactSim)); - fprintf(file, "island sim: %d\n", islandSimCapacity * (int)sizeof(islandSimCapacity)); - fprintf(file, "\n"); + fprintf( file, "solver sets\n" ); + fprintf( file, "body sim: %d\n", bodySimCapacity * (int)sizeof( b2BodySim ) ); + fprintf( file, "body state: %d\n", bodyStateCapacity * (int)sizeof( b2BodyState ) ); + fprintf( file, "joint sim: %d\n", jointSimCapacity * (int)sizeof( b2JointSim ) ); + fprintf( file, "contact sim: %d\n", contactSimCapacity * (int)sizeof( b2ContactSim ) ); + fprintf( file, "island sim: %d\n", islandSimCapacity * (int)sizeof( islandSimCapacity ) ); + fprintf( file, "\n" ); // constraint graph int bodyBitSetBytes = 0; contactSimCapacity = 0; jointSimCapacity = 0; - for (int i = 0; i < b2_graphColorCount; ++i) + for ( int i = 0; i < b2_graphColorCount; ++i ) { b2GraphColor* c = world->constraintGraph.colors + i; - bodyBitSetBytes += b2GetBitSetBytes(&c->bodySet); + bodyBitSetBytes += b2GetBitSetBytes( &c->bodySet ); contactSimCapacity += c->contacts.capacity; jointSimCapacity += c->joints.capacity; } - fprintf(file, "constraint graph\n"); - fprintf(file, "body bit sets: %d\n", bodyBitSetBytes); - fprintf(file, "joint sim: %d\n", jointSimCapacity * (int)sizeof(b2JointSim)); - fprintf(file, "contact sim: %d\n", contactSimCapacity * (int)sizeof(b2ContactSim)); - fprintf(file, "\n"); + fprintf( file, "constraint graph\n" ); + fprintf( file, "body bit sets: %d\n", bodyBitSetBytes ); + fprintf( file, "joint sim: %d\n", jointSimCapacity * (int)sizeof( b2JointSim ) ); + fprintf( file, "contact sim: %d\n", contactSimCapacity * (int)sizeof( b2ContactSim ) ); + fprintf( file, "\n" ); // stack allocator - fprintf(file, "stack allocator: %d\n\n", world->stackAllocator.capacity); + fprintf( file, "stack allocator: %d\n\n", world->stackAllocator.capacity ); // chain shapes // todo - fclose(file); + fclose( file ); } typedef struct WorldQueryContext @@ -1792,45 +1800,45 @@ typedef struct WorldQueryContext void* userContext; } WorldQueryContext; -static bool TreeQueryCallback(int proxyId, int shapeId, void* context) +static bool TreeQueryCallback( int proxyId, int shapeId, void* context ) { - B2_MAYBE_UNUSED(proxyId); + B2_MAYBE_UNUSED( proxyId ); WorldQueryContext* worldContext = context; b2World* world = worldContext->world; - b2CheckId(world->shapeArray, shapeId); + b2CheckId( world->shapeArray, shapeId ); b2Shape* shape = world->shapeArray + shapeId; b2Filter shapeFilter = shape->filter; b2QueryFilter queryFilter = worldContext->filter; - if ((shapeFilter.categoryBits & queryFilter.maskBits) == 0 || (shapeFilter.maskBits & queryFilter.categoryBits) == 0) + if ( ( shapeFilter.categoryBits & queryFilter.maskBits ) == 0 || ( shapeFilter.maskBits & queryFilter.categoryBits ) == 0 ) { return true; } - b2ShapeId id = {shapeId + 1, world->worldId, shape->revision}; - bool result = worldContext->fcn(id, worldContext->userContext); + b2ShapeId id = { shapeId + 1, world->worldId, shape->revision }; + bool result = worldContext->fcn( id, worldContext->userContext ); return result; } -void b2World_OverlapAABB(b2WorldId worldId, b2AABB aabb, b2QueryFilter filter, b2OverlapResultFcn* fcn, void* context) +void b2World_OverlapAABB( b2WorldId worldId, b2AABB aabb, b2QueryFilter filter, b2OverlapResultFcn* fcn, void* context ) { - b2World* world = b2GetWorldFromId(worldId); - B2_ASSERT(world->locked == false); - if (world->locked) + b2World* world = b2GetWorldFromId( worldId ); + B2_ASSERT( world->locked == false ); + if ( world->locked ) { return; } - B2_ASSERT(b2AABB_IsValid(aabb)); + B2_ASSERT( b2AABB_IsValid( aabb ) ); - WorldQueryContext worldContext = {world, fcn, filter, context}; + WorldQueryContext worldContext = { world, fcn, filter, context }; - for (int i = 0; i < b2_bodyTypeCount; ++i) + for ( int i = 0; i < b2_bodyTypeCount; ++i ) { - b2DynamicTree_Query(world->broadPhase.trees + i, aabb, filter.maskBits, TreeQueryCallback, &worldContext); + b2DynamicTree_Query( world->broadPhase.trees + i, aabb, filter.maskBits, TreeQueryCallback, &worldContext ); } } @@ -1844,116 +1852,116 @@ typedef struct WorldOverlapContext void* userContext; } WorldOverlapContext; -static bool TreeOverlapCallback(int proxyId, int shapeId, void* context) +static bool TreeOverlapCallback( int proxyId, int shapeId, void* context ) { - B2_MAYBE_UNUSED(proxyId); + B2_MAYBE_UNUSED( proxyId ); WorldOverlapContext* worldContext = context; b2World* world = worldContext->world; - b2CheckId(world->shapeArray, shapeId); + b2CheckId( world->shapeArray, shapeId ); b2Shape* shape = world->shapeArray + shapeId; b2Filter shapeFilter = shape->filter; b2QueryFilter queryFilter = worldContext->filter; - if ((shapeFilter.categoryBits & queryFilter.maskBits) == 0 || (shapeFilter.maskBits & queryFilter.categoryBits) == 0) + if ( ( shapeFilter.categoryBits & queryFilter.maskBits ) == 0 || ( shapeFilter.maskBits & queryFilter.categoryBits ) == 0 ) { return true; } - b2Body* body = b2GetBody(world, shape->bodyId); - b2Transform transform = b2GetBodyTransformQuick(world, body); + b2Body* body = b2GetBody( world, shape->bodyId ); + b2Transform transform = b2GetBodyTransformQuick( world, body ); b2DistanceInput input; input.proxyA = worldContext->proxy; - input.proxyB = b2MakeShapeDistanceProxy(shape); + input.proxyB = b2MakeShapeDistanceProxy( shape ); input.transformA = worldContext->transform; input.transformB = transform; input.useRadii = true; - b2DistanceCache cache = {0}; - b2DistanceOutput output = b2ShapeDistance(&cache, &input, NULL, 0); + b2DistanceCache cache = { 0 }; + b2DistanceOutput output = b2ShapeDistance( &cache, &input, NULL, 0 ); - if (output.distance > 0.0f) + if ( output.distance > 0.0f ) { return true; } - b2ShapeId id = {shape->id + 1, world->worldId, shape->revision}; - bool result = worldContext->fcn(id, worldContext->userContext); + b2ShapeId id = { shape->id + 1, world->worldId, shape->revision }; + bool result = worldContext->fcn( id, worldContext->userContext ); return result; } -void b2World_OverlapCircle(b2WorldId worldId, const b2Circle* circle, b2Transform transform, b2QueryFilter filter, - b2OverlapResultFcn* fcn, void* context) +void b2World_OverlapCircle( b2WorldId worldId, const b2Circle* circle, b2Transform transform, b2QueryFilter filter, + b2OverlapResultFcn* fcn, void* context ) { - b2World* world = b2GetWorldFromId(worldId); - B2_ASSERT(world->locked == false); - if (world->locked) + b2World* world = b2GetWorldFromId( worldId ); + B2_ASSERT( world->locked == false ); + if ( world->locked ) { return; } - B2_ASSERT(b2Vec2_IsValid(transform.p)); - B2_ASSERT(b2Rot_IsValid(transform.q)); + B2_ASSERT( b2Vec2_IsValid( transform.p ) ); + B2_ASSERT( b2Rot_IsValid( transform.q ) ); - b2AABB aabb = b2ComputeCircleAABB(circle, transform); + b2AABB aabb = b2ComputeCircleAABB( circle, transform ); WorldOverlapContext worldContext = { - world, fcn, filter, b2MakeProxy(&circle->center, 1, circle->radius), transform, context, + world, fcn, filter, b2MakeProxy( &circle->center, 1, circle->radius ), transform, context, }; - for (int i = 0; i < b2_bodyTypeCount; ++i) + for ( int i = 0; i < b2_bodyTypeCount; ++i ) { - b2DynamicTree_Query(world->broadPhase.trees + i, aabb, filter.maskBits, TreeOverlapCallback, &worldContext); + b2DynamicTree_Query( world->broadPhase.trees + i, aabb, filter.maskBits, TreeOverlapCallback, &worldContext ); } } -void b2World_OverlapCapsule(b2WorldId worldId, const b2Capsule* capsule, b2Transform transform, b2QueryFilter filter, - b2OverlapResultFcn* fcn, void* context) +void b2World_OverlapCapsule( b2WorldId worldId, const b2Capsule* capsule, b2Transform transform, b2QueryFilter filter, + b2OverlapResultFcn* fcn, void* context ) { - b2World* world = b2GetWorldFromId(worldId); - B2_ASSERT(world->locked == false); - if (world->locked) + b2World* world = b2GetWorldFromId( worldId ); + B2_ASSERT( world->locked == false ); + if ( world->locked ) { return; } - B2_ASSERT(b2Vec2_IsValid(transform.p)); - B2_ASSERT(b2Rot_IsValid(transform.q)); + B2_ASSERT( b2Vec2_IsValid( transform.p ) ); + B2_ASSERT( b2Rot_IsValid( transform.q ) ); - b2AABB aabb = b2ComputeCapsuleAABB(capsule, transform); + b2AABB aabb = b2ComputeCapsuleAABB( capsule, transform ); WorldOverlapContext worldContext = { - world, fcn, filter, b2MakeProxy(&capsule->center1, 2, capsule->radius), transform, context, + world, fcn, filter, b2MakeProxy( &capsule->center1, 2, capsule->radius ), transform, context, }; - for (int i = 0; i < b2_bodyTypeCount; ++i) + for ( int i = 0; i < b2_bodyTypeCount; ++i ) { - b2DynamicTree_Query(world->broadPhase.trees + i, aabb, filter.maskBits, TreeOverlapCallback, &worldContext); + b2DynamicTree_Query( world->broadPhase.trees + i, aabb, filter.maskBits, TreeOverlapCallback, &worldContext ); } } -void b2World_OverlapPolygon(b2WorldId worldId, const b2Polygon* polygon, b2Transform transform, b2QueryFilter filter, - b2OverlapResultFcn* fcn, void* context) +void b2World_OverlapPolygon( b2WorldId worldId, const b2Polygon* polygon, b2Transform transform, b2QueryFilter filter, + b2OverlapResultFcn* fcn, void* context ) { - b2World* world = b2GetWorldFromId(worldId); - B2_ASSERT(world->locked == false); - if (world->locked) + b2World* world = b2GetWorldFromId( worldId ); + B2_ASSERT( world->locked == false ); + if ( world->locked ) { return; } - B2_ASSERT(b2Vec2_IsValid(transform.p)); - B2_ASSERT(b2Rot_IsValid(transform.q)); + B2_ASSERT( b2Vec2_IsValid( transform.p ) ); + B2_ASSERT( b2Rot_IsValid( transform.q ) ); - b2AABB aabb = b2ComputePolygonAABB(polygon, transform); + b2AABB aabb = b2ComputePolygonAABB( polygon, transform ); WorldOverlapContext worldContext = { - world, fcn, filter, b2MakeProxy(polygon->vertices, polygon->count, polygon->radius), transform, context, + world, fcn, filter, b2MakeProxy( polygon->vertices, polygon->count, polygon->radius ), transform, context, }; - for (int i = 0; i < b2_bodyTypeCount; ++i) + for ( int i = 0; i < b2_bodyTypeCount; ++i ) { - b2DynamicTree_Query(world->broadPhase.trees + i, aabb, filter.maskBits, TreeOverlapCallback, &worldContext); + b2DynamicTree_Query( world->broadPhase.trees + i, aabb, filter.maskBits, TreeOverlapCallback, &worldContext ); } } @@ -1966,31 +1974,31 @@ typedef struct WorldRayCastContext void* userContext; } WorldRayCastContext; -static float RayCastCallback(const b2RayCastInput* input, int proxyId, int shapeId, void* context) +static float RayCastCallback( const b2RayCastInput* input, int proxyId, int shapeId, void* context ) { - B2_MAYBE_UNUSED(proxyId); + B2_MAYBE_UNUSED( proxyId ); WorldRayCastContext* worldContext = context; b2World* world = worldContext->world; - b2CheckId(world->shapeArray, shapeId); + b2CheckId( world->shapeArray, shapeId ); b2Shape* shape = world->shapeArray + shapeId; b2Filter shapeFilter = shape->filter; b2QueryFilter queryFilter = worldContext->filter; - if ((shapeFilter.categoryBits & queryFilter.maskBits) == 0 || (shapeFilter.maskBits & queryFilter.categoryBits) == 0) + if ( ( shapeFilter.categoryBits & queryFilter.maskBits ) == 0 || ( shapeFilter.maskBits & queryFilter.categoryBits ) == 0 ) { return input->maxFraction; } - b2Body* body = b2GetBody(world, shape->bodyId); - b2Transform transform = b2GetBodyTransformQuick(world, body); - b2CastOutput output = b2RayCastShape(input, shape, transform); + b2Body* body = b2GetBody( world, shape->bodyId ); + b2Transform transform = b2GetBodyTransformQuick( world, body ); + b2CastOutput output = b2RayCastShape( input, shape, transform ); - if (output.hit) + if ( output.hit ) { - b2ShapeId id = {shapeId + 1, world->worldId, shape->revision}; - float fraction = worldContext->fcn(id, output.point, output.normal, output.fraction, worldContext->userContext); + b2ShapeId id = { shapeId + 1, world->worldId, shape->revision }; + float fraction = worldContext->fcn( id, output.point, output.normal, output.fraction, worldContext->userContext ); worldContext->fraction = fraction; return fraction; } @@ -1998,28 +2006,28 @@ static float RayCastCallback(const b2RayCastInput* input, int proxyId, int shape return input->maxFraction; } -void b2World_CastRay(b2WorldId worldId, b2Vec2 origin, b2Vec2 translation, b2QueryFilter filter, b2CastResultFcn* fcn, - void* context) +void b2World_CastRay( b2WorldId worldId, b2Vec2 origin, b2Vec2 translation, b2QueryFilter filter, b2CastResultFcn* fcn, + void* context ) { - b2World* world = b2GetWorldFromId(worldId); - B2_ASSERT(world->locked == false); - if (world->locked) + b2World* world = b2GetWorldFromId( worldId ); + B2_ASSERT( world->locked == false ); + if ( world->locked ) { return; } - B2_ASSERT(b2Vec2_IsValid(origin)); - B2_ASSERT(b2Vec2_IsValid(translation)); + B2_ASSERT( b2Vec2_IsValid( origin ) ); + B2_ASSERT( b2Vec2_IsValid( translation ) ); - b2RayCastInput input = {origin, translation, 1.0f}; + b2RayCastInput input = { origin, translation, 1.0f }; - WorldRayCastContext worldContext = {world, fcn, filter, 1.0f, context}; + WorldRayCastContext worldContext = { world, fcn, filter, 1.0f, context }; - for (int i = 0; i < b2_bodyTypeCount; ++i) + for ( int i = 0; i < b2_bodyTypeCount; ++i ) { - b2DynamicTree_RayCast(world->broadPhase.trees + i, &input, filter.maskBits, RayCastCallback, &worldContext); + b2DynamicTree_RayCast( world->broadPhase.trees + i, &input, filter.maskBits, RayCastCallback, &worldContext ); - if (worldContext.fraction == 0.0f) + if ( worldContext.fraction == 0.0f ) { return; } @@ -2029,7 +2037,7 @@ void b2World_CastRay(b2WorldId worldId, b2Vec2 origin, b2Vec2 translation, b2Que } // This callback finds the closest hit. This is the most common callback used in games. -static float b2RayCastClosestFcn(b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* context) +static float b2RayCastClosestFcn( b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* context ) { b2RayResult* rayResult = (b2RayResult*)context; rayResult->shapeId = shapeId; @@ -2040,28 +2048,28 @@ static float b2RayCastClosestFcn(b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, return fraction; } -b2RayResult b2World_CastRayClosest(b2WorldId worldId, b2Vec2 origin, b2Vec2 translation, b2QueryFilter filter) +b2RayResult b2World_CastRayClosest( b2WorldId worldId, b2Vec2 origin, b2Vec2 translation, b2QueryFilter filter ) { - b2RayResult result = {0}; + b2RayResult result = { 0 }; - b2World* world = b2GetWorldFromId(worldId); - B2_ASSERT(world->locked == false); - if (world->locked) + b2World* world = b2GetWorldFromId( worldId ); + B2_ASSERT( world->locked == false ); + if ( world->locked ) { return result; } - B2_ASSERT(b2Vec2_IsValid(origin)); - B2_ASSERT(b2Vec2_IsValid(translation)); + B2_ASSERT( b2Vec2_IsValid( origin ) ); + B2_ASSERT( b2Vec2_IsValid( translation ) ); - b2RayCastInput input = {origin, translation, 1.0f}; - WorldRayCastContext worldContext = {world, b2RayCastClosestFcn, filter, 1.0f, &result}; + b2RayCastInput input = { origin, translation, 1.0f }; + WorldRayCastContext worldContext = { world, b2RayCastClosestFcn, filter, 1.0f, &result }; - for (int i = 0; i < b2_bodyTypeCount; ++i) + for ( int i = 0; i < b2_bodyTypeCount; ++i ) { - b2DynamicTree_RayCast(world->broadPhase.trees + i, &input, filter.maskBits, RayCastCallback, &worldContext); + b2DynamicTree_RayCast( world->broadPhase.trees + i, &input, filter.maskBits, RayCastCallback, &worldContext ); - if (worldContext.fraction == 0.0f) + if ( worldContext.fraction == 0.0f ) { return result; } @@ -2072,31 +2080,31 @@ b2RayResult b2World_CastRayClosest(b2WorldId worldId, b2Vec2 origin, b2Vec2 tran return result; } -static float ShapeCastCallback(const b2ShapeCastInput* input, int proxyId, int shapeId, void* context) +static float ShapeCastCallback( const b2ShapeCastInput* input, int proxyId, int shapeId, void* context ) { - B2_MAYBE_UNUSED(proxyId); + B2_MAYBE_UNUSED( proxyId ); WorldRayCastContext* worldContext = context; b2World* world = worldContext->world; - b2CheckId(world->shapeArray, shapeId); + b2CheckId( world->shapeArray, shapeId ); b2Shape* shape = world->shapeArray + shapeId; b2Filter shapeFilter = shape->filter; b2QueryFilter queryFilter = worldContext->filter; - if ((shapeFilter.categoryBits & queryFilter.maskBits) == 0 || (shapeFilter.maskBits & queryFilter.categoryBits) == 0) + if ( ( shapeFilter.categoryBits & queryFilter.maskBits ) == 0 || ( shapeFilter.maskBits & queryFilter.categoryBits ) == 0 ) { return input->maxFraction; } - b2Body* body = b2GetBody(world, shape->bodyId); - b2Transform transform = b2GetBodyTransformQuick(world, body); - b2CastOutput output = b2ShapeCastShape(input, shape, transform); + b2Body* body = b2GetBody( world, shape->bodyId ); + b2Transform transform = b2GetBodyTransformQuick( world, body ); + b2CastOutput output = b2ShapeCastShape( input, shape, transform ); - if (output.hit) + if ( output.hit ) { - b2ShapeId id = {shapeId + 1, world->worldId, shape->revision}; - float fraction = worldContext->fcn(id, output.point, output.normal, output.fraction, worldContext->userContext); + b2ShapeId id = { shapeId + 1, world->worldId, shape->revision }; + float fraction = worldContext->fcn( id, output.point, output.normal, output.fraction, worldContext->userContext ); worldContext->fraction = fraction; return fraction; } @@ -2104,34 +2112,34 @@ static float ShapeCastCallback(const b2ShapeCastInput* input, int proxyId, int s return input->maxFraction; } -void b2World_CastCircle(b2WorldId worldId, const b2Circle* circle, b2Transform originTransform, b2Vec2 translation, - b2QueryFilter filter, b2CastResultFcn* fcn, void* context) +void b2World_CastCircle( b2WorldId worldId, const b2Circle* circle, b2Transform originTransform, b2Vec2 translation, + b2QueryFilter filter, b2CastResultFcn* fcn, void* context ) { - b2World* world = b2GetWorldFromId(worldId); - B2_ASSERT(world->locked == false); - if (world->locked) + b2World* world = b2GetWorldFromId( worldId ); + B2_ASSERT( world->locked == false ); + if ( world->locked ) { return; } - B2_ASSERT(b2Vec2_IsValid(originTransform.p)); - B2_ASSERT(b2Rot_IsValid(originTransform.q)); - B2_ASSERT(b2Vec2_IsValid(translation)); + B2_ASSERT( b2Vec2_IsValid( originTransform.p ) ); + B2_ASSERT( b2Rot_IsValid( originTransform.q ) ); + B2_ASSERT( b2Vec2_IsValid( translation ) ); b2ShapeCastInput input; - input.points[0] = b2TransformPoint(originTransform, circle->center); + input.points[0] = b2TransformPoint( originTransform, circle->center ); input.count = 1; input.radius = circle->radius; input.translation = translation; input.maxFraction = 1.0f; - WorldRayCastContext worldContext = {world, fcn, filter, 1.0f, context}; + WorldRayCastContext worldContext = { world, fcn, filter, 1.0f, context }; - for (int i = 0; i < b2_bodyTypeCount; ++i) + for ( int i = 0; i < b2_bodyTypeCount; ++i ) { - b2DynamicTree_ShapeCast(world->broadPhase.trees + i, &input, filter.maskBits, ShapeCastCallback, &worldContext); + b2DynamicTree_ShapeCast( world->broadPhase.trees + i, &input, filter.maskBits, ShapeCastCallback, &worldContext ); - if (worldContext.fraction == 0.0f) + if ( worldContext.fraction == 0.0f ) { return; } @@ -2140,35 +2148,35 @@ void b2World_CastCircle(b2WorldId worldId, const b2Circle* circle, b2Transform o } } -void b2World_CastCapsule(b2WorldId worldId, const b2Capsule* capsule, b2Transform originTransform, b2Vec2 translation, - b2QueryFilter filter, b2CastResultFcn* fcn, void* context) +void b2World_CastCapsule( b2WorldId worldId, const b2Capsule* capsule, b2Transform originTransform, b2Vec2 translation, + b2QueryFilter filter, b2CastResultFcn* fcn, void* context ) { - b2World* world = b2GetWorldFromId(worldId); - B2_ASSERT(world->locked == false); - if (world->locked) + b2World* world = b2GetWorldFromId( worldId ); + B2_ASSERT( world->locked == false ); + if ( world->locked ) { return; } - B2_ASSERT(b2Vec2_IsValid(originTransform.p)); - B2_ASSERT(b2Rot_IsValid(originTransform.q)); - B2_ASSERT(b2Vec2_IsValid(translation)); + B2_ASSERT( b2Vec2_IsValid( originTransform.p ) ); + B2_ASSERT( b2Rot_IsValid( originTransform.q ) ); + B2_ASSERT( b2Vec2_IsValid( translation ) ); b2ShapeCastInput input; - input.points[0] = b2TransformPoint(originTransform, capsule->center1); - input.points[1] = b2TransformPoint(originTransform, capsule->center2); + input.points[0] = b2TransformPoint( originTransform, capsule->center1 ); + input.points[1] = b2TransformPoint( originTransform, capsule->center2 ); input.count = 2; input.radius = capsule->radius; input.translation = translation; input.maxFraction = 1.0f; - WorldRayCastContext worldContext = {world, fcn, filter, 1.0f, context}; + WorldRayCastContext worldContext = { world, fcn, filter, 1.0f, context }; - for (int i = 0; i < b2_bodyTypeCount; ++i) + for ( int i = 0; i < b2_bodyTypeCount; ++i ) { - b2DynamicTree_ShapeCast(world->broadPhase.trees + i, &input, filter.maskBits, ShapeCastCallback, &worldContext); + b2DynamicTree_ShapeCast( world->broadPhase.trees + i, &input, filter.maskBits, ShapeCastCallback, &worldContext ); - if (worldContext.fraction == 0.0f) + if ( worldContext.fraction == 0.0f ) { return; } @@ -2177,37 +2185,37 @@ void b2World_CastCapsule(b2WorldId worldId, const b2Capsule* capsule, b2Transfor } } -void b2World_CastPolygon(b2WorldId worldId, const b2Polygon* polygon, b2Transform originTransform, b2Vec2 translation, - b2QueryFilter filter, b2CastResultFcn* fcn, void* context) +void b2World_CastPolygon( b2WorldId worldId, const b2Polygon* polygon, b2Transform originTransform, b2Vec2 translation, + b2QueryFilter filter, b2CastResultFcn* fcn, void* context ) { - b2World* world = b2GetWorldFromId(worldId); - B2_ASSERT(world->locked == false); - if (world->locked) + b2World* world = b2GetWorldFromId( worldId ); + B2_ASSERT( world->locked == false ); + if ( world->locked ) { return; } - B2_ASSERT(b2Vec2_IsValid(originTransform.p)); - B2_ASSERT(b2Rot_IsValid(originTransform.q)); - B2_ASSERT(b2Vec2_IsValid(translation)); + B2_ASSERT( b2Vec2_IsValid( originTransform.p ) ); + B2_ASSERT( b2Rot_IsValid( originTransform.q ) ); + B2_ASSERT( b2Vec2_IsValid( translation ) ); b2ShapeCastInput input; - for (int i = 0; i < polygon->count; ++i) + for ( int i = 0; i < polygon->count; ++i ) { - input.points[i] = b2TransformPoint(originTransform, polygon->vertices[i]); + input.points[i] = b2TransformPoint( originTransform, polygon->vertices[i] ); } input.count = polygon->count; input.radius = polygon->radius; input.translation = translation; input.maxFraction = 1.0f; - WorldRayCastContext worldContext = {world, fcn, filter, 1.0f, context}; + WorldRayCastContext worldContext = { world, fcn, filter, 1.0f, context }; - for (int i = 0; i < b2_bodyTypeCount; ++i) + for ( int i = 0; i < b2_bodyTypeCount; ++i ) { - b2DynamicTree_ShapeCast(world->broadPhase.trees + i, &input, filter.maskBits, ShapeCastCallback, &worldContext); + b2DynamicTree_ShapeCast( world->broadPhase.trees + i, &input, filter.maskBits, ShapeCastCallback, &worldContext ); - if (worldContext.fraction == 0.0f) + if ( worldContext.fraction == 0.0f ) { return; } @@ -2306,29 +2314,29 @@ void b2World_Dump() } #endif -void b2World_SetCustomFilterCallback(b2WorldId worldId, b2CustomFilterFcn* fcn, void* context) +void b2World_SetCustomFilterCallback( b2WorldId worldId, b2CustomFilterFcn* fcn, void* context ) { - b2World* world = b2GetWorldFromId(worldId); + b2World* world = b2GetWorldFromId( worldId ); world->customFilterFcn = fcn; world->customFilterContext = context; } -void b2World_SetPreSolveCallback(b2WorldId worldId, b2PreSolveFcn* fcn, void* context) +void b2World_SetPreSolveCallback( b2WorldId worldId, b2PreSolveFcn* fcn, void* context ) { - b2World* world = b2GetWorldFromId(worldId); + b2World* world = b2GetWorldFromId( worldId ); world->preSolveFcn = fcn; world->preSolveContext = context; } -void b2World_SetGravity(b2WorldId worldId, b2Vec2 gravity) +void b2World_SetGravity( b2WorldId worldId, b2Vec2 gravity ) { - b2World* world = b2GetWorldFromId(worldId); + b2World* world = b2GetWorldFromId( worldId ); world->gravity = gravity; } -b2Vec2 b2World_GetGravity(b2WorldId worldId) +b2Vec2 b2World_GetGravity( b2WorldId worldId ) { - b2World* world = b2GetWorldFromId(worldId); + b2World* world = b2GetWorldFromId( worldId ); return world->gravity; } @@ -2340,87 +2348,87 @@ struct ExplosionContext float magnitude; }; -static bool ExplosionCallback(int proxyId, int shapeId, void* context) +static bool ExplosionCallback( int proxyId, int shapeId, void* context ) { - B2_MAYBE_UNUSED(proxyId); + B2_MAYBE_UNUSED( proxyId ); struct ExplosionContext* explosionContext = context; b2World* world = explosionContext->world; - b2CheckId(world->shapeArray, shapeId); + b2CheckId( world->shapeArray, shapeId ); b2Shape* shape = world->shapeArray + shapeId; - b2CheckId(world->bodyArray, shape->bodyId); + b2CheckId( world->bodyArray, shape->bodyId ); b2Body* body = world->bodyArray + shape->bodyId; - if (body->type == b2_kinematicBody) + if ( body->type == b2_kinematicBody ) { return true; } - b2WakeBody(world, body); + b2WakeBody( world, body ); - if (body->setIndex != b2_awakeSet) + if ( body->setIndex != b2_awakeSet ) { return true; } - b2Transform transform = b2GetBodyTransformQuick(world, body); + b2Transform transform = b2GetBodyTransformQuick( world, body ); b2DistanceInput input; - input.proxyA = b2MakeShapeDistanceProxy(shape); - input.proxyB = b2MakeProxy(&explosionContext->position, 1, 0.0f); + input.proxyA = b2MakeShapeDistanceProxy( shape ); + input.proxyB = b2MakeProxy( &explosionContext->position, 1, 0.0f ); input.transformA = transform; input.transformB = b2Transform_identity; input.useRadii = true; - b2DistanceCache cache = {0}; - b2DistanceOutput output = b2ShapeDistance(&cache, &input, NULL, 0); + b2DistanceCache cache = { 0 }; + b2DistanceOutput output = b2ShapeDistance( &cache, &input, NULL, 0 ); - if (output.distance > explosionContext->radius) + if ( output.distance > explosionContext->radius ) { return true; } b2Vec2 closestPoint = output.pointA; - if (output.distance == 0.0f) + if ( output.distance == 0.0f ) { - b2Vec2 localCentroid = b2GetShapeCentroid(shape); - closestPoint = b2TransformPoint(transform, localCentroid); + b2Vec2 localCentroid = b2GetShapeCentroid( shape ); + closestPoint = b2TransformPoint( transform, localCentroid ); } float falloff = 0.4f; - float perimeter = b2GetShapePerimeter(shape); - float magnitude = explosionContext->magnitude * perimeter * (1.0f - falloff * output.distance / explosionContext->radius); + float perimeter = b2GetShapePerimeter( shape ); + float magnitude = explosionContext->magnitude * perimeter * ( 1.0f - falloff * output.distance / explosionContext->radius ); - b2Vec2 direction = b2Normalize(b2Sub(closestPoint, explosionContext->position)); - b2Vec2 impulse = b2MulSV(magnitude, direction); + b2Vec2 direction = b2Normalize( b2Sub( closestPoint, explosionContext->position ) ); + b2Vec2 impulse = b2MulSV( magnitude, direction ); int localIndex = body->localIndex; b2SolverSet* set = world->solverSetArray + b2_awakeSet; - B2_ASSERT(0 <= localIndex && localIndex < set->states.count); + B2_ASSERT( 0 <= localIndex && localIndex < set->states.count ); b2BodyState* state = set->states.data + localIndex; b2BodySim* bodySim = set->sims.data + localIndex; - state->linearVelocity = b2MulAdd(state->linearVelocity, bodySim->invMass, impulse); - state->angularVelocity += bodySim->invInertia * b2Cross(b2Sub(closestPoint, bodySim->center), impulse); + state->linearVelocity = b2MulAdd( state->linearVelocity, bodySim->invMass, impulse ); + state->angularVelocity += bodySim->invInertia * b2Cross( b2Sub( closestPoint, bodySim->center ), impulse ); return true; } -void b2World_Explode(b2WorldId worldId, b2Vec2 position, float radius, float magnitude) +void b2World_Explode( b2WorldId worldId, b2Vec2 position, float radius, float magnitude ) { - B2_ASSERT(b2Vec2_IsValid(position)); - B2_ASSERT(b2IsValid(radius) && radius > 0.0f); - B2_ASSERT(b2IsValid(magnitude)); + B2_ASSERT( b2Vec2_IsValid( position ) ); + B2_ASSERT( b2IsValid( radius ) && radius > 0.0f ); + B2_ASSERT( b2IsValid( magnitude ) ); - b2World* world = b2GetWorldFromId(worldId); - B2_ASSERT(world->locked == false); - if (world->locked) + b2World* world = b2GetWorldFromId( worldId ); + B2_ASSERT( world->locked == false ); + if ( world->locked ) { return; } - struct ExplosionContext explosionContext = {world, position, radius, magnitude}; + struct ExplosionContext explosionContext = { world, position, radius, magnitude }; b2AABB aabb; aabb.lowerBound.x = position.x - radius; @@ -2428,28 +2436,29 @@ void b2World_Explode(b2WorldId worldId, b2Vec2 position, float radius, float mag aabb.upperBound.x = position.x + radius; aabb.upperBound.y = position.y + radius; - b2DynamicTree_Query(world->broadPhase.trees + b2_dynamicBody, aabb, b2_defaultMaskBits, ExplosionCallback, &explosionContext); + b2DynamicTree_Query( world->broadPhase.trees + b2_dynamicBody, aabb, b2_defaultMaskBits, ExplosionCallback, + &explosionContext ); } #if B2_VALIDATE // When validating islands ids I have to compare the root island // ids because islands are not merged until the next time step. -static int b2GetRootIslandId(b2World* world, int islandId) +static int b2GetRootIslandId( b2World* world, int islandId ) { - if (islandId == B2_NULL_INDEX) + if ( islandId == B2_NULL_INDEX ) { return B2_NULL_INDEX; } b2Island* islands = world->islandArray; - b2CheckIndex(islands, islandId); + b2CheckIndex( islands, islandId ); b2Island* island = islands + islandId; int rootId = islandId; b2Island* rootIsland = island; - while (rootIsland->parentIsland != B2_NULL_INDEX) + while ( rootIsland->parentIsland != B2_NULL_INDEX ) { - b2CheckIndex(islands, rootIsland->parentIsland); + b2CheckIndex( islands, rootIsland->parentIsland ); b2Island* parent = islands + rootIsland->parentIsland; rootId = rootIsland->parentIsland; rootIsland = parent; @@ -2459,81 +2468,81 @@ static int b2GetRootIslandId(b2World* world, int islandId) } // This validates island graph connectivity for each body -void b2ValidateConnectivity(b2World* world) +void b2ValidateConnectivity( b2World* world ) { b2Body* bodies = world->bodyArray; - int bodyCapacity = b2Array(bodies).count; + int bodyCapacity = b2Array( bodies ).count; - for (int bodyIndex = 0; bodyIndex < bodyCapacity; ++bodyIndex) + for ( int bodyIndex = 0; bodyIndex < bodyCapacity; ++bodyIndex ) { b2Body* body = bodies + bodyIndex; - if (body->id == B2_NULL_INDEX) + if ( body->id == B2_NULL_INDEX ) { - b2ValidateFreeId(&world->bodyIdPool, bodyIndex); + b2ValidateFreeId( &world->bodyIdPool, bodyIndex ); continue; } - B2_ASSERT(bodyIndex == body->id); + B2_ASSERT( bodyIndex == body->id ); // Need to get the root island because islands are not merged until the next time step - int bodyIslandId = b2GetRootIslandId(world, body->islandId); + int bodyIslandId = b2GetRootIslandId( world, body->islandId ); int bodySetIndex = body->setIndex; int contactKey = body->headContactKey; - while (contactKey != B2_NULL_INDEX) + while ( contactKey != B2_NULL_INDEX ) { int contactId = contactKey >> 1; int edgeIndex = contactKey & 1; - b2CheckIndex(world->contactArray, contactId); + b2CheckIndex( world->contactArray, contactId ); b2Contact* contact = world->contactArray + contactId; - bool touching = (contact->flags & b2_contactTouchingFlag) != 0; - if (touching && (contact->flags & b2_contactSensorFlag) == 0) + bool touching = ( contact->flags & b2_contactTouchingFlag ) != 0; + if ( touching && ( contact->flags & b2_contactSensorFlag ) == 0 ) { - if (bodySetIndex != b2_staticSet) + if ( bodySetIndex != b2_staticSet ) { - int contactIslandId = b2GetRootIslandId(world, contact->islandId); - B2_ASSERT(contactIslandId == bodyIslandId); + int contactIslandId = b2GetRootIslandId( world, contact->islandId ); + B2_ASSERT( contactIslandId == bodyIslandId ); } } else { - B2_ASSERT(contact->islandId == B2_NULL_INDEX); + B2_ASSERT( contact->islandId == B2_NULL_INDEX ); } contactKey = contact->edges[edgeIndex].nextKey; } int jointKey = body->headJointKey; - while (jointKey != B2_NULL_INDEX) + while ( jointKey != B2_NULL_INDEX ) { int jointId = jointKey >> 1; int edgeIndex = jointKey & 1; - b2CheckIndex(world->jointArray, jointId); + b2CheckIndex( world->jointArray, jointId ); b2Joint* joint = world->jointArray + jointId; int otherEdgeIndex = edgeIndex ^ 1; - b2CheckIndex(world->bodyArray, joint->edges[otherEdgeIndex].bodyId); + b2CheckIndex( world->bodyArray, joint->edges[otherEdgeIndex].bodyId ); b2Body* otherBody = world->bodyArray + joint->edges[otherEdgeIndex].bodyId; - if (bodySetIndex == b2_disabledSet || otherBody->setIndex == b2_disabledSet) + if ( bodySetIndex == b2_disabledSet || otherBody->setIndex == b2_disabledSet ) { - B2_ASSERT(joint->islandId == B2_NULL_INDEX); + B2_ASSERT( joint->islandId == B2_NULL_INDEX ); } - else if (bodySetIndex == b2_staticSet) + else if ( bodySetIndex == b2_staticSet ) { - if (otherBody->setIndex == b2_staticSet) + if ( otherBody->setIndex == b2_staticSet ) { - B2_ASSERT(joint->islandId == B2_NULL_INDEX); + B2_ASSERT( joint->islandId == B2_NULL_INDEX ); } } else { - int jointIslandId = b2GetRootIslandId(world, joint->islandId); - B2_ASSERT(jointIslandId == bodyIslandId); + int jointIslandId = b2GetRootIslandId( world, joint->islandId ); + B2_ASSERT( jointIslandId == bodyIslandId ); } jointKey = joint->edges[edgeIndex].nextKey; @@ -2542,13 +2551,13 @@ void b2ValidateConnectivity(b2World* world) } // Validates solver sets, but not island connectivity -void b2ValidateSolverSets(b2World* world) +void b2ValidateSolverSets( b2World* world ) { - B2_ASSERT(b2GetIdCapacity(&world->bodyIdPool) == b2Array(world->bodyArray).count); - B2_ASSERT(b2GetIdCapacity(&world->contactIdPool) == b2Array(world->contactArray).count); - B2_ASSERT(b2GetIdCapacity(&world->jointIdPool) == b2Array(world->jointArray).count); - B2_ASSERT(b2GetIdCapacity(&world->islandIdPool) == b2Array(world->islandArray).count); - B2_ASSERT(b2GetIdCapacity(&world->solverSetIdPool) == b2Array(world->solverSetArray).count); + B2_ASSERT( b2GetIdCapacity( &world->bodyIdPool ) == b2Array( world->bodyArray ).count ); + B2_ASSERT( b2GetIdCapacity( &world->contactIdPool ) == b2Array( world->contactArray ).count ); + B2_ASSERT( b2GetIdCapacity( &world->jointIdPool ) == b2Array( world->jointArray ).count ); + B2_ASSERT( b2GetIdCapacity( &world->islandIdPool ) == b2Array( world->islandArray ).count ); + B2_ASSERT( b2GetIdCapacity( &world->solverSetIdPool ) == b2Array( world->solverSetArray ).count ); int activeSetCount = 0; int totalBodyCount = 0; @@ -2557,77 +2566,77 @@ void b2ValidateSolverSets(b2World* world) int totalIslandCount = 0; // Validate all solver sets - int setCount = b2Array(world->solverSetArray).count; - for (int setIndex = 0; setIndex < setCount; ++setIndex) + int setCount = b2Array( world->solverSetArray ).count; + for ( int setIndex = 0; setIndex < setCount; ++setIndex ) { b2SolverSet* set = world->solverSetArray + setIndex; - if (set->setIndex != B2_NULL_INDEX) + if ( set->setIndex != B2_NULL_INDEX ) { activeSetCount += 1; - if (setIndex == b2_staticSet) + if ( setIndex == b2_staticSet ) { - B2_ASSERT(set->contacts.count == 0); - B2_ASSERT(set->islands.count == 0); - B2_ASSERT(set->states.count == 0); + B2_ASSERT( set->contacts.count == 0 ); + B2_ASSERT( set->islands.count == 0 ); + B2_ASSERT( set->states.count == 0 ); } - else if (setIndex == b2_awakeSet) + else if ( setIndex == b2_awakeSet ) { - B2_ASSERT(set->sims.count == set->states.count); - B2_ASSERT(set->joints.count == 0); + B2_ASSERT( set->sims.count == set->states.count ); + B2_ASSERT( set->joints.count == 0 ); } - else if (setIndex == b2_disabledSet) + else if ( setIndex == b2_disabledSet ) { - B2_ASSERT(set->islands.count == 0); - B2_ASSERT(set->states.count == 0); + B2_ASSERT( set->islands.count == 0 ); + B2_ASSERT( set->states.count == 0 ); } else { - B2_ASSERT(set->states.count == 0); + B2_ASSERT( set->states.count == 0 ); } // Validate bodies { b2Body* bodies = world->bodyArray; - B2_ASSERT(set->sims.count >= 0); + B2_ASSERT( set->sims.count >= 0 ); totalBodyCount += set->sims.count; - for (int i = 0; i < set->sims.count; ++i) + for ( int i = 0; i < set->sims.count; ++i ) { b2BodySim* bodySim = set->sims.data + i; int bodyId = bodySim->bodyId; - b2CheckIndex(bodies, bodyId); + b2CheckIndex( bodies, bodyId ); b2Body* body = bodies + bodyId; - B2_ASSERT(body->setIndex == setIndex); - B2_ASSERT(body->localIndex == i); - B2_ASSERT(body->revision == body->revision); + B2_ASSERT( body->setIndex == setIndex ); + B2_ASSERT( body->localIndex == i ); + B2_ASSERT( body->revision == body->revision ); - if (setIndex == b2_disabledSet) + if ( setIndex == b2_disabledSet ) { - B2_ASSERT(body->headContactKey == B2_NULL_INDEX); + B2_ASSERT( body->headContactKey == B2_NULL_INDEX ); } // Validate body shapes int prevShapeId = B2_NULL_INDEX; int shapeId = body->headShapeId; - while (shapeId != B2_NULL_INDEX) + while ( shapeId != B2_NULL_INDEX ) { - b2CheckId(world->shapeArray, shapeId); + b2CheckId( world->shapeArray, shapeId ); b2Shape* shape = world->shapeArray + shapeId; - B2_ASSERT(shape->prevShapeId == prevShapeId); + B2_ASSERT( shape->prevShapeId == prevShapeId ); - if (setIndex == b2_disabledSet) + if ( setIndex == b2_disabledSet ) { - B2_ASSERT(shape->proxyKey == B2_NULL_INDEX); + B2_ASSERT( shape->proxyKey == B2_NULL_INDEX ); } - else if (setIndex == b2_staticSet) + else if ( setIndex == b2_staticSet ) { - B2_ASSERT(B2_PROXY_TYPE(shape->proxyKey) == b2_staticBody); + B2_ASSERT( B2_PROXY_TYPE( shape->proxyKey ) == b2_staticBody ); } else { - b2BodyType proxyType = B2_PROXY_TYPE(shape->proxyKey); - B2_ASSERT(proxyType == b2_kinematicBody || proxyType == b2_dynamicBody); + b2BodyType proxyType = B2_PROXY_TYPE( shape->proxyKey ); + B2_ASSERT( proxyType == b2_kinematicBody || proxyType == b2_dynamicBody ); } prevShapeId = shapeId; @@ -2636,54 +2645,54 @@ void b2ValidateSolverSets(b2World* world) // Validate body contacts int contactKey = body->headContactKey; - while (contactKey != B2_NULL_INDEX) + while ( contactKey != B2_NULL_INDEX ) { int contactId = contactKey >> 1; int edgeIndex = contactKey & 1; - b2CheckIndex(world->contactArray, contactId); + b2CheckIndex( world->contactArray, contactId ); b2Contact* contact = world->contactArray + contactId; - B2_ASSERT(contact->setIndex != b2_staticSet); - B2_ASSERT(contact->edges[0].bodyId == bodyId || contact->edges[1].bodyId == bodyId); + B2_ASSERT( contact->setIndex != b2_staticSet ); + B2_ASSERT( contact->edges[0].bodyId == bodyId || contact->edges[1].bodyId == bodyId ); contactKey = contact->edges[edgeIndex].nextKey; } // Validate body joints int jointKey = body->headJointKey; - while (jointKey != B2_NULL_INDEX) + while ( jointKey != B2_NULL_INDEX ) { int jointId = jointKey >> 1; int edgeIndex = jointKey & 1; - b2CheckIndex(world->jointArray, jointId); + b2CheckIndex( world->jointArray, jointId ); b2Joint* joint = world->jointArray + jointId; int otherEdgeIndex = edgeIndex ^ 1; - b2CheckIndex(world->bodyArray, joint->edges[otherEdgeIndex].bodyId); + b2CheckIndex( world->bodyArray, joint->edges[otherEdgeIndex].bodyId ); b2Body* otherBody = world->bodyArray + joint->edges[otherEdgeIndex].bodyId; - if (setIndex == b2_disabledSet || otherBody->setIndex == b2_disabledSet) + if ( setIndex == b2_disabledSet || otherBody->setIndex == b2_disabledSet ) { - B2_ASSERT(joint->setIndex == b2_disabledSet); + B2_ASSERT( joint->setIndex == b2_disabledSet ); } - else if (setIndex == b2_staticSet && otherBody->setIndex == b2_staticSet) + else if ( setIndex == b2_staticSet && otherBody->setIndex == b2_staticSet ) { - B2_ASSERT(joint->setIndex == b2_staticSet); + B2_ASSERT( joint->setIndex == b2_staticSet ); } - else if (setIndex == b2_awakeSet) + else if ( setIndex == b2_awakeSet ) { - B2_ASSERT(joint->setIndex == b2_awakeSet); + B2_ASSERT( joint->setIndex == b2_awakeSet ); } - else if (setIndex >= b2_firstSleepingSet) + else if ( setIndex >= b2_firstSleepingSet ) { - B2_ASSERT(joint->setIndex == setIndex); + B2_ASSERT( joint->setIndex == setIndex ); } - b2JointSim* jointSim = b2GetJointSim(world, joint); - B2_ASSERT(jointSim->jointId == jointId); - B2_ASSERT(jointSim->bodyIdA == joint->edges[0].bodyId); - B2_ASSERT(jointSim->bodyIdB == joint->edges[1].bodyId); + b2JointSim* jointSim = b2GetJointSim( world, joint ); + B2_ASSERT( jointSim->jointId == jointId ); + B2_ASSERT( jointSim->bodyIdA == joint->edges[0].bodyId ); + B2_ASSERT( jointSim->bodyIdB == joint->edges[1].bodyId ); jointKey = joint->edges[edgeIndex].nextKey; } @@ -2693,145 +2702,146 @@ void b2ValidateSolverSets(b2World* world) // Validate contacts { b2Contact* contacts = world->contactArray; - B2_ASSERT(set->contacts.count >= 0); + B2_ASSERT( set->contacts.count >= 0 ); totalContactCount += set->contacts.count; - for (int i = 0; i < set->contacts.count; ++i) + for ( int i = 0; i < set->contacts.count; ++i ) { b2ContactSim* contactSim = set->contacts.data + i; - b2CheckIndex(contacts, contactSim->contactId); + b2CheckIndex( contacts, contactSim->contactId ); b2Contact* contact = contacts + contactSim->contactId; - if (setIndex == b2_awakeSet) + if ( setIndex == b2_awakeSet ) { // contact should be non-touching if awake // or it could be this contact hasn't been transferred yet - B2_ASSERT(contactSim->manifold.pointCount == 0 || (contactSim->simFlags & b2_simStartedTouching) != 0); + B2_ASSERT( contactSim->manifold.pointCount == 0 || + ( contactSim->simFlags & b2_simStartedTouching ) != 0 ); } - B2_ASSERT(contact->setIndex == setIndex); - B2_ASSERT(contact->colorIndex == B2_NULL_INDEX); - B2_ASSERT(contact->localIndex == i); + B2_ASSERT( contact->setIndex == setIndex ); + B2_ASSERT( contact->colorIndex == B2_NULL_INDEX ); + B2_ASSERT( contact->localIndex == i ); } } // Validate joints { b2Joint* joints = world->jointArray; - B2_ASSERT(set->joints.count >= 0); + B2_ASSERT( set->joints.count >= 0 ); totalJointCount += set->joints.count; - for (int i = 0; i < set->joints.count; ++i) + for ( int i = 0; i < set->joints.count; ++i ) { b2JointSim* jointSim = set->joints.data + i; - b2CheckIndex(joints, jointSim->jointId); + b2CheckIndex( joints, jointSim->jointId ); b2Joint* joint = joints + jointSim->jointId; - B2_ASSERT(joint->setIndex == setIndex); - B2_ASSERT(joint->colorIndex == B2_NULL_INDEX); - B2_ASSERT(joint->localIndex == i); + B2_ASSERT( joint->setIndex == setIndex ); + B2_ASSERT( joint->colorIndex == B2_NULL_INDEX ); + B2_ASSERT( joint->localIndex == i ); } } // Validate islands { b2Island* islands = world->islandArray; - B2_ASSERT(set->islands.count >= 0); + B2_ASSERT( set->islands.count >= 0 ); totalIslandCount += set->islands.count; - for (int i = 0; i < set->islands.count; ++i) + for ( int i = 0; i < set->islands.count; ++i ) { b2IslandSim* islandSim = set->islands.data + i; - b2CheckIndex(islands, islandSim->islandId); + b2CheckIndex( islands, islandSim->islandId ); b2Island* island = islands + islandSim->islandId; - B2_ASSERT(island->setIndex == setIndex); - B2_ASSERT(island->localIndex == i); + B2_ASSERT( island->setIndex == setIndex ); + B2_ASSERT( island->localIndex == i ); } } } else { - B2_ASSERT(set->sims.count == 0); - B2_ASSERT(set->contacts.count == 0); - B2_ASSERT(set->joints.count == 0); - B2_ASSERT(set->islands.count == 0); - B2_ASSERT(set->states.count == 0); + B2_ASSERT( set->sims.count == 0 ); + B2_ASSERT( set->contacts.count == 0 ); + B2_ASSERT( set->joints.count == 0 ); + B2_ASSERT( set->islands.count == 0 ); + B2_ASSERT( set->states.count == 0 ); } } - int setIdCount = b2GetIdCount(&world->solverSetIdPool); - B2_ASSERT(activeSetCount == setIdCount); + int setIdCount = b2GetIdCount( &world->solverSetIdPool ); + B2_ASSERT( activeSetCount == setIdCount ); - int bodyIdCount = b2GetIdCount(&world->bodyIdPool); - B2_ASSERT(totalBodyCount == bodyIdCount); + int bodyIdCount = b2GetIdCount( &world->bodyIdPool ); + B2_ASSERT( totalBodyCount == bodyIdCount ); - int islandIdCount = b2GetIdCount(&world->islandIdPool); - B2_ASSERT(totalIslandCount == islandIdCount); + int islandIdCount = b2GetIdCount( &world->islandIdPool ); + B2_ASSERT( totalIslandCount == islandIdCount ); // Validate constraint graph - for (int colorIndex = 0; colorIndex < b2_graphColorCount; ++colorIndex) + for ( int colorIndex = 0; colorIndex < b2_graphColorCount; ++colorIndex ) { b2GraphColor* color = world->constraintGraph.colors + colorIndex; { b2Contact* contacts = world->contactArray; - B2_ASSERT(color->contacts.count >= 0); + B2_ASSERT( color->contacts.count >= 0 ); totalContactCount += color->contacts.count; - for (int i = 0; i < color->contacts.count; ++i) + for ( int i = 0; i < color->contacts.count; ++i ) { b2ContactSim* contactSim = color->contacts.data + i; - b2CheckIndex(contacts, contactSim->contactId); + b2CheckIndex( contacts, contactSim->contactId ); b2Contact* contact = contacts + contactSim->contactId; // contact should be touching in the constraint graph or awaiting transfer to non-touching - B2_ASSERT(contactSim->manifold.pointCount > 0 || - (contactSim->simFlags & (b2_simStoppedTouching | b2_simDisjoint)) != 0); - B2_ASSERT(contact->setIndex == b2_awakeSet); - B2_ASSERT(contact->colorIndex == colorIndex); - B2_ASSERT(contact->localIndex == i); + B2_ASSERT( contactSim->manifold.pointCount > 0 || + ( contactSim->simFlags & ( b2_simStoppedTouching | b2_simDisjoint ) ) != 0 ); + B2_ASSERT( contact->setIndex == b2_awakeSet ); + B2_ASSERT( contact->colorIndex == colorIndex ); + B2_ASSERT( contact->localIndex == i ); int bodyIdA = contact->edges[0].bodyId; int bodyIdB = contact->edges[1].bodyId; - b2CheckIndex(world->bodyArray, bodyIdA); - b2CheckIndex(world->bodyArray, bodyIdB); + b2CheckIndex( world->bodyArray, bodyIdA ); + b2CheckIndex( world->bodyArray, bodyIdB ); - if (colorIndex < b2_overflowIndex) + if ( colorIndex < b2_overflowIndex ) { b2Body* bodyA = world->bodyArray + bodyIdA; b2Body* bodyB = world->bodyArray + bodyIdB; - B2_ASSERT(b2GetBit(&color->bodySet, bodyIdA) == (bodyA->type != b2_staticBody)); - B2_ASSERT(b2GetBit(&color->bodySet, bodyIdB) == (bodyB->type != b2_staticBody)); + B2_ASSERT( b2GetBit( &color->bodySet, bodyIdA ) == ( bodyA->type != b2_staticBody ) ); + B2_ASSERT( b2GetBit( &color->bodySet, bodyIdB ) == ( bodyB->type != b2_staticBody ) ); } } } { b2Joint* joints = world->jointArray; - B2_ASSERT(color->joints.count >= 0); + B2_ASSERT( color->joints.count >= 0 ); totalJointCount += color->joints.count; - for (int i = 0; i < color->joints.count; ++i) + for ( int i = 0; i < color->joints.count; ++i ) { b2JointSim* jointSim = color->joints.data + i; - b2CheckIndex(joints, jointSim->jointId); + b2CheckIndex( joints, jointSim->jointId ); b2Joint* joint = joints + jointSim->jointId; - B2_ASSERT(joint->setIndex == b2_awakeSet); - B2_ASSERT(joint->colorIndex == colorIndex); - B2_ASSERT(joint->localIndex == i); + B2_ASSERT( joint->setIndex == b2_awakeSet ); + B2_ASSERT( joint->colorIndex == colorIndex ); + B2_ASSERT( joint->localIndex == i ); int bodyIdA = joint->edges[0].bodyId; int bodyIdB = joint->edges[1].bodyId; - b2CheckIndex(world->bodyArray, bodyIdA); - b2CheckIndex(world->bodyArray, bodyIdB); + b2CheckIndex( world->bodyArray, bodyIdA ); + b2CheckIndex( world->bodyArray, bodyIdB ); - if (colorIndex < b2_overflowIndex) + if ( colorIndex < b2_overflowIndex ) { b2Body* bodyA = world->bodyArray + bodyIdA; b2Body* bodyB = world->bodyArray + bodyIdB; - B2_ASSERT(b2GetBit(&color->bodySet, bodyIdA) == (bodyA->type != b2_staticBody)); - B2_ASSERT(b2GetBit(&color->bodySet, bodyIdB) == (bodyB->type != b2_staticBody)); + B2_ASSERT( b2GetBit( &color->bodySet, bodyIdA ) == ( bodyA->type != b2_staticBody ) ); + B2_ASSERT( b2GetBit( &color->bodySet, bodyIdB ) == ( bodyB->type != b2_staticBody ) ); } } } } - int contactIdCount = b2GetIdCount(&world->contactIdPool); - B2_ASSERT(totalContactCount == contactIdCount); - B2_ASSERT(totalContactCount == world->broadPhase.pairSet.count); + int contactIdCount = b2GetIdCount( &world->contactIdPool ); + B2_ASSERT( totalContactCount == contactIdCount ); + B2_ASSERT( totalContactCount == world->broadPhase.pairSet.count ); - int jointIdCount = b2GetIdCount(&world->jointIdPool); - B2_ASSERT(totalJointCount == jointIdCount); + int jointIdCount = b2GetIdCount( &world->jointIdPool ); + B2_ASSERT( totalJointCount == jointIdCount ); // Validate shapes // This is very slow on compounds @@ -2879,87 +2889,87 @@ void b2ValidateSolverSets(b2World* world) } // Validate contact touching status. -void b2ValidateContacts(b2World* world) +void b2ValidateContacts( b2World* world ) { - int contactCount = b2Array(world->contactArray).count; - B2_ASSERT(contactCount == b2GetIdCapacity(&world->contactIdPool)); + int contactCount = b2Array( world->contactArray ).count; + B2_ASSERT( contactCount == b2GetIdCapacity( &world->contactIdPool ) ); int allocatedContactCount = 0; - for (int contactIndex = 0; contactIndex < contactCount; ++contactIndex) + for ( int contactIndex = 0; contactIndex < contactCount; ++contactIndex ) { b2Contact* contact = world->contactArray + contactIndex; - if (contact->contactId == B2_NULL_INDEX) + if ( contact->contactId == B2_NULL_INDEX ) { continue; } - B2_ASSERT(contact->contactId == contactIndex); + B2_ASSERT( contact->contactId == contactIndex ); allocatedContactCount += 1; - bool touching = (contact->flags & b2_contactTouchingFlag) != 0; - bool sensorTouching = (contact->flags & b2_contactSensorTouchingFlag) != 0; - bool isSensor = (contact->flags & b2_contactSensorFlag) != 0; + bool touching = ( contact->flags & b2_contactTouchingFlag ) != 0; + bool sensorTouching = ( contact->flags & b2_contactSensorTouchingFlag ) != 0; + bool isSensor = ( contact->flags & b2_contactSensorFlag ) != 0; - B2_ASSERT(touching == false || sensorTouching == false); - B2_ASSERT(touching == false || isSensor == false); + B2_ASSERT( touching == false || sensorTouching == false ); + B2_ASSERT( touching == false || isSensor == false ); int setId = contact->setIndex; - if (setId == b2_awakeSet) + if ( setId == b2_awakeSet ) { // If touching and not a sensor - if (touching && isSensor == false) + if ( touching && isSensor == false ) { - B2_ASSERT(0 <= contact->colorIndex && contact->colorIndex < b2_graphColorCount); + B2_ASSERT( 0 <= contact->colorIndex && contact->colorIndex < b2_graphColorCount ); } else { - B2_ASSERT(contact->colorIndex == B2_NULL_INDEX); + B2_ASSERT( contact->colorIndex == B2_NULL_INDEX ); } } - else if (setId >= b2_firstSleepingSet) + else if ( setId >= b2_firstSleepingSet ) { // Only touching contacts allowed in a sleeping set - B2_ASSERT(touching == true && isSensor == false); + B2_ASSERT( touching == true && isSensor == false ); } else { // Sleeping and non-touching contacts or sensor contacts belong in the disabled set - B2_ASSERT(touching == false && setId == b2_disabledSet); + B2_ASSERT( touching == false && setId == b2_disabledSet ); } - b2ContactSim* contactSim = b2GetContactSim(world, contact); - B2_ASSERT(contactSim->contactId == contactIndex); - B2_ASSERT(contactSim->bodyIdA == contact->edges[0].bodyId); - B2_ASSERT(contactSim->bodyIdB == contact->edges[1].bodyId); + b2ContactSim* contactSim = b2GetContactSim( world, contact ); + B2_ASSERT( contactSim->contactId == contactIndex ); + B2_ASSERT( contactSim->bodyIdA == contact->edges[0].bodyId ); + B2_ASSERT( contactSim->bodyIdB == contact->edges[1].bodyId ); // Sim touching is true for solid and sensor contacts - bool simTouching = (contactSim->simFlags & b2_simTouchingFlag) != 0; - B2_ASSERT(touching == simTouching || sensorTouching == simTouching); + bool simTouching = ( contactSim->simFlags & b2_simTouchingFlag ) != 0; + B2_ASSERT( touching == simTouching || sensorTouching == simTouching ); - B2_ASSERT(0 <= contactSim->manifold.pointCount && contactSim->manifold.pointCount <= 2); + B2_ASSERT( 0 <= contactSim->manifold.pointCount && contactSim->manifold.pointCount <= 2 ); } - int contactIdCount = b2GetIdCount(&world->contactIdPool); - B2_ASSERT(allocatedContactCount == contactIdCount); + int contactIdCount = b2GetIdCount( &world->contactIdPool ); + B2_ASSERT( allocatedContactCount == contactIdCount ); } #else -void b2ValidateConnectivity(b2World* world) +void b2ValidateConnectivity( b2World* world ) { - B2_MAYBE_UNUSED(world); + B2_MAYBE_UNUSED( world ); } -void b2ValidateSolverSets(b2World* world) +void b2ValidateSolverSets( b2World* world ) { - B2_MAYBE_UNUSED(world); + B2_MAYBE_UNUSED( world ); } -void b2ValidateContacts(b2World* world) +void b2ValidateContacts( b2World* world ) { - B2_MAYBE_UNUSED(world); + B2_MAYBE_UNUSED( world ); } #endif diff --git a/src/world.h b/src/world.h index 1a39a7b2..b27aa4bc 100644 --- a/src/world.h +++ b/src/world.h @@ -87,7 +87,7 @@ typedef struct b2World // This is a sparse array that maps island ids to the island data stored in the solver sets. struct b2Island* islandArray; - + b2IdPool shapeIdPool; b2IdPool chainIdPool; @@ -162,10 +162,10 @@ typedef struct b2World bool inUse; } b2World; -b2World* b2GetWorldFromId(b2WorldId id); -b2World* b2GetWorld(int index); -b2World* b2GetWorldLocked(int index); +b2World* b2GetWorldFromId( b2WorldId id ); +b2World* b2GetWorld( int index ); +b2World* b2GetWorldLocked( int index ); -void b2ValidateConnectivity(b2World* world); -void b2ValidateSolverSets(b2World* world); -void b2ValidateContacts(b2World* world); +void b2ValidateConnectivity( b2World* world ); +void b2ValidateSolverSets( b2World* world ); +void b2ValidateContacts( b2World* world ); diff --git a/test/main.c b/test/main.c index 0624d2ad..418619aa 100644 --- a/test/main.c +++ b/test/main.c @@ -3,10 +3,10 @@ #include "test_macros.h" -#if defined(_WIN32) -#include +#if defined( _WIN32 ) + #include -//int MyAllocHook(int allocType, void* userData, size_t size, int blockType, long requestNumber, const unsigned char* filename, +// int MyAllocHook(int allocType, void* userData, size_t size, int blockType, long requestNumber, const unsigned char* filename, // int lineNumber) //{ // if (size == 16416) @@ -15,51 +15,51 @@ // } // // return 1; -//} +// } #endif -extern int BitSetTest(void); -extern int MathTest(void); -extern int CollisionTest(void); -extern int DeterminismTest(void); -extern int DistanceTest(void); -extern int WorldTest(void); -extern int ShapeTest(void); -extern int TableTest(void); +extern int BitSetTest( void ); +extern int MathTest( void ); +extern int CollisionTest( void ); +extern int DeterminismTest( void ); +extern int DistanceTest( void ); +extern int WorldTest( void ); +extern int ShapeTest( void ); +extern int TableTest( void ); -int main(void) +int main( void ) { -#if defined(_WIN32) +#if defined( _WIN32 ) // Enable memory-leak reports // How to break at the leaking allocation, in the watch window enter this variable // and set it to the allocation number in {}. Do this at the first line in main. // {,,ucrtbased.dll}_crtBreakAlloc = 3970 - _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE); - _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); + _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE ); + _CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDERR ); //_CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF | _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG)); //_CrtSetAllocHook(MyAllocHook); //_CrtSetBreakAlloc(196); #endif - printf("Starting Box2D unit tests\n"); - printf("======================================\n"); + printf( "Starting Box2D unit tests\n" ); + printf( "======================================\n" ); - RUN_TEST(MathTest); - RUN_TEST(CollisionTest); - RUN_TEST(DeterminismTest); - RUN_TEST(DistanceTest); - RUN_TEST(WorldTest); - RUN_TEST(ShapeTest); - RUN_TEST(TableTest); - RUN_TEST(BitSetTest); + RUN_TEST( MathTest ); + RUN_TEST( CollisionTest ); + RUN_TEST( DeterminismTest ); + RUN_TEST( DistanceTest ); + RUN_TEST( WorldTest ); + RUN_TEST( ShapeTest ); + RUN_TEST( TableTest ); + RUN_TEST( BitSetTest ); - printf("======================================\n"); - printf("All Box2D tests passed!\n"); + printf( "======================================\n" ); + printf( "All Box2D tests passed!\n" ); -#if defined(_WIN32) - if (_CrtDumpMemoryLeaks()) +#if defined( _WIN32 ) + if ( _CrtDumpMemoryLeaks() ) { return 1; } diff --git a/test/test_bitset.c b/test/test_bitset.c index 1f9a6c11..e01f7824 100644 --- a/test/test_bitset.c +++ b/test/test_bitset.c @@ -1,38 +1,38 @@ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT -#include "test_macros.h" #include "bitset.h" +#include "test_macros.h" #define COUNT 169 -int BitSetTest(void) +int BitSetTest( void ) { - b2BitSet bitSet = b2CreateBitSet(COUNT); - - b2SetBitCountAndClear(&bitSet, COUNT); - bool values[COUNT] = {false}; + b2BitSet bitSet = b2CreateBitSet( COUNT ); + + b2SetBitCountAndClear( &bitSet, COUNT ); + bool values[COUNT] = { false }; int32_t i1 = 0, i2 = 1; - b2SetBit(&bitSet, i1); - values[i1] = true; + b2SetBit( &bitSet, i1 ); + values[i1] = true; - while (i2 < COUNT) + while ( i2 < COUNT ) { - b2SetBit(&bitSet, i2); + b2SetBit( &bitSet, i2 ); values[i2] = true; int32_t next = i1 + i2; i1 = i2; i2 = next; } - for (int32_t i = 0; i < COUNT; ++i) + for ( int32_t i = 0; i < COUNT; ++i ) { - bool value = b2GetBit(&bitSet, i); - ENSURE(value == values[i]); + bool value = b2GetBit( &bitSet, i ); + ENSURE( value == values[i] ); } - b2DestroyBitSet(&bitSet); + b2DestroyBitSet( &bitSet ); return 0; } diff --git a/test/test_collision.c b/test/test_collision.c index 88c8ffcc..cf980bb6 100644 --- a/test/test_collision.c +++ b/test/test_collision.c @@ -6,34 +6,34 @@ #include "box2d/math_functions.h" -static int AABBTest(void) +static int AABBTest( void ) { b2AABB a; - a.lowerBound = (b2Vec2){-1.0f, -1.0f}; - a.upperBound = (b2Vec2){-2.0f, -2.0f}; + a.lowerBound = ( b2Vec2 ){ -1.0f, -1.0f }; + a.upperBound = ( b2Vec2 ){ -2.0f, -2.0f }; - ENSURE(b2AABB_IsValid(a) == false); + ENSURE( b2AABB_IsValid( a ) == false ); - a.upperBound = (b2Vec2){1.0f, 1.0f}; - ENSURE(b2AABB_IsValid(a) == true); + a.upperBound = ( b2Vec2 ){ 1.0f, 1.0f }; + ENSURE( b2AABB_IsValid( a ) == true ); - b2AABB b = {{2.0f, 2.0f}, {4.0f, 4.0f}}; - ENSURE(b2AABB_Overlaps(a, b) == false); - ENSURE(b2AABB_Contains(a, b) == false); + b2AABB b = { { 2.0f, 2.0f }, { 4.0f, 4.0f } }; + ENSURE( b2AABB_Overlaps( a, b ) == false ); + ENSURE( b2AABB_Contains( a, b ) == false ); - b2Vec2 p1 = (b2Vec2){-2.0f, 0.0f}; - b2Vec2 p2 = (b2Vec2){2.0f, 0.0f}; + b2Vec2 p1 = ( b2Vec2 ){ -2.0f, 0.0f }; + b2Vec2 p2 = ( b2Vec2 ){ 2.0f, 0.0f }; - b2CastOutput output = b2AABB_RayCast(a, p1, p2); - ENSURE(output.hit == true); - ENSURE(0.1f < output.fraction && output.fraction < 0.9f); + b2CastOutput output = b2AABB_RayCast( a, p1, p2 ); + ENSURE( output.hit == true ); + ENSURE( 0.1f < output.fraction && output.fraction < 0.9f ); return 0; } -int CollisionTest(void) +int CollisionTest( void ) { - RUN_SUBTEST(AABBTest); + RUN_SUBTEST( AABBTest ); return 0; } diff --git a/test/test_determinism.c b/test/test_determinism.c index 5688da61..50b3bef6 100644 --- a/test/test_determinism.c +++ b/test/test_determinism.c @@ -1,19 +1,19 @@ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT +#include "TaskScheduler_c.h" +#include "test_macros.h" + #include "box2d/box2d.h" #include "box2d/math_functions.h" #include "box2d/types.h" -#include "test_macros.h" - -#include "TaskScheduler_c.h" #include #ifdef BOX2D_PROFILE -#include + #include #else -#define TracyCFrameMark + #define TracyCFrameMark #endif enum @@ -38,17 +38,17 @@ enkiTaskSet* tasks[e_maxTasks]; TaskData taskData[e_maxTasks]; int taskCount; -void ExecuteRangeTask(uint32_t start, uint32_t end, uint32_t threadIndex, void* context) +void ExecuteRangeTask( uint32_t start, uint32_t end, uint32_t threadIndex, void* context ) { TaskData* data = context; - data->box2dTask(start, end, threadIndex, data->box2dContext); + data->box2dTask( start, end, threadIndex, data->box2dContext ); } -static void* EnqueueTask(b2TaskCallback* box2dTask, int itemCount, int minRange, void* box2dContext, void* userContext) +static void* EnqueueTask( b2TaskCallback* box2dTask, int itemCount, int minRange, void* box2dContext, void* userContext ) { - MAYBE_UNUSED(userContext); + MAYBE_UNUSED( userContext ); - if (taskCount < e_maxTasks) + if ( taskCount < e_maxTasks ) { enkiTaskSet* task = tasks[taskCount]; TaskData* data = taskData + taskCount; @@ -61,8 +61,8 @@ static void* EnqueueTask(b2TaskCallback* box2dTask, int itemCount, int minRange, params.pArgs = data; params.priority = 0; - enkiSetParamsTaskSet(task, params); - enkiAddTaskSet(scheduler, task); + enkiSetParamsTaskSet( task, params ); + enkiAddTaskSet( scheduler, task ); ++taskCount; @@ -70,34 +70,34 @@ static void* EnqueueTask(b2TaskCallback* box2dTask, int itemCount, int minRange, } else { - box2dTask(0, itemCount, 0, box2dContext); + box2dTask( 0, itemCount, 0, box2dContext ); return NULL; } } -static void FinishTask(void* userTask, void* userContext) +static void FinishTask( void* userTask, void* userContext ) { - MAYBE_UNUSED(userContext); + MAYBE_UNUSED( userContext ); enkiTaskSet* task = userTask; - enkiWaitForTaskSet(scheduler, task); + enkiWaitForTaskSet( scheduler, task ); } -void TiltedStacks(int testIndex, int workerCount) +void TiltedStacks( int testIndex, int workerCount ) { scheduler = enkiNewTaskScheduler(); - struct enkiTaskSchedulerConfig config = enkiGetTaskSchedulerConfig(scheduler); + struct enkiTaskSchedulerConfig config = enkiGetTaskSchedulerConfig( scheduler ); config.numTaskThreadsToCreate = workerCount - 1; - enkiInitTaskSchedulerWithConfig(scheduler, config); + enkiInitTaskSchedulerWithConfig( scheduler, config ); - for (int i = 0; i < e_maxTasks; ++i) + for ( int i = 0; i < e_maxTasks; ++i ) { - tasks[i] = enkiCreateTaskSet(scheduler, ExecuteRangeTask); + tasks[i] = enkiCreateTaskSet( scheduler, ExecuteRangeTask ); } // Define the gravity vector. - b2Vec2 gravity = {0.0f, -10.0f}; + b2Vec2 gravity = { 0.0f, -10.0f }; // Construct a world object, which will hold and simulate the rigid bodies. b2WorldDef worldDef = b2DefaultWorldDef(); @@ -107,95 +107,95 @@ void TiltedStacks(int testIndex, int workerCount) worldDef.workerCount = workerCount; worldDef.enableSleep = false; - b2WorldId worldId = b2CreateWorld(&worldDef); + b2WorldId worldId = b2CreateWorld( &worldDef ); b2BodyId bodies[e_count]; { b2BodyDef bd = b2DefaultBodyDef(); - bd.position = (b2Vec2){0.0f, -1.0f}; - b2BodyId groundId = b2CreateBody(worldId, &bd); + bd.position = ( b2Vec2 ){ 0.0f, -1.0f }; + b2BodyId groundId = b2CreateBody( worldId, &bd ); - b2Polygon box = b2MakeBox(1000.0f, 1.0f); + b2Polygon box = b2MakeBox( 1000.0f, 1.0f ); b2ShapeDef sd = b2DefaultShapeDef(); - b2CreatePolygonShape(groundId, &sd, &box); + b2CreatePolygonShape( groundId, &sd, &box ); } - b2Polygon box = b2MakeRoundedBox(0.45f, 0.45f, 0.05f); + b2Polygon box = b2MakeRoundedBox( 0.45f, 0.45f, 0.05f ); b2ShapeDef sd = b2DefaultShapeDef(); sd.density = 1.0f; sd.friction = 0.3f; float offset = 0.2f; float dx = 5.0f; - float xroot = -0.5f * dx * (e_columns - 1.0f); + float xroot = -0.5f * dx * ( e_columns - 1.0f ); - for (int j = 0; j < e_columns; ++j) + for ( int j = 0; j < e_columns; ++j ) { float x = xroot + j * dx; - for (int i = 0; i < e_rows; ++i) + for ( int i = 0; i < e_rows; ++i ) { b2BodyDef bd = b2DefaultBodyDef(); bd.type = b2_dynamicBody; int n = j * e_rows + i; - bd.position = (b2Vec2){x + offset * i, 0.5f + 1.0f * i}; - b2BodyId bodyId = b2CreateBody(worldId, &bd); + bd.position = ( b2Vec2 ){ x + offset * i, 0.5f + 1.0f * i }; + b2BodyId bodyId = b2CreateBody( worldId, &bd ); bodies[n] = bodyId; - b2CreatePolygonShape(bodyId, &sd, &box); + b2CreatePolygonShape( bodyId, &sd, &box ); } } float timeStep = 1.0f / 60.0f; int subStepCount = 3; - for (int i = 0; i < 100; ++i) + for ( int i = 0; i < 100; ++i ) { - b2World_Step(worldId, timeStep, subStepCount); + b2World_Step( worldId, timeStep, subStepCount ); taskCount = 0; TracyCFrameMark; } - for (int i = 0; i < e_count; ++i) + for ( int i = 0; i < e_count; ++i ) { - finalPositions[testIndex][i] = b2Body_GetPosition(bodies[i]); - finalRotations[testIndex][i] = b2Body_GetRotation(bodies[i]); + finalPositions[testIndex][i] = b2Body_GetPosition( bodies[i] ); + finalRotations[testIndex][i] = b2Body_GetRotation( bodies[i] ); } - b2DestroyWorld(worldId); + b2DestroyWorld( worldId ); - for (int i = 0; i < e_maxTasks; ++i) + for ( int i = 0; i < e_maxTasks; ++i ) { - enkiDeleteTaskSet(scheduler, tasks[i]); + enkiDeleteTaskSet( scheduler, tasks[i] ); } - enkiDeleteTaskScheduler(scheduler); + enkiDeleteTaskScheduler( scheduler ); } // Test multithreaded determinism. -int DeterminismTest(void) +int DeterminismTest( void ) { // Test 1 : 4 threads - TiltedStacks(0, 4); + TiltedStacks( 0, 4 ); // Test 2 : 1 thread - TiltedStacks(1, 1); + TiltedStacks( 1, 1 ); // Both runs should produce identical results - for (int i = 0; i < e_count; ++i) + for ( int i = 0; i < e_count; ++i ) { b2Vec2 p1 = finalPositions[0][i]; b2Vec2 p2 = finalPositions[1][i]; b2Rot rot1 = finalRotations[0][i]; b2Rot rot2 = finalRotations[1][i]; - ENSURE(p1.x == p2.x); - ENSURE(p1.y == p2.y); - ENSURE(rot1.c == rot2.c); - ENSURE(rot1.s == rot2.s); + ENSURE( p1.x == p2.x ); + ENSURE( p1.y == p2.y ); + ENSURE( rot1.c == rot2.c ); + ENSURE( rot1.s == rot2.s ); } return 0; diff --git a/test/test_distance.c b/test/test_distance.c index 867b391c..27cee4da 100644 --- a/test/test_distance.c +++ b/test/test_distance.c @@ -1,123 +1,112 @@ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT +#include "test_macros.h" + #include "box2d/collision.h" #include "box2d/math_functions.h" -#include "test_macros.h" #include -static int SegmentDistanceTest(void) +static int SegmentDistanceTest( void ) { - b2Vec2 p1 = {-1.0f, -1.0f}; - b2Vec2 q1 = {-1.0f, 1.0f}; - b2Vec2 p2 = {2.0f, 0.0f}; - b2Vec2 q2 = {1.0f, 0.0f}; + b2Vec2 p1 = { -1.0f, -1.0f }; + b2Vec2 q1 = { -1.0f, 1.0f }; + b2Vec2 p2 = { 2.0f, 0.0f }; + b2Vec2 q2 = { 1.0f, 0.0f }; - b2SegmentDistanceResult result = b2SegmentDistance(p1, q1, p2, q2); + b2SegmentDistanceResult result = b2SegmentDistance( p1, q1, p2, q2 ); - ENSURE_SMALL(result.fraction1 - 0.5f, FLT_EPSILON); - ENSURE_SMALL(result.fraction2 - 1.0f, FLT_EPSILON); - ENSURE_SMALL(result.closest1.x + 1.0f, FLT_EPSILON); - ENSURE_SMALL(result.closest1.y, FLT_EPSILON); - ENSURE_SMALL(result.closest2.x - 1.0f, FLT_EPSILON); - ENSURE_SMALL(result.closest2.y, FLT_EPSILON); - ENSURE_SMALL(result.distanceSquared - 4.0f, FLT_EPSILON); + ENSURE_SMALL( result.fraction1 - 0.5f, FLT_EPSILON ); + ENSURE_SMALL( result.fraction2 - 1.0f, FLT_EPSILON ); + ENSURE_SMALL( result.closest1.x + 1.0f, FLT_EPSILON ); + ENSURE_SMALL( result.closest1.y, FLT_EPSILON ); + ENSURE_SMALL( result.closest2.x - 1.0f, FLT_EPSILON ); + ENSURE_SMALL( result.closest2.y, FLT_EPSILON ); + ENSURE_SMALL( result.distanceSquared - 4.0f, FLT_EPSILON ); return 0; } -static int ShapeDistanceTest(void) +static int ShapeDistanceTest( void ) { - b2Vec2 vas[] = { - (b2Vec2){-1.0f, -1.0f}, - (b2Vec2){1.0f, -1.0f}, - (b2Vec2){1.0f, 1.0f}, - (b2Vec2){-1.0f, 1.0f}}; + b2Vec2 vas[] = { ( b2Vec2 ){ -1.0f, -1.0f }, ( b2Vec2 ){ 1.0f, -1.0f }, ( b2Vec2 ){ 1.0f, 1.0f }, ( b2Vec2 ){ -1.0f, 1.0f } }; b2Vec2 vbs[] = { - (b2Vec2){2.0f, -1.0f}, - (b2Vec2){2.0f, 1.0f}, + ( b2Vec2 ){ 2.0f, -1.0f }, + ( b2Vec2 ){ 2.0f, 1.0f }, }; b2DistanceInput input; - input.proxyA = b2MakeProxy(vas, ARRAY_COUNT(vas), 0.0f); - input.proxyB = b2MakeProxy(vbs, ARRAY_COUNT(vbs), 0.0f); + input.proxyA = b2MakeProxy( vas, ARRAY_COUNT( vas ), 0.0f ); + input.proxyB = b2MakeProxy( vbs, ARRAY_COUNT( vbs ), 0.0f ); input.transformA = b2Transform_identity; input.transformB = b2Transform_identity; input.useRadii = false; - b2DistanceCache cache = {0}; - b2DistanceOutput output = b2ShapeDistance(&cache, &input, NULL, 0); + b2DistanceCache cache = { 0 }; + b2DistanceOutput output = b2ShapeDistance( &cache, &input, NULL, 0 ); - ENSURE_SMALL(output.distance - 1.0f, FLT_EPSILON); + ENSURE_SMALL( output.distance - 1.0f, FLT_EPSILON ); return 0; } -static int ShapeCastTest(void) +static int ShapeCastTest( void ) { - b2Vec2 vas[] = { - (b2Vec2){-1.0f, -1.0f}, - (b2Vec2){1.0f, -1.0f}, - (b2Vec2){1.0f, 1.0f}, - (b2Vec2){-1.0f, 1.0f}}; + b2Vec2 vas[] = { ( b2Vec2 ){ -1.0f, -1.0f }, ( b2Vec2 ){ 1.0f, -1.0f }, ( b2Vec2 ){ 1.0f, 1.0f }, ( b2Vec2 ){ -1.0f, 1.0f } }; b2Vec2 vbs[] = { - (b2Vec2){2.0f, -1.0f}, - (b2Vec2){2.0f, 1.0f}, + ( b2Vec2 ){ 2.0f, -1.0f }, + ( b2Vec2 ){ 2.0f, 1.0f }, }; b2ShapeCastPairInput input; - input.proxyA = b2MakeProxy(vas, ARRAY_COUNT(vas), 0.0f); - input.proxyB = b2MakeProxy(vbs, ARRAY_COUNT(vbs), 0.0f); + input.proxyA = b2MakeProxy( vas, ARRAY_COUNT( vas ), 0.0f ); + input.proxyB = b2MakeProxy( vbs, ARRAY_COUNT( vbs ), 0.0f ); input.transformA = b2Transform_identity; input.transformB = b2Transform_identity; - input.translationB = (b2Vec2){-2.0f, 0.0f}; + input.translationB = ( b2Vec2 ){ -2.0f, 0.0f }; input.maxFraction = 1.0f; - b2CastOutput output = b2ShapeCast(&input); + b2CastOutput output = b2ShapeCast( &input ); - ENSURE(output.hit); - ENSURE_SMALL(output.fraction - 0.5f, 0.005f); + ENSURE( output.hit ); + ENSURE_SMALL( output.fraction - 0.5f, 0.005f ); return 0; } -static int TimeOfImpactTest(void) +static int TimeOfImpactTest( void ) { - b2Vec2 vas[] = { - {-1.0f, -1.0f}, - {1.0f, -1.0f}, - {1.0f, 1.0f}, - {-1.0f, 1.0f}}; + b2Vec2 vas[] = { { -1.0f, -1.0f }, { 1.0f, -1.0f }, { 1.0f, 1.0f }, { -1.0f, 1.0f } }; b2Vec2 vbs[] = { - {2.0f, -1.0f}, - {2.0f, 1.0f}, + { 2.0f, -1.0f }, + { 2.0f, 1.0f }, }; b2TOIInput input; - input.proxyA = b2MakeProxy(vas, ARRAY_COUNT(vas), 0.0f); - input.proxyB = b2MakeProxy(vbs, ARRAY_COUNT(vbs), 0.0f); - input.sweepA = (b2Sweep){b2Vec2_zero, b2Vec2_zero, b2Vec2_zero, b2Rot_identity, b2Rot_identity}; - input.sweepB = (b2Sweep){b2Vec2_zero, b2Vec2_zero, (b2Vec2){-2.0f, 0.0f}, b2Rot_identity, b2Rot_identity}; + input.proxyA = b2MakeProxy( vas, ARRAY_COUNT( vas ), 0.0f ); + input.proxyB = b2MakeProxy( vbs, ARRAY_COUNT( vbs ), 0.0f ); + input.sweepA = ( b2Sweep ){ b2Vec2_zero, b2Vec2_zero, b2Vec2_zero, b2Rot_identity, b2Rot_identity }; + input.sweepB = ( b2Sweep ){ b2Vec2_zero, b2Vec2_zero, ( b2Vec2 ){ -2.0f, 0.0f }, b2Rot_identity, b2Rot_identity }; input.tMax = 1.0f; - b2TOIOutput output = b2TimeOfImpact(&input); + b2TOIOutput output = b2TimeOfImpact( &input ); - ENSURE(output.state == b2_toiStateHit); - ENSURE_SMALL(output.t - 0.5f, 0.005f); + ENSURE( output.state == b2_toiStateHit ); + ENSURE_SMALL( output.t - 0.5f, 0.005f ); return 0; } -int DistanceTest(void) +int DistanceTest( void ) { - RUN_SUBTEST(SegmentDistanceTest); - RUN_SUBTEST(ShapeDistanceTest); - RUN_SUBTEST(ShapeCastTest); - RUN_SUBTEST(TimeOfImpactTest); + RUN_SUBTEST( SegmentDistanceTest ); + RUN_SUBTEST( ShapeDistanceTest ); + RUN_SUBTEST( ShapeCastTest ); + RUN_SUBTEST( TimeOfImpactTest ); return 0; } diff --git a/test/test_macros.h b/test/test_macros.h index f02d8757..a0944892 100644 --- a/test/test_macros.h +++ b/test/test_macros.h @@ -1,59 +1,69 @@ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT +#pragma once + +#include #include #include -#include -#define RUN_TEST(T) \ - do { \ - int result = T(); \ - if (result == 1) \ - { \ - printf("test failed: " #T "\n"); \ - return 1; \ - } \ - else \ - { \ - printf("test passed: " #T "\n"); \ - } \ - } while (false) - -#define RUN_SUBTEST(T) \ - do { \ - int result = T(); \ - if (result == 1) \ - { \ - printf(" subtest failed: " #T "\n"); \ - return 1; \ - } \ - else \ - { \ - printf(" subtest passed: " #T "\n"); \ - } \ - } while (false) - -#define ENSURE(C) \ - do { \ - if ((C) == false) \ - { \ - printf("condition false: " #C "\n"); \ - assert(false); \ - return 1; \ - } \ - } while (false) - -#define ENSURE_SMALL(C, tol) \ - do { \ - if ((C) < -(tol) || (tol) < (C)) \ - { \ - printf("condition false: abs(" #C ") < %g\n", tol); \ - assert(false); \ - return 1; \ - } \ - } while (false) - -#define ARRAY_COUNT(A) (int)(sizeof(A) / sizeof(A[0])) +#define RUN_TEST( T ) \ + do \ + { \ + int result = T(); \ + if ( result == 1 ) \ + { \ + printf( "test failed: " #T "\n" ); \ + return 1; \ + } \ + else \ + { \ + printf( "test passed: " #T "\n" ); \ + } \ + } \ + while ( false ) + +#define RUN_SUBTEST( T ) \ + do \ + { \ + int result = T(); \ + if ( result == 1 ) \ + { \ + printf( " subtest failed: " #T "\n" ); \ + return 1; \ + } \ + else \ + { \ + printf( " subtest passed: " #T "\n" ); \ + } \ + } \ + while ( false ) + +#define ENSURE( C ) \ + do \ + { \ + if ( ( C ) == false ) \ + { \ + printf( "condition false: " #C "\n" ); \ + assert( false ); \ + return 1; \ + } \ + } \ + while ( false ) + +#define ENSURE_SMALL( C, tol ) \ + do \ + { \ + if ( ( C ) < -( tol ) || ( tol ) < ( C ) ) \ + { \ + printf( "condition false: abs(" #C ") < %g\n", tol ); \ + assert( false ); \ + return 1; \ + } \ + } \ + while ( false ) + +#define ARRAY_COUNT( A ) (int)( sizeof( A ) / sizeof( A[0] ) ) /// Used to prevent the compiler from warning about unused variables -#define MAYBE_UNUSED(x) ((void)(x)) +#define MAYBE_UNUSED( x ) ( (void)( x ) ) diff --git a/test/test_math.c b/test/test_math.c index 873722aa..ed545f66 100644 --- a/test/test_math.c +++ b/test/test_math.c @@ -1,43 +1,44 @@ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT -#include "box2d/math_functions.h" #include "test_macros.h" +#include "box2d/math_functions.h" + #include -int MathTest(void) +int MathTest( void ) { b2Vec2 zero = b2Vec2_zero; - b2Vec2 one = {1.0f, 1.0f}; - b2Vec2 two = {2.0f, 2.0f}; + b2Vec2 one = { 1.0f, 1.0f }; + b2Vec2 two = { 2.0f, 2.0f }; - b2Vec2 v = b2Add(one, two); - ENSURE(v.x == 3.0f && v.y == 3.0f); + b2Vec2 v = b2Add( one, two ); + ENSURE( v.x == 3.0f && v.y == 3.0f ); - v = b2Sub(zero, two); - ENSURE(v.x == -2.0f && v.y == -2.0f); + v = b2Sub( zero, two ); + ENSURE( v.x == -2.0f && v.y == -2.0f ); - v = b2Add(two, two); - ENSURE(v.x != 5.0f && v.y != 5.0f); + v = b2Add( two, two ); + ENSURE( v.x != 5.0f && v.y != 5.0f ); - b2Transform transform1 = {{-2.0f, 3.0f}, b2MakeRot(1.0f)}; - b2Transform transform2 = {{1.0f, 0.0f}, b2MakeRot(-2.0f)}; + b2Transform transform1 = { { -2.0f, 3.0f }, b2MakeRot( 1.0f ) }; + b2Transform transform2 = { { 1.0f, 0.0f }, b2MakeRot( -2.0f ) }; - b2Transform transform = b2MulTransforms(transform2, transform1); + b2Transform transform = b2MulTransforms( transform2, transform1 ); - v = b2TransformPoint(transform2, b2TransformPoint(transform1, two)); + v = b2TransformPoint( transform2, b2TransformPoint( transform1, two ) ); - b2Vec2 u = b2TransformPoint(transform, two); + b2Vec2 u = b2TransformPoint( transform, two ); - ENSURE_SMALL(u.x - v.x, 10.0f * FLT_EPSILON); - ENSURE_SMALL(u.y - v.y, 10.0f * FLT_EPSILON); + ENSURE_SMALL( u.x - v.x, 10.0f * FLT_EPSILON ); + ENSURE_SMALL( u.y - v.y, 10.0f * FLT_EPSILON ); - v = b2TransformPoint(transform1, two); - v = b2InvTransformPoint(transform1, v); + v = b2TransformPoint( transform1, two ); + v = b2InvTransformPoint( transform1, v ); - ENSURE_SMALL(v.x - two.x, 8.0f * FLT_EPSILON); - ENSURE_SMALL(v.y - two.y, 8.0f * FLT_EPSILON); + ENSURE_SMALL( v.x - two.x, 8.0f * FLT_EPSILON ); + ENSURE_SMALL( v.y - two.y, 8.0f * FLT_EPSILON ); return 0; } diff --git a/test/test_shape.c b/test/test_shape.c index 5c3bb2ae..ab2b2a0b 100644 --- a/test/test_shape.c +++ b/test/test_shape.c @@ -1,168 +1,169 @@ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT +#include "test_macros.h" + #include "box2d/collision.h" #include "box2d/math_functions.h" -#include "test_macros.h" #include -static b2Capsule capsule = {{-1.0f, 0.0f}, {1.0f, 0.0f}, 1.0f}; -static b2Circle circle = {{1.0f, 0.0f}, 1.0f}; +static b2Capsule capsule = { { -1.0f, 0.0f }, { 1.0f, 0.0f }, 1.0f }; +static b2Circle circle = { { 1.0f, 0.0f }, 1.0f }; static b2Polygon box; -static b2Segment segment = {{0.0f, 1.0f}, {0.0f, -1.0f}}; +static b2Segment segment = { { 0.0f, 1.0f }, { 0.0f, -1.0f } }; #define N 4 -static int ShapeMassTest(void) +static int ShapeMassTest( void ) { { - b2MassData md = b2ComputeCircleMass(&circle, 1.0f); - ENSURE_SMALL(md.mass - b2_pi, FLT_EPSILON); - ENSURE(md.center.x == 1.0f && md.center.y == 0.0f); - ENSURE_SMALL(md.rotationalInertia - 1.5f * b2_pi, FLT_EPSILON); + b2MassData md = b2ComputeCircleMass( &circle, 1.0f ); + ENSURE_SMALL( md.mass - b2_pi, FLT_EPSILON ); + ENSURE( md.center.x == 1.0f && md.center.y == 0.0f ); + ENSURE_SMALL( md.rotationalInertia - 1.5f * b2_pi, FLT_EPSILON ); } { float radius = capsule.radius; - float length = b2Distance(capsule.center1, capsule.center2); + float length = b2Distance( capsule.center1, capsule.center2 ); - b2MassData md = b2ComputeCapsuleMass(&capsule, 1.0f); + b2MassData md = b2ComputeCapsuleMass( &capsule, 1.0f ); // Box that full contains capsule - b2Polygon r = b2MakeBox(radius, radius + 0.5f * length); - b2MassData mdr = b2ComputePolygonMass(&r, 1.0f); + b2Polygon r = b2MakeBox( radius, radius + 0.5f * length ); + b2MassData mdr = b2ComputePolygonMass( &r, 1.0f ); // Approximate capsule using convex hull b2Vec2 points[2 * N]; - float d = b2_pi / (N - 1.0f); + float d = b2_pi / ( N - 1.0f ); float angle = -0.5f * b2_pi; - for (int i = 0; i < N; ++i) + for ( int i = 0; i < N; ++i ) { - points[i].x = 1.0f + radius * cosf(angle); - points[i].y = radius * sinf(angle); + points[i].x = 1.0f + radius * cosf( angle ); + points[i].y = radius * sinf( angle ); angle += d; } - + angle = 0.5f * b2_pi; - for (int i = N; i < 2 * N; ++i) + for ( int i = N; i < 2 * N; ++i ) { - points[i].x = -1.0f + radius * cosf(angle); - points[i].y = radius * sinf(angle); + points[i].x = -1.0f + radius * cosf( angle ); + points[i].y = radius * sinf( angle ); angle += d; } - - b2Hull hull = b2ComputeHull(points, 2 * N); - b2Polygon ac = b2MakePolygon(&hull, 0.0f); - b2MassData ma = b2ComputePolygonMass(&ac, 1.0f); - ENSURE(ma.mass < md.mass && md.mass < mdr.mass); - ENSURE(ma.rotationalInertia < md.rotationalInertia && md.rotationalInertia < mdr.rotationalInertia); + b2Hull hull = b2ComputeHull( points, 2 * N ); + b2Polygon ac = b2MakePolygon( &hull, 0.0f ); + b2MassData ma = b2ComputePolygonMass( &ac, 1.0f ); + + ENSURE( ma.mass < md.mass && md.mass < mdr.mass ); + ENSURE( ma.rotationalInertia < md.rotationalInertia && md.rotationalInertia < mdr.rotationalInertia ); } { - b2MassData md = b2ComputePolygonMass(&box, 1.0f); - ENSURE_SMALL(md.mass - 4.0f, FLT_EPSILON); - ENSURE_SMALL(md.center.x, FLT_EPSILON); - ENSURE_SMALL(md.center.y, FLT_EPSILON); - ENSURE_SMALL(md.rotationalInertia - 8.0f / 3.0f, 2.0f * FLT_EPSILON); + b2MassData md = b2ComputePolygonMass( &box, 1.0f ); + ENSURE_SMALL( md.mass - 4.0f, FLT_EPSILON ); + ENSURE_SMALL( md.center.x, FLT_EPSILON ); + ENSURE_SMALL( md.center.y, FLT_EPSILON ); + ENSURE_SMALL( md.rotationalInertia - 8.0f / 3.0f, 2.0f * FLT_EPSILON ); } return 0; } -static int ShapeAABBTest(void) +static int ShapeAABBTest( void ) { { - b2AABB b = b2ComputeCircleAABB(&circle, b2Transform_identity); - ENSURE_SMALL(b.lowerBound.x, FLT_EPSILON); - ENSURE_SMALL(b.lowerBound.y + 1.0f, FLT_EPSILON); - ENSURE_SMALL(b.upperBound.x - 2.0f, FLT_EPSILON); - ENSURE_SMALL(b.upperBound.y - 1.0f, FLT_EPSILON); + b2AABB b = b2ComputeCircleAABB( &circle, b2Transform_identity ); + ENSURE_SMALL( b.lowerBound.x, FLT_EPSILON ); + ENSURE_SMALL( b.lowerBound.y + 1.0f, FLT_EPSILON ); + ENSURE_SMALL( b.upperBound.x - 2.0f, FLT_EPSILON ); + ENSURE_SMALL( b.upperBound.y - 1.0f, FLT_EPSILON ); } { - b2AABB b = b2ComputePolygonAABB(&box, b2Transform_identity); - ENSURE_SMALL(b.lowerBound.x + 1.0f, FLT_EPSILON); - ENSURE_SMALL(b.lowerBound.y + 1.0f, FLT_EPSILON); - ENSURE_SMALL(b.upperBound.x - 1.0f, FLT_EPSILON); - ENSURE_SMALL(b.upperBound.y - 1.0f, FLT_EPSILON); + b2AABB b = b2ComputePolygonAABB( &box, b2Transform_identity ); + ENSURE_SMALL( b.lowerBound.x + 1.0f, FLT_EPSILON ); + ENSURE_SMALL( b.lowerBound.y + 1.0f, FLT_EPSILON ); + ENSURE_SMALL( b.upperBound.x - 1.0f, FLT_EPSILON ); + ENSURE_SMALL( b.upperBound.y - 1.0f, FLT_EPSILON ); } { - b2AABB b = b2ComputeSegmentAABB(&segment, b2Transform_identity); - ENSURE_SMALL(b.lowerBound.x, FLT_EPSILON); - ENSURE_SMALL(b.lowerBound.y + 1.0f, FLT_EPSILON); - ENSURE_SMALL(b.upperBound.x, FLT_EPSILON); - ENSURE_SMALL(b.upperBound.y - 1.0f, FLT_EPSILON); + b2AABB b = b2ComputeSegmentAABB( &segment, b2Transform_identity ); + ENSURE_SMALL( b.lowerBound.x, FLT_EPSILON ); + ENSURE_SMALL( b.lowerBound.y + 1.0f, FLT_EPSILON ); + ENSURE_SMALL( b.upperBound.x, FLT_EPSILON ); + ENSURE_SMALL( b.upperBound.y - 1.0f, FLT_EPSILON ); } return 0; } -static int PointInShapeTest(void) +static int PointInShapeTest( void ) { - b2Vec2 p1 = {0.5f, 0.5f}; - b2Vec2 p2 = {4.0f, -4.0f}; - + b2Vec2 p1 = { 0.5f, 0.5f }; + b2Vec2 p2 = { 4.0f, -4.0f }; + { bool hit; - hit = b2PointInCircle(p1, &circle); - ENSURE(hit == true); - hit = b2PointInCircle(p2, &circle); - ENSURE(hit == false); + hit = b2PointInCircle( p1, &circle ); + ENSURE( hit == true ); + hit = b2PointInCircle( p2, &circle ); + ENSURE( hit == false ); } { bool hit; - hit = b2PointInPolygon(p1, &box); - ENSURE(hit == true); - hit = b2PointInPolygon(p2, &box); - ENSURE(hit == false); + hit = b2PointInPolygon( p1, &box ); + ENSURE( hit == true ); + hit = b2PointInPolygon( p2, &box ); + ENSURE( hit == false ); } return 0; } -static int RayCastShapeTest(void) +static int RayCastShapeTest( void ) { - b2RayCastInput input = {{-4.0f, 0.0f}, {8.0f, 0.0f}, 1.0f}; - + b2RayCastInput input = { { -4.0f, 0.0f }, { 8.0f, 0.0f }, 1.0f }; + { - b2CastOutput output = b2RayCastCircle(&input, &circle); - ENSURE(output.hit); - ENSURE_SMALL(output.normal.x + 1.0f, FLT_EPSILON); - ENSURE_SMALL(output.normal.y, FLT_EPSILON); - ENSURE_SMALL(output.fraction - 0.5f, FLT_EPSILON); + b2CastOutput output = b2RayCastCircle( &input, &circle ); + ENSURE( output.hit ); + ENSURE_SMALL( output.normal.x + 1.0f, FLT_EPSILON ); + ENSURE_SMALL( output.normal.y, FLT_EPSILON ); + ENSURE_SMALL( output.fraction - 0.5f, FLT_EPSILON ); } { - b2CastOutput output = b2RayCastPolygon(&input, &box); - ENSURE(output.hit); - ENSURE_SMALL(output.normal.x + 1.0f, FLT_EPSILON); - ENSURE_SMALL(output.normal.y, FLT_EPSILON); - ENSURE_SMALL(output.fraction - 3.0f / 8.0f, FLT_EPSILON); + b2CastOutput output = b2RayCastPolygon( &input, &box ); + ENSURE( output.hit ); + ENSURE_SMALL( output.normal.x + 1.0f, FLT_EPSILON ); + ENSURE_SMALL( output.normal.y, FLT_EPSILON ); + ENSURE_SMALL( output.fraction - 3.0f / 8.0f, FLT_EPSILON ); } { - b2CastOutput output = b2RayCastSegment(&input, &segment, true); - ENSURE(output.hit); - ENSURE_SMALL(output.normal.x + 1.0f, FLT_EPSILON); - ENSURE_SMALL(output.normal.y, FLT_EPSILON); - ENSURE_SMALL(output.fraction - 0.5f, FLT_EPSILON); + b2CastOutput output = b2RayCastSegment( &input, &segment, true ); + ENSURE( output.hit ); + ENSURE_SMALL( output.normal.x + 1.0f, FLT_EPSILON ); + ENSURE_SMALL( output.normal.y, FLT_EPSILON ); + ENSURE_SMALL( output.fraction - 0.5f, FLT_EPSILON ); } return 0; } -int ShapeTest(void) +int ShapeTest( void ) { - box = b2MakeBox(1.0f, 1.0f); + box = b2MakeBox( 1.0f, 1.0f ); - RUN_SUBTEST(ShapeMassTest); - RUN_SUBTEST(ShapeAABBTest); - RUN_SUBTEST(PointInShapeTest); - RUN_SUBTEST(RayCastShapeTest); + RUN_SUBTEST( ShapeMassTest ); + RUN_SUBTEST( ShapeAABBTest ); + RUN_SUBTEST( PointInShapeTest ); + RUN_SUBTEST( RayCastShapeTest ); return 0; } diff --git a/test/test_table.c b/test/test_table.c index 66423246..3cfe7886 100644 --- a/test/test_table.c +++ b/test/test_table.c @@ -10,47 +10,47 @@ #include #define SET_SPAN 317 -#define ITEM_COUNT ((SET_SPAN * SET_SPAN - SET_SPAN) / 2) +#define ITEM_COUNT ( ( SET_SPAN * SET_SPAN - SET_SPAN ) / 2 ) -int TableTest(void) +int TableTest( void ) { - int power = b2BoundingPowerOf2(3008); - ENSURE(power == 12); + int power = b2BoundingPowerOf2( 3008 ); + ENSURE( power == 12 ); - int nextPowerOf2 = b2RoundUpPowerOf2(3008); - ENSURE(nextPowerOf2 == (1 << power)); + int nextPowerOf2 = b2RoundUpPowerOf2( 3008 ); + ENSURE( nextPowerOf2 == ( 1 << power ) ); const int32_t N = SET_SPAN; const uint32_t itemCount = ITEM_COUNT; - bool removed[ITEM_COUNT] = {0}; + bool removed[ITEM_COUNT] = { 0 }; - for (int32_t iter = 0; iter < 1; ++iter) + for ( int32_t iter = 0; iter < 1; ++iter ) { - b2HashSet set = b2CreateSet(16); + b2HashSet set = b2CreateSet( 16 ); // Fill set - for (int32_t i = 0; i < N; ++i) + for ( int32_t i = 0; i < N; ++i ) { - for (int32_t j = i + 1; j < N; ++j) + for ( int32_t j = i + 1; j < N; ++j ) { - uint64_t key = B2_SHAPE_PAIR_KEY(i, j); - b2AddKey(&set, key); + uint64_t key = B2_SHAPE_PAIR_KEY( i, j ); + b2AddKey( &set, key ); } } - ENSURE(set.count == itemCount); + ENSURE( set.count == itemCount ); // Remove a portion of the set int32_t k = 0; uint32_t removeCount = 0; - for (int32_t i = 0; i < N; ++i) + for ( int32_t i = 0; i < N; ++i ) { - for (int32_t j = i + 1; j < N; ++j) + for ( int32_t j = i + 1; j < N; ++j ) { - if (j == i + 1) + if ( j == i + 1 ) { - uint64_t key = B2_SHAPE_PAIR_KEY(i, j); - b2RemoveKey(&set, key); + uint64_t key = B2_SHAPE_PAIR_KEY( i, j ); + b2RemoveKey( &set, key ); removed[k++] = true; removeCount += 1; } @@ -61,7 +61,7 @@ int TableTest(void) } } - ENSURE(set.count == (itemCount - removeCount)); + ENSURE( set.count == ( itemCount - removeCount ) ); #ifndef NDEBUG extern _Atomic int g_probeCount; @@ -73,12 +73,12 @@ int TableTest(void) b2Timer timer = b2CreateTimer(); k = 0; - for (int32_t i = 0; i < N; ++i) + for ( int32_t i = 0; i < N; ++i ) { - for (int32_t j = i + 1; j < N; ++j) + for ( int32_t j = i + 1; j < N; ++j ) { - uint64_t key = B2_SHAPE_PAIR_KEY(j, i); - ENSURE(b2ContainsKey(&set, key) || removed[k]); + uint64_t key = B2_SHAPE_PAIR_KEY( j, i ); + ENSURE( b2ContainsKey( &set, key ) || removed[k] ); k += 1; } } @@ -86,27 +86,27 @@ int TableTest(void) // uint64_t ticks = b2GetTicks(&timer); // printf("set ticks = %llu\n", ticks); - float ms = b2GetMilliseconds(&timer); - printf("set: count = %d, b2ContainsKey = %.5f ms, ave = %.5f us\n", itemCount, ms, 1000.0f * ms / itemCount); + float ms = b2GetMilliseconds( &timer ); + printf( "set: count = %d, b2ContainsKey = %.5f ms, ave = %.5f us\n", itemCount, ms, 1000.0f * ms / itemCount ); #if !NDEBUG float aveProbeCount = (float)g_probeCount / (float)itemCount; - printf("item count = %d, probe count = %d, ave probe count %.2f\n", itemCount, g_probeCount, aveProbeCount); + printf( "item count = %d, probe count = %d, ave probe count %.2f\n", itemCount, g_probeCount, aveProbeCount ); #endif // Remove all keys from set - for (int32_t i = 0; i < N; ++i) + for ( int32_t i = 0; i < N; ++i ) { - for (int32_t j = i + 1; j < N; ++j) + for ( int32_t j = i + 1; j < N; ++j ) { - uint64_t key = B2_SHAPE_PAIR_KEY(i, j); - b2RemoveKey(&set, key); + uint64_t key = B2_SHAPE_PAIR_KEY( i, j ); + b2RemoveKey( &set, key ); } } - ENSURE(set.count == 0); + ENSURE( set.count == 0 ); - b2DestroySet(&set); + b2DestroySet( &set ); } return 0; diff --git a/test/test_world.c b/test/test_world.c index 490e005d..deeaea30 100644 --- a/test/test_world.c +++ b/test/test_world.c @@ -1,10 +1,11 @@ // SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT +#include "test_macros.h" + #include "box2d/box2d.h" #include "box2d/collision.h" #include "box2d/math_functions.h" -#include "test_macros.h" #include @@ -13,41 +14,41 @@ // box. // There are no graphics for this example. Box2D is meant to be used // with your rendering engine in your game engine. -int HelloWorld(void) +int HelloWorld( void ) { // Construct a world object, which will hold and simulate the rigid bodies. b2WorldDef worldDef = b2DefaultWorldDef(); - worldDef.gravity = (b2Vec2){0.0f, -10.0f}; + worldDef.gravity = ( b2Vec2 ){ 0.0f, -10.0f }; - b2WorldId worldId = b2CreateWorld(&worldDef); - ENSURE(b2World_IsValid(worldId)); + b2WorldId worldId = b2CreateWorld( &worldDef ); + ENSURE( b2World_IsValid( worldId ) ); // Define the ground body. b2BodyDef groundBodyDef = b2DefaultBodyDef(); - groundBodyDef.position = (b2Vec2){0.0f, -10.0f}; + groundBodyDef.position = ( b2Vec2 ){ 0.0f, -10.0f }; // Call the body factory which allocates memory for the ground body // from a pool and creates the ground box shape (also from a pool). // The body is also added to the world. - b2BodyId groundId = b2CreateBody(worldId, &groundBodyDef); - ENSURE(b2Body_IsValid(groundId)); + b2BodyId groundId = b2CreateBody( worldId, &groundBodyDef ); + ENSURE( b2Body_IsValid( groundId ) ); // Define the ground box shape. The extents are the half-widths of the box. - b2Polygon groundBox = b2MakeBox(50.0f, 10.0f); + b2Polygon groundBox = b2MakeBox( 50.0f, 10.0f ); // Add the box shape to the ground body. b2ShapeDef groundShapeDef = b2DefaultShapeDef(); - b2CreatePolygonShape(groundId, &groundShapeDef, &groundBox); + b2CreatePolygonShape( groundId, &groundShapeDef, &groundBox ); // Define the dynamic body. We set its position and call the body factory. b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - bodyDef.position = (b2Vec2){0.0f, 4.0f}; + bodyDef.position = ( b2Vec2 ){ 0.0f, 4.0f }; - b2BodyId bodyId = b2CreateBody(worldId, &bodyDef); + b2BodyId bodyId = b2CreateBody( worldId, &bodyDef ); // Define another box shape for our dynamic body. - b2Polygon dynamicBox = b2MakeBox(1.0f, 1.0f); + b2Polygon dynamicBox = b2MakeBox( 1.0f, 1.0f ); // Define the dynamic body shape b2ShapeDef shapeDef = b2DefaultShapeDef(); @@ -59,7 +60,7 @@ int HelloWorld(void) shapeDef.friction = 0.3f; // Add the shape to the body. - b2CreatePolygonShape(bodyId, &shapeDef, &dynamicBox); + b2CreatePolygonShape( bodyId, &shapeDef, &dynamicBox ); // Prepare for simulation. Typically we use a time step of 1/60 of a // second (60Hz) and 4 sub-steps. This provides a high quality simulation @@ -67,61 +68,61 @@ int HelloWorld(void) float timeStep = 1.0f / 60.0f; int subStepCount = 4; - b2Vec2 position = b2Body_GetPosition(bodyId); - b2Rot rotation = b2Body_GetRotation(bodyId); + b2Vec2 position = b2Body_GetPosition( bodyId ); + b2Rot rotation = b2Body_GetRotation( bodyId ); // This is our little game loop. - for (int i = 0; i < 90; ++i) + for ( int i = 0; i < 90; ++i ) { // Instruct the world to perform a single step of simulation. // It is generally best to keep the time step and iterations fixed. - b2World_Step(worldId, timeStep, subStepCount); + b2World_Step( worldId, timeStep, subStepCount ); // Now print the position and angle of the body. - position = b2Body_GetPosition(bodyId); - rotation = b2Body_GetRotation(bodyId); + position = b2Body_GetPosition( bodyId ); + rotation = b2Body_GetRotation( bodyId ); - //printf("%4.2f %4.2f %4.2f\n", position.x, position.y, b2Rot_GetAngle(rotation)); + // printf("%4.2f %4.2f %4.2f\n", position.x, position.y, b2Rot_GetAngle(rotation)); } // When the world destructor is called, all bodies and joints are freed. This can // create orphaned ids, so be careful about your world management. - b2DestroyWorld(worldId); + b2DestroyWorld( worldId ); - ENSURE(b2AbsFloat(position.x) < 0.01f); - ENSURE(b2AbsFloat(position.y - 1.00f) < 0.01f); - ENSURE(b2AbsFloat(b2Rot_GetAngle(rotation)) < 0.01f); + ENSURE( b2AbsFloat( position.x ) < 0.01f ); + ENSURE( b2AbsFloat( position.y - 1.00f ) < 0.01f ); + ENSURE( b2AbsFloat( b2Rot_GetAngle( rotation ) ) < 0.01f ); return 0; } -int EmptyWorld(void) +int EmptyWorld( void ) { b2WorldDef worldDef = b2DefaultWorldDef(); - b2WorldId worldId = b2CreateWorld(&worldDef); - ENSURE(b2World_IsValid(worldId) == true); + b2WorldId worldId = b2CreateWorld( &worldDef ); + ENSURE( b2World_IsValid( worldId ) == true ); float timeStep = 1.0f / 60.0f; int32_t subStepCount = 1; - for (int32_t i = 0; i < 60; ++i) + for ( int32_t i = 0; i < 60; ++i ) { - b2World_Step(worldId, timeStep, subStepCount); + b2World_Step( worldId, timeStep, subStepCount ); } - b2DestroyWorld(worldId); + b2DestroyWorld( worldId ); - ENSURE(b2World_IsValid(worldId) == false); + ENSURE( b2World_IsValid( worldId ) == false ); return 0; } #define BODY_COUNT 10 -int DestroyAllBodiesWorld(void) +int DestroyAllBodiesWorld( void ) { b2WorldDef worldDef = b2DefaultWorldDef(); - b2WorldId worldId = b2CreateWorld(&worldDef); - ENSURE(b2World_IsValid(worldId) == true); + b2WorldId worldId = b2CreateWorld( &worldDef ); + ENSURE( b2World_IsValid( worldId ) == true ); int count = 0; bool creating = true; @@ -129,18 +130,18 @@ int DestroyAllBodiesWorld(void) b2BodyId bodyIds[BODY_COUNT]; b2BodyDef bodyDef = b2DefaultBodyDef(); bodyDef.type = b2_dynamicBody; - b2Polygon square = b2MakeSquare(0.5f); + b2Polygon square = b2MakeSquare( 0.5f ); - for (int32_t i = 0; i < 2 * BODY_COUNT + 10; ++i) + for ( int32_t i = 0; i < 2 * BODY_COUNT + 10; ++i ) { - if (creating) + if ( creating ) { - if (count < BODY_COUNT) + if ( count < BODY_COUNT ) { - bodyIds[count] = b2CreateBody(worldId, &bodyDef); + bodyIds[count] = b2CreateBody( worldId, &bodyDef ); b2ShapeDef shapeDef = b2DefaultShapeDef(); - b2CreatePolygonShape(bodyIds[count], &shapeDef, &square); + b2CreatePolygonShape( bodyIds[count], &shapeDef, &square ); count += 1; } else @@ -148,61 +149,61 @@ int DestroyAllBodiesWorld(void) creating = false; } } - else if (count > 0) + else if ( count > 0 ) { - b2DestroyBody(bodyIds[count - 1]); + b2DestroyBody( bodyIds[count - 1] ); bodyIds[count - 1] = b2_nullBodyId; count -= 1; } - b2World_Step(worldId, 1.0f / 60.0f, 3); + b2World_Step( worldId, 1.0f / 60.0f, 3 ); } - b2Counters counters = b2World_GetCounters(worldId); - ENSURE(counters.bodyCount == 0); + b2Counters counters = b2World_GetCounters( worldId ); + ENSURE( counters.bodyCount == 0 ); - b2DestroyWorld(worldId); + b2DestroyWorld( worldId ); - ENSURE(b2World_IsValid(worldId) == false); + ENSURE( b2World_IsValid( worldId ) == false ); return 0; } -static int TestIsValid(void) +static int TestIsValid( void ) { b2WorldDef worldDef = b2DefaultWorldDef(); - b2WorldId worldId = b2CreateWorld(&worldDef); - ENSURE(b2World_IsValid(worldId)); + b2WorldId worldId = b2CreateWorld( &worldDef ); + ENSURE( b2World_IsValid( worldId ) ); b2BodyDef bodyDef = b2DefaultBodyDef(); - - b2BodyId bodyId1 = b2CreateBody(worldId, &bodyDef); - ENSURE(b2Body_IsValid(bodyId1) == true); - b2BodyId bodyId2 = b2CreateBody(worldId, &bodyDef); - ENSURE(b2Body_IsValid(bodyId2) == true); + b2BodyId bodyId1 = b2CreateBody( worldId, &bodyDef ); + ENSURE( b2Body_IsValid( bodyId1 ) == true ); + + b2BodyId bodyId2 = b2CreateBody( worldId, &bodyDef ); + ENSURE( b2Body_IsValid( bodyId2 ) == true ); - b2DestroyBody(bodyId1); - ENSURE(b2Body_IsValid(bodyId1) == false); + b2DestroyBody( bodyId1 ); + ENSURE( b2Body_IsValid( bodyId1 ) == false ); - b2DestroyBody(bodyId2); - ENSURE(b2Body_IsValid(bodyId2) == false); + b2DestroyBody( bodyId2 ); + ENSURE( b2Body_IsValid( bodyId2 ) == false ); - b2DestroyWorld(worldId); + b2DestroyWorld( worldId ); - ENSURE(b2World_IsValid(worldId) == false); - ENSURE(b2Body_IsValid(bodyId2) == false); - ENSURE(b2Body_IsValid(bodyId1) == false); + ENSURE( b2World_IsValid( worldId ) == false ); + ENSURE( b2Body_IsValid( bodyId2 ) == false ); + ENSURE( b2Body_IsValid( bodyId1 ) == false ); return 0; } -int WorldTest(void) +int WorldTest( void ) { - RUN_SUBTEST(HelloWorld); - RUN_SUBTEST(EmptyWorld); - RUN_SUBTEST(DestroyAllBodiesWorld); - RUN_SUBTEST(TestIsValid); + RUN_SUBTEST( HelloWorld ); + RUN_SUBTEST( EmptyWorld ); + RUN_SUBTEST( DestroyAllBodiesWorld ); + RUN_SUBTEST( TestIsValid ); return 0; }