Path: blob/master/thirdparty/jolt_physics/Jolt/Physics/Collision/CastSphereVsTriangles.cpp
9913 views
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)1// SPDX-FileCopyrightText: 2021 Jorrit Rouwe2// SPDX-License-Identifier: MIT34#include <Jolt/Jolt.h>56#include <Jolt/Physics/Collision/CastSphereVsTriangles.h>7#include <Jolt/Physics/Collision/TransformedShape.h>8#include <Jolt/Physics/Collision/Shape/ScaleHelpers.h>9#include <Jolt/Physics/Collision/Shape/SphereShape.h>10#include <Jolt/Physics/Collision/ActiveEdges.h>11#include <Jolt/Physics/Collision/NarrowPhaseStats.h>12#include <Jolt/Geometry/ClosestPoint.h>13#include <Jolt/Geometry/RaySphere.h>14#include <Jolt/Core/Profiler.h>1516JPH_NAMESPACE_BEGIN1718CastSphereVsTriangles::CastSphereVsTriangles(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, CastShapeCollector &ioCollector) :19mStart(inShapeCast.mCenterOfMassStart.GetTranslation()),20mDirection(inShapeCast.mDirection),21mShapeCastSettings(inShapeCastSettings),22mCenterOfMassTransform2(inCenterOfMassTransform2),23mScale(inScale),24mSubShapeIDCreator1(inSubShapeIDCreator1),25mCollector(ioCollector)26{27// Cast to sphere shape28JPH_ASSERT(inShapeCast.mShape->GetSubType() == EShapeSubType::Sphere);29const SphereShape *sphere = static_cast<const SphereShape *>(inShapeCast.mShape);3031// Scale the radius32mRadius = sphere->GetRadius() * abs(inShapeCast.mScale.GetX());3334// Determine if shape is inside out or not35mScaleSign = ScaleHelpers::IsInsideOut(inScale)? -1.0f : 1.0f;36}3738void CastSphereVsTriangles::AddHit(bool inBackFacing, const SubShapeID &inSubShapeID2, float inFraction, Vec3Arg inContactPointA, Vec3Arg inContactPointB, Vec3Arg inContactNormal)39{40// Convert to world space41Vec3 contact_point_a = mCenterOfMassTransform2 * (mStart + inContactPointA);42Vec3 contact_point_b = mCenterOfMassTransform2 * (mStart + inContactPointB);43Vec3 contact_normal_world = mCenterOfMassTransform2.Multiply3x3(inContactNormal);4445// Its a hit, store the sub shape id's46ShapeCastResult result(inFraction, contact_point_a, contact_point_b, contact_normal_world, inBackFacing, mSubShapeIDCreator1.GetID(), inSubShapeID2, TransformedShape::sGetBodyID(mCollector.GetContext()));4748// Note: We don't gather faces here because that's only useful if both shapes have a face. Since the sphere always has only 1 contact point, the manifold is always a point.4950JPH_IF_TRACK_NARROWPHASE_STATS(TrackNarrowPhaseCollector track;)51mCollector.AddHit(result);52}5354void CastSphereVsTriangles::AddHitWithActiveEdgeDetection(Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2, bool inBackFacing, Vec3Arg inTriangleNormal, uint8 inActiveEdges, const SubShapeID &inSubShapeID2, float inFraction, Vec3Arg inContactPointA, Vec3Arg inContactPointB, Vec3Arg inContactNormal)55{56// Check if we have enabled active edge detection57Vec3 contact_normal = inContactNormal;58if (mShapeCastSettings.mActiveEdgeMode == EActiveEdgeMode::CollideOnlyWithActive && inActiveEdges != 0b111)59{60// Convert the active edge velocity hint to local space61Vec3 active_edge_movement_direction = mCenterOfMassTransform2.Multiply3x3Transposed(mShapeCastSettings.mActiveEdgeMovementDirection);6263// Update the contact normal to account for active edges64// Note that we flip the triangle normal as the penetration axis is pointing towards the triangle instead of away65contact_normal = ActiveEdges::FixNormal(inV0, inV1, inV2, inBackFacing? inTriangleNormal : -inTriangleNormal, inActiveEdges, inContactPointB, inContactNormal, active_edge_movement_direction);66}6768AddHit(inBackFacing, inSubShapeID2, inFraction, inContactPointA, inContactPointB, contact_normal);69}7071// This is a simplified version of the ray cylinder test from: Real Time Collision Detection - Christer Ericson72// Chapter 5.3.7, page 194-197. Some conditions have been removed as we're not interested in hitting the caps of the cylinder.73// Note that the ray origin is assumed to be the origin here.74float CastSphereVsTriangles::RayCylinder(Vec3Arg inRayDirection, Vec3Arg inCylinderA, Vec3Arg inCylinderB, float inRadius) const75{76// Calculate cylinder axis77Vec3 axis = inCylinderB - inCylinderA;7879// Make ray start relative to cylinder side A (moving cylinder A to the origin)80Vec3 start = -inCylinderA;8182// Test if segment is fully on the A side of the cylinder83float start_dot_axis = start.Dot(axis);84float direction_dot_axis = inRayDirection.Dot(axis);85float end_dot_axis = start_dot_axis + direction_dot_axis;86if (start_dot_axis < 0.0f && end_dot_axis < 0.0f)87return FLT_MAX;8889// Test if segment is fully on the B side of the cylinder90float axis_len_sq = axis.LengthSq();91if (start_dot_axis > axis_len_sq && end_dot_axis > axis_len_sq)92return FLT_MAX;9394// Calculate a, b and c, the factors for quadratic equation95// We're basically solving the ray: x = start + direction * t96// The closest point to x on the segment A B is: w = (x . axis) * axis / (axis . axis)97// The distance between x and w should be radius: (x - w) . (x - w) = radius^298// Solving this gives the following:99float a = axis_len_sq * inRayDirection.LengthSq() - Square(direction_dot_axis);100if (abs(a) < 1.0e-6f)101return FLT_MAX; // Segment runs parallel to cylinder axis, stop processing, we will either hit at fraction = 0 or we'll hit a vertex102float b = axis_len_sq * start.Dot(inRayDirection) - direction_dot_axis * start_dot_axis; // should be multiplied by 2, instead we'll divide a and c by 2 when we solve the quadratic equation103float c = axis_len_sq * (start.LengthSq() - Square(inRadius)) - Square(start_dot_axis);104float det = Square(b) - a * c; // normally 4 * a * c but since both a and c need to be divided by 2 we lose the 4105if (det < 0.0f)106return FLT_MAX; // No solution to quadratic equation107108// Solve fraction t where the ray hits the cylinder109float t = -(b + sqrt(det)) / a; // normally divided by 2 * a but since a should be divided by 2 we lose the 2110if (t < 0.0f || t > 1.0f)111return FLT_MAX; // Intersection lies outside segment112if (start_dot_axis + t * direction_dot_axis < 0.0f || start_dot_axis + t * direction_dot_axis > axis_len_sq)113return FLT_MAX; // Intersection outside the end point of the cylinder, stop processing, we will possibly hit a vertex114return t;115}116117void CastSphereVsTriangles::Cast(Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2, uint8 inActiveEdges, const SubShapeID &inSubShapeID2)118{119JPH_PROFILE_FUNCTION();120121// Scale triangle and make it relative to the start of the cast122Vec3 v0 = mScale * inV0 - mStart;123Vec3 v1 = mScale * inV1 - mStart;124Vec3 v2 = mScale * inV2 - mStart;125126// Calculate triangle normal127Vec3 triangle_normal = mScaleSign * (v1 - v0).Cross(v2 - v0);128float triangle_normal_len = triangle_normal.Length();129if (triangle_normal_len == 0.0f)130return; // Degenerate triangle131triangle_normal /= triangle_normal_len;132133// Backface check134float normal_dot_direction = triangle_normal.Dot(mDirection);135bool back_facing = normal_dot_direction > 0.0f;136if (mShapeCastSettings.mBackFaceModeTriangles == EBackFaceMode::IgnoreBackFaces && back_facing)137return;138139// Test if distance between the sphere and plane of triangle is smaller or equal than the radius140if (abs(v0.Dot(triangle_normal)) <= mRadius)141{142// Check if the sphere intersects at the start of the cast143uint32 closest_feature;144Vec3 q = ClosestPoint::GetClosestPointOnTriangle(v0, v1, v2, closest_feature);145float q_len_sq = q.LengthSq();146if (q_len_sq <= Square(mRadius))147{148// Early out if this hit is deeper than the collector's early out value149float q_len = sqrt(q_len_sq);150float penetration_depth = mRadius - q_len;151if (-penetration_depth >= mCollector.GetEarlyOutFraction())152return;153154// Generate contact point155Vec3 contact_normal = q_len > 0.0f? q / q_len : Vec3::sAxisY();156Vec3 contact_point_a = q + contact_normal * penetration_depth;157Vec3 contact_point_b = q;158AddHitWithActiveEdgeDetection(v0, v1, v2, back_facing, triangle_normal, inActiveEdges, inSubShapeID2, 0.0f, contact_point_a, contact_point_b, contact_normal);159return;160}161}162else163{164// Check if cast is not parallel to the plane of the triangle165float abs_normal_dot_direction = abs(normal_dot_direction);166if (abs_normal_dot_direction > 1.0e-6f)167{168// Calculate the point on the sphere that will hit the triangle's plane first and calculate a fraction where it will do so169Vec3 d = Sign(normal_dot_direction) * mRadius * triangle_normal;170float plane_intersection = (v0 - d).Dot(triangle_normal) / normal_dot_direction;171172// Check if sphere will hit in the interval that we're interested in173if (plane_intersection * abs_normal_dot_direction < -mRadius // Sphere hits the plane before the sweep, cannot intersect174|| plane_intersection >= mCollector.GetEarlyOutFraction()) // Sphere hits the plane after the sweep / early out fraction, cannot intersect175return;176177// We can only report an interior hit if we're hitting the plane during our sweep and not before178if (plane_intersection >= 0.0f)179{180// Calculate the point of contact on the plane181Vec3 p = d + plane_intersection * mDirection;182183// Check if this is an interior point184float u, v, w;185if (ClosestPoint::GetBaryCentricCoordinates(v0 - p, v1 - p, v2 - p, u, v, w)186&& u >= 0.0f && v >= 0.0f && w >= 0.0f)187{188// Interior point, we found the collision point. We don't need to check active edges.189AddHit(back_facing, inSubShapeID2, plane_intersection, p, p, back_facing? triangle_normal : -triangle_normal);190return;191}192}193}194}195196// Test 3 edges197float fraction = RayCylinder(mDirection, v0, v1, mRadius);198fraction = min(fraction, RayCylinder(mDirection, v1, v2, mRadius));199fraction = min(fraction, RayCylinder(mDirection, v2, v0, mRadius));200201// Test 3 vertices202fraction = min(fraction, RaySphere(Vec3::sZero(), mDirection, v0, mRadius));203fraction = min(fraction, RaySphere(Vec3::sZero(), mDirection, v1, mRadius));204fraction = min(fraction, RaySphere(Vec3::sZero(), mDirection, v2, mRadius));205206// Check if we have a collision207JPH_ASSERT(fraction >= 0.0f);208if (fraction < mCollector.GetEarlyOutFraction())209{210// Calculate the center of the sphere at the point of contact211Vec3 p = fraction * mDirection;212213// Get contact point and normal214uint32 closest_feature;215Vec3 q = ClosestPoint::GetClosestPointOnTriangle(v0 - p, v1 - p, v2 - p, closest_feature);216Vec3 contact_normal = q.Normalized();217Vec3 contact_point_ab = p + q;218AddHitWithActiveEdgeDetection(v0, v1, v2, back_facing, triangle_normal, inActiveEdges, inSubShapeID2, fraction, contact_point_ab, contact_point_ab, contact_normal);219}220}221222JPH_NAMESPACE_END223224225