diff --git a/include/box3d/box3d.h b/include/box3d/box3d.h index 2275663..6bc963a 100644 --- a/include/box3d/box3d.h +++ b/include/box3d/box3d.h @@ -167,6 +167,21 @@ B3_API void b3World_SetPreSolveCallback( b3WorldId worldId, b3PreSolveFcn* fcn, /// @see b3WorldDef B3_API void b3World_SetGravity( b3WorldId worldId, b3Vec3 gravity ); +/// GameCult fork: an external constraint solver run inside the soft step. Called on the solver's +/// orchestrating thread subStepCount times per b3World_Step, after the biased solve and before +/// positions integrate (also when no body is awake). Not recorded. +B3_API void b3World_SetSubStepCallback( b3WorldId worldId, b3SubStepFcn* fcn, void* context ); + +/// GameCult fork, valid only inside the substep callback: the body's centre of mass and rotation at +/// the start of this substep and its velocity after the biased solve. Returns false (and zero +/// velocity) for a body the solver does not move this step: static or asleep. +B3_API bool b3Body_GetSubStepState( b3BodyId bodyId, b3Pos* center, b3Quat* rotation, b3Vec3* linearVelocity, + b3Vec3* angularVelocity ); + +/// GameCult fork, valid only inside the substep callback: a velocity change from a linear impulse at +/// the centre of mass and an angular impulse, on an awake body. Never wakes a body. +B3_API void b3Body_ApplySubStepImpulse( b3BodyId bodyId, b3Vec3 linearImpulse, b3Vec3 angularImpulse ); + /// Get the gravity vector B3_API b3Vec3 b3World_GetGravity( b3WorldId worldId ); @@ -224,6 +239,10 @@ B3_API void* b3World_GetUserData( b3WorldId worldId ); /// Set the friction callback. Passing NULL resets to default. B3_API void b3World_SetFrictionCallback( b3WorldId worldId, b3FrictionCallback* callback ); +/// Set the per-contact friction hook (GameCult fork). Passing NULL removes it. The hook is called on worker threads, so the +/// context must be read-only for the duration of a step. +B3_API void b3World_SetContactFrictionCallback( b3WorldId worldId, b3ContactFrictionFcn* fcn, void* context ); + /// Set the restitution callback. Passing NULL resets to default. B3_API void b3World_SetRestitutionCallback( b3WorldId worldId, b3RestitutionCallback* callback ); diff --git a/include/box3d/types.h b/include/box3d/types.h index 2c75977..281ab34 100644 --- a/include/box3d/types.h +++ b/include/box3d/types.h @@ -53,6 +53,14 @@ typedef void b3DestroyDebugShapeCallback( void* userShape, void* userContext ); /// @ingroup world typedef float b3FrictionCallback( float frictionA, uint64_t userMaterialIdA, float frictionB, uint64_t userMaterialIdB ); +/// Optional per-contact friction override (GameCult fork). Called from b3UpdateConvexContact right after the friction mix, +/// from a worker thread, with the mean of the manifold points expressed in each body's frame, the bodies' user data, and the +/// mixed friction. Return the friction to use for this contact this update. Convex contacts only; mesh contacts are not hooked. +/// @warning Must be pure and read-only: no Box3D calls, no writes to application state. +/// @ingroup world +typedef float b3ContactFrictionFcn( void* bodyUserDataA, void* bodyUserDataB, b3Vec3 localPointA, b3Vec3 localPointB, float mixed, + void* context ); + /// Optional restitution mixing callback. This intentionally provides no context objects because this is called /// from a worker thread. /// @warning This function should not attempt to modify Box3D state or user application state. @@ -94,6 +102,9 @@ typedef bool b3PreSolveFcn( b3ShapeId shapeIdA, b3ShapeId shapeIdB, b3Pos point, /// @ingroup world typedef bool b3OverlapResultFcn( b3ShapeId shapeId, void* context ); +/// GameCult fork: see b3World_SetSubStepCallback +typedef void b3SubStepFcn( b3WorldId worldId, int subStepIndex, float h, void* context ); + /// Prototype callback for ray casts. /// Called for each shape found in the query. You control how the ray cast /// proceeds by returning a float: @@ -2576,6 +2587,9 @@ typedef struct b3ManifoldPoint /// to identify speculative contact points that had an interaction in the time step. float totalNormalImpulse; + /// Sum over sub-steps of the impulse each sub-step applied, plus restitution: the step impulse. + float stepNormalImpulse; + /// Relative normal velocity pre-solve. Used for hit events. If the normal impulse is /// zero then there was no hit. Negative means shapes are approaching. float normalVelocity; diff --git a/src/body.c b/src/body.c index aa4e91e..37ed757 100644 --- a/src/body.c +++ b/src/body.c @@ -1119,6 +1119,44 @@ b3Vec3 b3Body_GetLinearVelocity( b3BodyId bodyId ) return b3Vec3_zero; } +bool b3Body_GetSubStepState( b3BodyId bodyId, b3Pos* center, b3Quat* rotation, b3Vec3* linearVelocity, + b3Vec3* angularVelocity ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + B3_ASSERT( world->inSubStep ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + b3BodySim* sim = b3GetBodySim( world, body ); + b3BodyState* state = b3GetBodyState( world, body ); + if ( state == NULL ) + { + *center = sim->center; + *rotation = sim->transform.q; + *linearVelocity = b3Vec3_zero; + *angularVelocity = b3Vec3_zero; + return false; + } + *center = b3OffsetPos( sim->center, state->deltaPosition ); + *rotation = b3NormalizeQuat( b3MulQuat( state->deltaRotation, sim->transform.q ) ); + *linearVelocity = state->linearVelocity; + *angularVelocity = state->angularVelocity; + return true; +} + +void b3Body_ApplySubStepImpulse( b3BodyId bodyId, b3Vec3 linearImpulse, b3Vec3 angularImpulse ) +{ + b3World* world = b3GetWorld( bodyId.world0 ); + B3_ASSERT( world->inSubStep ); + b3Body* body = b3GetBodyFullId( world, bodyId ); + b3BodyState* state = b3GetBodyState( world, body ); + if ( state == NULL ) + { + return; + } + b3BodySim* sim = b3GetBodySim( world, body ); + state->linearVelocity = b3MulAdd( state->linearVelocity, sim->invMass, linearImpulse ); + state->angularVelocity = b3Add( state->angularVelocity, b3MulMV( sim->invInertiaWorld, angularImpulse ) ); +} + b3Vec3 b3Body_GetAngularVelocity( b3BodyId bodyId ) { b3World* world = b3GetWorld( bodyId.world0 ); diff --git a/src/broad_phase.c b/src/broad_phase.c index a14a1a2..058aa79 100644 --- a/src/broad_phase.c +++ b/src/broad_phase.c @@ -403,6 +403,9 @@ void b3UpdateBroadPhasePairs( b3World* world ) if ( moveCount == 0 ) { + // GameCult fork: destroying a proxy unbuffers its move but leaves its ancestors flagged enlarged, so an empty + // move buffer does not mean the trees are clean. The rebuild clears the flags; on a clean tree it is a no-op. + b3UpdateTreesTask( world ); return; } diff --git a/src/contact.c b/src/contact.c index 3486e3c..6a9d4d3 100644 --- a/src/contact.c +++ b/src/contact.c @@ -607,6 +607,53 @@ static bool b3ComputeConvexManifold( b3World* world, int workerIndex, b3Contact* return true; } +// The per-contact friction hook, when one is installed: the mean manifold point in each body's frame (the anchors' frame, rotated back +// by q and moved by the offset: zero for origin-relative anchors, the local centre for centre-relative ones), the bodies' user data and +// the mixed friction. Convex contacts only. +void b3ApplyContactFrictionHook( b3World* world, b3Contact* contact, const b3Shape* shapeA, const b3Shape* shapeB, b3Quat qA, b3Quat qB, + b3Vec3 offsetA, b3Vec3 offsetB, float mixed ) +{ + if ( world->contactFrictionFcn == NULL ) + { + return; + } + + b3Manifold* manifold = contact->manifolds + 0; + int pointCount = manifold->pointCount; + b3Vec3 sumA = b3Vec3_zero; + b3Vec3 sumB = b3Vec3_zero; + for ( int i = 0; i < pointCount; ++i ) + { + sumA = b3Add( sumA, manifold->points[i].anchorA ); + sumB = b3Add( sumB, manifold->points[i].anchorB ); + } + float inv = 1.0f / (float)pointCount; + b3Vec3 localA = b3Add( b3InvRotateVector( qA, b3MulSV( inv, sumA ) ), offsetA ); + b3Vec3 localB = b3Add( b3InvRotateVector( qB, b3MulSV( inv, sumB ) ), offsetB ); + void* userDataA = b3Array_Get( world->bodies, shapeA->bodyId )->userData; + void* userDataB = b3Array_Get( world->bodies, shapeB->bodyId )->userData; + contact->friction = world->contactFrictionFcn( userDataA, userDataB, localA, localB, mixed, world->contactFrictionContext ); +} + +// A recycled contact skips its update, and with it the friction mix: with a hook installed, mix again and run the hook so the friction follows +// the application's patches under a body at rest. Anchors are centre-relative here, in the frame the contact was cached in. +void b3RefreshRecycledFriction( b3World* world, b3Contact* contact, const b3Shape* shapeA, const b3Shape* shapeB, b3Vec3 localCenterA, + b3Vec3 localCenterB ) +{ + if ( world->contactFrictionFcn == NULL || ( contact->flags & b3_simMeshContact ) || contact->manifoldCount != 1 || + contact->manifolds[0].pointCount == 0 || shapeA->type == b3_compoundShape || shapeB->type == b3_compoundShape ) + { + return; + } + + const b3SurfaceMaterial* materialA = b3GetShapeMaterials( shapeA ); + const b3SurfaceMaterial* materialB = b3GetShapeMaterials( shapeB ); + float mixed = + world->frictionCallback( materialA->friction, materialA->userMaterialId, materialB->friction, materialB->userMaterialId ); + b3ApplyContactFrictionHook( world, contact, shapeA, shapeB, contact->cachedRotationA, contact->cachedRotationB, localCenterA, + localCenterB, mixed ); +} + static bool b3UpdateConvexContact( b3World* world, int workerIndex, b3Contact* contact, b3Shape* shapeA, b3WorldTransform xfA, b3Shape* shapeB, b3WorldTransform xfB, bool flip, b3Arena arena ) { @@ -640,6 +687,8 @@ static bool b3UpdateConvexContact( b3World* world, int workerIndex, b3Contact* c // Keep these updated in case the values on the shapes are modified contact->friction = world->frictionCallback( materialA->friction, materialA->userMaterialId, materialB->friction, materialB->userMaterialId ); + + b3ApplyContactFrictionHook( world, contact, shapeA, shapeB, xfA.q, xfB.q, b3Vec3_zero, b3Vec3_zero, contact->friction ); contact->restitution = world->restitutionCallback( materialA->restitution, materialA->userMaterialId, materialB->restitution, materialB->userMaterialId ); diff --git a/src/contact.h b/src/contact.h index bd5b91a..50472f5 100644 --- a/src/contact.h +++ b/src/contact.h @@ -173,6 +173,11 @@ void b3InitializeContactRegisters( void ); void b3CreateContact( b3World* world, b3Shape* shapeA, b3Shape* shapeB, int childIndex ); void b3DestroyContact( b3World* world, b3Contact* contact, bool wakeBodies ); +void b3ApplyContactFrictionHook( b3World* world, b3Contact* contact, const b3Shape* shapeA, const b3Shape* shapeB, b3Quat qA, b3Quat qB, + b3Vec3 offsetA, b3Vec3 offsetB, float mixed ); +void b3RefreshRecycledFriction( b3World* world, b3Contact* contact, const b3Shape* shapeA, const b3Shape* shapeB, b3Vec3 localCenterA, + b3Vec3 localCenterB ); + bool b3UpdateContact( b3World* world, int workerIndex, b3Contact* contact, b3Shape* shapeA, b3Vec3 localCenterA, b3WorldTransform xfA, b3Shape* shapeB, b3Vec3 localCenterB, b3WorldTransform xfB, bool isFast, b3Arena arena ); diff --git a/src/contact_solver.c b/src/contact_solver.c index 501f858..c0f58e0 100644 --- a/src/contact_solver.c +++ b/src/contact_solver.c @@ -196,6 +196,7 @@ void b3PrepareContacts_Mesh( b3SolverBlock block, b3StepContext* context ) cp->baseSeparation = mp->separation - b3Dot( b3Sub( cp->rB, cp->rA ), normal ); cp->normalImpulse = warmStartScale * mp->normalImpulse; cp->totalNormalImpulse = 0.0f; + cp->stepNormalImpulse = 0.0f; b3Vec3 rA = cp->rA; b3Vec3 rB = cp->rB; @@ -456,6 +457,7 @@ void b3SolveContacts_Mesh( b3SolverBlock block, b3StepContext* context, bool use deltaImpulse = newImpulse - cp->normalImpulse; cp->normalImpulse = newImpulse; cp->totalNormalImpulse += newImpulse; + if ( useBias == false ) cp->stepNormalImpulse += newImpulse; totalNormalImpulse += newImpulse; totalTwistLimit += cp->leverArm * cp->normalImpulse; @@ -650,6 +652,7 @@ void b3ApplyRestitution_Mesh( b3SolverBlock block, b3StepContext* context ) impulse = newImpulse - cp->normalImpulse; cp->normalImpulse = newImpulse; cp->totalNormalImpulse += impulse; + cp->stepNormalImpulse += impulse; // apply contact impulse b3Vec3 P = b3MulSV( impulse, normal ); @@ -754,6 +757,7 @@ void b3StoreImpulses_Mesh( b3SolverBlock block, b3StepContext* context, int work b3ManifoldPoint* mp = manifold->points + pointIndex; mp->normalImpulse = cp->normalImpulse; mp->totalNormalImpulse = cp->totalNormalImpulse; + mp->stepNormalImpulse = cp->stepNormalImpulse; mp->normalVelocity = cp->relativeVelocity; if ( checkHitEvents && flagged == false && @@ -1330,6 +1334,7 @@ typedef struct b3ContactConstraintPointWide b3FloatW baseSeparations; b3FloatW normalImpulses; b3FloatW totalNormalImpulses; + b3FloatW stepNormalImpulses; b3FloatW normalMasses; b3FloatW leverArms; b3FloatW relativeVelocities; @@ -1805,6 +1810,7 @@ void b3PrepareContacts_Convex( b3SolverBlock block, b3StepContext* context ) ( (float*)&cp->normalImpulses )[lane] = warmStartScale * mp->normalImpulse; ( (float*)&cp->totalNormalImpulses )[lane] = 0.0f; + ( (float*)&cp->stepNormalImpulses )[lane] = 0.0f; b3Vec3 rnA = b3Cross( rA, normal ); b3Vec3 rnB = b3Cross( rB, normal ); @@ -1892,6 +1898,7 @@ void b3PrepareContacts_Convex( b3SolverBlock block, b3StepContext* context ) ( (float*)&cp->baseSeparations )[lane] = 0.0f; ( (float*)&cp->normalImpulses )[lane] = 0.0f; ( (float*)&cp->totalNormalImpulses )[lane] = 0.0f; + ( (float*)&cp->stepNormalImpulses )[lane] = 0.0f; ( (float*)&cp->normalMasses )[lane] = 0.0f; ( (float*)&cp->relativeVelocities )[lane] = 0.0f; ( (float*)&cp->leverArms )[lane] = 0.0f; @@ -2051,6 +2058,7 @@ void b3SolveContacts_Convex( b3SolverBlock block, b3StepContext* context, bool u b3FloatW deltaImpulse = b3SubW( newImpulse, cp->normalImpulses ); cp->normalImpulses = newImpulse; cp->totalNormalImpulses = b3AddW( cp->totalNormalImpulses, newImpulse ); + if ( useBias == false ) cp->stepNormalImpulses = b3AddW( cp->stepNormalImpulses, newImpulse ); totalNormalImpulse = b3AddW( totalNormalImpulse, newImpulse ); totalTwistLimit = b3AddW( totalTwistLimit, b3MulW( cp->leverArms, newImpulse ) ); @@ -2232,6 +2240,7 @@ void b3ApplyRestitution_Convex( b3SolverBlock block, b3StepContext* context ) b3FloatW deltaImpulse = b3SubW( newImpulse, cp->normalImpulses ); cp->normalImpulses = newImpulse; cp->totalNormalImpulses = b3AddW( cp->totalNormalImpulses, deltaImpulse ); + cp->stepNormalImpulses = b3AddW( cp->stepNormalImpulses, deltaImpulse ); // Apply contact impulse b3Vec3W P = b3MulSVW( deltaImpulse, c->normal ); @@ -2335,6 +2344,7 @@ void b3StoreImpulses_Convex( b3SolverBlock block, b3StepContext* context, int wo b3ManifoldPoint* mp = m->points + pointIndex; mp->normalImpulse = normalImpulse[lane]; mp->totalNormalImpulse = totalNormalImpulse[lane]; + mp->stepNormalImpulse = ((const float*)&cp->stepNormalImpulses)[lane]; mp->normalVelocity = normalVelocity[lane]; } diff --git a/src/contact_solver.h b/src/contact_solver.h index fab17ee..547edac 100644 --- a/src/contact_solver.h +++ b/src/contact_solver.h @@ -13,6 +13,7 @@ typedef struct b3ManifoldConstraintPoint float relativeVelocity; float normalImpulse; float totalNormalImpulse; + float stepNormalImpulse; float normalMass; float leverArm; } b3ManifoldConstraintPoint; diff --git a/src/physics_world.c b/src/physics_world.c index 7f5630b..e55cf70 100644 --- a/src/physics_world.c +++ b/src/physics_world.c @@ -721,6 +721,7 @@ static void b3CollideTask( int startIndex, int endIndex, int workerIndex, void* // Contact is recycled. This also skips updating other aspects of the contact // such as material parameters. + b3RefreshRecycledFriction( world, contact, shapeA, shapeB, bodySimA->localCenter, bodySimB->localCenter ); continue; } } @@ -2214,6 +2215,18 @@ void b3World_SetFrictionCallback( b3WorldId worldId, b3FrictionCallback* callbac world->frictionCallback = callback != NULL ? callback : b3DefaultFrictionCallback; } +void b3World_SetContactFrictionCallback( b3WorldId worldId, b3ContactFrictionFcn* fcn, void* context ) +{ + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return; + } + + world->contactFrictionFcn = fcn; + world->contactFrictionContext = context; +} + void b3World_SetRestitutionCallback( b3WorldId worldId, b3RestitutionCallback* callback ) { b3World* world = b3GetUnlockedWorldFromId( worldId ); @@ -3333,6 +3346,14 @@ void b3World_SetGravity( b3WorldId worldId, b3Vec3 gravity ) world->gravity = gravity; } +void b3World_SetSubStepCallback( b3WorldId worldId, b3SubStepFcn* fcn, void* context ) +{ + b3World* world = b3GetWorldFromId( worldId ); + B3_ASSERT( world->locked == false ); + world->subStepFcn = fcn; + world->subStepContext = context; +} + b3Vec3 b3World_GetGravity( b3WorldId worldId ) { b3World* world = b3GetWorldFromId( worldId ); diff --git a/src/physics_world.h b/src/physics_world.h index 8387e2a..53a5c46 100644 --- a/src/physics_world.h +++ b/src/physics_world.h @@ -231,6 +231,8 @@ typedef struct b3World float contactRecycleDistance; b3FrictionCallback* frictionCallback; + b3ContactFrictionFcn* contactFrictionFcn; + void* contactFrictionContext; b3RestitutionCallback* restitutionCallback; uint16_t generation; @@ -275,6 +277,11 @@ typedef struct b3World // not a real mutex. This should have minimal performance impact. bool locked; + // GameCult fork: the substep callback, and whether it is running + b3SubStepFcn* subStepFcn; + void* subStepContext; + bool inSubStep; + // Non-NULL while a recording session is active. Set by b3World_StartRecording, // cleared by b3World_StopRecording. Hooks in mutators check this before writing. struct b3Recording* recording; @@ -285,6 +292,11 @@ typedef struct b3World bool inUse; } b3World; +static inline b3WorldId b3MakeWorldIdFromWorld( b3World* world ) +{ + return (b3WorldId){ (uint16_t)( world->worldId + 1 ), world->generation }; +} + b3World* b3GetUnlockedWorldFromId( b3WorldId id ); b3World* b3GetWorldFromId( b3WorldId id ); diff --git a/src/solver.c b/src/solver.c index 4c5c114..562d7c5 100644 --- a/src/solver.c +++ b/src/solver.c @@ -28,6 +28,10 @@ #define ITERATIONS 1 #define RELAX_ITERATIONS 1 +// stepNormalImpulse (contact_solver.c) sums the impulse applied after each relax pass; it is the step +// impulse only with one relax pass per sub-step +_Static_assert( RELAX_ITERATIONS == 1, "stepNormalImpulse is exact only with one relax iteration" ); + #if ( defined( __GNUC__ ) || defined( __clang__ ) ) && ( defined( __i386__ ) || defined( __x86_64__ ) ) static void b3Pause( void ) { @@ -1265,6 +1269,15 @@ static void b3SolverTask( void* taskContext ) profile->solveImpulses += b3GetMillisecondsAndReset( &ticks ); + // GameCult fork: the external solver's substep, on this thread while the workers wait + b3World* world = context->world; + if ( world->subStepFcn != NULL ) + { + world->inSubStep = true; + world->subStepFcn( b3MakeWorldIdFromWorld( world ), subStepIndex, context->h, world->subStepContext ); + world->inSubStep = false; + } + // Integrate positions B3_ASSERT( stages[iterationStageIndex].type == b3_stageIntegratePositions ); syncBits = ( bodySyncIndex << 16 ) | iterationStageIndex; @@ -1427,6 +1440,16 @@ void b3Solve( b3World* world, b3StepContext* stepContext ) int awakeBodyCount = awakeSet->bodySims.count; if ( awakeBodyCount == 0 ) { + // GameCult fork: the external solver still runs its substeps + if ( world->subStepFcn != NULL ) + { + world->inSubStep = true; + for ( int i = 0; i < stepContext->subStepCount; ++i ) + { + world->subStepFcn( b3MakeWorldIdFromWorld( world ), i, stepContext->h, world->subStepContext ); + } + world->inSubStep = false; + } b3ValidateNoEnlarged( &world->broadPhase ); return; } diff --git a/test/test_world.c b/test/test_world.c index 062dca3..0517671 100644 --- a/test/test_world.c +++ b/test/test_world.c @@ -995,6 +995,174 @@ static int TestExplosion( void ) return 0; } +static int s_hookCalls; +static int s_hookBad; +static float ZeroFrictionHook( void* userDataA, void* userDataB, b3Vec3 localA, b3Vec3 localB, float mixed, void* context ) +{ + // Ground is body A (user data 1), box is body B (user data 2); the box rests 1 m above its ground contact point. + s_hookCalls += 1; + if ( userDataA != (void*)(intptr_t)1 || userDataB != (void*)(intptr_t)2 || b3AbsFloat( localB.y + 1.0f ) > 0.1f || + b3AbsFloat( mixed - 0.6f ) > 1.0e-5f || context != &s_hookCalls ) + { + s_hookBad += 1; + } + return 0.0f; +} + +static float SlideSpeed( bool hooked ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + worldDef.gravity = (b3Vec3){ 0.0f, -10.0f, 0.0f }; + b3WorldId worldId = b3CreateWorld( &worldDef ); + + b3BodyDef groundDef = b3DefaultBodyDef(); + groundDef.position = (b3Pos){ 0.0f, -10.0f, 0.0f }; + groundDef.userData = (void*)(intptr_t)1; + b3BodyId groundId = b3CreateBody( worldId, &groundDef ); + b3BoxHull groundBox = b3MakeBoxHull( 50.0f, 10.0f, 50.0f ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.baseMaterial.friction = 0.6f; + b3CreateHullShape( groundId, &shapeDef, &groundBox.base ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = (b3Pos){ 0.0f, 1.0f, 0.0f }; + bodyDef.linearVelocity = (b3Vec3){ 5.0f, 0.0f, 0.0f }; + bodyDef.userData = (void*)(intptr_t)2; + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + b3BoxHull box = b3MakeCubeHull( 1.0f ); + shapeDef.density = 1.0f; + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + + if ( hooked ) + { + b3World_SetContactFrictionCallback( worldId, ZeroFrictionHook, &s_hookCalls ); + } + + for ( int i = 0; i < 60; ++i ) + { + b3World_Step( worldId, 1.0f / 60.0f, 4 ); + } + + float speed = b3Body_GetLinearVelocity( bodyId ).x; + b3DestroyWorld( worldId ); + return speed; +} + +// Run by name: `test.exe WorldTest` (the unfiltered run stops at CompoundTest, which fails at fb719c4 as well: CompoundMaterialDedup). +int ContactFrictionHookTest( void ) +{ + s_hookCalls = 0; + s_hookBad = 0; + float dry = SlideSpeed( false ); + ENSURE( s_hookCalls == 0 ); + ENSURE( dry < 0.5f ); + + float slick = SlideSpeed( true ); + ENSURE( s_hookCalls > 0 ); + ENSURE( s_hookBad == 0 ); + ENSURE( slick > 4.9f ); + return 0; +} + +static float SwitchHook( void* userDataA, void* userDataB, b3Vec3 localA, b3Vec3 localB, float mixed, void* context ) +{ + return *(bool*)context ? 0.0f : mixed; +} + +// A box rests for 30 ticks under no push, the hook's answer changes, then a push of 30 N (below mu m g = 48 N) runs for 30 ticks. The +// contact is recycled all the while the box rests, so the answer reaches it only if the hook runs on recycled contacts too. +static float PushedSpeed( bool slickWhileResting, bool slickWhilePushed ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + worldDef.gravity = (b3Vec3){ 0.0f, -10.0f, 0.0f }; + b3WorldId worldId = b3CreateWorld( &worldDef ); + + b3BodyDef groundDef = b3DefaultBodyDef(); + groundDef.position = (b3Pos){ 0.0f, -10.0f, 0.0f }; + b3BodyId groundId = b3CreateBody( worldId, &groundDef ); + b3BoxHull groundBox = b3MakeBoxHull( 50.0f, 10.0f, 50.0f ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.baseMaterial.friction = 0.6f; + b3CreateHullShape( groundId, &shapeDef, &groundBox.base ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.position = (b3Pos){ 0.0f, 1.0f, 0.0f }; + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + b3BoxHull box = b3MakeCubeHull( 1.0f ); + shapeDef.density = 1.0f; + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + + bool slick = slickWhileResting; + b3World_SetContactFrictionCallback( worldId, SwitchHook, &slick ); + for ( int i = 0; i < 30; ++i ) + { + b3World_Step( worldId, 1.0f / 60.0f, 4 ); + } + + slick = slickWhilePushed; + for ( int i = 0; i < 30; ++i ) + { + b3Body_ApplyForceToCenter( bodyId, (b3Vec3){ 30.0f, 0.0f, 0.0f }, true ); + b3World_Step( worldId, 1.0f / 60.0f, 4 ); + } + + float speed = b3Body_GetLinearVelocity( bodyId ).x; + b3DestroyWorld( worldId ); + return speed; +} + +int ContactFrictionRecycledTest( void ) +{ + // Friction lowered under a box that has rested: it slides. Friction restored under a box that rested on the lowered value: it holds. + ENSURE( PushedSpeed( false, true ) > 1.0f ); + ENSURE( PushedSpeed( true, false ) < 0.05f ); + ENSURE( PushedSpeed( false, false ) < 0.05f ); + return 0; +} + +// GameCult fork. A body whose proxy was enlarged in the last step is destroyed before the next step, and it was +// the only proxy in the move buffer. Its ancestors in the dynamic tree are still flagged enlarged, so the next +// step must still rebuild the tree: with validation on, a skipped rebuild trips ValidateNoEnlarged in the solver. +int DestroyEnlargedProxyTest( void ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + worldDef.gravity = b3Vec3_zero; + b3WorldId worldId = b3CreateWorld( &worldDef ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3Sphere sphere = { b3Vec3_zero, 0.25f }; + + // Resting bodies far apart: they never leave their fat AABBs, so after the first step only the mover is buffered. + enum + { + e_count = 8 + }; + b3BodyId bodyIds[e_count]; + for ( int i = 0; i < e_count; ++i ) + { + bodyDef.position = (b3Pos){ 4.0f * i, 0.0f, 0.0f }; + bodyIds[i] = b3CreateBody( worldId, &bodyDef ); + b3CreateSphereShape( bodyIds[i], &shapeDef, &sphere ); + } + b3World_Step( worldId, 1.0f / 60.0f, 4 ); + + // Each body in turn is the mover; some lie deep enough that an enlarged ancestor outlives their removal. + for ( int i = 0; i < e_count; ++i ) + { + b3Body_SetLinearVelocity( bodyIds[i], (b3Vec3){ 0.0f, 30.0f, 0.0f } ); + b3World_Step( worldId, 1.0f / 60.0f, 4 ); + b3DestroyBody( bodyIds[i] ); + b3World_Step( worldId, 1.0f / 60.0f, 4 ); + } + + b3DestroyWorld( worldId ); + return 0; +} + int WorldTest( void ) { RUN_SUBTEST( HelloWorld ); @@ -1016,6 +1184,9 @@ int WorldTest( void ) RUN_SUBTEST( EnableContactRecyclingTest ); RUN_SUBTEST( TestSetWorkerCount ); RUN_SUBTEST( TestHullDatabase ); + RUN_SUBTEST( ContactFrictionHookTest ); + RUN_SUBTEST( ContactFrictionRecycledTest ); + RUN_SUBTEST( DestroyEnlargedProxyTest ); return 0; }