diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 06e89d1..ffd6f8e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -85,6 +85,9 @@ jobs: run: ${{ matrix.test }} # mingw needs some extra setup so keeping it separate from the matrix. + # Also the one optimized test run. Debug -O0 copies whole structs and hid the + # b3SurfaceMaterial padding dedup bug. RelWithDebInfo tests -O2 codegen while + # B3_ENABLE_ASSERT keeps asserts alive, heavy validation stays Debug only. build-windows-mingw: name: windows-mingw runs-on: windows-latest @@ -107,10 +110,10 @@ jobs: mingw-w64-ucrt-x86_64-ninja - name: Configure CMake - run: cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DBOX3D_SAMPLES=OFF -DBUILD_SHARED_LIBS=OFF -DBOX3D_VALIDATE=ON -DCMAKE_COMPILE_WARNING_AS_ERROR=ON + run: cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DBOX3D_SAMPLES=OFF -DBUILD_SHARED_LIBS=OFF -DBOX3D_VALIDATE=ON -DCMAKE_COMPILE_WARNING_AS_ERROR=ON - name: Build - run: cmake --build build --config ${{env.BUILD_TYPE}} + run: cmake --build build --config RelWithDebInfo - name: Test working-directory: build diff --git a/CMakePresets.json b/CMakePresets.json index 04b0cd2..e387835 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -28,6 +28,32 @@ "generator": "Xcode", "condition": { "type": "equals", "lhs": "${hostSystemName}", "rhs": "Darwin" }, "binaryDir": "${sourceDir}/build" + }, + { + "name": "mingw-debug", + "displayName": "Windows MinGW Debug (Ninja, needs gcc on PATH)", + "generator": "Ninja", + "condition": { "type": "equals", "lhs": "${hostSystemName}", "rhs": "Windows" }, + "binaryDir": "${sourceDir}/build/mingw", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Debug", + "CMAKE_C_COMPILER": "gcc", + "CMAKE_CXX_COMPILER": "g++", + "FETCHCONTENT_BASE_DIR": "${sourceDir}/.fetchcontent-cache/mingw" + } + }, + { + "name": "mingw-release", + "displayName": "Windows MinGW Release (Ninja, needs gcc on PATH)", + "generator": "Ninja", + "condition": { "type": "equals", "lhs": "${hostSystemName}", "rhs": "Windows" }, + "binaryDir": "${sourceDir}/build/mingw", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Release", + "CMAKE_C_COMPILER": "gcc", + "CMAKE_CXX_COMPILER": "g++", + "FETCHCONTENT_BASE_DIR": "${sourceDir}/.fetchcontent-cache/mingw" + } } ], "buildPresets": [ @@ -36,6 +62,8 @@ { "name": "linux-debug", "configurePreset": "linux-debug" }, { "name": "linux-release", "configurePreset": "linux-release" }, { "name": "macos-debug", "configurePreset": "macos", "configuration": "Debug" }, - { "name": "macos-release", "configurePreset": "macos", "configuration": "Release" } + { "name": "macos-release", "configurePreset": "macos", "configuration": "Release" }, + { "name": "mingw-debug", "configurePreset": "mingw-debug" }, + { "name": "mingw-release", "configurePreset": "mingw-release" } ] } diff --git a/README.md b/README.md index baf138e..cfe16e4 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,7 @@ This uses the presets in `CMakePresets.json`. - Windows: `cmake --preset windows` then `cmake --build --preset windows-release` - Linux: `cmake --preset linux-release` then `cmake --build --preset linux-release` - macOS: `cmake --preset macos` then `cmake --build --preset macos-release` +- Windows MinGW: `cmake --preset mingw-release` then `cmake --build --preset mingw-release` Run the samples app (must be in the Box3D directory). diff --git a/include/box3d/config.h b/include/box3d/config.h index 2790fc0..f39eb7e 100644 --- a/include/box3d/config.h +++ b/include/box3d/config.h @@ -29,3 +29,5 @@ // so this suits embedding more than shipping Box3D as its own DLL. //#define BOX3D_EXPORT MYENGINE_API +// Enable assertions when NDEBUG is defined +// #define B3_ENABLE_ASSERT diff --git a/include/box3d/types.h b/include/box3d/types.h index 96df9df..37984c9 100644 --- a/include/box3d/types.h +++ b/include/box3d/types.h @@ -419,6 +419,9 @@ typedef struct b3SurfaceMaterial /// carry a b3DebugMaterial preset, see b3MakeDebugColor. /// @see b3HexColor uint32_t customColor; + + /// Explicit padding. Must be zero. + uint32_t padding; } b3SurfaceMaterial; /// Use this to initialize your surface material @@ -2968,8 +2971,10 @@ typedef struct b3DebugShape /// it stays accurate far from the origin. Shift into your own camera frame inside the callbacks. typedef struct b3DebugDraw { - /// Draws a shape and returns true if drawing should continue - bool ( *DrawShapeFcn )( void* userShape, b3WorldTransform transform, b3HexColor color, void* context ); + /// Draws a user shape. The userShape pointer is owned by the application and is known to Box3D as + /// an opaque pointer returned from b3CreateDebugShapeCallback. When this is called the drawn shape has + /// passed a culling test against drawingBounds below. + void ( *DrawShapeFcn )( void* userShape, b3WorldTransform transform, b3HexColor color, void* context ); /// Draw a line segment. void ( *DrawSegmentFcn )( b3Pos p1, b3Pos p2, b3HexColor color, void* context ); @@ -3029,7 +3034,7 @@ typedef struct b3DebugDraw bool drawContacts; /// Draw contact anchor A or B - int drawAnchorA; + bool drawAnchorA; /// Option to visualize the graph coloring used for contacts and joints bool drawGraphColors; diff --git a/samples/CMakeLists.txt b/samples/CMakeLists.txt index 3c4eb51..319fb85 100644 --- a/samples/CMakeLists.txt +++ b/samples/CMakeLists.txt @@ -155,6 +155,8 @@ set(SAMPLE_FILES sample.h mesh_loader.cpp mesh_loader.h + mover.cpp + mover.h jsmn.h tiny_obj_loader.h earcut.h diff --git a/samples/gfx/debug_adapter.c b/samples/gfx/debug_adapter.c index 68a21e1..9ac13a6 100644 --- a/samples/gfx/debug_adapter.c +++ b/samples/gfx/debug_adapter.c @@ -122,6 +122,7 @@ typedef struct b3DebugDraw guiDraw; bool transparentDynamic; + bool transparentKinematic; // View box for compound child culling, world space, refreshed once per frame. b3AABB viewBounds; @@ -159,6 +160,7 @@ void InitAdapter( void ) s_adapter.selectedBodyId = b3_nullBodyId; s_adapter.selectedShapeId = b3_nullShapeId; s_adapter.transparentDynamic = false; + s_adapter.transparentKinematic = false; s_adapter.hasViewBounds = false; s_adapter.lastCompoundAppended = 0; @@ -198,6 +200,7 @@ void ResetAdapterPool( void ) s_adapter.selectedBodyId = b3_nullBodyId; s_adapter.selectedShapeId = b3_nullShapeId; s_adapter.transparentDynamic = false; + s_adapter.transparentKinematic = false; s_adapter.hasViewBounds = false; s_adapter.lastCompoundAppended = 0; @@ -235,9 +238,9 @@ void SetTransparentDynamic( bool enabled ) s_adapter.transparentDynamic = enabled; } -bool GetTransparentDynamic( void ) +void SetTransparentKinematic( bool enabled ) { - return s_adapter.transparentDynamic; + s_adapter.transparentKinematic = enabled; } void SetViewBounds( b3AABB bounds ) @@ -733,7 +736,7 @@ static void DestroyDebugShape( void* userShape, void* context ) // origin to the same grid period. // Alpha applied to non-static shapes when box3dAdapterSetTransparentDynamic is on. -#define BOX3D_TRANSPARENT_DYNAMIC_ALPHA 0.5f +#define BOX3D_TRANSPARENT_ALPHA 0.5f // Emit one resolved primitive at baseTransform. The per-kind offset (sphere // center, capsule frame) layers on top of baseTransform, so the same path @@ -810,12 +813,12 @@ static bool CompoundCullCallback( int proxyId, uint64_t userData, void* context return true; } -static bool DrawShape( void* userShape, b3WorldTransform shapeTransform, b3HexColor color, void* context ) +static void DrawShape( void* userShape, b3WorldTransform shapeTransform, b3HexColor color, void* context ) { (void)context; if ( userShape == NULL ) { - return true; // unsupported shape type, skip and continue + return; } // Shift the world transform into the camera relative frame the primitives render in @@ -856,7 +859,12 @@ static bool DrawShape( void* userShape, b3WorldTransform shapeTransform, b3HexCo if ( s_adapter.transparentDynamic && us->bodyType == b3_dynamicBody ) { - c.w = BOX3D_TRANSPARENT_DYNAMIC_ALPHA; + c.w = BOX3D_TRANSPARENT_ALPHA; + } + + if ( s_adapter.transparentKinematic && us->bodyType == b3_kinematicBody ) + { + c.w = BOX3D_TRANSPARENT_ALPHA; } TransparentShadowCast shadowCast = TRANSPARENT_SHADOW_NONE; @@ -912,8 +920,6 @@ static bool DrawShape( void* userShape, b3WorldTransform shapeTransform, b3HexCo { AppendResolvedShape( us, shapeRelative, c, metallic, roughness, shadowCast, hk ); } - - return true; } #define BOX3D_LINE_THICKNESS_PX 2.5f diff --git a/samples/gfx/debug_adapter.h b/samples/gfx/debug_adapter.h index cf28f3e..e92f15d 100644 --- a/samples/gfx/debug_adapter.h +++ b/samples/gfx/debug_adapter.h @@ -35,7 +35,7 @@ int GetDebugShapeCount( void ); void SetGroundShape( b3ShapeId shapeId ); void SetShapeMaterial( b3ShapeId shapeId, Vec4 color, float metallic, float roughness ); void SetTransparentDynamic( bool enabled ); -bool GetTransparentDynamic( void ); +void SetTransparentKinematic( bool enabled ); // View box for compound child culling, world space. Set once per frame before // b3World_Draw. A compound then submits only the children overlapping this box diff --git a/samples/main.cpp b/samples/main.cpp index 361223b..134af8b 100644 --- a/samples/main.cpp +++ b/samples/main.cpp @@ -411,6 +411,7 @@ static void OnFrame( void ) // queues the HUD text; Render fills the instance and overlay arenas via the // b3DebugDraw adapter and the sample's own Draw* calls. SetTransparentDynamic( s_context.transparentDynamic ); + SetTransparentKinematic( s_context.transparentKinematic ); s_context.sample->ResetText(); s_context.sample->Step(); diff --git a/samples/mover.cpp b/samples/mover.cpp new file mode 100644 index 0000000..9a4d361 --- /dev/null +++ b/samples/mover.cpp @@ -0,0 +1,347 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +#include "mover.h" + +#include "gfx/draw.h" +#include "sample.h" + +#include "box3d/box3d.h" + +#include +#include + +static bool MoverFilterCallback( b3ShapeId shapeId, void* context ) +{ + CharacterMover* self = (CharacterMover*)context; + for ( int i = 0; i < self->m_ignoreCount; ++i ) + { + if ( B3_ID_EQUALS( shapeId, self->m_ignoreShapeIds[i] ) ) + { + return false; + } + } + + return true; +} + +void CharacterMover::Initialize( Sample* sample, b3Pos position ) +{ + m_sample = sample; + m_transform.p = position; + m_transform.q = b3Quat_identity; + m_velocity = { 0.0f, 0.0f, 0.0f }; + m_capsule = { { 0.0f, -0.5f, 0.0f }, { 0.0f, 0.5f, 0.0f }, 0.3f }; + + m_planeCount = 0; + m_totalIterations = 0; + m_pogoVelocity = 0.0f; + m_onGround = false; + m_sprint = false; + + m_ignoreShapeIds = nullptr; + m_ignoreCount = 0; +} + +static bool PlaneResultFcn( b3ShapeId shapeId, const b3PlaneResult* planeResults, int planeCount, void* context ) +{ + if ( MoverFilterCallback( shapeId, context ) == false ) + { + // ignore these planes but continue looking for more + return true; + } + + CharacterMover* self = static_cast( context ); + float maxPush = FLT_MAX; + bool clipVelocity = true; + MoverShapeUserData* userData = static_cast( (void*)b3Shape_GetUserData( shapeId ) ); + if ( userData != nullptr ) + { + maxPush = userData->maxPush; + clipVelocity = userData->clipVelocity; + } + + for ( int i = 0; i < planeCount && self->m_planeCount < CharacterMover::m_planeCapacity; ++i ) + { + assert( b3IsValidPlane( planeResults[i].plane ) ); + self->m_planes[self->m_planeCount] = { + .plane = planeResults[i].plane, + .pushLimit = maxPush, + .push = 0.0f, + .clipVelocity = clipVelocity, + }; + self->m_planeExtras[self->m_planeCount] = { + .point = b3OffsetPos( self->m_transform.p, planeResults[i].point ), + .shapeId = shapeId, + }; + self->m_planeCount += 1; + } + + return true; +} + +void CharacterMover::SolveMove( float timeStep, b3Vec3 forward, b3Vec3 right, b3Vec2 throttle, bool clipVelocity ) +{ + // Friction + float speed = b3Length( m_velocity ); + if ( speed < m_minSpeed ) + { + m_velocity.x = 0.0f; + m_velocity.z = 0.0f; + } + else + { + // Linear damping above stopSpeed and fixed reduction below stopSpeed + float control = speed < m_stopSpeed ? m_stopSpeed : speed; + + // friction has units of 1/time + float drop = control * m_friction * timeStep; + float newSpeed = b3MaxFloat( 0.0f, speed - drop ); + float ratio = newSpeed / speed; + m_velocity.x *= newSpeed / speed; + m_velocity.z *= newSpeed / speed; + } + + float maxSpeed = m_sprint ? 1.5f * m_maxSpeed : m_maxSpeed; + + b3Vec3 desiredVelocity = maxSpeed * throttle.x * forward + maxSpeed * throttle.y * right; + float desiredSpeed; + b3Vec3 desiredDirection = b3GetLengthAndNormalize( &desiredSpeed, desiredVelocity ); + + if ( desiredSpeed > maxSpeed ) + { + desiredVelocity *= maxSpeed / desiredSpeed; + desiredSpeed = maxSpeed; + } + + if ( m_onGround ) + { + m_velocity.y = 0.0f; + } + + // Accelerate + float currentSpeed = b3Dot( m_velocity, desiredDirection ); + float addSpeed = desiredSpeed - currentSpeed; + if ( addSpeed > 0.0f ) + { + float accelSpeed = m_accelerate * maxSpeed * timeStep; + if ( accelSpeed > addSpeed ) + { + accelSpeed = addSpeed; + } + + m_velocity += accelSpeed * desiredDirection; + } + + m_velocity.y -= m_gravity * timeStep; + + b3WorldId worldId = m_sample->m_worldId; + + float pogoRestLength = 3.0f * m_capsule.radius; + float rayLength = pogoRestLength + m_capsule.radius; + b3Pos rayOrigin = b3TransformWorldPoint( m_transform, m_capsule.center1 ); + b3Vec3 rayTranslation = -rayLength * b3Vec3_axisY; + b3QueryFilter skipTeamFilter = { 1, ~2u }; + skipTeamFilter.name = "pogo"; + b3RayResult rayResult = b3World_CastRayClosest( worldId, rayOrigin, rayTranslation, skipTeamFilter ); + + // After gravity was applied, disable pogo when still moving up. + // Avoids getting pulled back to the ground when jumping. + bool suppressPogo = m_velocity.y > 0.0f; + + if ( rayResult.hit == false || suppressPogo ) + { + m_onGround = false; + m_pogoVelocity = 0.0f; + + DrawLine( rayOrigin, b3OffsetPos( rayOrigin, rayTranslation ), MakeColor( b3_colorGray ) ); + } + else + { + m_onGround = true; + float pogoCurrentLength = rayResult.fraction * rayLength; + + float zeta = 0.7f; + float hertz = 4.0f; + float omega = 2.0f * B3_PI * hertz; + float omegaH = omega * timeStep; + + m_pogoVelocity = ( m_pogoVelocity - omega * omegaH * ( pogoCurrentLength - pogoRestLength ) ) / + ( 1.0f + 2.0f * zeta * omegaH + omegaH * omegaH ); + DrawLine( rayOrigin, rayResult.point, MakeColor( b3_colorGreen ) ); + } + + b3Pos startPosition = m_transform.p; + b3Pos target = m_transform.p + timeStep * m_velocity + timeStep * m_pogoVelocity * b3Vec3_axisY; + + // Want the mover to collide with allies + b3QueryFilter moverFilter = { .categoryBits = 1, .maskBits = ~0u, .id = 1, .name = "mover_collide" }; + + // The cast should ignore allies + b3QueryFilter castFilter = { .categoryBits = 1, .maskBits = ~2u, .id = 1, .name = "mover_cast" }; + + m_totalIterations = 0; + float tolerance = 0.01f; + + for ( int iteration = 0; iteration < 5; ++iteration ) + { + m_planeCount = 0; + + b3Capsule mover; + mover.center1 = m_capsule.center1; + mover.center2 = m_capsule.center2; + mover.radius = m_capsule.radius; + + b3World_CollideMover( worldId, m_transform.p, &mover, moverFilter, PlaneResultFcn, this ); + + b3Vec3 targetDelta = target - m_transform.p; + b3PlaneSolverResult result = b3SolvePlanes( targetDelta, m_planes, m_planeCount ); + + m_totalIterations += result.iterationCount; + + b3Vec3 delta = result.delta; + + float fraction = b3World_CastMover( worldId, m_transform.p, &mover, delta, castFilter, MoverFilterCallback, this ); + + delta *= fraction; + m_transform.p = m_transform.p + delta; + + if ( b3LengthSquared( delta ) < tolerance * tolerance ) + { + break; + } + } + + for ( int i = 0; i < m_planeCount; ++i ) + { + b3BodyId bodyId = b3Shape_GetBody( m_planeExtras[i].shapeId ); + b3BodyType bodyType = b3Body_GetType( bodyId ); + if ( bodyType != b3_dynamicBody ) + { + continue; + } + + b3Pos point = m_planeExtras[i].point; + b3Vec3 normal = b3Neg( m_planes[i].plane.normal ); + + float invMassA = 0.0f; + float invMassB = b3Body_GetInverseMass( bodyId ); + b3Matrix3 invIB = b3Body_GetWorldInverseRotationalInertia( bodyId ); + + b3Pos pB = b3Body_GetWorldCenter( bodyId ); + b3Vec3 rB = b3SubPos( point, pB ); + + b3Vec3 rnB = b3Cross( rB, normal ); + float kNormal = invMassA + invMassB + b3Dot( rnB, b3MulMV( invIB, rnB ) ); + float normalMass = kNormal > 0.0f ? 1.0f / kNormal : 0.0f; + + b3Vec3 vB = b3Body_GetLinearVelocity( bodyId ); + b3Vec3 omegaB = b3Body_GetAngularVelocity( bodyId ); + b3Vec3 vrB = b3Add( vB, b3Cross( omegaB, rB ) ); + float vn = b3Dot( b3Sub( vrB, m_velocity ), normal ); + float impulse = b3MaxFloat( -normalMass * vn, 0.0f ); + + b3Vec3 P = b3MulSV( impulse, normal ); + m_velocity = b3MulSub( m_velocity, invMassA, P ); + + b3Body_ApplyLinearImpulse( bodyId, P, point, true ); + } + + if ( clipVelocity ) + { + // Using the velocity clipper can avoid picking up velocity from depenetration. + // This allows the mover to avoid velocity from soft collision depenetration. + m_velocity = b3ClipVector( m_velocity, m_planes, m_planeCount ); + } + else if ( timeStep > 0.0f ) + { + // Using the position delta is more holistic and intuitive in some cases. + m_velocity = ( 1.0f / timeStep ) * ( m_transform.p - startPosition ); + } +} + +void CharacterMover::Step( b3ShapeId* ignoreShapes, int ignoreCount, bool clipVelocity ) +{ + m_ignoreShapeIds = ignoreShapes; + m_ignoreCount = ignoreCount; + + b3Vec2 throttle = { 0.0f, 0.0f }; + b3Vec3 forward = -m_sample->m_camera->GetForward(); + b3Vec3 right = m_sample->m_camera->GetRight(); + + forward.y = 0.0f; + forward = b3Normalize( forward ); + + if ( m_sample->m_camera->m_thirdPerson ) + { + if ( IsKeyDown( KEY_W ) ) + { + throttle.x += 1.0f; + } + + if ( IsKeyDown( KEY_S ) ) + { + throttle.x -= 1.0f; + } + + if ( IsKeyDown( KEY_A ) ) + { + throttle.y -= 1.0f; + } + + if ( IsKeyDown( KEY_D ) ) + { + throttle.y += 1.0f; + } + + if ( IsKeyDown( KEY_SPACE ) && m_onGround == true ) + { + m_velocity.y = m_jumpSpeed; + m_onGround = false; + } + + if ( m_onGround == true ) + { + m_sprint = IsKeyDown( KEY_LEFT_SHIFT ); + } + else + { + m_sprint = false; + } + } + + float hertz = m_sample->m_context->hertz; + float timeStep = hertz > 0.0f ? 1.0f / hertz : 0.0f; + + // throttle = { 0.0f, 0.0f, -1.0f }; + + SolveMove( timeStep, forward, right, throttle, clipVelocity ); + + b3Pos position = m_transform.p; + + // Follow the mover and latch the draw origin before drawing, so the overlays below demote + // against the same eye the view renders from. + if ( m_sample->m_camera->m_thirdPerson ) + { + m_sample->m_camera->m_pivot = position; + m_sample->m_camera->UpdateTransform(); + } + + SetDrawOrigin( m_sample->m_camera->DrawOrigin() ); + + int count = m_planeCount; + for ( int i = 0; i < count; ++i ) + { + b3Plane plane = m_planes[i].plane; + b3Pos p1 = position + ( plane.offset - m_capsule.radius ) * plane.normal; + b3Pos p2 = p1 + 0.1f * plane.normal; + DrawPoint( p1, 5.0f, MakeColor( b3_colorYellow ) ); + DrawLine( p1, p2, MakeColor( b3_colorYellow ) ); + } + + DrawSolidCapsule( m_transform, m_capsule, MakeColor( b3_colorBlue ) ); + DrawLine( position, position + m_velocity, MakeColor( b3_colorPurple ) ); + + m_ignoreShapeIds = nullptr; + m_ignoreCount = 0; +} diff --git a/samples/mover.h b/samples/mover.h new file mode 100644 index 0000000..bde81ef --- /dev/null +++ b/samples/mover.h @@ -0,0 +1,52 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +#pragma once + +#include "box3d/types.h" + +class Sample; + +struct MoverShapeUserData +{ + float maxPush; + bool clipVelocity; +}; + +struct PlaneExtra +{ + b3Pos point; + b3ShapeId shapeId; +}; + +struct CharacterMover +{ + static constexpr int m_planeCapacity = 8; + static constexpr float m_jumpSpeed = 5.0f; + static constexpr float m_maxSpeed = 6.0f; + static constexpr float m_minSpeed = 0.01f; + static constexpr float m_stopSpeed = 1.0f; + static constexpr float m_accelerate = 30.0f; + static constexpr float m_friction = 4.0f; + static constexpr float m_gravity = 15.0f; + + void Initialize( Sample* sample, b3Pos position ); + void SolveMove( float timeStep, b3Vec3 forward, b3Vec3 right, b3Vec2 throttle, bool clipVelocity ); + void Step( b3ShapeId* ignoreShapes, int ignoreCount, bool clipVelocity ); + + Sample* m_sample; + b3WorldTransform m_transform; + b3Vec3 m_velocity; + b3Capsule m_capsule; + b3CollisionPlane m_planes[m_planeCapacity] = {}; + PlaneExtra m_planeExtras[m_planeCapacity] = {}; + int m_planeCount; + int m_totalIterations; + float m_pogoVelocity; + bool m_onGround; + bool m_sprint; + + // Transient + b3ShapeId* m_ignoreShapeIds; + int m_ignoreCount; +}; diff --git a/samples/sample.cpp b/samples/sample.cpp index 16d6c99..ded550b 100644 --- a/samples/sample.cpp +++ b/samples/sample.cpp @@ -1616,7 +1616,12 @@ static void DrawMenuBar( SampleContext* context ) cam.Frame( aabb, aspect, 0.75f ); } ImGui::MenuItem( "Shapes", nullptr, &gd->drawShapes ); - ImGui::MenuItem( "Transparent", nullptr, &context->transparentDynamic ); + if ( ImGui::BeginMenu( "Transparency" ) ) + { + ImGui::MenuItem( "Dynamic", nullptr, &context->transparentDynamic ); + ImGui::MenuItem( "Kinematic", nullptr, &context->transparentKinematic ); + ImGui::EndMenu(); + } ImGui::MenuItem( "Joints", nullptr, &gd->drawJoints ); ImGui::MenuItem( "Joint Extras", nullptr, &gd->drawJointExtras ); ImGui::MenuItem( "Bounds", nullptr, &gd->drawBounds ); @@ -1632,13 +1637,13 @@ static void DrawMenuBar( SampleContext* context ) ImGui::MenuItem( "Contact Forces", nullptr, &gd->drawContactForces ); if ( ImGui::BeginMenu( "Anchor" ) ) { - if ( ImGui::MenuItem( "Anchor A", nullptr, gd->drawAnchorA != 0 ) ) + if ( ImGui::MenuItem( "Anchor A", nullptr, gd->drawAnchorA == true ) ) { - gd->drawAnchorA = 1; + gd->drawAnchorA = true; } - if ( ImGui::MenuItem( "Anchor B", nullptr, gd->drawAnchorA == 0 ) ) + if ( ImGui::MenuItem( "Anchor B", nullptr, gd->drawAnchorA == false ) ) { - gd->drawAnchorA = 0; + gd->drawAnchorA = false; } ImGui::EndMenu(); } @@ -2068,330 +2073,3 @@ float CastClosestCallback( b3ShapeId shapeId, b3Pos point, b3Vec3 normal, float rayContext->hit = true; return fraction; } - -static bool MoverFilterCallback( b3ShapeId shapeId, void* context ) -{ - CharacterMover* self = (CharacterMover*)context; - for ( int i = 0; i < self->m_ignoreCount; ++i ) - { - if ( B3_ID_EQUALS( shapeId, self->m_ignoreShapeIds[i] ) ) - { - return false; - } - } - - return true; -} - -void CharacterMover::Initialize( Sample* sample, b3Pos position ) -{ - m_sample = sample; - m_transform.p = position; - m_transform.q = b3Quat_identity; - m_velocity = { 0.0f, 0.0f, 0.0f }; - m_capsule = { { 0.0f, -0.5f, 0.0f }, { 0.0f, 0.5f, 0.0f }, 0.3f }; - - m_planeCount = 0; - m_totalIterations = 0; - m_pogoVelocity = 0.0f; - m_onGround = false; - m_sprint = false; - - m_ignoreShapeIds = nullptr; - m_ignoreCount = 0; -} - -static bool PlaneResultFcn( b3ShapeId shapeId, const b3PlaneResult* planeResults, int planeCount, void* context ) -{ - if ( MoverFilterCallback( shapeId, context ) == false ) - { - // ignore these planes but continue looking for more - return true; - } - - CharacterMover* self = static_cast( context ); - float maxPush = FLT_MAX; - bool clipVelocity = true; - MoverShapeUserData* userData = static_cast( (void*)b3Shape_GetUserData( shapeId ) ); - if ( userData != nullptr ) - { - maxPush = userData->maxPush; - clipVelocity = userData->clipVelocity; - } - - for ( int i = 0; i < planeCount && self->m_planeCount < CharacterMover::m_planeCapacity; ++i ) - { - assert( b3IsValidPlane( planeResults[i].plane ) ); - self->m_planes[self->m_planeCount] = { - .plane = planeResults[i].plane, - .pushLimit = maxPush, - .push = 0.0f, - .clipVelocity = clipVelocity, - }; - self->m_planeExtras[self->m_planeCount] = { - .point = b3OffsetPos( self->m_transform.p, planeResults[i].point ), - .shapeId = shapeId, - }; - self->m_planeCount += 1; - } - - return true; -} - -void CharacterMover::SolveMove( float timeStep, b3Vec3 forward, b3Vec3 right, b3Vec2 throttle, bool clipVelocity ) -{ - // Friction - float speed = b3Length( m_velocity ); - if ( speed < m_minSpeed ) - { - m_velocity.x = 0.0f; - m_velocity.y = 0.0f; - } - else - { - // Linear damping above stopSpeed and fixed reduction below stopSpeed - float control = speed < m_stopSpeed ? m_stopSpeed : speed; - - // friction has units of 1/time - float drop = control * m_friction * timeStep; - float newSpeed = b3MaxFloat( 0.0f, speed - drop ); - m_velocity *= newSpeed / speed; - } - - float maxSpeed = m_sprint ? 1.5f * m_maxSpeed : m_maxSpeed; - - b3Vec3 desiredVelocity = maxSpeed * throttle.x * forward + maxSpeed * throttle.y * right; - float desiredSpeed; - b3Vec3 desiredDirection = b3GetLengthAndNormalize( &desiredSpeed, desiredVelocity ); - - if ( desiredSpeed > maxSpeed ) - { - desiredVelocity *= maxSpeed / desiredSpeed; - desiredSpeed = maxSpeed; - } - - if ( m_onGround ) - { - m_velocity.y = 0.0f; - } - - // Accelerate - float currentSpeed = b3Dot( m_velocity, desiredDirection ); - float addSpeed = desiredSpeed - currentSpeed; - if ( addSpeed > 0.0f ) - { - float accelSpeed = m_accelerate * maxSpeed * timeStep; - if ( accelSpeed > addSpeed ) - { - accelSpeed = addSpeed; - } - - m_velocity += accelSpeed * desiredDirection; - } - - m_velocity.y -= m_gravity * timeStep; - - b3WorldId worldId = m_sample->m_worldId; - - float pogoRestLength = 3.0f * m_capsule.radius; - float rayLength = pogoRestLength + m_capsule.radius; - b3Pos rayOrigin = b3TransformWorldPoint( m_transform, m_capsule.center1 ); - b3Vec3 rayTranslation = -rayLength * b3Vec3_axisY; - b3QueryFilter skipTeamFilter = { 1, ~2u }; - skipTeamFilter.name = "pogo"; - b3RayResult rayResult = b3World_CastRayClosest( worldId, rayOrigin, rayTranslation, skipTeamFilter ); - - if ( rayResult.hit == false ) - { - m_onGround = false; - m_pogoVelocity = 0.0f; - - DrawLine( rayOrigin, b3OffsetPos( rayOrigin, rayTranslation ), MakeColor( b3_colorGray ) ); - } - else - { - m_onGround = true; - float pogoCurrentLength = rayResult.fraction * rayLength; - - float zeta = 0.7f; - float hertz = 4.0f; - float omega = 2.0f * B3_PI * hertz; - float omegaH = omega * timeStep; - - m_pogoVelocity = ( m_pogoVelocity - omega * omegaH * ( pogoCurrentLength - pogoRestLength ) ) / - ( 1.0f + 2.0f * zeta * omegaH + omegaH * omegaH ); - DrawLine( rayOrigin, rayResult.point, MakeColor( b3_colorGreen ) ); - } - - b3Pos startPosition = m_transform.p; - b3Pos target = m_transform.p + timeStep * m_velocity + timeStep * m_pogoVelocity * b3Vec3_axisY; - - // Want the mover to collide with allies - b3QueryFilter moverFilter = { .categoryBits = 1, .maskBits = ~0u, .id = 1, .name = "mover_collide" }; - - // The cast should ignore allies - b3QueryFilter castFilter = { .categoryBits = 1, .maskBits = ~2u, .id = 1, .name = "mover_cast" }; - - m_totalIterations = 0; - float tolerance = 0.01f; - - for ( int iteration = 0; iteration < 5; ++iteration ) - { - m_planeCount = 0; - - b3Capsule mover; - mover.center1 = m_capsule.center1; - mover.center2 = m_capsule.center2; - mover.radius = m_capsule.radius; - - b3World_CollideMover( worldId, m_transform.p, &mover, moverFilter, PlaneResultFcn, this ); - - b3Vec3 targetDelta = target - m_transform.p; - b3PlaneSolverResult result = b3SolvePlanes( targetDelta, m_planes, m_planeCount ); - - m_totalIterations += result.iterationCount; - - b3Vec3 delta = result.delta; - - float fraction = b3World_CastMover( worldId, m_transform.p, &mover, delta, castFilter, MoverFilterCallback, this ); - - delta *= fraction; - m_transform.p = m_transform.p + delta; - - if ( b3LengthSquared( delta ) < tolerance * tolerance ) - { - break; - } - } - - for ( int i = 0; i < m_planeCount; ++i ) - { - b3BodyId bodyId = b3Shape_GetBody( m_planeExtras[i].shapeId ); - b3BodyType bodyType = b3Body_GetType( bodyId ); - if ( bodyType != b3_dynamicBody ) - { - continue; - } - - b3Pos point = m_planeExtras[i].point; - b3Vec3 normal = b3Neg( m_planes[i].plane.normal ); - - float invMassA = 0.0f; - float invMassB = b3Body_GetInverseMass( bodyId ); - b3Matrix3 invIB = b3Body_GetWorldInverseRotationalInertia( bodyId ); - - b3Pos pB = b3Body_GetWorldCenter( bodyId ); - b3Vec3 rB = b3SubPos( point, pB ); - - b3Vec3 rnB = b3Cross( rB, normal ); - float kNormal = invMassA + invMassB + b3Dot( rnB, b3MulMV( invIB, rnB ) ); - float normalMass = kNormal > 0.0f ? 1.0f / kNormal : 0.0f; - - b3Vec3 vB = b3Body_GetLinearVelocity( bodyId ); - b3Vec3 omegaB = b3Body_GetAngularVelocity( bodyId ); - b3Vec3 vrB = b3Add( vB, b3Cross( omegaB, rB ) ); - float vn = b3Dot( b3Sub( vrB, m_velocity ), normal ); - float impulse = b3MaxFloat( -normalMass * vn, 0.0f ); - - b3Vec3 P = b3MulSV( impulse, normal ); - m_velocity = b3MulSub( m_velocity, invMassA, P ); - - b3Body_ApplyLinearImpulse( bodyId, P, point, true ); - } - - if ( clipVelocity ) - { - // Using the velocity clipper can avoid picking up velocity from depenetration. - // This allows the mover to avoid velocity from soft collision depenetration. - m_velocity = b3ClipVector( m_velocity, m_planes, m_planeCount ); - } - else if ( timeStep > 0.0f ) - { - // Using the position delta is more holistic and intuitive in some cases. - m_velocity = ( 1.0f / timeStep ) * ( m_transform.p - startPosition ); - } -} - -void CharacterMover::Step( b3ShapeId* ignoreShapes, int ignoreCount, bool clipVelocity ) -{ - m_ignoreShapeIds = ignoreShapes; - m_ignoreCount = ignoreCount; - - b3Vec2 throttle = { 0.0f, 0.0f }; - b3Vec3 forward = -m_sample->m_camera->GetForward(); - b3Vec3 right = m_sample->m_camera->GetRight(); - forward.y = 0.0f; - - if ( m_sample->m_camera->m_thirdPerson ) - { - if ( IsKeyDown( KEY_W ) ) - { - throttle.x += 1.0f; - } - - if ( IsKeyDown( KEY_S ) ) - { - throttle.x -= 1.0f; - } - - if ( IsKeyDown( KEY_A ) ) - { - throttle.y -= 1.0f; - } - - if ( IsKeyDown( KEY_D ) ) - { - throttle.y += 1.0f; - } - - if ( IsKeyDown( KEY_SPACE ) && m_onGround == true ) - { - m_velocity.y = m_jumpSpeed; - m_onGround = false; - } - - if ( m_onGround == true ) - { - m_sprint = IsKeyDown( KEY_LEFT_SHIFT ); - } - else - { - m_sprint = false; - } - } - - float hertz = m_sample->m_context->hertz; - float timeStep = hertz > 0.0f ? 1.0f / hertz : 0.0f; - - // throttle = { 0.0f, 0.0f, -1.0f }; - - SolveMove( timeStep, forward, right, throttle, clipVelocity ); - - b3Pos position = m_transform.p; - - // Follow the mover and latch the draw origin before drawing, so the overlays below demote - // against the same eye the view renders from. - if ( m_sample->m_camera->m_thirdPerson ) - { - m_sample->m_camera->m_pivot = position; - m_sample->m_camera->UpdateTransform(); - } - - SetDrawOrigin( m_sample->m_camera->DrawOrigin() ); - - int count = m_planeCount; - for ( int i = 0; i < count; ++i ) - { - b3Plane plane = m_planes[i].plane; - b3Pos p1 = position + ( plane.offset - m_capsule.radius ) * plane.normal; - b3Pos p2 = p1 + 0.1f * plane.normal; - DrawPoint( p1, 5.0f, MakeColor( b3_colorYellow ) ); - DrawLine( p1, p2, MakeColor( b3_colorYellow ) ); - } - - DrawSolidCapsule( m_transform, m_capsule, MakeColor( b3_colorBlue ) ); - DrawLine( position, position + m_velocity, MakeColor( b3_colorPurple ) ); - - m_ignoreShapeIds = nullptr; - m_ignoreCount = 0; -} diff --git a/samples/sample.h b/samples/sample.h index cce7f29..d460308 100644 --- a/samples/sample.h +++ b/samples/sample.h @@ -60,7 +60,7 @@ struct SampleContext int subStepCount = 4; int workerCount = 1; bool transparentDynamic = false; - bool transparent = false; + bool transparentKinematic = false; bool enableWarmStarting = true; bool enableContinuous = true; bool enableSleep = true; @@ -278,47 +278,3 @@ struct CastClosestContext float CastClosestCallback( b3ShapeId shapeId, b3Pos point, b3Vec3 normal, float fraction, uint64_t materialId, int triangleIndex, int childIndex, void* context ); - -struct MoverShapeUserData -{ - float maxPush; - bool clipVelocity; -}; - -struct PlaneExtra -{ - b3Pos point; - b3ShapeId shapeId; -}; - -struct CharacterMover -{ - static constexpr int m_planeCapacity = 8; - static constexpr float m_jumpSpeed = 5.0f; - static constexpr float m_maxSpeed = 6.0f; - static constexpr float m_minSpeed = 0.01f; - static constexpr float m_stopSpeed = 1.0f; - static constexpr float m_accelerate = 30.0f; - static constexpr float m_friction = 4.0f; - static constexpr float m_gravity = 15.0f; - - void Initialize( Sample* sample, b3Pos position ); - void SolveMove( float timeStep, b3Vec3 forward, b3Vec3 right, b3Vec2 throttle, bool clipVelocity ); - void Step( b3ShapeId* ignoreShapes, int ignoreCount, bool clipVelocity ); - - Sample* m_sample; - b3WorldTransform m_transform; - b3Vec3 m_velocity; - b3Capsule m_capsule; - b3CollisionPlane m_planes[m_planeCapacity] = {}; - PlaneExtra m_planeExtras[m_planeCapacity] = {}; - int m_planeCount; - int m_totalIterations; - float m_pogoVelocity; - bool m_onGround; - bool m_sprint; - - // Transient - b3ShapeId* m_ignoreShapeIds; - int m_ignoreCount; -}; diff --git a/samples/sample_character.cpp b/samples/sample_character.cpp index 17af0f2..6d65648 100644 --- a/samples/sample_character.cpp +++ b/samples/sample_character.cpp @@ -4,6 +4,7 @@ #include "gfx/draw.h" #include "gfx/keycodes.h" #include "mesh_loader.h" +#include "mover.h" #include "sample.h" #include "box3d/box3d.h" diff --git a/samples/sample_compound.cpp b/samples/sample_compound.cpp index c7c6f95..65c87c9 100644 --- a/samples/sample_compound.cpp +++ b/samples/sample_compound.cpp @@ -5,6 +5,7 @@ #include "gfx/draw.h" #include "human.h" #include "mesh_loader.h" +#include "mover.h" #include "sample.h" #include "utils.h" diff --git a/samples/sample_issues.cpp b/samples/sample_issues.cpp index d0892c6..d3d17e7 100644 --- a/samples/sample_issues.cpp +++ b/samples/sample_issues.cpp @@ -924,3 +924,225 @@ public: }; static int sampleSBoxGhostCollisions = RegisterSample( "Issues", "s&box Ghost Collisions", SBoxGhostCollisions::Create ); + +static const b3Vec3 s_metalWheel1Verts[317] = { + { 0.010279f, 0.086341f, 0.051768f }, { -0.010314f, -0.084708f, 0.051804f }, { 0.010279f, -0.084708f, 0.051768f }, + { -0.010314f, 0.086341f, 0.051804f }, { 0.029138f, -0.084708f, -0.043911f }, { 0.043724f, -0.084708f, -0.029376f }, + { 0.010098f, -0.084708f, -0.051759f }, { -0.010494f, -0.084708f, -0.051723f }, { 0.051638f, -0.084708f, -0.010364f }, + { 0.051674f, -0.084708f, 0.010229f }, { 0.043827f, -0.084708f, 0.029268f }, { 0.029291f, -0.084708f, 0.043855f }, + { -0.029353f, -0.084708f, 0.043957f }, { -0.051889f, -0.084708f, -0.010183f }, { -0.051853f, -0.084708f, 0.010409f }, + { -0.043939f, -0.084708f, 0.029421f }, { -0.029506f, -0.084708f, -0.043809f }, { -0.044042f, -0.084708f, -0.029222f }, + { -0.029353f, 0.086341f, 0.043957f }, { 0.043724f, 0.086341f, -0.029376f }, { 0.029138f, 0.086341f, -0.043911f }, + { 0.010098f, 0.086341f, -0.051759f }, { 0.051638f, 0.086341f, -0.010364f }, { 0.051674f, 0.086341f, 0.010229f }, + { -0.044042f, 0.086341f, -0.029222f }, { 0.043827f, 0.086341f, 0.029268f }, { -0.051889f, 0.086341f, -0.010183f }, + { -0.043939f, 0.086341f, 0.029421f }, { -0.029506f, 0.086341f, -0.043809f }, { 0.035354f, 0.070897f, 0.035658f }, + { 0.035354f, -0.069397f, 0.035658f }, { -0.035498f, 0.070897f, 0.035658f }, { -0.035498f, -0.069397f, 0.035658f }, + { 0.035354f, -0.069397f, 0.365503f }, { 0.035354f, 0.070897f, 0.365503f }, { -0.035498f, 0.070897f, 0.365503f }, + { -0.035498f, -0.069397f, 0.365503f }, { 0.035354f, 0.070897f, -0.365033f }, { 0.035354f, -0.069397f, -0.365033f }, + { -0.035498f, 0.070897f, -0.365033f }, { -0.035498f, -0.069397f, -0.365033f }, { 0.035354f, -0.069397f, -0.035187f }, + { 0.035354f, 0.070897f, -0.035187f }, { -0.035498f, 0.070897f, -0.035187f }, { -0.035498f, -0.069397f, -0.035187f }, + { -0.035494f, -0.069397f, -0.035191f }, { -0.365340f, -0.069397f, -0.035191f }, { -0.035494f, 0.070897f, -0.035191f }, + { -0.365340f, 0.070897f, -0.035191f }, { -0.365340f, -0.069397f, 0.035661f }, { -0.035494f, -0.069397f, 0.035661f }, + { -0.035494f, 0.070897f, 0.035661f }, { -0.365340f, 0.070897f, 0.035661f }, { 0.035350f, 0.070897f, -0.035191f }, + { 0.365196f, 0.070897f, -0.035191f }, { 0.035350f, -0.069397f, -0.035191f }, { 0.365196f, -0.069397f, -0.035191f }, + { 0.365196f, 0.070897f, 0.035661f }, { 0.035350f, 0.070897f, 0.035661f }, { 0.035350f, -0.069397f, 0.035661f }, + { 0.365196f, -0.069397f, 0.035661f }, { -0.070802f, 0.086337f, 0.355420f }, { -0.070802f, -0.084705f, 0.355420f }, + { -0.097081f, 0.086335f, 0.487537f }, { -0.097081f, -0.084704f, 0.487537f }, { -0.000108f, 0.086337f, 0.362383f }, + { -0.000108f, 0.086335f, 0.497088f }, { -0.000108f, -0.084704f, 0.497088f }, { -0.000108f, -0.084705f, 0.362383f }, + { -0.138787f, -0.084705f, 0.334799f }, { -0.138787f, 0.086337f, 0.334799f }, { -0.070810f, -0.084705f, 0.355419f }, + { -0.070810f, 0.086337f, 0.355419f }, { -0.097090f, 0.086335f, 0.487536f }, { -0.190336f, 0.086335f, 0.459250f }, + { -0.190336f, -0.084704f, 0.459250f }, { -0.097090f, -0.084704f, 0.487536f }, { -0.138795f, 0.086337f, 0.334796f }, + { -0.138795f, -0.084705f, 0.334796f }, { -0.201442f, 0.086337f, 0.301310f }, { -0.201442f, -0.084705f, 0.301310f }, + { -0.276280f, -0.084704f, 0.413313f }, { -0.276280f, 0.086335f, 0.413313f }, { -0.190344f, 0.086335f, 0.459247f }, + { -0.190344f, -0.084704f, 0.459247f }, { -0.201450f, -0.084705f, 0.301306f }, { -0.256361f, -0.084705f, 0.256241f }, + { -0.201450f, 0.086337f, 0.301306f }, { -0.256361f, 0.086337f, 0.256241f }, { -0.351612f, 0.086335f, 0.351492f }, + { -0.351612f, -0.084704f, 0.351492f }, { -0.276288f, 0.086335f, 0.413309f }, { -0.276288f, -0.084704f, 0.413309f }, + { -0.301431f, -0.084705f, 0.201325f }, { -0.413435f, -0.084704f, 0.276163f }, { -0.413435f, 0.086335f, 0.276163f }, + { -0.301431f, 0.086337f, 0.201325f }, { -0.256367f, -0.084705f, 0.256236f }, { -0.256367f, 0.086337f, 0.256236f }, + { -0.351618f, 0.086335f, 0.351487f }, { -0.351618f, -0.084704f, 0.351487f }, { -0.334922f, -0.084705f, 0.138670f }, + { -0.459374f, -0.084704f, 0.190220f }, { -0.459374f, 0.086335f, 0.190220f }, { -0.334922f, 0.086337f, 0.138670f }, + { -0.301436f, 0.086337f, 0.201318f }, { -0.301436f, -0.084705f, 0.201318f }, { -0.413440f, 0.086335f, 0.276156f }, + { -0.413440f, -0.084704f, 0.276156f }, { -0.487663f, -0.084704f, 0.096966f }, { -0.355546f, -0.084705f, 0.070686f }, + { -0.459377f, -0.084704f, 0.190212f }, { -0.334926f, -0.084705f, 0.138663f }, { -0.355546f, 0.086337f, 0.070686f }, + { -0.334926f, 0.086337f, 0.138663f }, { -0.487663f, 0.086335f, 0.096966f }, { -0.459377f, 0.086335f, 0.190212f }, + { -0.362511f, -0.084705f, -0.000016f }, { -0.355549f, -0.084705f, 0.070678f }, { -0.497217f, -0.084704f, -0.000016f }, + { -0.487665f, -0.084704f, 0.096957f }, { -0.497217f, 0.086335f, -0.000016f }, { -0.362511f, 0.086337f, -0.000016f }, + { -0.355549f, 0.086337f, 0.070678f }, { -0.487665f, 0.086335f, 0.096957f }, { -0.362512f, 0.086337f, -0.000024f }, + { -0.362512f, -0.084705f, -0.000024f }, { -0.355549f, 0.086337f, -0.070717f }, { -0.355549f, -0.084705f, -0.070717f }, + { -0.497217f, -0.084704f, -0.000024f }, { -0.487666f, -0.084704f, -0.096997f }, { -0.497217f, 0.086335f, -0.000024f }, + { -0.487666f, 0.086335f, -0.096997f }, { -0.334927f, -0.084705f, -0.138702f }, { -0.355548f, 0.086337f, -0.070726f }, + { -0.355548f, -0.084705f, -0.070726f }, { -0.334927f, 0.086337f, -0.138702f }, { -0.487665f, -0.084704f, -0.097005f }, + { -0.459379f, -0.084704f, -0.190252f }, { -0.487665f, 0.086335f, -0.097005f }, { -0.459379f, 0.086335f, -0.190252f }, + { -0.413442f, -0.084704f, -0.276196f }, { -0.301439f, -0.084705f, -0.201358f }, { -0.334925f, -0.084705f, -0.138710f }, + { -0.459376f, -0.084704f, -0.190260f }, { -0.334925f, 0.086337f, -0.138710f }, { -0.301439f, 0.086337f, -0.201358f }, + { -0.459376f, 0.086335f, -0.190260f }, { -0.413442f, 0.086335f, -0.276196f }, { -0.256370f, -0.084705f, -0.256276f }, + { -0.301434f, 0.086337f, -0.201365f }, { -0.301434f, -0.084705f, -0.201365f }, { -0.256370f, 0.086337f, -0.256276f }, + { -0.413438f, 0.086335f, -0.276203f }, { -0.351621f, 0.086335f, -0.351527f }, { -0.413438f, -0.084704f, -0.276203f }, + { -0.351621f, -0.084704f, -0.351527f }, { -0.256364f, -0.084705f, -0.256283f }, { -0.201453f, 0.086337f, -0.301347f }, + { -0.256364f, 0.086337f, -0.256283f }, { -0.201453f, -0.084705f, -0.301347f }, { -0.276292f, -0.084704f, -0.413350f }, + { -0.351615f, -0.084704f, -0.351534f }, { -0.351615f, 0.086335f, -0.351534f }, { -0.276292f, 0.086335f, -0.413350f }, + { -0.201447f, -0.084705f, -0.301352f }, { -0.276285f, -0.084704f, -0.413355f }, { -0.138799f, -0.084705f, -0.334838f }, + { -0.190349f, -0.084704f, -0.459289f }, { -0.276285f, 0.086335f, -0.413355f }, { -0.201447f, 0.086337f, -0.301352f }, + { -0.190349f, 0.086335f, -0.459289f }, { -0.138799f, 0.086337f, -0.334838f }, { -0.190341f, 0.086335f, -0.459293f }, + { -0.190341f, -0.084704f, -0.459293f }, { -0.138791f, -0.084705f, -0.334842f }, { -0.138791f, 0.086337f, -0.334842f }, + { -0.070815f, 0.086337f, -0.355462f }, { -0.070815f, -0.084705f, -0.355462f }, { -0.097095f, 0.086335f, -0.487579f }, + { -0.097095f, -0.084704f, -0.487579f }, { -0.070807f, 0.086337f, -0.355464f }, { -0.097086f, 0.086335f, -0.487581f }, + { -0.097086f, -0.084704f, -0.487581f }, { -0.070807f, -0.084705f, -0.355464f }, { -0.000113f, -0.084705f, -0.362427f }, + { -0.000113f, 0.086337f, -0.362427f }, { -0.000113f, 0.086335f, -0.497132f }, { -0.000113f, -0.084704f, -0.497132f }, + { 0.070588f, 0.086337f, -0.355465f }, { 0.096868f, -0.084704f, -0.487582f }, { 0.096868f, 0.086335f, -0.487582f }, + { 0.070588f, -0.084705f, -0.355465f }, { -0.000105f, 0.086337f, -0.362427f }, { -0.000105f, 0.086335f, -0.497133f }, + { -0.000105f, -0.084704f, -0.497133f }, { -0.000105f, -0.084705f, -0.362427f }, { 0.190123f, -0.084704f, -0.459294f }, + { 0.190123f, 0.086335f, -0.459294f }, { 0.138573f, -0.084705f, -0.334843f }, { 0.138573f, 0.086337f, -0.334843f }, + { 0.070597f, 0.086337f, -0.355463f }, { 0.070597f, -0.084705f, -0.355463f }, { 0.096876f, -0.084704f, -0.487580f }, + { 0.096876f, 0.086335f, -0.487580f }, { 0.201229f, -0.084705f, -0.301354f }, { 0.276067f, -0.084704f, -0.413358f }, + { 0.201229f, 0.086337f, -0.301354f }, { 0.138581f, -0.084705f, -0.334840f }, { 0.138581f, 0.086337f, -0.334840f }, + { 0.190131f, 0.086335f, -0.459292f }, { 0.276067f, 0.086335f, -0.413358f }, { 0.190131f, -0.084704f, -0.459292f }, + { 0.201236f, 0.086337f, -0.301350f }, { 0.256147f, -0.084705f, -0.256286f }, { 0.256147f, 0.086337f, -0.256286f }, + { 0.201236f, -0.084705f, -0.301350f }, { 0.351398f, -0.084704f, -0.351537f }, { 0.351398f, 0.086335f, -0.351537f }, + { 0.276074f, -0.084704f, -0.413353f }, { 0.276074f, 0.086335f, -0.413353f }, { 0.301218f, -0.084705f, -0.201369f }, + { 0.301218f, 0.086337f, -0.201369f }, { 0.256154f, -0.084705f, -0.256280f }, { 0.256154f, 0.086337f, -0.256280f }, + { 0.413221f, 0.086335f, -0.276207f }, { 0.413221f, -0.084704f, -0.276207f }, { 0.351405f, 0.086335f, -0.351531f }, + { 0.351405f, -0.084704f, -0.351531f }, { 0.334709f, 0.086337f, -0.138715f }, { 0.301223f, 0.086337f, -0.201362f }, + { 0.334709f, -0.084705f, -0.138715f }, { 0.301223f, -0.084705f, -0.201362f }, { 0.459160f, -0.084704f, -0.190264f }, + { 0.459160f, 0.086335f, -0.190264f }, { 0.413226f, 0.086335f, -0.276200f }, { 0.413226f, -0.084704f, -0.276200f }, + { 0.334713f, -0.084705f, -0.138707f }, { 0.355333f, -0.084705f, -0.070731f }, { 0.334713f, 0.086337f, -0.138707f }, + { 0.355333f, 0.086337f, -0.070731f }, { 0.459164f, 0.086335f, -0.190257f }, { 0.487450f, 0.086335f, -0.097010f }, + { 0.487450f, -0.084704f, -0.097010f }, { 0.459164f, -0.084704f, -0.190257f }, { 0.355335f, -0.084705f, -0.070722f }, + { 0.362298f, -0.084705f, -0.000029f }, { 0.355335f, 0.086337f, -0.070722f }, { 0.362298f, 0.086337f, -0.000029f }, + { 0.497003f, -0.084704f, -0.000029f }, { 0.497003f, 0.086335f, -0.000029f }, { 0.487452f, 0.086335f, -0.097002f }, + { 0.487452f, -0.084704f, -0.097002f }, { 0.362298f, -0.084705f, -0.000021f }, { 0.497003f, -0.084704f, -0.000021f }, + { 0.355336f, -0.084705f, 0.070673f }, { 0.487453f, -0.084704f, 0.096952f }, { 0.497003f, 0.086335f, -0.000021f }, + { 0.362298f, 0.086337f, -0.000021f }, { 0.355336f, 0.086337f, 0.070673f }, { 0.487453f, 0.086335f, 0.096952f }, + { 0.355334f, -0.084705f, 0.070681f }, { 0.355334f, 0.086337f, 0.070681f }, { 0.487451f, 0.086335f, 0.096961f }, + { 0.487451f, -0.084704f, 0.096961f }, { 0.334714f, -0.084705f, 0.138658f }, { 0.459165f, -0.084704f, 0.190207f }, + { 0.334714f, 0.086337f, 0.138658f }, { 0.459165f, 0.086335f, 0.190207f }, { 0.334711f, 0.086337f, 0.138666f }, + { 0.301225f, 0.086337f, 0.201313f }, { 0.459163f, 0.086335f, 0.190215f }, { 0.413229f, 0.086335f, 0.276151f }, + { 0.334711f, -0.084705f, 0.138666f }, { 0.301225f, -0.084705f, 0.201313f }, { 0.413229f, -0.084704f, 0.276151f }, + { 0.459163f, -0.084704f, 0.190215f }, { 0.301221f, -0.084705f, 0.201321f }, { 0.256157f, -0.084705f, 0.256232f }, + { 0.301221f, 0.086337f, 0.201321f }, { 0.256157f, 0.086337f, 0.256232f }, { 0.413224f, -0.084704f, 0.276159f }, + { 0.413224f, 0.086335f, 0.276159f }, { 0.351408f, 0.086335f, 0.351483f }, { 0.351408f, -0.084704f, 0.351483f }, + { 0.201240f, -0.084705f, 0.301302f }, { 0.201240f, 0.086337f, 0.301302f }, { 0.256151f, -0.084705f, 0.256238f }, + { 0.256151f, 0.086337f, 0.256238f }, { 0.351402f, 0.086335f, 0.351489f }, { 0.351402f, -0.084704f, 0.351489f }, + { 0.276078f, 0.086335f, 0.413305f }, { 0.276078f, -0.084704f, 0.413305f }, { 0.138586f, -0.084705f, 0.334793f }, + { 0.201233f, -0.084705f, 0.301307f }, { 0.190135f, -0.084704f, 0.459244f }, { 0.276071f, -0.084704f, 0.413311f }, + { 0.201233f, 0.086337f, 0.301307f }, { 0.138586f, 0.086337f, 0.334793f }, { 0.276071f, 0.086335f, 0.413311f }, + { 0.190135f, 0.086335f, 0.459244f }, { 0.138578f, -0.084705f, 0.334797f }, { 0.070602f, -0.084705f, 0.355417f }, + { 0.138578f, 0.086337f, 0.334797f }, { 0.070602f, 0.086337f, 0.355417f }, { 0.190127f, 0.086335f, 0.459248f }, + { 0.190127f, -0.084704f, 0.459248f }, { 0.096881f, 0.086335f, 0.487534f }, { 0.096881f, -0.084704f, 0.487534f }, + { 0.070593f, -0.084705f, 0.355419f }, { 0.096873f, 0.086335f, 0.487536f }, { 0.096873f, -0.084704f, 0.487536f }, + { 0.070593f, 0.086337f, 0.355419f }, { -0.000100f, 0.086337f, 0.362382f }, { -0.000100f, 0.086335f, 0.497087f }, + { -0.000100f, -0.084704f, 0.497087f }, { -0.000100f, -0.084705f, 0.362382f }, +}; + +typedef struct WheelHullSpan +{ + int offset; + int count; +} WheelHullSpan; +static const WheelHullSpan s_metalWheel1Hulls[37] = { + { 0, 29 }, { 29, 8 }, { 37, 8 }, { 45, 8 }, { 53, 8 }, { 61, 8 }, { 69, 8 }, { 77, 8 }, { 85, 8 }, { 93, 8 }, + { 101, 8 }, { 109, 8 }, { 117, 8 }, { 125, 8 }, { 133, 8 }, { 141, 8 }, { 149, 8 }, { 157, 8 }, { 165, 8 }, { 173, 8 }, + { 181, 8 }, { 189, 8 }, { 197, 8 }, { 205, 8 }, { 213, 8 }, { 221, 8 }, { 229, 8 }, { 237, 8 }, { 245, 8 }, { 253, 8 }, + { 261, 8 }, { 269, 8 }, { 277, 8 }, { 285, 8 }, { 293, 8 }, { 301, 8 }, { 309, 8 }, +}; +#define s_metalWheel1HullCount 37 + +// 30 metal_wheel1 props (37-piece convex decompositions) stacked. Body-pair contact merging +// lets them settle and sleep instead of wobbling. +class WheelStack : public Sample +{ +public: + explicit WheelStack( SampleContext* context ) + : Sample( context ) + { + if ( context->restart == false ) + { + m_camera->SetView( 0.0f, 12.0f, 5.0f, { 0.0f, 0.85f, 0.0f } ); + } + + AddGroundBox( 10.0f ); + + constexpr int N = 512; + b3Vec3 buffer[N]; + int bufferCount = 0; + for ( int h = 0; h < s_metalWheel1HullCount; ++h ) + { + const WheelHullSpan& span = s_metalWheel1Hulls[h]; + m_hulls[h] = b3CreateHull( &s_metalWheel1Verts[span.offset], span.count, span.count ); + + const b3Vec3* points = b3GetHullPoints( m_hulls[h] ); + for ( int j = 0; j < m_hulls[h]->vertexCount && bufferCount < N; ++j ) + { + buffer[bufferCount] = points[j]; + ++bufferCount; + } + } + + // Create a single hull that wraps the input hulls. + b3HullData* wheelHull = b3CreateHull( buffer, bufferCount, bufferCount ); + + const float height = 0.171f; + const float spacing = height + 0.006f; + const float startY = 0.5f * height + 0.004f; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.baseMaterial.friction = 0.6f; + + for ( int i = 0; i < m_wheelCount; ++i ) + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.name = "wheel"; + bodyDef.position = { 0.0f, startY + i * spacing, 0.0f }; + b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef ); + + //for ( int h = 0; h < s_metalWheel1HullCount; ++h ) + //{ + // b3CreateHullShape( bodyId, &shapeDef, m_hulls[h] ); + //} + + // Using a single hull improves the simulation. + b3CreateHullShape( bodyId, &shapeDef, wheelHull ); + } + + b3DestroyHull( wheelHull ); + + b3World_SetContactTuning( m_worldId, 240.0f, 10.0f, 3.0f ); + } + + ~WheelStack() override + { + for ( int h = 0; h < s_metalWheel1HullCount; ++h ) + { + b3DestroyHull( m_hulls[h] ); + } + } + + void Step() override + { + Sample::Step(); + + b3Profile p = b3World_GetProfile( m_worldId ); + float substepRate = m_context->hertz * m_context->subStepCount; + + DrawTextLine( "wheels %d, hull pieces/wheel %d (%d total shapes)", m_wheelCount, s_metalWheel1HullCount, + m_wheelCount * s_metalWheel1HullCount ); + DrawTextLine( "step %.0f hz, sub-steps %d -> substep rate %.0f hz", m_context->hertz, m_context->subStepCount, + substepRate ); + DrawTextLine( "eff contact hz = min(240, %.0f) = %.0f", 0.125f * substepRate, + b3MinFloat( 240.0f, 0.125f * substepRate ) ); + DrawTextLine( "step %.3f ms | collide %.3f ms (%.0f%%) | solve %.3f ms (%.0f%%)", p.step, p.collide, + p.step > 0.0f ? 100.0f * p.collide / p.step : 0.0f, p.solve, + p.step > 0.0f ? 100.0f * p.solve / p.step : 0.0f ); + } + + static Sample* Create( SampleContext* context ) + { + return new WheelStack( context ); + } + + b3HullData* m_hulls[s_metalWheel1HullCount]; + static constexpr int m_wheelCount = 30; +}; + +static int sampleWheelStack = RegisterSample( "Issues", "GMod Wheel Stack", WheelStack::Create ); diff --git a/samples/sample_manifold.cpp b/samples/sample_manifold.cpp index 475986b..75bf01b 100644 --- a/samples/sample_manifold.cpp +++ b/samples/sample_manifold.cpp @@ -829,19 +829,18 @@ public: //m_triangle[1] = { 1.00000000, 0, 0.00000000 }; //m_triangle[2] = { 0.00000000, 0, 0.00000000 }; - m_triangle[0x00000000] = { -1.82879996, -0.0253999997, -0.609600008 }; - m_triangle[0x00000001] = { -1.82879996, -0.0253999997, -0.406399995 }; - m_triangle[0x00000002] = { -1.79069996, 0.00000000, -0.406399995 }; + m_triangle[0] = { 0.299769998f, -1.01549578f, -0.744717002f }; + m_triangle[1] = { 0.299769998f, -1.01549578f, 1.28728306f }; + m_triangle[2] = { 0.299769998f, -0.913895786f, 0.271283031f }; - float SRC = 0.0254f; - float bodyHalfWidth = 16.0f * SRC; - float bodyHalfHeight = 36.0f * SRC; + float bodyHalfWidth = 0.304800004f; + float bodyHalfHeight = 0.914399981f; m_boxHull = b3MakeBoxHull( bodyHalfWidth, bodyHalfHeight, bodyHalfWidth ); m_transformA = b3WorldTransform_identity; m_transformB = b3WorldTransform_identity; - m_transformB.p = { -2.16650009f, 0.912535489f, 0.00000000f }; + //m_transformB.p = { -2.16650009f, 0.912535489f, 0.00000000f }; // b3MeshEdgeFlags m_flags = 0; diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 0460f85..71b76d1 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -169,8 +169,11 @@ if (BOX3D_DOUBLE_PRECISION) target_compile_definitions(box3d PUBLIC BOX3D_DOUBLE_PRECISION) endif() +# Enable asserts in release with debug info +target_compile_definitions(box3d PUBLIC "$<$:B3_ENABLE_ASSERT>") + if (MSVC) - message(STATUS "Box3D on MSVC") + message(STATUS "Box3D on MSVC") if (BUILD_SHARED_LIBS) # this is needed by DLL users to import Box3D symbols target_compile_definitions(box3d INTERFACE BOX3D_DLL) @@ -179,9 +182,6 @@ if (MSVC) # Visual Studio won't load the natvis unless it is in the project target_sources(box3d PRIVATE box3d.natvis) - # Enable asserts in release with debug info - target_compile_definitions(box3d PUBLIC "$<$:B3_ENABLE_ASSERT>") - # Warnings Wall is problematic in mixed C/C++, so using W4 target_compile_options(box3d PRIVATE /W4) # target_compile_options(box3d PRIVATE /wd4820 /wd5045 /wd4061 /wd4711 /wd4514 /wd4365 /wd5219 /wd5039) diff --git a/src/compound.c b/src/compound.c index 1816475..c1af61c 100644 --- a/src/compound.c +++ b/src/compound.c @@ -226,13 +226,19 @@ static bool b3CompareMeshes( const b3MeshData* mesh1, const b3MeshData* mesh2 ) #define FREE_FN b3Free #include "verstable.h" +_Static_assert( sizeof( b3SurfaceMaterial ) == 40, "review padding" ); + static inline uint64_t b3HashMaterial( const b3SurfaceMaterial* material ) { + B3_ASSERT( material->padding == 0 ); + return vt_wyhash( material, sizeof( b3SurfaceMaterial ) ); } static bool b3CompareMaterials( const b3SurfaceMaterial* mat1, const b3SurfaceMaterial* mat2 ) { + B3_ASSERT( mat1->padding == 0 && mat2->padding == 0); + if ( mat1 == mat2 ) { return true; diff --git a/src/contact.c b/src/contact.c index 92e38b0..1506bdb 100644 --- a/src/contact.c +++ b/src/contact.c @@ -745,6 +745,16 @@ bool b3UpdateContact( b3World* world, int workerIndex, b3Contact* contact, b3Sha childShapeA.type = child.type; + // Handle child material for non-meshes. + if ( child.type != b3_meshShape ) + { + B3_ASSERT( 0 <= child.materialIndices[0] && child.materialIndices[0] < shapeA->materialCount ); + const b3SurfaceMaterial* parentMaterials = b3GetShapeMaterials( shapeA ); + childShapeA.material = parentMaterials[child.materialIndices[0]]; + childShapeA.materials = NULL; + childShapeA.materialCount = 1; + } + if ( child.type == b3_capsuleShape ) { childShapeA.capsule = child.capsule; diff --git a/src/contact_solver.c b/src/contact_solver.c index 5ee2eaf..25c4f0a 100644 --- a/src/contact_solver.c +++ b/src/contact_solver.c @@ -964,6 +964,8 @@ typedef struct b3ContactConstraintWide int indexA[B3_SIMD_WIDTH]; int indexB[B3_SIMD_WIDTH]; + int pointCounts[B3_SIMD_WIDTH]; + b3FloatW invMassA, invMassB; b3SymMatrix3W invIA, invIB; b3Vec3W normal; @@ -1403,6 +1405,8 @@ void b3PrepareContacts_Convex( b3SolverBlock block, b3StepContext* context ) ( (float*)&constraint->impulseScale )[lane] = soft.impulseScale; int pointCount = manifold->pointCount; + constraint->pointCounts[lane] = pointCount; + b3Vec3 centerA = b3Vec3_zero; b3Vec3 centerB = b3Vec3_zero; float totalFrictionWeight = 0.0f; @@ -1550,8 +1554,14 @@ void b3WarmStartContacts_Convex( b3SolverBlock block, b3StepContext* context ) b3BodyStateW bA = b3GatherBodies( states, c->indexA ); b3BodyStateW bB = b3GatherBodies( states, c->indexB ); + _Static_assert( B3_SIMD_WIDTH == 4, "width" ); + int pointCount1 = b3MaxInt( c->pointCounts[0], c->pointCounts[1] ); + int pointCount2 = b3MaxInt( c->pointCounts[2], c->pointCounts[3] ); + int pointCount = b3MaxInt( pointCount1, pointCount2 ); + B3_VALIDATE( 0 < pointCount && pointCount <= B3_SIMD_WIDTH ); + // Normal impulses - for ( int j = 0; j < B3_MAX_MANIFOLD_POINTS; ++j ) + for ( int j = 0; j < pointCount; ++j ) { b3ContactConstraintPointWide* cp = c->points + j; @@ -1618,6 +1628,12 @@ void b3SolveContacts_Convex( b3SolverBlock block, b3StepContext* context, bool u { b3ContactConstraintWide* c = constraints + wideIndex; + _Static_assert( B3_SIMD_WIDTH == 4, "width" ); + int pointCount1 = b3MaxInt( c->pointCounts[0], c->pointCounts[1] ); + int pointCount2 = b3MaxInt( c->pointCounts[2], c->pointCounts[3] ); + int pointCount = b3MaxInt( pointCount1, pointCount2 ); + B3_VALIDATE( 0 < pointCount && pointCount <= B3_SIMD_WIDTH ); + b3BodyStateW bA = b3GatherBodies( states, c->indexA ); b3BodyStateW bB = b3GatherBodies( states, c->indexB ); @@ -1640,8 +1656,7 @@ void b3SolveContacts_Convex( b3SolverBlock block, b3StepContext* context, bool u b3FloatW totalNormalImpulse = b3ZeroW(); b3FloatW totalTwistLimit = b3ZeroW(); - // todo_erin use the max point count of the four manifolds - for ( int pointIndex = 0; pointIndex < B3_MAX_MANIFOLD_POINTS; ++pointIndex ) + for ( int pointIndex = 0; pointIndex < pointCount; ++pointIndex ) { b3ContactConstraintPointWide* cp = c->points + pointIndex; @@ -1828,6 +1843,12 @@ void b3ApplyRestitution_Convex( b3SolverBlock block, b3StepContext* context ) continue; } + _Static_assert( B3_SIMD_WIDTH == 4, "width" ); + int pointCount1 = b3MaxInt( c->pointCounts[0], c->pointCounts[1] ); + int pointCount2 = b3MaxInt( c->pointCounts[2], c->pointCounts[3] ); + int pointCount = b3MaxInt( pointCount1, pointCount2 ); + B3_VALIDATE( 0 < pointCount && pointCount <= B3_SIMD_WIDTH ); + // Single gather for all manifolds b3BodyStateW bA = b3GatherBodies( states, c->indexA ); b3BodyStateW bB = b3GatherBodies( states, c->indexB ); @@ -1836,7 +1857,7 @@ void b3ApplyRestitution_Convex( b3SolverBlock block, b3StepContext* context ) // by the calculations below. b3FloatW restitutionMask = b3EqualsW( c->restitution, zero ); - for ( int pointIndex = 0; pointIndex < B3_MAX_MANIFOLD_POINTS; ++pointIndex ) + for ( int pointIndex = 0; pointIndex < pointCount; ++pointIndex ) { b3ContactConstraintPointWide* cp = c->points + pointIndex; diff --git a/src/physics_world.c b/src/physics_world.c index 2a065aa..50ffefe 100644 --- a/src/physics_world.c +++ b/src/physics_world.c @@ -1523,7 +1523,7 @@ void b3World_Draw( b3WorldId worldId, b3DebugDraw* draw, uint64_t maskBits ) b3Vec3 normal = manifold->normal; // Average the anchors not the world points so the friction center stays exact far from the origin - b3Pos contactCenter = draw->drawAnchorA == 1 ? bodySimA->center : bodySimB->center; + b3Pos contactCenter = draw->drawAnchorA ? bodySimA->center : bodySimB->center; b3Vec3 frictionAnchor = b3Vec3_zero; float totalWeight = 0.0f; float invTau = 1.0f / B3_SPECULATIVE_DISTANCE; @@ -1535,7 +1535,7 @@ void b3World_Draw( b3WorldId worldId, b3DebugDraw* draw, uint64_t maskBits ) char buffer[32]; - b3Vec3 anchor = draw->drawAnchorA == 1 ? mp->anchorA : mp->anchorB; + b3Vec3 anchor = draw->drawAnchorA ? mp->anchorA : mp->anchorB; b3Pos p = b3OffsetPos( contactCenter, anchor ); // See similar friction anchor weights in b3PrepareContacts_Mesh. diff --git a/src/triangle_manifold.c b/src/triangle_manifold.c index b964ea6..b7432b0 100644 --- a/src/triangle_manifold.c +++ b/src/triangle_manifold.c @@ -1233,10 +1233,9 @@ void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3 // Don't admit a hull face significantly opposed to the triangle face. // Need a tolerance to avoid ghost collisions. - // todo hull query skips faces that point along the triangle normal b3Vec3 hullNormal = hullPlanes[faceQueryB.faceIndex].normal; bool pushingDown = b3Dot( hullNormal, trianglePlane.normal ) > 0.25f; - if ( faceQueryB.separation > faceQueryA.separation + linearSlop && pushingDown == false ) + if ( faceQueryB.separation >= faceQueryA.separation && pushingDown == false ) { clippedFaceSeparation = b3CollideHullFace( manifold, capacity, &triangle, hullA, faceQueryB, cache, enableSpeculative ); } diff --git a/src/types.c b/src/types.c index b199cd1..7e2cd07 100644 --- a/src/types.c +++ b/src/types.c @@ -80,10 +80,9 @@ b3ShapeDef b3DefaultShapeDef( void ) return def; } -static bool b3EmptyDrawShape( void* userShape, b3WorldTransform transform, b3HexColor color, void* context ) +static void b3EmptyDrawShape( void* userShape, b3WorldTransform transform, b3HexColor color, void* context ) { B3_UNUSED( userShape, transform, color, context ); - return false; } static void b3EmptyDrawSegment( b3Pos p1, b3Pos p2, b3HexColor color, void* context ) diff --git a/test/test_determinism.c b/test/test_determinism.c index 0c92a90..af35f95 100644 --- a/test/test_determinism.c +++ b/test/test_determinism.c @@ -18,27 +18,27 @@ // Double precision accumulates body positions in double, so the settle/sleep step and the // state hash differ from the float build. Both modes are internally deterministic. #if defined( BOX3D_DOUBLE_PRECISION ) -#define EXPECTED_SLEEP_STEP 297 -#define EXPECTED_HASH 0x27FF38C1 -#define WAVE_PILE_SLEEP_STEP 287 -#define WAVE_PILE_HASH 0xFFC8DA49 +#define RAGDOLL_SLEEP_STEP 297 +#define RAGDOLL_HASH 0x27FF38C1 +#define WAVE_PILE_SLEEP_STEP 258 +#define WAVE_PILE_HASH 0xA3CDC61B #define QUERY_SPAWN_SLEEP_STEP 242 #define QUERY_SPAWN_HASH 0x1737F5BC #define QUERY_SPAWN_HIT_COUNT 59 #define QUERY_SPAWN_QUERY_HASH 0x31F090DC -#define MESH_DROP_SLEEP_STEP 206 -#define MESH_DROP_HASH 0xB6A9E1DE +#define MESH_DROP_SLEEP_STEP 251 +#define MESH_DROP_HASH 0x465381C5 #else -#define EXPECTED_SLEEP_STEP 308 -#define EXPECTED_HASH 0x1E5EDD79 -#define WAVE_PILE_SLEEP_STEP 285 -#define WAVE_PILE_HASH 0x4057173C +#define RAGDOLL_SLEEP_STEP 308 +#define RAGDOLL_HASH 0x1E5EDD79 +#define WAVE_PILE_SLEEP_STEP 239 +#define WAVE_PILE_HASH 0xA2F4D472 #define QUERY_SPAWN_SLEEP_STEP 242 #define QUERY_SPAWN_HASH 0xB9F993A5 #define QUERY_SPAWN_HIT_COUNT 59 #define QUERY_SPAWN_QUERY_HASH 0xB9D3863D -#define MESH_DROP_SLEEP_STEP 205 -#define MESH_DROP_HASH 0x8F55FB2D +#define MESH_DROP_SLEEP_STEP 251 +#define MESH_DROP_HASH 0xE58C7240 #endif static int SingleMultithreadingTest( int workerCount ) @@ -68,13 +68,13 @@ static int SingleMultithreadingTest( int workerCount ) b3DestroyWorld( worldId ); - if ( data.sleepStep != EXPECTED_SLEEP_STEP || data.hash != EXPECTED_HASH ) + if ( data.sleepStep != RAGDOLL_SLEEP_STEP || data.hash != RAGDOLL_HASH ) { printf( " workers=%d sleepStep=%d hash=0x%08X\n", workerCount, data.sleepStep, data.hash ); } - ENSURE( data.sleepStep == EXPECTED_SLEEP_STEP ); - ENSURE( data.hash == EXPECTED_HASH ); + ENSURE( data.sleepStep == RAGDOLL_SLEEP_STEP ); + ENSURE( data.hash == RAGDOLL_HASH ); DestroyFallingRagdolls( &data ); @@ -113,13 +113,13 @@ static int CrossPlatformTest( void ) done = UpdateFallingRagdolls( worldId, &data ); } - if ( data.sleepStep != EXPECTED_SLEEP_STEP || data.hash != EXPECTED_HASH ) + if ( data.sleepStep != RAGDOLL_SLEEP_STEP || data.hash != RAGDOLL_HASH ) { printf( " cross-platform sleepStep=%d hash=0x%08X\n", data.sleepStep, data.hash ); } - ENSURE( data.sleepStep == EXPECTED_SLEEP_STEP ); - ENSURE( data.hash == EXPECTED_HASH ); + ENSURE( data.sleepStep == RAGDOLL_SLEEP_STEP ); + ENSURE( data.hash == RAGDOLL_HASH ); DestroyFallingRagdolls( &data ); diff --git a/test/test_recording.c b/test/test_recording.c index e877f3a..9307e55 100644 --- a/test/test_recording.c +++ b/test/test_recording.c @@ -448,13 +448,12 @@ static void RecTestDestroyDebugShape( void* userShape, void* userContext ) counters->destroyed += 1; } -static bool RecTestDrawShape( void* userShape, b3WorldTransform transform, b3HexColor color, void* context ) +static void RecTestDrawShape( void* userShape, b3WorldTransform transform, b3HexColor color, void* context ) { (void)userShape; (void)transform; (void)color; (void)context; - return true; } // b3World_Draw lazily fires createDebugShape for shapes entering the draw set, the same way the diff --git a/test/test_world.c b/test/test_world.c index 69d0f37..d5a3561 100644 --- a/test/test_world.c +++ b/test/test_world.c @@ -11,6 +11,7 @@ #include "box3d/math_functions.h" #include +#include // This is a simple example of building and running a simulation // using Box3D. Here we create a large ground box and a small dynamic @@ -617,6 +618,139 @@ static int TestCompoundHitEvents( void ) return 0; } +enum +{ + kChild0MaterialId = 101, + kChild1MaterialId = 202, + kProbeMaterialId = 999, +}; + +// No context pointer on mixing callbacks, so capture through file scope +static struct +{ + int callCount; + bool sawChild0; + bool sawChild1; + float mixedFriction; +} materialCapture; + +static float CaptureFrictionMix( float frictionA, uint64_t userMaterialIdA, float frictionB, uint64_t userMaterialIdB ) +{ + materialCapture.callCount += 1; + + if ( userMaterialIdA == kChild0MaterialId || userMaterialIdB == kChild0MaterialId ) + { + materialCapture.sawChild0 = true; + } + + if ( userMaterialIdA == kChild1MaterialId || userMaterialIdB == kChild1MaterialId ) + { + materialCapture.sawChild1 = true; + materialCapture.mixedFriction = sqrtf( frictionA * frictionB ); + } + + return sqrtf( frictionA * frictionB ); +} + +// Contact material selection must use the struck compound child's material, not entry 0 +// of the compound material table. Child 0 gets low friction, child 1 high friction, and a +// unit friction sphere strikes only child 1, so the mixing callback must see child 1's +// values. Covers sphere, capsule, and hull children. Issue #69. +static int TestCompoundContactMaterials( void ) +{ + b3SurfaceMaterial mat0 = b3DefaultSurfaceMaterial(); + mat0.friction = 0.04f; + mat0.userMaterialId = kChild0MaterialId; + + b3SurfaceMaterial mat1 = b3DefaultSurfaceMaterial(); + mat1.friction = 0.81f; + mat1.userMaterialId = kChild1MaterialId; + + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + + // Children at x = -3 and x = +3, all with their top face or surface at y = 0.5 + b3CompoundSphereDef spheres[2] = { + { .sphere = { { -3.0f, 0.0f, 0.0f }, 0.5f }, .material = mat0 }, + { .sphere = { { 3.0f, 0.0f, 0.0f }, 0.5f }, .material = mat1 }, + }; + + b3CompoundCapsuleDef capsules[2] = { + { .capsule = { { -3.0f, 0.0f, -0.5f }, { -3.0f, 0.0f, 0.5f }, 0.5f }, .material = mat0 }, + { .capsule = { { 3.0f, 0.0f, -0.5f }, { 3.0f, 0.0f, 0.5f }, 0.5f }, .material = mat1 }, + }; + + b3CompoundHullDef hulls[2] = { + { .hull = &box.base, .transform = { { -3.0f, 0.0f, 0.0f }, b3Quat_identity }, .material = mat0 }, + { .hull = &box.base, .transform = { { 3.0f, 0.0f, 0.0f }, b3Quat_identity }, .material = mat1 }, + }; + + for ( int childType = 0; childType < 3; ++childType ) + { + b3CompoundDef compoundDef = { 0 }; + if ( childType == 0 ) + { + compoundDef.spheres = spheres; + compoundDef.sphereCount = 2; + } + else if ( childType == 1 ) + { + compoundDef.capsules = capsules; + compoundDef.capsuleCount = 2; + } + else + { + compoundDef.hulls = hulls; + compoundDef.hullCount = 2; + } + + b3CompoundData* compound = b3CreateCompound( &compoundDef ); + ENSURE( compound != NULL ); + + memset( &materialCapture, 0, sizeof( materialCapture ) ); + + b3WorldDef worldDef = b3DefaultWorldDef(); + worldDef.frictionCallback = CaptureFrictionMix; + b3WorldId worldId = b3CreateWorld( &worldDef ); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_staticBody; + b3BodyId compoundBodyId = b3CreateBody( worldId, &bodyDef ); + b3ShapeDef compoundShapeDef = b3DefaultShapeDef(); + b3CreateBakedCompoundShape( compoundBodyId, &compoundShapeDef, compound ); + + // Sphere driven straight down onto child 1 + bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + bodyDef.gravityScale = 0.0f; + bodyDef.position = (b3Pos){ 3.0f, 3.0f, 0.0f }; + bodyDef.linearVelocity = (b3Vec3){ 0.0f, -30.0f, 0.0f }; + b3BodyId sphereBodyId = b3CreateBody( worldId, &bodyDef ); + b3ShapeDef sphereShapeDef = b3DefaultShapeDef(); + sphereShapeDef.density = 1.0f; + sphereShapeDef.baseMaterial.friction = 1.0f; + sphereShapeDef.baseMaterial.userMaterialId = kProbeMaterialId; + b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, 0.5f }; + b3CreateSphereShape( sphereBodyId, &sphereShapeDef, &sphere ); + + for ( int i = 0; i < 30; ++i ) + { + b3World_Step( worldId, 1.0f / 60.0f, 4 ); + } + + b3DestroyWorld( worldId ); + b3DestroyCompound( compound ); + + ENSURE( materialCapture.callCount > 0 ); + // The pre-fix code fed material table entry 0 to the mixing callback for every child + ENSURE( materialCapture.sawChild0 == false ); + ENSURE( materialCapture.sawChild1 == true ); + // sqrt(0.81 * 1.0) + ENSURE_SMALL( materialCapture.mixedFriction - 0.9f, 1e-5f ); + } + + return 0; +} + static int TestSetWorkerCount( void ) { b3WorldDef worldDef = b3DefaultWorldDef(); @@ -1038,6 +1172,7 @@ int WorldTest( void ) RUN_SUBTEST( TestContactEvents ); RUN_SUBTEST( TestHitEvents ); RUN_SUBTEST( TestCompoundHitEvents ); + RUN_SUBTEST( TestCompoundContactMaterials ); RUN_SUBTEST( TestOverflowColorPile ); RUN_SUBTEST( SetBulletDriftTest ); RUN_SUBTEST( EnableSleepFlagSyncTest );