diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..1121938 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @erincatto diff --git a/include/box3d/collision.h b/include/box3d/collision.h index 47a5434..cb99349 100644 --- a/include/box3d/collision.h +++ b/include/box3d/collision.h @@ -201,7 +201,7 @@ B3_INLINE const float* b3GetHullSoaVertices( const b3HullData* hull ) /// Get read only SOA unit normal vectors. This is an array of normals with all x values, /// y values, and z values as separate arrays. The array lengths are padded to -/// a multiple of 4. The padded values are repeats of the first value. +/// a multiple of 4. The padded values are 0. B3_INLINE const float* b3GetHullSoaNormals( const b3HullData* hull ) { if ( hull->soaNormalOffset == 0 ) @@ -221,6 +221,9 @@ B3_API b3HullData* b3CreateCone( float height, float radius1, float radius2, int /// Create a rock shaped hull. B3_API b3HullData* b3CreateRock( float radius ); +// Hull of 32 pseudo random points on a sphere. From the convex pile hull in PEEL. +B3_API b3HullData* b3CreateComplexHull( float radius ); + /// Create a generic convex hull. This can fail if B3_MAX_HULL_VERTICES, B3_MAX_HULL_FACES, /// or B3_MAX_HULL_EDGES is exceeded. B3_API b3HullData* b3CreateHull( const b3Vec3* points, int pointCount, int maxVertexCount ); diff --git a/samples/sample_manifold.cpp b/samples/sample_manifold.cpp index ba366f5..12d77b2 100644 --- a/samples/sample_manifold.cpp +++ b/samples/sample_manifold.cpp @@ -10,6 +10,16 @@ #include +// Trackball about the camera axes so the near side of the shape follows the cursor regardless of the +// shape or camera orientation. A drag across the window height is a full turn. +static b3Quat DragRotation( const Camera* camera, b3Quat q, float dx, float dy ) +{ + float scale = 2.0f * B3_PI / b3MaxFloat( (float)camera->m_height, 1.0f ); + b3Quat yaw = b3MakeQuatFromAxisAngle( camera->GetUp(), scale * dx ); + b3Quat pitch = b3MakeQuatFromAxisAngle( camera->GetRight(), scale * dy ); + return b3NormalizeQuat( b3MulQuat( b3MulQuat( pitch, yaw ), q ) ); +} + class Manifold : public Sample { public: @@ -39,10 +49,10 @@ public: m_satCache = {}; m_manualFeature = 0; m_baseTranslation = b3Pos_zero; - m_baseQuaternion = b3Quat_identity; - m_baseX = 0; - m_baseY = 0; + m_lastX = 0.0f; + m_lastY = 0.0f; m_origin = b3Pos_zero; + m_drawPoints = true; m_useCache = false; m_tracking = false; m_rotating = false; @@ -53,9 +63,9 @@ public: DrawTextLine( "origin: %g %g %g", m_origin.x, m_origin.y, m_origin.z ); DrawTextLine( "count = %d", m_manifold.pointCount ); - DrawAxes( b3WorldTransform_identity, 1.0f ); + DrawAxes( b3WorldTransform_identity, 0.5f ); - if ( m_manifold.pointCount == 0 ) + if ( m_manifold.pointCount == 0 || m_drawPoints == false ) { return; } @@ -107,6 +117,8 @@ public: ImGui::RadioButton( "edgePair", &m_manualFeature, 3 ); } + ImGui::Checkbox( "Draw Points", &m_drawPoints ); + return true; } @@ -116,9 +128,8 @@ public: { if ( modifiers & MOD_SHIFT ) { - m_baseX = p.x; - m_baseY = p.y; - m_baseQuaternion = m_transformB.q; + m_lastX = p.x; + m_lastY = p.y; m_rotating = true; } else @@ -148,12 +159,9 @@ public: if ( m_rotating ) { - int x = p.x; - int y = p.y; - - b3Quat qx = b3MakeQuatFromAxisAngle( b3Vec3_axisY, 0.01f * ( x - m_baseX ) ); - b3Quat qz = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, 0.01f * ( y - m_baseY ) ); - m_transformB.q = b3NormalizeQuat( b3MulQuat( m_baseQuaternion, b3MulQuat( qx, qz ) ) ); + m_transformB.q = DragRotation( m_camera, m_transformB.q, p.x - m_lastX, p.y - m_lastY ); + m_lastX = p.x; + m_lastY = p.y; } } @@ -163,16 +171,16 @@ public: b3WorldTransform m_transformA; b3WorldTransform m_transformB; b3Pos m_baseTranslation; - b3Quat m_baseQuaternion; b3Pos m_origin; b3SimplexCache m_simplexCache; b3SATCache m_satCache; int m_manualFeature; - int m_baseX; - int m_baseY; + float m_lastX; + float m_lastY; bool m_useCache; bool m_tracking; bool m_rotating; + bool m_drawPoints; }; class TriangleManifold : public Sample @@ -203,9 +211,8 @@ public: m_simplexCache = {}; m_satCache = {}; m_baseTranslation = b3Pos_zero; - m_baseQuaternion = b3Quat_identity; - m_baseX = 0; - m_baseY = 0; + m_lastX = 0.0f; + m_lastY = 0.0f; m_origin = b3Pos_zero; m_useCache = false; m_tracking = false; @@ -293,9 +300,8 @@ public: { if ( modifiers & MOD_SHIFT ) { - m_baseX = p.x; - m_baseY = p.y; - m_baseQuaternion = m_transformB.q; + m_lastX = p.x; + m_lastY = p.y; m_rotating = true; } else @@ -325,12 +331,9 @@ public: if ( m_rotating ) { - int x = p.x; - int y = p.y; - - b3Quat qx = b3MakeQuatFromAxisAngle( b3Vec3_axisY, 0.01f * ( x - m_baseX ) ); - b3Quat qz = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, 0.01f * ( y - m_baseY ) ); - m_transformB.q = b3NormalizeQuat( b3MulQuat( m_baseQuaternion, b3MulQuat( qx, qz ) ) ); + m_transformB.q = DragRotation( m_camera, m_transformB.q, p.x - m_lastX, p.y - m_lastY ); + m_lastX = p.x; + m_lastY = p.y; } } @@ -346,13 +349,12 @@ public: b3Vec3 m_triangle[3] = {}; b3Pos m_baseTranslation; - b3Quat m_baseQuaternion; b3Pos m_origin; b3SimplexCache m_simplexCache; b3SATCache m_satCache; int m_manualFeature; - int m_baseX; - int m_baseY; + float m_lastX; + float m_lastY; bool m_useCache; bool m_tracking; bool m_rotating; @@ -809,6 +811,939 @@ public: static int sampleCollideHulls = RegisterSample( "Manifold", "Hull vs Hull", HullAndHull::Create ); +// Shows the candidate axes culled by the inscribed sphere bound in the separating axis test. No axis n +// can separate the hulls by more than dot(n, centerB - centerA) - innerRadiusA - innerRadiusB, so any +// face or edge whose bound is below the best separation found so far is skipped. This recomputes the +// culling decisions of b3ComputeSeparatingAxis from public hull data and must be kept in sync with it. +class HullCulling : public Manifold +{ +public: + enum FeatureState + { + e_unreached = 0, + e_culled, + e_tested, + }; + + explicit HullCulling( SampleContext* context ) + : Manifold( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 20.0f, 20.0f, 14.0f, { 0.0f, 1.8f, 0.0f } ); + } + + m_useCylinders = false; + m_cylinderHeight = 2.0f; + m_cylinderRadius = 2.0f; + m_cylinderSides = 32; + m_hullA = nullptr; + m_hullB = nullptr; + CreateHulls(); + + m_transformA = { { 0.0f, 0.0f, 0.0f }, b3Quat_identity }; + m_transformB = { { 0.4f, 3.6f, 0.2f }, b3MakeQuatFromAxisAngle( b3Normalize( { 1.0f, 0.0f, 1.0f } ), 0.3f ) }; + + m_showSpheres = true; + m_showCulled = true; + m_showNormals = true; + ResetCounts(); + } + + ~HullCulling() override + { + b3DestroyHull( m_hullA ); + b3DestroyHull( m_hullB ); + } + + void CreateHulls() + { + if ( m_hullA != nullptr ) + { + b3DestroyHull( m_hullA ); + b3DestroyHull( m_hullB ); + } + + if ( m_useCylinders ) + { + float yOffset = -0.5f * m_cylinderHeight; + m_hullA = b3CreateCylinder( m_cylinderHeight, m_cylinderRadius, yOffset, m_cylinderSides ); + m_hullB = b3CreateCylinder( m_cylinderHeight, m_cylinderRadius, yOffset, m_cylinderSides ); + } + else + { + m_hullA = b3CreateComplexHull( 2.0f ); + m_hullB = b3CreateComplexHull( 2.0f ); + } + } + + bool DrawControls() override + { + Manifold::DrawControls(); + + ImGui::Checkbox( "Inscribed spheres", &m_showSpheres ); + ImGui::Checkbox( "Culled features", &m_showCulled ); + ImGui::Checkbox( "Face normals", &m_showNormals ); + + bool rebuild = ImGui::Checkbox( "Cylinders", &m_useCylinders ); + if ( m_useCylinders ) + { + rebuild |= ImGui::SliderFloat( "Height", &m_cylinderHeight, 0.1f, 8.0f, "%.2f" ); + rebuild |= ImGui::SliderFloat( "Radius", &m_cylinderRadius, 0.1f, 4.0f, "%.2f" ); + rebuild |= ImGui::SliderInt( "Sides", &m_cylinderSides, 3, 32 ); + } + + if ( rebuild ) + { + m_cylinderHeight = b3ClampFloat( m_cylinderHeight, 0.1f, 8.0f ); + m_cylinderRadius = b3ClampFloat( m_cylinderRadius, 0.1f, 4.0f ); + m_cylinderSides = b3ClampInt( m_cylinderSides, 3, 32 ); + CreateHulls(); + } + + return true; + } + + void ResetCounts() + { + memset( m_faceStateA, 0, sizeof( m_faceStateA ) ); + memset( m_faceStateB, 0, sizeof( m_faceStateB ) ); + memset( m_edgeStateA, 0, sizeof( m_edgeStateA ) ); + memset( m_edgeStateB, 0, sizeof( m_edgeStateB ) ); + m_seedA = 0; + m_seedB = 0; + m_keptEdgeCountA = 0; + m_keptEdgeCountB = 0; + m_separationA = -FLT_MAX; + m_separationB = -FLT_MAX; + m_gap = 0.0f; + m_separatedFeature = b3_invalidAxis; + } + + // Face of A against the vertices of B, in frame A + static float FaceSeparationA( const b3HullData* hullA, const b3HullData* hullB, b3Transform transformBtoA, int faceIndex ) + { + b3Plane plane = b3GetHullPlanes( hullA )[faceIndex]; + const b3Vec3* points = b3GetHullPoints( hullB ); + float separation = FLT_MAX; + for ( int i = 0; i < hullB->vertexCount; ++i ) + { + b3Vec3 point = b3TransformPoint( transformBtoA, points[i] ); + separation = b3MinFloat( separation, b3Dot( plane.normal, point ) - plane.offset ); + } + return separation; + } + + // Face of B against the vertices of A, in frame B + static float FaceSeparationB( const b3HullData* hullA, const b3HullData* hullB, b3Transform transformBtoA, int faceIndex ) + { + b3Plane plane = b3GetHullPlanes( hullB )[faceIndex]; + const b3Vec3* points = b3GetHullPoints( hullA ); + float separation = FLT_MAX; + for ( int i = 0; i < hullA->vertexCount; ++i ) + { + b3Vec3 point = b3InvTransformPoint( transformBtoA, points[i] ); + separation = b3MinFloat( separation, b3Dot( plane.normal, point ) - plane.offset ); + } + return separation; + } + + // Mirrors b3ArcCanReach + static bool ArcCanReach( float a, float b, float c, float length, float bound ) + { + const float parallelTolerance = 1.0e-4f; + float s = 1.0f - c * c; + float t = a * a + b * b - 2.0f * a * b * c; + bool endpoint = b3MaxFloat( a, b ) >= bound; + bool interior = + a >= c * b && b >= c * a && length >= bound && ( bound <= 0.0f || s < parallelTolerance || t >= bound * bound * s ); + return endpoint || interior; + } + + // Mirrors the culling in b3ComputeSeparatingAxis with early return enabled + void ComputeCulling( b3Transform transformBtoA ) + { + ResetCounts(); + + const b3HullData* hullA = m_hullA; + const b3HullData* hullB = m_hullB; + const b3Plane* planesA = b3GetHullPlanes( hullA ); + const b3Plane* planesB = b3GetHullPlanes( hullB ); + float speculativeDistance = B3_SPECULATIVE_DISTANCE; + + b3Vec3 deltaCenter = b3Sub( b3TransformPoint( transformBtoA, hullB->center ), hullA->center ); + float centerDistance = b3Length( deltaCenter ); + float radius = hullA->innerRadius + hullB->innerRadius; + float radiusBound = radius - ( B3_LINEAR_SLOP + 0.001f * ( centerDistance + radius ) ); + m_gap = centerDistance - radius; + + float dotA[B3_MAX_HULL_FACES]; + for ( int i = 0; i < hullA->faceCount; ++i ) + { + dotA[i] = b3Dot( planesA[i].normal, deltaCenter ); + m_seedA = dotA[i] > dotA[m_seedA] ? i : m_seedA; + } + + float floorA = b3MinFloat( FaceSeparationA( hullA, hullB, transformBtoA, m_seedA ), speculativeDistance ); + for ( int i = 0; i < hullA->faceCount; ++i ) + { + if ( dotA[i] - radiusBound < b3MaxFloat( floorA, m_separationA ) ) + { + m_faceStateA[i] = e_culled; + continue; + } + + m_faceStateA[i] = e_tested; + float separation = FaceSeparationA( hullA, hullB, transformBtoA, i ); + if ( separation > m_separationA ) + { + m_separationA = separation; + if ( separation > speculativeDistance ) + { + m_separatedFeature = b3_faceAxisA; + return; + } + } + } + + b3Vec3 deltaCenterB = b3Neg( b3InvRotateVector( transformBtoA.q, deltaCenter ) ); + float dotB[B3_MAX_HULL_FACES]; + for ( int i = 0; i < hullB->faceCount; ++i ) + { + dotB[i] = b3Dot( planesB[i].normal, deltaCenterB ); + m_seedB = dotB[i] > dotB[m_seedB] ? i : m_seedB; + } + + float floorB = b3MaxFloat( FaceSeparationB( hullA, hullB, transformBtoA, m_seedB ), m_separationA ); + floorB = b3MinFloat( floorB, speculativeDistance ); + for ( int i = 0; i < hullB->faceCount; ++i ) + { + if ( dotB[i] - radiusBound < b3MaxFloat( floorB, m_separationB ) ) + { + m_faceStateB[i] = e_culled; + continue; + } + + m_faceStateB[i] = e_tested; + float separation = FaceSeparationB( hullA, hullB, transformBtoA, i ); + if ( separation > m_separationB ) + { + m_separationB = separation; + if ( separation > speculativeDistance ) + { + m_separatedFeature = b3_faceAxisB; + return; + } + } + } + + float edgeBound = b3MaxFloat( m_separationA, m_separationB ) + radiusBound; + + const b3HullHalfEdge* edgesA = b3GetHullEdges( hullA ); + for ( int i = 0; i < hullA->edgeCount; i += 2 ) + { + int face1 = edgesA[i].face; + int face2 = edgesA[i + 1].face; + float c = b3Dot( planesA[face1].normal, planesA[face2].normal ); + bool kept = ArcCanReach( dotA[face1], dotA[face2], c, centerDistance, edgeBound ); + m_edgeStateA[i / 2] = kept ? e_tested : e_culled; + m_keptEdgeCountA += kept ? 1 : 0; + } + + const b3HullHalfEdge* edgesB = b3GetHullEdges( hullB ); + for ( int i = 0; i < hullB->edgeCount; i += 2 ) + { + int face1 = edgesB[i].face; + int face2 = edgesB[i + 1].face; + float c = b3Dot( planesB[face1].normal, planesB[face2].normal ); + bool kept = ArcCanReach( dotB[face1], dotB[face2], c, centerDistance, edgeBound ); + m_edgeStateB[i / 2] = kept ? e_tested : e_culled; + m_keptEdgeCountB += kept ? 1 : 0; + } + } + + void Step() override + { + // Clear the cache so every step runs the full separating axis test + m_satCache = {}; + b3Transform transformBtoA = b3InvMulWorldTransforms( m_transformA, m_transformB ); + b3CollideHulls( &m_manifold, m_pointCapacity, m_hullA, m_hullB, transformBtoA, &m_satCache ); + ComputeCulling( transformBtoA ); + } + + static int CountState( const uint8_t* states, int count, FeatureState state ) + { + int n = 0; + for ( int i = 0; i < count; ++i ) + { + n += states[i] == state ? 1 : 0; + } + return n; + } + + void DrawEdges( b3WorldTransform transform, const b3HullData* hull, const uint8_t* states, Vec4 keptColor ) + { + const b3HullHalfEdge* edges = b3GetHullEdges( hull ); + const b3Vec3* points = b3GetHullPoints( hull ); + for ( int i = 0; i < hull->edgeCount; i += 2 ) + { + b3Pos p1 = b3TransformWorldPoint( transform, points[edges[i].origin] ); + b3Pos p2 = b3TransformWorldPoint( transform, points[edges[i + 1].origin] ); + uint8_t state = states[i / 2]; + if ( state == e_tested ) + { + DrawLineEx( p1, p2, keptColor, 4.0f, OVERLAY_THICKNESS_PIXELS, OVERLAY_OCCLUSION_DIM ); + } + else if ( state == e_culled && m_showCulled ) + { + DrawLine( p1, p2, MakeColor( b3_colorSlateGray ) ); + } + else if ( state == e_unreached ) + { + DrawLineEx( p1, p2, MakeColor( b3_colorDimGray ), 1.0f, OVERLAY_THICKNESS_PIXELS, OVERLAY_OCCLUSION_DASHED ); + } + } + } + + void DrawFaceNormals( b3WorldTransform transform, const b3HullData* hull, const uint8_t* states, int seed, Vec4 testedColor ) + { + const b3HullFace* faces = b3GetHullFaces( hull ); + const b3HullHalfEdge* edges = b3GetHullEdges( hull ); + const b3Plane* planes = b3GetHullPlanes( hull ); + const b3Vec3* points = b3GetHullPoints( hull ); + float length = 0.4f * b3GetLengthUnitsPerMeter(); + + for ( int i = 0; i < hull->faceCount; ++i ) + { + uint8_t state = states[i]; + if ( state == e_unreached || ( state == e_culled && m_showCulled == false ) ) + { + continue; + } + + b3Vec3 centroid = b3Vec3_zero; + int count = 0; + int edgeIndex = faces[i].edge; + do + { + centroid = b3Add( centroid, points[edges[edgeIndex].origin] ); + count += 1; + edgeIndex = edges[edgeIndex].next; + } + while ( edgeIndex != faces[i].edge ); + centroid = b3MulSV( 1.0f / (float)count, centroid ); + + b3Pos p1 = b3TransformWorldPoint( transform, centroid ); + b3Pos p2 = b3TransformWorldPoint( transform, b3MulAdd( centroid, length, planes[i].normal ) ); + + if ( i == seed ) + { + DrawArrowEx( p1, p2, MakeColor( b3_colorGold ), 3.0f, OVERLAY_THICKNESS_PIXELS, OVERLAY_OCCLUSION_DIM, 0.25f ); + } + else if ( state == e_tested ) + { + DrawArrowEx( p1, p2, testedColor, 2.0f, OVERLAY_THICKNESS_PIXELS, OVERLAY_OCCLUSION_DIM, 0.25f ); + } + else + { + DrawLine( p1, p2, MakeColor( b3_colorSlateGray ) ); + } + } + } + + void Render() override + { + const b3HullData* hullA = m_hullA; + const b3HullData* hullB = m_hullB; + + DrawEdges( m_transformA, hullA, m_edgeStateA, MakeColor( b3_colorOrange ) ); + DrawEdges( m_transformB, hullB, m_edgeStateB, MakeColor( b3_colorDeepSkyBlue ) ); + + if ( m_showNormals ) + { + DrawFaceNormals( m_transformA, hullA, m_faceStateA, m_seedA, MakeColor( b3_colorOrange ) ); + DrawFaceNormals( m_transformB, hullB, m_faceStateB, m_seedB, MakeColor( b3_colorDeepSkyBlue ) ); + } + + b3Pos centerA = b3TransformWorldPoint( m_transformA, hullA->center ); + b3Pos centerB = b3TransformWorldPoint( m_transformB, hullB->center ); + DrawLine( centerA, centerB, MakeColor( b3_colorWhite ) ); + + if ( m_showSpheres ) + { + b3Sphere sphereA = { hullA->center, hullA->innerRadius }; + b3Sphere sphereB = { hullB->center, hullB->innerRadius }; + DrawWireSphere( m_transformA, &sphereA, 32, MakeColor( b3_colorOrange ) ); + DrawWireSphere( m_transformB, &sphereB, 32, MakeColor( b3_colorDeepSkyBlue ) ); + } + + int faceCountA = hullA->faceCount; + int faceCountB = hullB->faceCount; + int edgeCountA = hullA->edgeCount / 2; + int edgeCountB = hullB->edgeCount / 2; + int testedA = CountState( m_faceStateA, faceCountA, e_tested ); + int testedB = CountState( m_faceStateB, faceCountB, e_tested ); + int culledA = CountState( m_faceStateA, faceCountA, e_culled ); + int culledB = CountState( m_faceStateB, faceCountB, e_culled ); + bool edgesReached = m_separatedFeature == b3_invalidAxis; + int seedCount = m_separatedFeature == b3_faceAxisA ? 1 : 2; + + DrawTextLine( "drag to move B, shift + drag to rotate B" ); + DrawTextLine( "vertices %d, faces %d, edges %d", hullA->vertexCount, faceCountA, edgeCountA ); + DrawTextLine( "|d| - rA - rB = %.3f", m_gap ); + DrawTextLine( "faces A: tested %d, culled %d of %d, best separation %.4f", testedA, culledA, faceCountA, m_separationA ); + + if ( m_separatedFeature == b3_faceAxisA ) + { + DrawTextLine( "separated by face A, B faces and edges not reached" ); + } + else + { + DrawTextLine( "faces B: tested %d, culled %d of %d, best separation %.4f", testedB, culledB, faceCountB, + m_separationB ); + } + + if ( m_separatedFeature == b3_faceAxisB ) + { + DrawTextLine( "separated by face B, edges not reached" ); + } + + DrawTextLine( "support queries: %d of %d (including %d seed)", testedA + testedB + seedCount, faceCountA + faceCountB, + seedCount ); + + if ( edgesReached ) + { + int pairCount = m_keptEdgeCountA * m_keptEdgeCountB; + int totalPairCount = edgeCountA * edgeCountB; + DrawTextLine( "edges kept: A %d of %d, B %d of %d", m_keptEdgeCountA, edgeCountA, m_keptEdgeCountB, edgeCountB ); + DrawTextLine( "edge pairs: %d of %d (%.1f%%)", pairCount, totalPairCount, 100.0f * pairCount / totalPairCount ); + } + + DrawTextLine( "SAT type: %d", m_satCache.type ); + + Manifold::Render(); + } + + static Sample* Create( SampleContext* context ) + { + return new HullCulling( context ); + } + + b3HullData* m_hullA; + b3HullData* m_hullB; + uint8_t m_faceStateA[B3_MAX_HULL_FACES]; + uint8_t m_faceStateB[B3_MAX_HULL_FACES]; + uint8_t m_edgeStateA[B3_MAX_HULL_EDGES]; + uint8_t m_edgeStateB[B3_MAX_HULL_EDGES]; + int m_seedA; + int m_seedB; + int m_keptEdgeCountA; + int m_keptEdgeCountB; + float m_separationA; + float m_separationB; + float m_gap; + b3SeparatingFeature m_separatedFeature; + float m_cylinderHeight; + float m_cylinderRadius; + int m_cylinderSides; + bool m_useCylinders; + bool m_showSpheres; + bool m_showCulled; + bool m_showNormals; +}; + +static int sampleHullCulling = RegisterSample( "Manifold", "Hull Culling", HullCulling::Create ); + +// Shows that an edge pair can win the separating axis test even when the direction between the hull +// centers peaks outside the Gauss map arc (wedge) of one of its edges. The inscribed sphere bound of such +// an edge peaks at a face normal at the end of its arc, yet the edge axis beats the real separation of +// those faces. So outside wedge edges can only be culled by their sphere bound, not by the face results. +// Everything here is brute force over all faces and all edge pairs, independent of the pruning in the SAT. +class EdgeAxisWedge : public Manifold +{ +public: + struct EdgeAxis + { + b3Vec3 normal; + float separation; + int edgeA; + int edgeB; + }; + + // Gauss map arc of one edge in frame A, with the peak of dot(n, d) on its great circle + struct Arc + { + b3Vec3 u; + b3Vec3 v; + b3Vec3 peak; + float a; + float b; + float c; + float separationU; + float separationV; + + // Angle from the peak to the nearest end of the arc, negative when the peak is on the arc + float outsideDegrees; + bool inside; + }; + + explicit EdgeAxisWedge( SampleContext* context ) + : Manifold( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 0.0f, 15.0f, 22.0f, { -4.5f, 1.0f, 0.0f } ); + } + + m_transformA = { { 0.0f, 0.0f, 0.0f }, b3Quat_identity }; + m_transformB = { { 0.0f, 3.6f, 0.0f }, b3Quat_identity }; + + m_gaussCenter = { -10.0f, 1.0f, 0.0f }; + m_gaussRadius = 2.0f; + m_searchCount = 0; + m_searchFound = false; + m_hullType = e_slab; + m_createdHull = nullptr; + + // Start with an example + SetHull( m_hullType ); + } + + ~EdgeAxisWedge() override + { + if ( m_createdHull != nullptr ) + { + b3DestroyHull( m_createdHull ); + } + } + + enum HullType + { + e_slab = 0, + e_tetrahedron, + e_complex, + }; + + // Both hulls are the same shape + void SetHull( int type ) + { + if ( m_createdHull != nullptr ) + { + b3DestroyHull( m_createdHull ); + m_createdHull = nullptr; + } + + if ( type == e_slab ) + { + m_box = b3MakeBoxHull( 2.0f, 0.25f, 1.0f ); + m_hullA = &m_box.base; + } + else if ( type == e_tetrahedron ) + { + b3Vec3 points[4] = { { 1.0f, 1.0f, 1.0f }, { 1.0f, -1.0f, -1.0f }, { -1.0f, 1.0f, -1.0f }, { -1.0f, -1.0f, 1.0f } }; + m_createdHull = b3CreateHull( points, 4, 4 ); + m_hullA = m_createdHull; + } + else + { + m_createdHull = b3CreateComplexHull( 2.0f ); + m_hullA = m_createdHull; + } + + m_hullB = m_hullA; + m_hullType = type; + m_seed = 12345; + Search(); + } + + float RandomFloat() + { + m_seed = m_seed * 1664525u + 1013904223u; + return (float)( m_seed >> 8 ) / 16777216.0f; + } + + b3Vec3 RandomDirection() + { + b3Vec3 v; + float lengthSquared; + do + { + v = { 2.0f * RandomFloat() - 1.0f, 2.0f * RandomFloat() - 1.0f, 2.0f * RandomFloat() - 1.0f }; + lengthSquared = b3Dot( v, v ); + } + while ( lengthSquared > 1.0f || lengthSquared < 0.01f ); + + return b3Normalize( v ); + } + + // Mirrors the Gauss map test and edge axis of the scalar path in b3ComputeSeparatingAxis, without pruning + static EdgeAxis FindBestEdgeAxis( const b3HullData* hullA, const b3HullData* hullB, b3Transform transformBtoA ) + { + const b3HullHalfEdge* edgesA = b3GetHullEdges( hullA ); + const b3Plane* planesA = b3GetHullPlanes( hullA ); + const b3Vec3* pointsA = b3GetHullPoints( hullA ); + const b3HullHalfEdge* edgesB = b3GetHullEdges( hullB ); + const b3Plane* planesB = b3GetHullPlanes( hullB ); + const b3Vec3* pointsB = b3GetHullPoints( hullB ); + + const float eps = -0.0001f; + float squaredTolerance = B3_PARALLEL_EDGE_TOL * B3_PARALLEL_EDGE_TOL; + + EdgeAxis best = { b3Vec3_zero, -FLT_MAX, B3_NULL_INDEX, B3_NULL_INDEX }; + + for ( int j = 0; j < hullB->edgeCount; j += 2 ) + { + // B face normals and vertices in frame A, negated + b3Vec3 C = b3Neg( b3RotateVector( transformBtoA.q, planesB[edgesB[j].face].normal ) ); + b3Vec3 D = b3Neg( b3RotateVector( transformBtoA.q, planesB[edgesB[j + 1].face].normal ) ); + b3Vec3 bv0 = b3Neg( b3TransformPoint( transformBtoA, pointsB[edgesB[j].origin] ) ); + b3Vec3 bv1 = b3Neg( b3TransformPoint( transformBtoA, pointsB[edgesB[j + 1].origin] ) ); + b3Vec3 DC = b3Sub( bv1, bv0 ); + + for ( int i = 0; i < hullA->edgeCount; i += 2 ) + { + b3Vec3 n0 = planesA[edgesA[i].face].normal; + b3Vec3 n1 = planesA[edgesA[i + 1].face].normal; + b3Vec3 av0 = pointsA[edgesA[i].origin]; + b3Vec3 edge = b3Sub( pointsA[edgesA[i + 1].origin], av0 ); + + float CBA = b3Dot( C, edge ); + float DBA = b3Dot( D, edge ); + float ADC = b3Dot( n0, DC ); + float BDC = b3Dot( n1, DC ); + if ( CBA * DBA >= eps || ADC * BDC >= eps || CBA * BDC >= eps ) + { + continue; + } + + if ( b3MaxFloat( CBA * CBA, DBA * DBA ) <= squaredTolerance * b3Dot( edge, edge ) ) + { + continue; + } + + float t = -CBA / ( DBA - CBA ); + b3Vec3 normal = b3Normalize( b3MulAdd( C, t, b3Sub( D, C ) ) ); + float separation = -b3Dot( normal, b3Add( av0, bv0 ) ); + if ( separation > best.separation ) + { + best = { normal, separation, i, j }; + } + } + } + + return best; + } + + // The peak of dot(n, d) over the great circle through u and v, and whether it lies on the arc + static Arc MakeArc( b3Vec3 u, b3Vec3 v, b3Vec3 d, float separationU, float separationV ) + { + Arc arc; + arc.u = u; + arc.v = v; + arc.a = b3Dot( u, d ); + arc.b = b3Dot( v, d ); + arc.c = b3Dot( u, v ); + arc.inside = arc.a >= arc.c * arc.b && arc.b >= arc.c * arc.a; + arc.separationU = separationU; + arc.separationV = separationV; + + b3Vec3 axis = b3Normalize( b3Cross( u, v ) ); + b3Vec3 inPlane = b3MulSub( d, b3Dot( d, axis ), axis ); + arc.peak = b3LengthSquared( inPlane ) > 1.0e-12f ? b3Normalize( inPlane ) : u; + + float arcAngle = acosf( b3ClampFloat( arc.c, -1.0f, 1.0f ) ); + float angleU = acosf( b3ClampFloat( b3Dot( u, arc.peak ), -1.0f, 1.0f ) ); + float angleV = acosf( b3ClampFloat( b3Dot( v, arc.peak ), -1.0f, 1.0f ) ); + float nearest = b3MinFloat( angleU, angleV ) * 180.0f / B3_PI; + arc.outsideDegrees = ( angleU <= arcAngle && angleV <= arcAngle ) ? -nearest : nearest; + return arc; + } + + float MaxSeparation( b3Transform transformBtoA, float* faceSeparationA, float* faceSeparationB, EdgeAxis* edgeAxis ) const + { + float separationA = -FLT_MAX; + for ( int i = 0; i < m_hullA->faceCount; ++i ) + { + separationA = b3MaxFloat( separationA, HullCulling::FaceSeparationA( m_hullA, m_hullB, transformBtoA, i ) ); + } + + float separationB = -FLT_MAX; + for ( int i = 0; i < m_hullB->faceCount; ++i ) + { + separationB = b3MaxFloat( separationB, HullCulling::FaceSeparationB( m_hullA, m_hullB, transformBtoA, i ) ); + } + + EdgeAxis edge = FindBestEdgeAxis( m_hullA, m_hullB, transformBtoA ); + + if ( faceSeparationA != nullptr ) + { + *faceSeparationA = separationA; + *faceSeparationB = separationB; + *edgeAxis = edge; + } + + return b3MaxFloat( edge.separation, b3MaxFloat( separationA, separationB ) ); + } + + // Random poses placed just into contact until an edge axis wins with an edge outside its wedge + void Search() + { + m_searchFound = false; + m_searchCount = 0; + + for ( int trial = 0; trial < 500 && m_searchFound == false; ++trial ) + { + m_searchCount += 1; + + b3Vec3 direction = RandomDirection(); + b3Vec3 axis = RandomDirection(); + float angle = 2.0f * B3_PI * RandomFloat(); + b3Quat rotation = b3MakeQuatFromAxisAngle( axis, angle ); + + // Bisect on the center distance to reach a slight overlap + float target = -0.02f * b3GetLengthUnitsPerMeter(); + float lower = 0.0f; + float upper = 1.1f * ( b3Length( b3AABB_Extents( m_hullA->aabb ) ) + b3Length( b3AABB_Extents( m_hullB->aabb ) ) ); + for ( int iteration = 0; iteration < 24; ++iteration ) + { + float mid = 0.5f * ( lower + upper ); + b3Transform transform = { b3MulSV( mid, direction ), rotation }; + if ( MaxSeparation( transform, nullptr, nullptr, nullptr ) < target ) + { + lower = mid; + } + else + { + upper = mid; + } + } + + m_transformB = { m_transformA.p + b3MulSV( upper, direction ), rotation }; + Compute(); + + // Only accept clear examples, well outside the wedge with a clear edge win + float margin = m_edge.separation - b3MaxFloat( m_faceSeparationA, m_faceSeparationB ); + float outside = b3MaxFloat( m_arcA.outsideDegrees, m_arcB.outsideDegrees ); + m_searchFound = m_edgeWins && outside >= 10.0f && margin >= 0.02f * b3GetLengthUnitsPerMeter(); + } + } + + void Compute() + { + b3Transform transformBtoA = b3InvMulWorldTransforms( m_transformA, m_transformB ); + MaxSeparation( transformBtoA, &m_faceSeparationA, &m_faceSeparationB, &m_edge ); + m_edgeWins = m_edge.edgeA != B3_NULL_INDEX && m_edge.separation > b3MaxFloat( m_faceSeparationA, m_faceSeparationB ); + + m_centerOffset = b3Sub( b3TransformPoint( transformBtoA, m_hullB->center ), m_hullA->center ); + m_radius = m_hullA->innerRadius + m_hullB->innerRadius; + + if ( m_edge.edgeA == B3_NULL_INDEX ) + { + return; + } + + const b3HullHalfEdge* edgesA = b3GetHullEdges( m_hullA ); + const b3Plane* planesA = b3GetHullPlanes( m_hullA ); + int faceA1 = edgesA[m_edge.edgeA].face; + int faceA2 = edgesA[m_edge.edgeA + 1].face; + m_arcA = MakeArc( planesA[faceA1].normal, planesA[faceA2].normal, m_centerOffset, + HullCulling::FaceSeparationA( m_hullA, m_hullB, transformBtoA, faceA1 ), + HullCulling::FaceSeparationA( m_hullA, m_hullB, transformBtoA, faceA2 ) ); + + const b3HullHalfEdge* edgesB = b3GetHullEdges( m_hullB ); + const b3Plane* planesB = b3GetHullPlanes( m_hullB ); + int faceB1 = edgesB[m_edge.edgeB].face; + int faceB2 = edgesB[m_edge.edgeB + 1].face; + b3Vec3 C = b3Neg( b3RotateVector( transformBtoA.q, planesB[faceB1].normal ) ); + b3Vec3 D = b3Neg( b3RotateVector( transformBtoA.q, planesB[faceB2].normal ) ); + m_arcB = MakeArc( C, D, m_centerOffset, HullCulling::FaceSeparationB( m_hullA, m_hullB, transformBtoA, faceB1 ), + HullCulling::FaceSeparationB( m_hullA, m_hullB, transformBtoA, faceB2 ) ); + } + + bool DrawControls() override + { + const char* hullNames[] = { "Slab", "Tetrahedron", "Complex Hull" }; + int hullType = m_hullType; + if ( ImGui::Combo( "Hull", &hullType, hullNames, IM_ARRAYSIZE( hullNames ) ) ) + { + SetHull( hullType ); + } + + if ( ImGui::Button( "Find Example" ) ) + { + Search(); + } + + return true; + } + + void Step() override + { + Compute(); + } + + b3Pos GaussPoint( b3Vec3 directionInA ) const + { + return m_gaussCenter + b3MulSV( m_gaussRadius, b3RotateVector( m_transformA.q, directionInA ) ); + } + + void DrawGreatArc( b3Vec3 u, b3Vec3 v, Vec4 color, float thickness, OverlayOcclusionMode mode ) const + { + constexpr int segmentCount = 32; + b3Pos previous = GaussPoint( u ); + for ( int i = 1; i <= segmentCount; ++i ) + { + float s = (float)i / segmentCount; + b3Pos point = GaussPoint( b3Normalize( b3Add( b3MulSV( 1.0f - s, u ), b3MulSV( s, v ) ) ) ); + DrawLineEx( previous, point, color, thickness, OVERLAY_THICKNESS_PIXELS, mode ); + previous = point; + } + } + + // The full great circle through the arc, dashed + void DrawGreatCircle( b3Vec3 u, b3Vec3 v, Vec4 color ) const + { + b3Vec3 axis = b3Normalize( b3Cross( u, v ) ); + b3Vec3 w = b3Cross( axis, u ); + constexpr int segmentCount = 96; + b3Pos previous = GaussPoint( u ); + for ( int i = 1; i <= segmentCount; ++i ) + { + float angle = 2.0f * B3_PI * i / segmentCount; + b3CosSin cs = b3ComputeCosSin( angle ); + b3Pos point = GaussPoint( b3Add( b3MulSV( cs.cosine, u ), b3MulSV( cs.sine, w ) ) ); + DrawLineEx( previous, point, color, 1.0f, OVERLAY_THICKNESS_PIXELS, OVERLAY_OCCLUSION_DASHED ); + previous = point; + } + } + + void DrawEdge( b3WorldTransform transform, const b3HullData* hull, int edgeIndex, Vec4 color ) const + { + const b3HullHalfEdge* edges = b3GetHullEdges( hull ); + const b3Vec3* points = b3GetHullPoints( hull ); + b3Pos p1 = b3TransformWorldPoint( transform, points[edges[edgeIndex].origin] ); + b3Pos p2 = b3TransformWorldPoint( transform, points[edges[edgeIndex + 1].origin] ); + DrawLineEx( p1, p2, color, 5.0f, OVERLAY_THICKNESS_PIXELS, OVERLAY_OCCLUSION_DIM ); + } + + void DrawArcText( const char* name, const Arc& arc, float edgeBound ) + { + if ( arc.inside ) + { + DrawTextLine( "%s edge: d peak inside wedge", name ); + } + else + { + DrawTextLine( "%s edge: d peak OUTSIDE wedge by %.1f degrees", name, arc.outsideDegrees ); + } + DrawTextLine( " sphere bound u %.3f v %.3f n %.3f", arc.a - m_radius, arc.b - m_radius, edgeBound ); + DrawTextLine( " separation u %.4f v %.4f n %.4f", arc.separationU, arc.separationV, m_edge.separation ); + } + + void Render() override + { + DrawHull( m_transformA, m_hullA, MakeColor( b3_colorSlateGray ) ); + DrawHull( m_transformB, m_hullB, MakeColor( b3_colorSlateGray ) ); + + b3Pos centerA = b3TransformWorldPoint( m_transformA, m_hullA->center ); + b3Pos centerB = b3TransformWorldPoint( m_transformB, m_hullB->center ); + DrawLine( centerA, centerB, MakeColor( b3_colorWhite ) ); + + DrawTextLine( "drag to move B, shift + drag to rotate B" ); + DrawTextLine( "search: %s after %d poses", m_searchFound ? "found" : "not found", m_searchCount ); + DrawTextLine( "best separation: face A %.4f, face B %.4f, edge %.4f -> %s", m_faceSeparationA, m_faceSeparationB, + m_edge.separation, m_edgeWins ? "EDGE WINS" : "face wins" ); + + if ( m_edge.edgeA == B3_NULL_INDEX ) + { + Manifold::Render(); + return; + } + + Vec4 colorA = MakeColor( b3_colorOrange ); + Vec4 colorB = MakeColor( b3_colorDeepSkyBlue ); + Vec4 colorN = MakeColor( b3_colorGold ); + Vec4 colorPeak = MakeColor( b3_colorMagenta ); + + DrawEdge( m_transformA, m_hullA, m_edge.edgeA, colorA ); + DrawEdge( m_transformB, m_hullB, m_edge.edgeB, colorB ); + + // Winning axis from the midpoint of edge A + { + const b3HullHalfEdge* edges = b3GetHullEdges( m_hullA ); + const b3Vec3* points = b3GetHullPoints( m_hullA ); + b3Vec3 mid = b3Lerp( points[edges[m_edge.edgeA].origin], points[edges[m_edge.edgeA + 1].origin], 0.5f ); + b3Pos p = b3TransformWorldPoint( m_transformA, mid ); + b3Vec3 n = b3RotateVector( m_transformA.q, m_edge.normal ); + DrawArrowEx( p, p + b3MulSV( 1.0f, n ), colorN, 3.0f, OVERLAY_THICKNESS_PIXELS, OVERLAY_OCCLUSION_DIM, 0.2f ); + } + + // Gauss map: both arcs cross at the edge axis n. The magenta dots are the peaks of dot(n, d) on each + // great circle. The peak of an arc is only reachable when it lies on the arc. + b3Sphere unitSphere = { b3Vec3_zero, m_gaussRadius }; + DrawWireSphere( { m_gaussCenter, b3Quat_identity }, &unitSphere, 24, MakeColor( b3_colorDimGray ) ); + + DrawGreatCircle( m_arcA.u, m_arcA.v, colorA ); + DrawGreatCircle( m_arcB.u, m_arcB.v, colorB ); + DrawGreatArc( m_arcA.u, m_arcA.v, colorA, 5.0f, OVERLAY_OCCLUSION_DIM ); + DrawGreatArc( m_arcB.u, m_arcB.v, colorB, 5.0f, OVERLAY_OCCLUSION_DIM ); + + DrawPoint( GaussPoint( m_arcA.u ), 8.0f, colorA ); + DrawPoint( GaussPoint( m_arcA.v ), 8.0f, colorA ); + DrawPoint( GaussPoint( m_arcB.u ), 8.0f, colorB ); + DrawPoint( GaussPoint( m_arcB.v ), 8.0f, colorB ); + DrawString3D( GaussPoint( m_arcA.u ), colorA, " uA" ); + DrawString3D( GaussPoint( m_arcA.v ), colorA, " vA" ); + DrawString3D( GaussPoint( m_arcB.u ), colorB, " uB" ); + DrawString3D( GaussPoint( m_arcB.v ), colorB, " vB" ); + + DrawPoint( GaussPoint( m_arcA.peak ), 10.0f, colorPeak ); + DrawString3D( GaussPoint( m_arcA.peak ), colorPeak, " peak A" ); + DrawPoint( GaussPoint( m_arcB.peak ), 10.0f, colorPeak ); + DrawString3D( GaussPoint( m_arcB.peak ), colorPeak, " peak B" ); + + DrawPoint( GaussPoint( m_edge.normal ), 12.0f, colorN ); + DrawString3D( GaussPoint( m_edge.normal ), colorN, " n" ); + + b3Vec3 dHat = b3Normalize( m_centerOffset ); + DrawPoint( GaussPoint( dHat ), 10.0f, MakeColor( b3_colorWhite ) ); + DrawString3D( GaussPoint( dHat ), MakeColor( b3_colorWhite ), " d" ); + + float edgeBound = b3Dot( m_edge.normal, m_centerOffset ) - m_radius; + DrawTextLine( "|d| - rA - rB = %.3f", b3Length( m_centerOffset ) - m_radius ); + DrawArcText( "A", m_arcA, edgeBound ); + DrawArcText( "B", m_arcB, edgeBound ); + + Manifold::Render(); + } + + static Sample* Create( SampleContext* context ) + { + return new EdgeAxisWedge( context ); + } + + b3HullData* m_hullA; + b3HullData* m_hullB; + EdgeAxis m_edge; + Arc m_arcA; + Arc m_arcB; + b3Vec3 m_centerOffset; + b3Pos m_gaussCenter; + float m_gaussRadius; + float m_radius; + float m_faceSeparationA; + float m_faceSeparationB; + uint32_t m_seed; + int m_searchCount; + bool m_searchFound; + bool m_edgeWins; + b3BoxHull m_box; + b3HullData* m_createdHull; + int m_hullType; +}; + +static int sampleEdgeAxisWedge = RegisterSample( "Manifold", "Edge Axis Wedge", EdgeAxisWedge::Create ); + class TriangleAndHull : public TriangleManifold { public: @@ -825,12 +1760,12 @@ public: m_camera->SetView( 0.0f, 30.0f, 3.0f, b3Pos_zero ); } - //m_triangle[0] = { 1.00000000, 0, 1.00000000 }; - //m_triangle[1] = { 1.00000000, 0, 0.00000000 }; - //m_triangle[2] = { 0.00000000, 0, 0.00000000 }; + // m_triangle[0] = { 1.00000000, 0, 1.00000000 }; + // m_triangle[1] = { 1.00000000, 0, 0.00000000 }; + // m_triangle[2] = { 0.00000000, 0, 0.00000000 }; m_triangle[0] = { 0.299769998f, -1.01549578f, -0.744717002f }; - m_triangle[1] = { 0.299769998f, -1.01549578f, 1.28728306f }; + m_triangle[1] = { 0.299769998f, -1.01549578f, 1.28728306f }; m_triangle[2] = { 0.299769998f, -0.913895786f, 0.271283031f }; float bodyHalfWidth = 0.304800004f; @@ -840,7 +1775,7 @@ public: 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; @@ -913,8 +1848,8 @@ public: b3TransformPoint( xf, m_triangle[2] ), }; - b3CollideTriangleAndHull( &m_manifold, m_pointCapacity, localTriangle[0], localTriangle[1], localTriangle[2], - m_flags, m_hull, &m_satCache, true ); + b3CollideTriangleAndHull( &m_manifold, m_pointCapacity, localTriangle[0], localTriangle[1], localTriangle[2], m_flags, + m_hull, &m_satCache, true ); } int m_flags; diff --git a/shared/benchmarks.c b/shared/benchmarks.c index 2cd3baa..a128fbb 100644 --- a/shared/benchmarks.c +++ b/shared/benchmarks.c @@ -908,44 +908,10 @@ void GetConvexPileCapacity( b3Capacity* capacity ) #ifdef NDEBUG capacity->dynamicShapeCount = 5120; capacity->dynamicBodyCount = 5120; - capacity->contactCount = 60 * 1024; + capacity->contactCount = 64 * 1024; #endif } -// PEEL's BasicRandom, kept verbatim so the point set matches the original -typedef struct ConvexPileRandom -{ - unsigned int state; -} ConvexPileRandom; - -static unsigned int NextConvexPileRandom( ConvexPileRandom* rng ) -{ - rng->state = rng->state * 2147001325u + 715136305u; - return rng->state; -} - -// Float in [-0.5, 0.5] -static float ConvexPileRandomFloat( ConvexPileRandom* rng ) -{ - return (float)( NextConvexPileRandom( rng ) & 0xffff ) / 65535.0f - 0.5f; -} - -// Uniform random direction, rejection sampled inside the unit sphere then pushed to the surface -static b3Vec3 UnitRandomPoint( ConvexPileRandom* rng ) -{ - b3Vec3 point; - float lengthSq; - do - { - point.x = ConvexPileRandomFloat( rng ); - point.y = ConvexPileRandomFloat( rng ); - point.z = ConvexPileRandomFloat( rng ); - lengthSq = b3Dot( point, point ); - } while ( lengthSq > 0.25f ); - - return b3Normalize( point ); -} - void CreateConvexPile( b3WorldId worldId ) { { @@ -962,19 +928,9 @@ void CreateConvexPile( b3WorldId worldId ) int countZ = 8; int layers = BENCHMARK_DEBUG ? 10 : 80; float amplitude = 2.0f; - int pointCount = 32; float scatter = 2.0f * amplitude; - // Hull around random points on a sphere of radius amplitude - assert( pointCount <= 64 ); - b3Vec3 points[64]; - ConvexPileRandom rng = { 42 }; - for ( int i = 0; i < pointCount; ++i ) - { - points[i] = b3MulSV( amplitude, UnitRandomPoint( &rng ) ); - } - - b3HullData* convex = b3CreateHull( points, pointCount, pointCount ); + b3HullData* convex = b3CreateComplexHull( amplitude ); b3BodyDef bodyDef = b3DefaultBodyDef(); bodyDef.type = b3_dynamicBody; diff --git a/src/contact_solver.c b/src/contact_solver.c index ce1cbd2..0998848 100644 --- a/src/contact_solver.c +++ b/src/contact_solver.c @@ -936,12 +936,6 @@ typedef struct b3Vec2W b3FloatW x, y; } b3Vec2W; -// Wide vec3 -typedef struct b3Vec3W -{ - b3FloatW X, Y, Z; -} b3Vec3W; - // Wide quaternion typedef struct b3QuatW { @@ -966,24 +960,6 @@ typedef struct b3Matrix3W b3Vec3W cx, cy, cz; } b3Matrix3W; -// s * a -static inline b3Vec3W b3MulSVW( b3FloatW s, b3Vec3W a ) -{ - return (b3Vec3W){ b3MulW( s, a.X ), b3MulW( s, a.Y ), b3MulW( s, a.Z ) }; -} - -// a - s * b -static inline b3Vec3W b3MulSubSVW( b3Vec3W a, b3FloatW s, b3Vec3W b ) -{ - return (b3Vec3W){ b3SubW( a.X, b3MulW( s, b.X ) ), b3SubW( a.Y, b3MulW( s, b.Y ) ), b3SubW( a.Z, b3MulW( s, b.Z ) ) }; -} - -// a + s * b -static inline b3Vec3W b3MulAddSVW( b3Vec3W a, b3FloatW s, b3Vec3W b ) -{ - return (b3Vec3W){ b3AddW( a.X, b3MulW( s, b.X ) ), b3AddW( a.Y, b3MulW( s, b.Y ) ), b3AddW( a.Z, b3MulW( s, b.Z ) ) }; -} - // a + b static inline b3Vec2W b3AddV2W( b3Vec2W a, b3Vec2W b ) { @@ -993,26 +969,6 @@ static inline b3Vec2W b3AddV2W( b3Vec2W a, b3Vec2W b ) }; } -// a - b -static inline b3Vec3W b3SubVW( b3Vec3W a, b3Vec3W b ) -{ - return (b3Vec3W){ - b3SubW( a.X, b.X ), - b3SubW( a.Y, b.Y ), - b3SubW( a.Z, b.Z ), - }; -} - -// a + b -static inline b3Vec3W b3AddVW( b3Vec3W a, b3Vec3W b ) -{ - return (b3Vec3W){ - b3AddW( a.X, b.X ), - b3AddW( a.Y, b.Y ), - b3AddW( a.Z, b.Z ), - }; -} - // m * a static inline b3Vec2W b3MulMV2W( b3SymMatrix2W m, b3Vec2W a ) { @@ -1060,20 +1016,6 @@ static inline b3Vec3W b3MulAddMVW( b3Vec3W a, b3SymMatrix3W m, b3Vec3W b ) return (b3Vec3W){ b3AddW( a.X, c.X ), b3AddW( a.Y, c.Y ), b3AddW( a.Z, c.Z ) }; } -static inline b3FloatW b3DotW( b3Vec3W a, b3Vec3W b ) -{ - return b3AddW( b3AddW( b3MulW( a.X, b.X ), b3MulW( a.Y, b.Y ) ), b3MulW( a.Z, b.Z ) ); -} - -static inline b3Vec3W b3CrossW( b3Vec3W a, b3Vec3W b ) -{ - b3Vec3W c; - c.X = b3SubW( b3MulW( a.Y, b.Z ), b3MulW( a.Z, b.Y ) ); - c.Y = b3SubW( b3MulW( a.Z, b.X ), b3MulW( a.X, b.Z ) ); - c.Z = b3SubW( b3MulW( a.X, b.Y ), b3MulW( a.Y, b.X ) ); - return c; -} - static inline b3Matrix3W b3MakeMatrixFromQuatW( b3QuatW q ) { b3FloatW x2 = b3AddW( q.V.X, q.V.X ); diff --git a/src/convex_manifold.c b/src/convex_manifold.c index ac2909e..f5bfde0 100644 --- a/src/convex_manifold.c +++ b/src/convex_manifold.c @@ -1246,56 +1246,33 @@ static bool b3BuildEdgeContact( b3LocalManifold* manifold, const b3HullData* hul // Transform a SoA point/normal stream (already split into X/Y/Z) by out = -(R*v (+t)). // The inputs come straight from the hull's stored SoA arrays, so there's no transpose here. -static inline void b3NegativeTransformFromSoA( b3Matrix3* R, b3Vec3 p, const float* inX, const float* inY, const float* inZ, +static inline void b3NegativeTransformFromSoA( b3Matrix3 R, b3Vec3 p, const float* inX, const float* inY, const float* inZ, int n, float* outX, float* outY, float* outZ, bool isPoint ) { - B3_VALIDATE( ( (uintptr_t)outX & 0xF ) == 0 ); - B3_VALIDATE( ( (uintptr_t)outY & 0xF ) == 0 ); - B3_VALIDATE( ( (uintptr_t)outZ & 0xF ) == 0 ); - // row-column - b3FloatW r00 = b3SplatW( R->cx.x ); - b3FloatW r01 = b3SplatW( R->cy.x ); - b3FloatW r02 = b3SplatW( R->cz.x ); - b3FloatW r10 = b3SplatW( R->cx.y ); - b3FloatW r11 = b3SplatW( R->cy.y ); - b3FloatW r12 = b3SplatW( R->cz.y ); - b3FloatW r20 = b3SplatW( R->cx.z ); - b3FloatW r21 = b3SplatW( R->cy.z ); - b3FloatW r22 = b3SplatW( R->cz.z ); - - b3FloatW tx = b3ZeroW(); - b3FloatW ty = b3ZeroW(); - b3FloatW tz = b3ZeroW(); + b3Vec3W r0 = { b3SplatW( R.cx.x ), b3SplatW( R.cy.x ), b3SplatW( R.cz.x ) }; + b3Vec3W r1 = { b3SplatW( R.cx.y ), b3SplatW( R.cy.y ), b3SplatW( R.cz.y ) }; + b3Vec3W r2 = { b3SplatW( R.cx.z ), b3SplatW( R.cy.z ), b3SplatW( R.cz.z ) }; + b3Vec3W t = { b3ZeroW(), b3ZeroW(), b3ZeroW() }; if ( isPoint ) { - tx = b3SplatW( p.x ); - ty = b3SplatW( p.y ); - tz = b3SplatW( p.z ); + t = b3SplatVW( p ); } for ( int i = 0; i < n; i += 4 ) { - b3FloatW x = b3LoadW( inX + i ); - b3FloatW y = b3LoadW( inY + i ); - b3FloatW z = b3LoadW( inZ + i ); + b3Vec3W v = b3LoadVW( inX + i, inY + i, inZ + i ); // Rotate four vectors at a time - b3FloatW ox = b3Dot3W( r00, r01, r02, x, y, z ); - b3FloatW oy = b3Dot3W( r10, r11, r12, x, y, z ); - b3FloatW oz = b3Dot3W( r20, r21, r22, x, y, z ); + b3Vec3W out = { b3DotW( r0, v ), b3DotW( r1, v ), b3DotW( r2, v ) }; if ( isPoint ) { - ox = b3AddW( ox, tx ); - oy = b3AddW( oy, ty ); - oz = b3AddW( oz, tz ); + out = b3AddVW( out, t ); } - b3StoreW( outX + i, b3NegW( ox ) ); - b3StoreW( outY + i, b3NegW( oy ) ); - b3StoreW( outZ + i, b3NegW( oz ) ); + b3StoreVW( outX + i, outY + i, outZ + i, b3NegVW( out ) ); } } @@ -1307,11 +1284,11 @@ _Static_assert( B3_MAX_HULL_VERTICES == 128, "must be 128" ); // to a multiple of 4. // // This minimizes (bias - dot), where the caller is expected to provide a bias that makes this always positive. -// It can be direction dependent. The bias should be just big enough to ensure the value if positive because +// It can be direction dependent. The bias should be just big enough to ensure the value is positive because // an excessive bias causes a precision loss in the support calculation. // // The vertex index is embedded in the low B3_HULL_BIT_COUNT mantissa bits of the value. By minimizing a value that -// is always positive, the minimum carries the smallest index so that padded SoA values will never win. This is +// is always positive, the minimum carries the smallest index so that padded SoA values will never win. This is the // purpose of using the bias instead of maximizing the dot directly. // // The support is then recomputed exactly as dot(normal, vertex), without the embedded index. @@ -1319,21 +1296,17 @@ _Static_assert( B3_MAX_HULL_VERTICES == 128, "must be 128" ); static inline void b3GetSupportWide( b3Vec3 normal, const float* vx, const float* vy, const float* vz, int n, float bias, float* support, int* vertexIndex ) { - const b3FloatW nx = b3SplatW( normal.x ); - const b3FloatW ny = b3SplatW( normal.y ); - const b3FloatW nz = b3SplatW( normal.z ); + const b3Vec3W normalW = b3SplatVW( normal ); const b3FloatW biasV = b3SplatW( bias ); // Start the minimum at a large value. - b3FloatW minValue = b3SplatW( B3_HUGE ); + b3FloatW minValue = b3SplatW( INFINITY ); // Tail lanes hold vertex 0 with index bits >= vertexCount, so they never become the min value. for ( int i = 0; i < n; i += 4 ) { - b3FloatW x = b3LoadW( vx + i ); - b3FloatW y = b3LoadW( vy + i ); - b3FloatW z = b3LoadW( vz + i ); - b3FloatW d = b3AddW( b3MulW( nz, z ), b3AddW( b3MulW( ny, y ), b3MulW( nx, x ) ) ); + b3Vec3W v = b3LoadVW( vx + i, vy + i, vz + i ); + b3FloatW d = b3DotW( normalW, v ); // This is always positive. b3FloatW value = b3SubW( biasV, d ); @@ -1368,65 +1341,95 @@ static inline void b3GetFaceDots( const b3HullData* hull, b3Vec3 d, float* dots const float* ny = nx + soaFaceCount; const float* nz = ny + soaFaceCount; - b3FloatW dx = b3SplatW( d.x ); - b3FloatW dy = b3SplatW( d.y ); - b3FloatW dz = b3SplatW( d.z ); + b3Vec3W dW = b3SplatVW( d ); for ( int i = 0; i < soaFaceCount; i += 4 ) { // dot product per lane - b3FloatW m = b3Dot3W( b3LoadW( nx + i ), b3LoadW( ny + i ), b3LoadW( nz + i ), dx, dy, dz ); + b3FloatW m = b3DotW( b3LoadVW( nx + i, ny + i, nz + i ), dW ); b3StoreW( dots + i, m ); } } #define B3_PARALLEL_TOL 1e-4f -// A hull edges is bounded by two face normals. On the Gauss map the edge becomes an arc between -// those two face normals. This edge can only build the best separating axis if a normal on that arc -// can beat the best separation value seen so far. This test determines of such a normal exists. +// A hull edge is bounded by two face normals. On the Gauss map the edge becomes an arc between +// those two face normals. An edge can only build the best separating axis if a normal on that arc +// can beat the best separation value seen so far. This function determines if the upper bound +// separation on that arc can possibly beat the current maximum face separation. +// // This follows the upper bound used for hull faces: // separation_upper_bound = dot(axis, centerB - centerA) - innerRadiusA - innerRadiusB -// +// // Inputs: // d the vector connecting the hull centers -// a = dot(u, d) -// b = dot(v, d) -// c = dot(u, v) -// length = length(d) -// bound = max_sep + radiusBound -// Note: this doesn't compute the separation, it just rules out potential candidates. So if some input -// is degenerate it just pass the candidate onto the next stage. -static inline int b3ArcCanReach( float a, float b, float c, float length, float bound ) +// a1 = dot(n1, d) +// a2 = dot(n2, d) +// c = dot(n1, n2) +// bound = maxFaceSeparation + radiusBound +// +// This returns 1 if the edges is a candidate and 0 otherwise. +static inline int b3TestEdgeCandidate( float a1, float a2, float c, float bound ) { // c = cos(theta), the angle between the normals. // s = sin(theta)^2 >= 0 float s = 1.0f - c * c; - // This is coincidently the law of cosines. Break out your protractor. - float t = a * a + b * b - 2.0f * a * b * c; + // This is coincidentally the law of cosines. Break out your protractor. + float t = a1 * a1 + a2 * a2 - 2.0f * a1 * a2 * c; - // Do either face normals beat the best separation? - int endpoint = b3MaxFloat( a, b ) >= bound; + // Exterior conditions: + // Can either face normal beat the best separation? These cover the case where + // d is outside the arc. Note that d pointing outside the arc does not cull this + // edge. It can still generate the maximum separation (happens commonly). + // Note: when earlyReturn == false, bound == -INFINITY and this is always true. + int exterior = b3MaxFloat( a1, a2 ) >= bound; - // Project d into the plane that holds both u and v, call that vector g: - // g = x*u + y*v - // Note that dot(u, g) == dot(u, d) == a, and dot(v, g) == dot(v, d) == b - // Dot the equation with u and v: - // a = x + y*c - // b = x*c + y - // Solve for x and y using Cramer's Rule - // x = (a - b * c) / (1 - c * c) - // y = (b - a * c) / (1 - c * c) - // s = 1 - c * c is greater than 0, so x and y must be positive for n to live between u and v. - // The peak value along d is then dot(g, n): - // dot(g, n) = x*a + y*b = (a*a - a*b*c + b*b - a*b*c) / s = (a*a + b*b - 2*a*b*c) / s = t / s - // If that peak value beats the threshold then this edge might form the best separating axis. - // Using bit ops here to prevent unpredictable branches. - int interior = ( a >= c * b ) & ( b >= c * a ) & ( length >= bound ) & - ( ( bound <= 0.0f ) | ( s < B3_PARALLEL_TOL ) | ( t >= bound * bound * s ) ); + // Project d into the plane that holds both n1 and n2, call that vector dp. + // Introduce the coordinates b1 and b2 (these have units of length). + // + // dp = b1*n1 + b2*n2 + // + // Since dp is the projection of d into the plane formed by the cross(n1, n2): + // dot(n1, dp) == dot(n1, d) == a1 + // dot(n2, dp) == dot(n2, d) == a2 + // + // Dot the equation with n1 and n2: + // a1 = b1 + b2*c + // a2 = b1*c + b2 + // + // Solve for b1 and b2 using Cramer's Rule + // b1 = (a1 - a2 * c) / s + // b2 = (a2 - a1 * c) / s + // + // s = 1 - c * c is positive, so b1 and b2 must be positive for d to live in + // the arc between n1 and n2. + // + // The peak value along d is then norm(dp): + // dot(dp, dp) = dot(b1*n1 + b2*n2, d) + // = b1*a1 + b2*a2 + // = (a1*a1 - a1*a2*c + a2*a2 - a1*a2*c) / s + // = (a1*a1 + a2*a2 - 2*a1*a2*c) / s + // = t / s + // + // The interior is a candidate if: + // norm(dp) > bound + // sqrt(t / s) > bound + // If bound < 0 this is always true. Otherwise + // t > bound^2 * s + // + // Interior conditions: + // b1 and b2 positive (interior arc): a1 >= c * a2 & a2 >= c * a1 + // bound <= 0.0: the interior arc is automatically a candidate because it is positive + // s < B3_PARALLEL_TOL : n1 and n2 are nearly parallel so give up and pass the edge to the next stage + // t >= bound * bound * s : bound is positive and the interior normal direction is a candidate + // + // Using bit ops here to avoid branches. - return endpoint | interior; + int interior = + ( a1 >= c * a2 ) & ( a2 >= c * a1 ) & ( ( bound <= 0.0f ) | ( s < B3_PARALLEL_TOL ) | ( t >= bound * bound * s ) ); + + return exterior | interior; } // Temporary abbreviations for convenience. @@ -1483,7 +1486,7 @@ b3AxisQuery b3ComputeSeparatingAxis( const b3HullData* hullA, const b3HullData* b3Vec3 hB = b3AABB_Extents( hullB->aabb ); // The hulls have a precomputed inner radius and centroid. - // A give axis cannot achieve a separation larger than: + // A given axis cannot achieve a separation larger than: // dot(axis, centerB - centerA) - innerRadiusA - innerRadiusB // So this is the upper bound for the separation of a candidate axis. // An axis can be skipped if it has an upper bound that is less than the current @@ -1619,7 +1622,6 @@ b3AxisQuery b3ComputeSeparatingAxis( const b3HullData* hullA, const b3HullData* res.faceB.separation = separation; res.faceB.indexA = vertexIndex; res.faceB.indexB = i; - // This points from A to B and is in frame A if ( separation > speculativeDistance && earlyReturn ) { res.separatedFeature = b3_faceAxisB; @@ -1637,7 +1639,9 @@ b3AxisQuery b3ComputeSeparatingAxis( const b3HullData* hullA, const b3HullData* // dot(edgeNormal, deltaCenter) - radiusBound > maxSep float edgeBound = earlyReturn ? b3MaxFloat( res.faceA.separation, res.faceB.separation ) + radiusBound : -INFINITY; - // Gather edges of A that can feasibly create a winning separating axis. + B3_VALIDATE( earlyReturn == false || centerDistance >= edgeBound ); + + // Gather edges of A that can feasibly create a separating axis that beats the maximum face separation. int halfEdgeCountA = hullA->edgeCount; const b3HullHalfEdge* halfEdgesA = b3GetHullEdges( hullA ); int edgeIndicesA[NE]; @@ -1648,10 +1652,10 @@ b3AxisQuery b3ComputeSeparatingAxis( const b3HullData* hullA, const b3HullData* int i2 = halfEdgesA[i + 1].face; float c = b3Dot( planesA[i1].normal, planesA[i2].normal ); edgeIndicesA[na] = i; - na += b3ArcCanReach( dotA[i1], dotA[i2], c, centerDistance, edgeBound ); + na += b3TestEdgeCandidate( dotA[i1], dotA[i2], c, edgeBound ); } - // Gather edges of B that can feasibly create a winning separating axis. + // Similar for edges of B. int halfEdgeCountB = hullB->edgeCount; const b3HullHalfEdge* halfEdgesB = b3GetHullEdges( hullB ); int edgeIndicesB[B3_MAX_HULL_EDGES]; @@ -1662,7 +1666,7 @@ b3AxisQuery b3ComputeSeparatingAxis( const b3HullData* hullA, const b3HullData* int i2 = halfEdgesB[i + 1].face; float c = b3Dot( planesB[i1].normal, planesB[i2].normal ); edgeIndicesB[nb] = i; - nb += b3ArcCanReach( dotB[i1], dotB[i2], c, centerDistance, edgeBound ); + nb += b3TestEdgeCandidate( dotB[i1], dotB[i2], c, edgeBound ); } if ( na == 0 || nb == 0 ) @@ -1688,45 +1692,8 @@ b3AxisQuery b3ComputeSeparatingAxis( const b3HullData* hullA, const b3HullData* const float* nyB = nxB + soaFaceCountB; const float* nzB = nyB + soaFaceCountB; - b3NegativeTransformFromSoA( &R, xfB.p, nxB, nyB, nzB, soaFaceCountB, bFNx, bFNy, bFNz, false ); - b3NegativeTransformFromSoA( &R, xfB.p, vxB, vyB, vzB, soaVertexCountB, bWx, bWy, bWz, true ); - - // Per B edge data. C and D are the two face normals, v0 a vertex, DC the edge vector. - _Alignas( 16 ) float bCx[NE]; - _Alignas( 16 ) float bCy[NE]; - _Alignas( 16 ) float bCz[NE]; - _Alignas( 16 ) float bDx[NE]; - _Alignas( 16 ) float bDy[NE]; - _Alignas( 16 ) float bDz[NE]; - _Alignas( 16 ) float bV0x[NE]; - _Alignas( 16 ) float bV0y[NE]; - _Alignas( 16 ) float bV0z[NE]; - _Alignas( 16 ) float bDCx[NE]; - _Alignas( 16 ) float bDCy[NE]; - _Alignas( 16 ) float bDCz[NE]; - - for ( int k = 0; k < nb; ++k ) - { - const b3HullHalfEdge* edge = halfEdgesB + edgeIndicesB[k]; - const b3HullHalfEdge* twin = edge + 1; - int f0 = edge->face; - int f1 = twin->face; - int v0 = edge->origin; - int v1 = twin->origin; - - bCx[k] = bFNx[f0]; - bCy[k] = bFNy[f0]; - bCz[k] = bFNz[f0]; - bDx[k] = bFNx[f1]; - bDy[k] = bFNy[f1]; - bDz[k] = bFNz[f1]; - bV0x[k] = bWx[v0]; - bV0y[k] = bWy[v0]; - bV0z[k] = bWz[v0]; - bDCx[k] = bWx[v1] - bWx[v0]; - bDCy[k] = bWy[v1] - bWy[v0]; - bDCz[k] = bWz[v1] - bWz[v0]; - } + b3NegativeTransformFromSoA( R, xfB.p, nxB, nyB, nzB, soaFaceCountB, bFNx, bFNy, bFNz, false ); + b3NegativeTransformFromSoA( R, xfB.p, vxB, vyB, vzB, soaVertexCountB, bWx, bWy, bWz, true ); // Per A edge data, already in A's space so just gathered. n0 and n1 are the two face // normals, d the edge vector av1-av0, v0 the first vertex. Tol is the @@ -1776,56 +1743,56 @@ b3AxisQuery b3ComputeSeparatingAxis( const b3HullData* hullA, const b3HullData* // Zero the tail lanes. b3FloatW zero = b3ZeroW(); - b3StoreW( aN0x + na, zero ); - b3StoreW( aN0y + na, zero ); - b3StoreW( aN0z + na, zero ); - b3StoreW( aN1x + na, zero ); - b3StoreW( aN1y + na, zero ); - b3StoreW( aN1z + na, zero ); - b3StoreW( aDx + na, zero ); - b3StoreW( aDy + na, zero ); - b3StoreW( aDz + na, zero ); - b3StoreW( aV0x + na, zero ); - b3StoreW( aV0y + na, zero ); - b3StoreW( aV0z + na, zero ); + b3Vec3W zeroV = { zero, zero, zero }; + b3StoreVW( aN0x + na, aN0y + na, aN0z + na, zeroV ); + b3StoreVW( aN1x + na, aN1y + na, aN1z + na, zeroV ); + b3StoreVW( aDx + na, aDy + na, aDz + na, zeroV ); + b3StoreVW( aV0x + na, aV0y + na, aV0z + na, zeroV ); b3StoreW( aTol + na, zero ); + float linearSlop = B3_LINEAR_SLOP; + #if defined( B3_SIMD_NONE ) // The SIMD emulated version of this code is very slow. This is a purely scalar version // for platforms that don't have SIMD capability. It is much faster than SIMD emulation. // WARNING: this math needs to match the SIMD version for cross platform determinism. - const float EPS = -0.0001f; + const float EPS = -linearSlop * linearSlop; for ( int j = 0; j < nb; ++j ) { - float Cx = bCx[j]; - float Cy = bCy[j]; - float Cz = bCz[j]; - float Dx = bDx[j]; - float Dy = bDy[j]; - float Dz = bDz[j]; - float DCx = bDCx[j]; - float DCy = bDCy[j]; - float DCz = bDCz[j]; - float bv0x = bV0x[j]; - float bv0y = bV0y[j]; - float bv0z = bV0z[j]; + const b3HullHalfEdge* edge = halfEdgesB + edgeIndicesB[j]; + const b3HullHalfEdge* twin = edge + 1; + int f0 = edge->face; + int f1 = twin->face; + int v0 = edge->origin; + int v1 = twin->origin; + + b3Vec3 C = { bFNx[f0], bFNy[f0], bFNz[f0] }; + b3Vec3 D = { bFNx[f1], bFNy[f1], bFNz[f1] }; + b3Vec3 bv0 = { bWx[v0], bWy[v0], bWz[v0] }; + b3Vec3 bv1 = { bWx[v1], bWy[v1], bWz[v1] }; + b3Vec3 DC = b3Sub( bv1, bv0 ); for ( int i = 0; i < na; ++i ) { + b3Vec3 d = { aDx[i], aDy[i], aDz[i] }; + // CBA = C.dir, DBA = D.dir, where dir = B_x_A - float CBA = Cx * aDx[i] + ( Cy * aDy[i] + Cz * aDz[i] ); - float DBA = Dx * aDx[i] + ( Dy * aDy[i] + Dz * aDz[i] ); + float CBA = b3Dot( C, d ); + float DBA = b3Dot( D, d ); if ( CBA * DBA >= EPS ) { continue; } + b3Vec3 n0 = { aN0x[i], aN0y[i], aN0z[i] }; + b3Vec3 n1 = { aN1x[i], aN1y[i], aN1z[i] }; + // ADC = n0.DC, BDC = n1.DC, where DC = D_x_C - float ADC = aN0x[i] * DCx + ( aN0y[i] * DCy + aN0z[i] * DCz ); - float BDC = aN1x[i] * DCx + ( aN1y[i] * DCy + aN1z[i] * DCz ); + float ADC = b3Dot( n0, DC ); + float BDC = b3Dot( n1, DC ); if ( ADC * BDC >= EPS || CBA * BDC >= EPS ) { continue; @@ -1842,24 +1809,17 @@ b3AxisQuery b3ComputeSeparatingAxis( const b3HullData* hullA, const b3HullData* float t = -CBA / ( DBA - CBA ); // normal = lerp(t, C, D) = C + (D-C)*t - float nx = Cx + t * ( Dx - Cx ); - float ny = Cy + t * ( Dy - Cy ); - float nz = Cz + t * ( Dz - Cz ); - float len2 = nx * nx + ( ny * ny + nz * nz ); + b3Vec3 n = b3MulAdd( C, t, b3Sub( D, C ) ); + float len2 = b3Dot( n, n ); float inv = 1.0f / sqrtf( len2 ); - nx *= inv; - ny *= inv; - nz *= inv; + n = b3MulSV( inv, n ); // separation = -dot(normal, av0 + bv0) - float sx = aV0x[i] + bv0x; - float sy = aV0y[i] + bv0y; - float sz = aV0z[i] + bv0z; - - float separation = -( sx * nx + ( sy * ny + sz * nz ) ); + b3Vec3 av0 = { aV0x[i], aV0y[i], aV0z[i] }; + float separation = -b3Dot( b3Add( av0, bv0 ), n ); if ( separation > res.edge.separation ) { - res.edge.normal = (b3Vec3){ nx, ny, nz }; + res.edge.normal = n; res.edge.separation = separation; // Half edge index @@ -1878,46 +1838,44 @@ b3AxisQuery b3ComputeSeparatingAxis( const b3HullData* hullA, const b3HullData* #else // Edge phase, one B edge against four A edges at a time, no transforms in the loop. - const b3FloatW EPS = b3SplatW( -0.0001f ); + + // This tolerance can skip edges shorter than 1cm. + const b3FloatW EPS = b3SplatW( -linearSlop * linearSlop ); const b3FloatW INF = b3SplatW( INFINITY ); for ( int j = 0; j < nb; ++j ) { - const b3FloatW Cx = b3SplatW( bCx[j] ); - const b3FloatW Cy = b3SplatW( bCy[j] ); - const b3FloatW Cz = b3SplatW( bCz[j] ); - const b3FloatW Dx = b3SplatW( bDx[j] ); - const b3FloatW Dy = b3SplatW( bDy[j] ); - const b3FloatW Dz = b3SplatW( bDz[j] ); - const b3FloatW DCx = b3SplatW( bDCx[j] ); - const b3FloatW DCy = b3SplatW( bDCy[j] ); - const b3FloatW DCz = b3SplatW( bDCz[j] ); - const b3FloatW bv0x = b3SplatW( bV0x[j] ); - const b3FloatW bv0y = b3SplatW( bV0y[j] ); - const b3FloatW bv0z = b3SplatW( bV0z[j] ); + const b3HullHalfEdge* edge = halfEdgesB + edgeIndicesB[j]; + const b3HullHalfEdge* twin = edge + 1; + int f0 = edge->face; + int f1 = twin->face; + int v0 = edge->origin; + int v1 = twin->origin; + + b3Vec3 nC = { bFNx[f0], bFNy[f0], bFNz[f0] }; + b3Vec3 nD = { bFNx[f1], bFNy[f1], bFNz[f1] }; + b3Vec3 pB = { bWx[v0], bWy[v0], bWz[v0] }; + b3Vec3 qB = { bWx[v1], bWy[v1], bWz[v1] }; + + const b3Vec3W C = b3SplatVW( nC ); + const b3Vec3W D = b3SplatVW( nD ); + const b3Vec3W DC = b3SplatVW( b3Sub( qB, pB ) ); + const b3Vec3W bv0 = b3SplatVW( pB ); for ( int i = 0; i < na; i += 4 ) { - b3FloatW n0x = b3LoadW( aN0x + i ); - b3FloatW n0y = b3LoadW( aN0y + i ); - b3FloatW n0z = b3LoadW( aN0z + i ); - b3FloatW n1x = b3LoadW( aN1x + i ); - b3FloatW n1y = b3LoadW( aN1y + i ); - b3FloatW n1z = b3LoadW( aN1z + i ); - b3FloatW dx = b3LoadW( aDx + i ); - b3FloatW dy = b3LoadW( aDy + i ); - b3FloatW dz = b3LoadW( aDz + i ); - b3FloatW v0x = b3LoadW( aV0x + i ); - b3FloatW v0y = b3LoadW( aV0y + i ); - b3FloatW v0z = b3LoadW( aV0z + i ); + b3Vec3W n0 = b3LoadVW( aN0x + i, aN0y + i, aN0z + i ); + b3Vec3W n1 = b3LoadVW( aN1x + i, aN1y + i, aN1z + i ); + b3Vec3W d = b3LoadVW( aDx + i, aDy + i, aDz + i ); + b3Vec3W av0 = b3LoadVW( aV0x + i, aV0y + i, aV0z + i ); b3FloatW tol = b3LoadW( aTol + i ); // CBA = C.dir, DBA = D.dir, where dir = B_x_A - b3FloatW CBA = b3Dot3W( Cx, Cy, Cz, dx, dy, dz ); - b3FloatW DBA = b3Dot3W( Dx, Dy, Dz, dx, dy, dz ); + b3FloatW CBA = b3DotW( C, d ); + b3FloatW DBA = b3DotW( D, d ); // ADC = n0.DC, BDC = n1.DC, where DC = D_x_C - b3FloatW ADC = b3Dot3W( n0x, n0y, n0z, DCx, DCy, DCz ); - b3FloatW BDC = b3Dot3W( n1x, n1y, n1z, DCx, DCy, DCz ); + b3FloatW ADC = b3DotW( n0, DC ); + b3FloatW BDC = b3DotW( n1, DC ); // Gauss map arc crossing test, CBA*DBAsupport only turns negative just before returning, - // so this never skips a lane that would trigger the early out. + // store and scalar reduction. b3FloatW improves = b3GreaterThanW( separation, b3SplatW( res.edge.separation ) ); if ( b3AnyTrueW( improves ) == false ) { @@ -1976,13 +1926,11 @@ b3AxisQuery b3ComputeSeparatingAxis( const b3HullData* hullA, const b3HullData* _Alignas( 16 ) float nyA[4]; _Alignas( 16 ) float nzA[4]; b3StoreW( sA, separation ); - b3StoreW( nxA, nx ); - b3StoreW( nyA, ny ); - b3StoreW( nzA, nz ); + b3StoreVW( nxA, nyA, nzA, n ); // Reduce in lane order so ties keep the first edge and the early out takes the first // improving support below zero. Padded tail lanes carry +INF support, so they never - // update or index a->edges out of range. + // update or index edges out of range. for ( int lane = 0; lane < 4; lane++ ) { int ei = i + lane; @@ -2014,10 +1962,6 @@ b3AxisQuery b3ComputeSeparatingAxis( const b3HullData* hullA, const b3HullData* #undef NF #undef NV -#define B3_SIMD_COLLIDE_HULLS 1 - -#if B3_SIMD_COLLIDE_HULLS == 1 - void b3CollideHulls( b3LocalManifold* manifold, int capacity, const b3HullData* hullA, const b3HullData* hullB, b3Transform transformBtoA, b3SATCache* cache ) { @@ -2303,25 +2247,22 @@ void b3CollideHulls( b3LocalManifold* manifold, int capacity, const b3HullData* b3SeparatingAxis edgeQuery = axisQuery.edge; - // If face clipping yields no points then I need to run a full SAT to get the best edge pair. - if ( manifold->pointCount == 0 && - edgeQuery.separation < b3MaxFloat( axisQuery.faceA.separation, axisQuery.faceB.separation ) ) - { - edgeQuery = b3ComputeSeparatingAxis( hullA, hullB, transformBtoA, false ).edge; - } - if ( edgeQuery.indexA == B3_NULL_INDEX ) { // There are no valid edge pairs (all edges parallel) return; } + float faceSeparation = b3MaxFloat( axisQuery.faceA.separation, axisQuery.faceB.separation ); float clipSeparation = cache->separation; float edgeTol = linearSlop; - // Face contact can be empty if it does not realize the axis of minimum penetration. - // Create edge contact if face contact fails or edge contact is significantly better! - if ( manifold->pointCount == 0 || edgeQuery.separation > clipSeparation + edgeTol ) + // Face contact can be empty if it is not the axis of maximum separation. It can also + // be empty in narrow cases in the speculative region. If that case was important then + // a GJK fallback would be used. So far it doesn't seem important. + // Create edge contact if face contact fails or edge contact is significantly better. + if ( ( manifold->pointCount == 0 && edgeQuery.separation > faceSeparation ) || + edgeQuery.separation > clipSeparation + edgeTol ) { B3_ASSERT( 0 <= edgeQuery.indexA && edgeQuery.indexA < hullA->edgeCount ); B3_ASSERT( 0 <= edgeQuery.indexB && edgeQuery.indexB < hullB->edgeCount ); @@ -2347,494 +2288,3 @@ void b3CollideHulls( b3LocalManifold* manifold, int capacity, const b3HullData* } } } - -#else - -// todo this code has gone stale, will be deleted soon - -typedef struct b3FaceQuery -{ - float separation; - int faceIndex; - int vertexIndex; -} b3FaceQuery; - -typedef struct b3EdgeQuery -{ - b3Vec3 normal; - float separation; - int indexA; - int indexB; -} b3EdgeQuery; - -// Old non-SIMD version. Keeping this for testing and comparisons - -static b3FaceQuery b3QueryFaceDirections( const b3HullData* hullA, const b3HullData* hullB, b3Transform relativeTransform ) -{ - // We perform all computations in local space of the second hull - b3Transform transform = b3InvertTransform( relativeTransform ); - const b3Plane* planesA = b3GetHullPlanes( hullA ); - const b3Vec3* pointsB = b3GetHullPoints( hullB ); - - int maxFaceIndex = -1; - int maxVertexIndex = -1; - float maxFaceSeparation = -FLT_MAX; - float speculativeDistance = B3_SPECULATIVE_DISTANCE; - - for ( int faceIndex = 0; faceIndex < hullA->faceCount; ++faceIndex ) - { - b3Plane plane = b3TransformPlane( transform, planesA[faceIndex] ); - int vertexIndex = b3FindHullSupportVertex( hullB, b3Neg( plane.normal ) ); - b3Vec3 support = pointsB[vertexIndex]; - - float separation = b3PlaneSeparation( plane, support ); - if ( separation > maxFaceSeparation ) - { - maxFaceIndex = faceIndex; - maxVertexIndex = vertexIndex; - maxFaceSeparation = separation; - - if ( separation >= speculativeDistance ) - { - return (b3FaceQuery){ - .separation = maxFaceSeparation, - .faceIndex = (uint8_t)maxFaceIndex, - .vertexIndex = (uint8_t)maxVertexIndex, - }; - } - } - } - - return (b3FaceQuery){ - .separation = maxFaceSeparation, - .faceIndex = (uint8_t)maxFaceIndex, - .vertexIndex = (uint8_t)maxVertexIndex, - }; -} - -static b3EdgeQuery b3QueryEdgeDirections( const b3HullData* hullA, const b3HullData* hullB, b3Transform transformBtoA ) -{ - // Find axis of minimum penetration - b3Vec3 maxNormal = b3Vec3_zero; - float maxSeparation = -FLT_MAX; - int maxIndexA = B3_NULL_INDEX; - int maxIndexB = B3_NULL_INDEX; - - const b3HullHalfEdge* edgesA = b3GetHullEdges( hullA ); - const b3Vec3* pointsA = b3GetHullPoints( hullA ); - const b3Plane* planesA = b3GetHullPlanes( hullA ); - const b3HullHalfEdge* edgesB = b3GetHullEdges( hullB ); - const b3Vec3* pointsB = b3GetHullPoints( hullB ); - const b3Plane* planesB = b3GetHullPlanes( hullB ); - - // Work in frame A - b3Matrix3 matrix = b3MakeMatrixFromQuat( transformBtoA.q ); - float speculativeDistance = B3_SPECULATIVE_DISTANCE; - float squaredTolerance = B3_PARALLEL_EDGE_TOL * B3_PARALLEL_EDGE_TOL; - - // Arranged to minimize transform operations - for ( int indexB = 0; indexB < hullB->edgeCount; indexB += 2 ) - { - const b3HullHalfEdge* edgeB = edgesB + indexB; - const b3HullHalfEdge* twinB = edgesB + indexB + 1; - B3_ASSERT( edgeB->twin == indexB + 1 && twinB->twin == indexB ); - - b3Vec3 qB = pointsB[twinB->origin]; - b3Vec3 eB = b3MulMV( matrix, b3Sub( qB, pointsB[edgeB->origin] ) ); - qB = b3Add( b3MulMV( matrix, qB ), transformBtoA.p ); - - b3Vec3 uB = b3MulMV( matrix, planesB[edgeB->face].normal ); - b3Vec3 vB = b3MulMV( matrix, planesB[twinB->face].normal ); - - for ( int indexA = 0; indexA < hullA->edgeCount; indexA += 2 ) - { - const b3HullHalfEdge* edgeA = edgesA + indexA; - const b3HullHalfEdge* twinA = edgesA + indexA + 1; - B3_ASSERT( edgeA->twin == indexA + 1 && twinA->twin == indexA ); - - b3Vec3 qA = pointsA[twinA->origin]; - b3Vec3 eA = b3Sub( qA, pointsA[edgeA->origin] ); - b3Vec3 uA = planesA[edgeA->face].normal; - b3Vec3 vA = planesA[twinA->face].normal; - - // See "Collision Detection of Convex Polyhedra Based on Duality Transformation" - // Two edges build a face on the Minkowski sum if the associated arcs AB and CD intersect on the Gauss map. - // The associated arcs are defined by the adjacent face normals of each edge. - - // These are signed volumes with an edge optimization to avoid cross products - // eA parallel to cross(vA, uA) - // eB parallel to cross(vB, uB) - // Since only signs are tested, length doesn't matter. - - float cba = b3Dot( uB, eA ); - float dba = b3Dot( vB, eA ); - float adc = -b3Dot( uA, eB ); - float bdc = -b3Dot( vA, eB ); - - if ( cba * dba < 0.0f && adc * bdc < 0.0f && cba * bdc > 0.0f ) - { - // Avoid nearly parallel edges that may lead to invalid separation values at the noise floor. - if ( b3MaxFloat( cba * cba, dba * dba ) < squaredTolerance * b3LengthSquared( eA ) ) - { - continue; - } - - // The intersection of the arcs on the Gauss map is the edge pair axis. Cast the - // arc of hull B (from uB to vB) against the plane containing the arc of hull A: - // dot(uB + t * (vB - uB), eA) == 0 - // then - // t = cba / (cba - dba) - // - // The signs of cba and dba differ (Minkowski test), so the division is safe. - // - // The axis generated points from B to A by construction since it lands between - // two face normals on B. This removes the need to orient the separation axis - // using the hull centers. - // - // The axis is perpendicular to both edges so I can use qA and qB as arbitrary - // points on edgeA and edgeB to measure the separation. - float t = cba / ( cba - dba ); - b3Vec3 axis = b3Lerp( uB, vB, t ); - B3_VALIDATE( b3LengthSquared( axis ) > 1000.0f * FLT_MIN ); - axis = b3Normalize( axis ); - float separation = b3Dot( axis, b3Sub( qA, qB ) ); - - if ( separation > maxSeparation ) - { - // Continues to find the maximum separating axis - // Flip normal so it points from A to B - maxNormal = b3Neg( axis ); - maxSeparation = separation; - maxIndexA = indexA; - maxIndexB = indexB; - - if ( separation >= speculativeDistance ) - { - // Cache hit, shapes are separated - return (b3EdgeQuery){ - .normal = maxNormal, - .separation = maxSeparation, - .indexA = maxIndexA, - .indexB = maxIndexB, - }; - } - } - } - } - } - - return (b3EdgeQuery){ - .normal = maxNormal, - .separation = maxSeparation, - .indexA = maxIndexA, - .indexB = maxIndexB, - }; -} - -void b3CollideHulls( b3LocalManifold* manifold, int capacity, const b3HullData* hullA, const b3HullData* hullB, - b3Transform transformBtoA, b3SATCache* cache ) -{ - manifold->pointCount = 0; - - if ( capacity < 4 ) - { - return; - } - - // Work in shapeA coordinates - float speculativeDistance = B3_SPECULATIVE_DISTANCE; - - float linearSlop = B3_LINEAR_SLOP; - const b3HullHalfEdge* edgesA = b3GetHullEdges( hullA ); - const b3Plane* planesA = b3GetHullPlanes( hullA ); - const b3Vec3* pointsA = b3GetHullPoints( hullA ); - - const b3HullHalfEdge* edgesB = b3GetHullEdges( hullB ); - const b3Plane* planesB = b3GetHullPlanes( hullB ); - const b3Vec3* pointsB = b3GetHullPoints( hullB ); - - // Attempt to use the cache to speed up collision - switch ( cache->type ) - { - case b3_invalidAxis: - *cache = (b3SATCache){ 0 }; - break; - - case b3_faceAxisA: - { - B3_ASSERT( cache->indexA < hullA->faceCount ); - - // Check for separation using cached face - b3Plane plane = planesA[cache->indexA]; - b3Vec3 searchDirectionInB = b3Neg( b3InvRotateVector( transformBtoA.q, plane.normal ) ); - int vertexIndex = b3FindHullSupportVertex( hullB, searchDirectionInB ); - b3Vec3 support = b3TransformPoint( transformBtoA, pointsB[vertexIndex] ); - float separation = b3PlaneSeparation( plane, support ); - - if ( separation >= speculativeDistance ) - { - // Cache hit, shapes are separated - return; - } - - // if ( cache->separation < speculativeDistance ) - { - // Attempt face contact using cached feature - b3FaceQuery faceQuery; - faceQuery.separation = 0.0f; - faceQuery.faceIndex = cache->indexA; - faceQuery.vertexIndex = vertexIndex; - - b3SATCache localCache = { 0 }; - bool touching = b3BuildFaceAContact( manifold, capacity, hullA, hullB, transformBtoA, faceQuery, &localCache ); - if ( touching == true && b3AbsFloat( cache->separation - localCache.separation ) < linearSlop ) - { - // Cache hit, contact points generated - return; - } - } - } - break; - - case b3_faceAxisB: - { - B3_ASSERT( cache->indexB < hullB->faceCount ); - - // Check for separation using cached face - b3Plane plane = planesB[cache->indexB]; - b3Vec3 searchDirectionInA = b3Neg( b3RotateVector( transformBtoA.q, plane.normal ) ); - int vertexIndex = b3FindHullSupportVertex( hullA, searchDirectionInA ); - b3Vec3 support = b3InvTransformPoint( transformBtoA, pointsA[vertexIndex] ); - float separation = b3PlaneSeparation( plane, support ); - - if ( separation >= speculativeDistance ) - { - // Cache hit, shapes are separated - return; - } - - // if ( cache->separation < speculativeDistance ) - { - // Attempt face contact using cached feature - b3FaceQuery faceQuery; - faceQuery.separation = 0.0f; - faceQuery.faceIndex = cache->indexB; - faceQuery.vertexIndex = vertexIndex; - - b3SATCache localCache = { 0 }; - bool touching = b3BuildFaceBContact( manifold, capacity, hullA, hullB, transformBtoA, faceQuery, &localCache ); - if ( touching == true && b3AbsFloat( cache->separation - localCache.separation ) < linearSlop ) - { - // Cache hit, contact points generated - return; - } - } - } - break; - - case b3_edgePairAxis: - { - int indexA = cache->indexA; - const b3HullHalfEdge* edge1 = edgesA + indexA; - const b3HullHalfEdge* twin1 = edgesA + indexA + 1; - B3_ASSERT( edge1->twin == indexA + 1 && twin1->twin == indexA ); - - b3Vec3 pA = pointsA[edge1->origin]; - b3Vec3 qA = pointsA[twin1->origin]; - b3Vec3 eA = b3Sub( qA, pA ); - - b3Vec3 uA = planesA[edge1->face].normal; - b3Vec3 vA = planesA[twin1->face].normal; - - int indexB = cache->indexB; - const b3HullHalfEdge* edge2 = edgesB + indexB; - const b3HullHalfEdge* twin2 = edgesB + indexB + 1; - B3_ASSERT( edge2->twin == indexB + 1 && twin2->twin == indexB ); - - b3Vec3 pB = b3TransformPoint( transformBtoA, pointsB[edge2->origin] ); - b3Vec3 qB = b3TransformPoint( transformBtoA, pointsB[twin2->origin] ); - b3Vec3 eB = b3Sub( qB, pB ); - - b3Vec3 uB = b3RotateVector( transformBtoA.q, planesB[edge2->face].normal ); - b3Vec3 vB = b3RotateVector( transformBtoA.q, planesB[twin2->face].normal ); - - // flipping the signs of u2 and v2 - // cross(v2, u2) == cross(-v2, -u2) - // so we still use -e2 - // but we can also use e1 = cross(u1, v1) and e2 = cross(u2, v2) - float cba = b3Dot( uB, eA ); - float dba = b3Dot( vB, eA ); - float adc = -b3Dot( uA, eB ); - float bdc = -b3Dot( vA, eB ); - - if ( cba * dba < 0.0f && adc * bdc < 0.0f && cba * bdc > 0.0f ) - { - // Avoid nearly parallel edges that may lead to invalid separation values at the noise floor. - float squaredTolerance = B3_PARALLEL_EDGE_TOL * B3_PARALLEL_EDGE_TOL; - if ( b3MaxFloat( cba * cba, dba * dba ) >= squaredTolerance * b3LengthSquared( eA ) ) - { - // Transform reference center of the first hull into local space of the second hull - float t = cba / ( cba - dba ); - b3Vec3 axis = b3Lerp( uB, vB, t ); - B3_VALIDATE( b3LengthSquared( axis ) > 1000.0f * FLT_MIN ); - axis = b3Normalize( axis ); - float separation = b3Dot( axis, b3Sub( qA, qB ) ); - - if ( separation > speculativeDistance ) - { - // Cache hit, shapes are separated - return; - } - - // Try to rebuild contact from last features - b3EdgeQuery edgeQuery = { 0 }; - edgeQuery.normal = b3Neg( axis ); - edgeQuery.separation = 0.0f; - edgeQuery.indexA = cache->indexA; - edgeQuery.indexB = cache->indexB; - - b3SATCache localCache = { 0 }; - bool touching = b3BuildEdgeContact( manifold, hullA, hullB, transformBtoA, edgeQuery, &localCache ); - if ( touching && b3AbsFloat( cache->separation - localCache.separation ) < linearSlop ) - { - // Cache hit, contact point generated - return; - } - } - } - } - break; - - // This case is for testing - case b3_manualFaceAxisA: - { - b3FaceQuery faceQueryA = b3QueryFaceDirections( hullA, hullB, transformBtoA ); - b3BuildFaceAContact( manifold, capacity, hullA, hullB, transformBtoA, faceQueryA, cache ); - return; - } - - // This case is for testing - case b3_manualFaceAxisB: - { - b3FaceQuery faceQueryB = b3QueryFaceDirections( hullB, hullA, b3InvertTransform( transformBtoA ) ); - b3BuildFaceBContact( manifold, capacity, hullA, hullB, transformBtoA, faceQueryB, cache ); - return; - } - - // This case is for testing - case b3_manualEdgePairAxis: - { - b3EdgeQuery edgeQuery = b3QueryEdgeDirections( hullA, hullB, transformBtoA ); - if ( edgeQuery.indexA != B3_NULL_INDEX ) - { - b3BuildEdgeContact( manifold, hullA, hullB, transformBtoA, edgeQuery, cache ); - } - return; - } - - default: - B3_ASSERT( false ); - break; - } - - manifold->pointCount = 0; - *cache = (b3SATCache){ 0 }; - - // Find axis of minimum penetration - b3FaceQuery faceQueryA = b3QueryFaceDirections( hullA, hullB, transformBtoA ); - if ( faceQueryA.separation > speculativeDistance ) - { - B3_ASSERT( faceQueryA.faceIndex < hullA->faceCount ); - B3_ASSERT( faceQueryA.vertexIndex < hullB->vertexCount ); - - // We found a separating axis - cache->separation = faceQueryA.separation; - cache->type = (uint8_t)b3_faceAxisA; - cache->indexA = (uint8_t)faceQueryA.faceIndex; - cache->indexB = (uint8_t)faceQueryA.vertexIndex; - return; - } - - b3FaceQuery faceQueryB = b3QueryFaceDirections( hullB, hullA, b3InvertTransform( transformBtoA ) ); - if ( faceQueryB.separation > speculativeDistance ) - { - B3_ASSERT( faceQueryB.faceIndex < hullB->faceCount ); - B3_ASSERT( faceQueryB.vertexIndex < hullA->vertexCount ); - - // We found a separating axis - cache->separation = faceQueryB.separation; - cache->type = (uint8_t)b3_faceAxisB; - cache->indexA = (uint8_t)faceQueryB.vertexIndex; - cache->indexB = (uint8_t)faceQueryB.faceIndex; - return; - } - - b3EdgeQuery edgeQuery = b3QueryEdgeDirections( hullA, hullB, transformBtoA ); - if ( edgeQuery.separation > speculativeDistance ) - { - // We found a separating axis - cache->separation = edgeQuery.separation; - cache->type = (uint8_t)b3_edgePairAxis; - cache->indexA = (uint8_t)edgeQuery.indexA; - cache->indexB = (uint8_t)edgeQuery.indexB; - return; - } - - // Always build a face contact (e.g. Jenga problem) - float faceSeparationA = faceQueryA.separation; - float faceSeparationB = faceQueryB.separation; - B3_VALIDATE( faceSeparationA <= speculativeDistance && faceSeparationB <= speculativeDistance ); - - if ( faceSeparationB > faceSeparationA + 0.5f * linearSlop ) - { - // Face contact B - b3BuildFaceBContact( manifold, capacity, hullA, hullB, transformBtoA, faceQueryB, cache ); - } - else - { - // Face contact A - b3BuildFaceAContact( manifold, capacity, hullA, hullB, transformBtoA, faceQueryA, cache ); - } - - if ( edgeQuery.indexA == B3_NULL_INDEX ) - { - // There are no valid edge pairs (all edges parallel) - return; - } - - float clippedFaceSeparation = cache->separation; - - B3_VALIDATE( edgeQuery.separation <= speculativeDistance ); - - // todo get rid of relative tolerance - const float kRelEdgeTolerance = 0.90f; - // const float kRelFaceTolerance = 0.98f; - const float kAbsTolerance = 0.5f * linearSlop; - - // Face contact can be empty if it does not realize the axis of minimum penetration. - // Create edge contact if face contact fails or edge contact is significantly better! - if ( manifold->pointCount == 0 || edgeQuery.separation > kRelEdgeTolerance * clippedFaceSeparation + kAbsTolerance ) - { - // Edge contact - b3LocalManifold edgeManifold = { 0 }; - b3LocalManifoldPoint edgePoint = { 0 }; - edgeManifold.points = &edgePoint; - - b3BuildEdgeContact( &edgeManifold, hullA, hullB, transformBtoA, edgeQuery, cache ); - - // It is possible with speculation to have vertex-vertex collision that is missed by SAT. - // todo I doubt this backup scheme matters because I'm using the clipped face separation. - // B3_VALIDATE( edgeManifold.pointCount == 1 ); - - if ( edgeManifold.pointCount == 1 ) - { - // Copy edge manifold out, being careful to preserve manifold point buffer. - b3LocalManifoldPoint* points = manifold->points; - *manifold = edgeManifold; - manifold->points = points; - manifold->points[0] = edgePoint; - } - } -} - -#endif diff --git a/src/hull.c b/src/hull.c index 27cb6f6..97026d9 100644 --- a/src/hull.c +++ b/src/hull.c @@ -1920,6 +1920,51 @@ b3HullData* b3CreateRock( float radius ) return b3CreateHull( points, pointCount, pointCount ); } +// PEEL's BasicRandom. This is just for testing. +static uint32_t b3NextComplexHullRandom( uint32_t* state ) +{ + *state = *state * 2147001325u + 715136305u; + return *state; +} + +static float b3ComplexHullRandomFloat( uint32_t* state ) +{ + return (float)( b3NextComplexHullRandom( state ) & 0xffff ) / 65535.0f - 0.5f; +} + +static b3Vec3 b3ComplexHullRandomDirection( uint32_t* state ) +{ + b3Vec3 point; + float lengthSquared; + do + { + point.x = b3ComplexHullRandomFloat( state ); + point.y = b3ComplexHullRandomFloat( state ); + point.z = b3ComplexHullRandomFloat( state ); + lengthSquared = b3Dot( point, point ); + } + while ( lengthSquared > 0.25f ); + + return b3Normalize( point ); +} + +b3HullData* b3CreateComplexHull( float radius ) +{ + enum + { + pointCount = 32 + }; + + b3Vec3 points[pointCount]; + uint32_t state = 42; + for ( int i = 0; i < pointCount; ++i ) + { + points[i] = b3MulSV( radius, b3ComplexHullRandomDirection( &state ) ); + } + + return b3CreateHull( points, pointCount, pointCount ); +} + static void b3UpdateHullBounds( b3HullData* hull ) { const b3Vec3* points = b3GetHullPoints( hull ); diff --git a/src/simd.h b/src/simd.h index e7b80bd..07ee15f 100644 --- a/src/simd.h +++ b/src/simd.h @@ -554,11 +554,6 @@ static inline b3FloatW b3BlendW( b3FloatW a, b3FloatW b, b3FloatW mask ) return vbslq_f32( mask32, b, a ); } -static inline b3FloatW b3Dot3W( b3FloatW ax, b3FloatW ay, b3FloatW az, b3FloatW bx, b3FloatW by, b3FloatW bz ) -{ - return vaddq_f32( vmulq_f32( ax, bx ), vaddq_f32( vmulq_f32( ay, by ), vmulq_f32( az, bz ) ) ); -} - static inline b3FloatW b3EmbedIndexW( b3FloatW value, int baseIndex, int bitCount ) { uint32_t mask = ( 1u << bitCount ) - 1; @@ -749,11 +744,6 @@ static inline b3FloatW b3BlendW( b3FloatW a, b3FloatW b, b3FloatW mask ) return _mm_or_ps( _mm_and_ps( mask, b ), _mm_andnot_ps( mask, a ) ); } -static inline b3FloatW b3Dot3W( b3FloatW ax, b3FloatW ay, b3FloatW az, b3FloatW bx, b3FloatW by, b3FloatW bz ) -{ - return _mm_add_ps( _mm_mul_ps( ax, bx ), _mm_add_ps( _mm_mul_ps( ay, by ), _mm_mul_ps( az, bz ) ) ); -} - // Replace the low bitCount mantissa bits of each lane with baseIndex + lane. The value must be // positive so the embedded index sorts with the value, and ties fall to the lower index. static inline b3FloatW b3EmbedIndexW( b3FloatW value, int baseIndex, int bitCount ) @@ -981,16 +971,6 @@ static inline b3FloatW b3BlendW( b3FloatW a, b3FloatW b, b3FloatW mask ) return r; } -static inline b3FloatW b3Dot3W( b3FloatW ax, b3FloatW ay, b3FloatW az, b3FloatW bx, b3FloatW by, b3FloatW bz ) -{ - b3FloatW r; - r.x = ax.x * bx.x + ( ay.x * by.x + az.x * bz.x ); - r.y = ax.y * bx.y + ( ay.y * by.y + az.y * bz.y ); - r.z = ax.z * bx.z + ( ay.z * by.z + az.z * bz.z ); - r.w = ax.w * bx.w + ( ay.w * by.w + az.w * bz.w ); - return r; -} - static inline b3FloatW b3EmbedIndexW( b3FloatW value, int baseIndex, int bitCount ) { uint32_t mask = ( 1u << bitCount ) - 1; @@ -1034,6 +1014,86 @@ static inline void b3TransposeW( b3FloatW r0, b3FloatW r1, b3FloatW r2, b3FloatW *c3 = b3UnpackHiW( t2, t3 ); } +// Wide vec3 +typedef struct b3Vec3W +{ + b3FloatW X, Y, Z; +} b3Vec3W; + +static inline b3Vec3W b3LoadVW( const float* x, const float* y, const float* z ) +{ + return (b3Vec3W){ b3LoadW( x ), b3LoadW( y ), b3LoadW( z ) }; +} + +static inline void b3StoreVW( float* x, float* y, float* z, b3Vec3W v ) +{ + b3StoreW( x, v.X ); + b3StoreW( y, v.Y ); + b3StoreW( z, v.Z ); +} + +static inline b3Vec3W b3SplatVW( b3Vec3 v ) +{ + return (b3Vec3W){ b3SplatW( v.x ), b3SplatW( v.y ), b3SplatW( v.z ) }; +} + +static inline b3Vec3W b3NegVW( b3Vec3W a ) +{ + return (b3Vec3W){ b3NegW( a.X ), b3NegW( a.Y ), b3NegW( a.Z ) }; +} + +// s * a +static inline b3Vec3W b3MulSVW( b3FloatW s, b3Vec3W a ) +{ + return (b3Vec3W){ b3MulW( s, a.X ), b3MulW( s, a.Y ), b3MulW( s, a.Z ) }; +} + +// a - s * b +static inline b3Vec3W b3MulSubSVW( b3Vec3W a, b3FloatW s, b3Vec3W b ) +{ + return (b3Vec3W){ b3SubW( a.X, b3MulW( s, b.X ) ), b3SubW( a.Y, b3MulW( s, b.Y ) ), b3SubW( a.Z, b3MulW( s, b.Z ) ) }; +} + +// a + s * b +static inline b3Vec3W b3MulAddSVW( b3Vec3W a, b3FloatW s, b3Vec3W b ) +{ + return (b3Vec3W){ b3AddW( a.X, b3MulW( s, b.X ) ), b3AddW( a.Y, b3MulW( s, b.Y ) ), b3AddW( a.Z, b3MulW( s, b.Z ) ) }; +} + +// a - b +static inline b3Vec3W b3SubVW( b3Vec3W a, b3Vec3W b ) +{ + return (b3Vec3W){ + b3SubW( a.X, b.X ), + b3SubW( a.Y, b.Y ), + b3SubW( a.Z, b.Z ), + }; +} + +// a + b +static inline b3Vec3W b3AddVW( b3Vec3W a, b3Vec3W b ) +{ + return (b3Vec3W){ + b3AddW( a.X, b.X ), + b3AddW( a.Y, b.Y ), + b3AddW( a.Z, b.Z ), + }; +} + +static inline b3FloatW b3DotW( b3Vec3W a, b3Vec3W b ) +{ + return b3AddW( b3AddW( b3MulW( a.X, b.X ), b3MulW( a.Y, b.Y ) ), b3MulW( a.Z, b.Z ) ); +} + +static inline b3Vec3W b3CrossW( b3Vec3W a, b3Vec3W b ) +{ + b3Vec3W c; + c.X = b3SubW( b3MulW( a.Y, b.Z ), b3MulW( a.Z, b.Y ) ); + c.Y = b3SubW( b3MulW( a.Z, b.X ), b3MulW( a.X, b.Z ) ); + c.Z = b3SubW( b3MulW( a.X, b.Y ), b3MulW( a.Y, b.X ) ); + return c; +} + #if defined( B3_SIMD_NEON ) typedef struct b3AABBV diff --git a/test/test_determinism.c b/test/test_determinism.c index 9333e03..23e74ad 100644 --- a/test/test_determinism.c +++ b/test/test_determinism.c @@ -21,7 +21,7 @@ #define RAGDOLL_SLEEP_STEP 273 #define RAGDOLL_HASH 0x0F4DD1EB #define WAVE_PILE_SLEEP_STEP 314 -#define WAVE_PILE_HASH 0xD9B88124 +#define WAVE_PILE_HASH 0x03B509B6 #define QUERY_SPAWN_SLEEP_STEP 242 #define QUERY_SPAWN_HASH 0x9B96A098 #define QUERY_SPAWN_HIT_COUNT 59 @@ -31,8 +31,8 @@ #else #define RAGDOLL_SLEEP_STEP 274 #define RAGDOLL_HASH 0x773AB8ED -#define WAVE_PILE_SLEEP_STEP 330 -#define WAVE_PILE_HASH 0x205D6055 +#define WAVE_PILE_SLEEP_STEP 314 +#define WAVE_PILE_HASH 0x8CB8F656 #define QUERY_SPAWN_SLEEP_STEP 242 #define QUERY_SPAWN_HASH 0xF1EDEF47 #define QUERY_SPAWN_HIT_COUNT 59