SphereShape.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <Jolt/Jolt.h>
  4. #include <Jolt/Physics/Collision/Shape/SphereShape.h>
  5. #include <Jolt/Physics/Collision/Shape/ScaleHelpers.h>
  6. #include <Jolt/Physics/Collision/Shape/GetTrianglesContext.h>
  7. #include <Jolt/Physics/Collision/RayCast.h>
  8. #include <Jolt/Physics/Collision/CastResult.h>
  9. #include <Jolt/Physics/Collision/CollidePointResult.h>
  10. #include <Jolt/Physics/Collision/TransformedShape.h>
  11. #include <Jolt/Geometry/RaySphere.h>
  12. #include <Jolt/Geometry/Plane.h>
  13. #include <Jolt/Core/StreamIn.h>
  14. #include <Jolt/Core/StreamOut.h>
  15. #include <Jolt/ObjectStream/TypeDeclarations.h>
  16. #ifdef JPH_DEBUG_RENDERER
  17. #include <Jolt/Renderer/DebugRenderer.h>
  18. #endif // JPH_DEBUG_RENDERER
  19. JPH_NAMESPACE_BEGIN
  20. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(SphereShapeSettings)
  21. {
  22. JPH_ADD_BASE_CLASS(SphereShapeSettings, ConvexShapeSettings)
  23. JPH_ADD_ATTRIBUTE(SphereShapeSettings, mRadius)
  24. }
  25. ShapeSettings::ShapeResult SphereShapeSettings::Create() const
  26. {
  27. if (mCachedResult.IsEmpty())
  28. Ref<Shape> shape = new SphereShape(*this, mCachedResult);
  29. return mCachedResult;
  30. }
  31. SphereShape::SphereShape(const SphereShapeSettings &inSettings, ShapeResult &outResult) :
  32. ConvexShape(EShapeSubType::Sphere, inSettings, outResult),
  33. mRadius(inSettings.mRadius)
  34. {
  35. if (inSettings.mRadius <= 0.0f)
  36. {
  37. outResult.SetError("Invalid radius");
  38. return;
  39. }
  40. outResult.Set(this);
  41. }
  42. float SphereShape::GetScaledRadius(Vec3Arg inScale) const
  43. {
  44. JPH_ASSERT(IsValidScale(inScale));
  45. Vec3 abs_scale = inScale.Abs();
  46. return abs_scale.GetX() * mRadius;
  47. }
  48. AABox SphereShape::GetLocalBounds() const
  49. {
  50. Vec3 half_extent = Vec3::sReplicate(mRadius);
  51. return AABox(-half_extent, half_extent);
  52. }
  53. AABox SphereShape::GetWorldSpaceBounds(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale) const
  54. {
  55. float scaled_radius = GetScaledRadius(inScale);
  56. Vec3 half_extent = Vec3::sReplicate(scaled_radius);
  57. AABox bounds(-half_extent, half_extent);
  58. bounds.Translate(inCenterOfMassTransform.GetTranslation());
  59. return bounds;
  60. }
  61. class SphereShape::SphereNoConvex final : public Support
  62. {
  63. public:
  64. explicit SphereNoConvex(float inRadius) :
  65. mRadius(inRadius)
  66. {
  67. static_assert(sizeof(SphereNoConvex) <= sizeof(SupportBuffer), "Buffer size too small");
  68. JPH_ASSERT(IsAligned(this, alignof(SphereNoConvex)));
  69. }
  70. virtual Vec3 GetSupport(Vec3Arg inDirection) const override
  71. {
  72. return Vec3::sZero();
  73. }
  74. virtual float GetConvexRadius() const override
  75. {
  76. return mRadius;
  77. }
  78. private:
  79. float mRadius;
  80. };
  81. class SphereShape::SphereWithConvex final : public Support
  82. {
  83. public:
  84. explicit SphereWithConvex(float inRadius) :
  85. mRadius(inRadius)
  86. {
  87. static_assert(sizeof(SphereWithConvex) <= sizeof(SupportBuffer), "Buffer size too small");
  88. JPH_ASSERT(IsAligned(this, alignof(SphereWithConvex)));
  89. }
  90. virtual Vec3 GetSupport(Vec3Arg inDirection) const override
  91. {
  92. float len = inDirection.Length();
  93. return len > 0.0f? (mRadius / len) * inDirection : Vec3::sZero();
  94. }
  95. virtual float GetConvexRadius() const override
  96. {
  97. return 0.0f;
  98. }
  99. private:
  100. float mRadius;
  101. };
  102. const ConvexShape::Support *SphereShape::GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const
  103. {
  104. float scaled_radius = GetScaledRadius(inScale);
  105. switch (inMode)
  106. {
  107. case ESupportMode::IncludeConvexRadius:
  108. return new (&inBuffer) SphereWithConvex(scaled_radius);
  109. case ESupportMode::ExcludeConvexRadius:
  110. return new (&inBuffer) SphereNoConvex(scaled_radius);
  111. }
  112. JPH_ASSERT(false);
  113. return nullptr;
  114. }
  115. MassProperties SphereShape::GetMassProperties() const
  116. {
  117. MassProperties p;
  118. // Calculate mass
  119. float r2 = mRadius * mRadius;
  120. p.mMass = (4.0f / 3.0f * JPH_PI) * mRadius * r2 * GetDensity();
  121. // Calculate inertia
  122. float inertia = (2.0f / 5.0f) * p.mMass * r2;
  123. p.mInertia = Mat44::sScale(inertia);
  124. return p;
  125. }
  126. Vec3 SphereShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
  127. {
  128. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  129. float len = inLocalSurfacePosition.Length();
  130. return len != 0.0f? inLocalSurfacePosition / len : Vec3::sAxisY();
  131. }
  132. void SphereShape::GetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const Plane &inSurface, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy JPH_IF_DEBUG_RENDERER(, RVec3Arg inBaseOffset)) const
  133. {
  134. float scaled_radius = GetScaledRadius(inScale);
  135. outTotalVolume = (4.0f / 3.0f * JPH_PI) * Cubed(scaled_radius);
  136. float distance_to_surface = inSurface.SignedDistance(inCenterOfMassTransform.GetTranslation());
  137. if (distance_to_surface >= scaled_radius)
  138. {
  139. // Above surface
  140. outSubmergedVolume = 0.0f;
  141. outCenterOfBuoyancy = Vec3::sZero();
  142. }
  143. else if (distance_to_surface <= -scaled_radius)
  144. {
  145. // Under surface
  146. outSubmergedVolume = outTotalVolume;
  147. outCenterOfBuoyancy = inCenterOfMassTransform.GetTranslation();
  148. }
  149. else
  150. {
  151. // Intersecting surface
  152. // Calculate submerged volume, see: https://en.wikipedia.org/wiki/Spherical_cap
  153. float h = scaled_radius - distance_to_surface;
  154. outSubmergedVolume = (JPH_PI / 3.0f) * Square(h) * (3.0f * scaled_radius - h);
  155. // Calculate center of buoyancy, see: http://mathworld.wolfram.com/SphericalCap.html (eq 10)
  156. float z = (3.0f / 4.0f) * Square(2.0f * scaled_radius - h) / (3.0f * scaled_radius - h);
  157. outCenterOfBuoyancy = inCenterOfMassTransform.GetTranslation() - z * inSurface.GetNormal(); // Negative normal since we want the portion under the water
  158. #ifdef JPH_DEBUG_RENDERER
  159. // Draw intersection between sphere and water plane
  160. if (sDrawSubmergedVolumes)
  161. {
  162. Vec3 circle_center = inCenterOfMassTransform.GetTranslation() - distance_to_surface * inSurface.GetNormal();
  163. float circle_radius = sqrt(Square(scaled_radius) - Square(distance_to_surface));
  164. DebugRenderer::sInstance->DrawPie(inBaseOffset + circle_center, circle_radius, inSurface.GetNormal(), inSurface.GetNormal().GetNormalizedPerpendicular(), -JPH_PI, JPH_PI, Color::sGreen, DebugRenderer::ECastShadow::Off);
  165. }
  166. #endif // JPH_DEBUG_RENDERER
  167. }
  168. #ifdef JPH_DEBUG_RENDERER
  169. // Draw center of buoyancy
  170. if (sDrawSubmergedVolumes)
  171. DebugRenderer::sInstance->DrawWireSphere(inBaseOffset + outCenterOfBuoyancy, 0.05f, Color::sRed, 1);
  172. #endif // JPH_DEBUG_RENDERER
  173. }
  174. #ifdef JPH_DEBUG_RENDERER
  175. void SphereShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  176. {
  177. DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid;
  178. inRenderer->DrawUnitSphere(inCenterOfMassTransform * Mat44::sScale(mRadius * inScale.Abs().GetX()), inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor, DebugRenderer::ECastShadow::On, draw_mode);
  179. }
  180. #endif // JPH_DEBUG_RENDERER
  181. bool SphereShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const
  182. {
  183. float fraction = RaySphere(inRay.mOrigin, inRay.mDirection, Vec3::sZero(), mRadius);
  184. if (fraction < ioHit.mFraction)
  185. {
  186. ioHit.mFraction = fraction;
  187. ioHit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  188. return true;
  189. }
  190. return false;
  191. }
  192. void SphereShape::CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  193. {
  194. // Test shape filter
  195. if (!inShapeFilter.ShouldCollide(inSubShapeIDCreator.GetID()))
  196. return;
  197. float min_fraction, max_fraction;
  198. int num_results = RaySphere(inRay.mOrigin, inRay.mDirection, Vec3::sZero(), mRadius, min_fraction, max_fraction);
  199. if (num_results > 0 // Ray should intersect
  200. && max_fraction >= 0.0f // End of ray should be inside sphere
  201. && min_fraction < ioCollector.GetEarlyOutFraction()) // Start of ray should be before early out fraction
  202. {
  203. // Better hit than the current hit
  204. RayCastResult hit;
  205. hit.mBodyID = TransformedShape::sGetBodyID(ioCollector.GetContext());
  206. hit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  207. // Check front side hit
  208. if (inRayCastSettings.mTreatConvexAsSolid || min_fraction > 0.0f)
  209. {
  210. hit.mFraction = max(0.0f, min_fraction);
  211. ioCollector.AddHit(hit);
  212. }
  213. // Check back side hit
  214. if (inRayCastSettings.mBackFaceMode == EBackFaceMode::CollideWithBackFaces
  215. && num_results > 1 // Ray should have 2 intersections
  216. && max_fraction < ioCollector.GetEarlyOutFraction()) // End of ray should be before early out fraction
  217. {
  218. hit.mFraction = max_fraction;
  219. ioCollector.AddHit(hit);
  220. }
  221. }
  222. }
  223. void SphereShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  224. {
  225. // Test shape filter
  226. if (!inShapeFilter.ShouldCollide(inSubShapeIDCreator.GetID()))
  227. return;
  228. if (inPoint.LengthSq() <= Square(mRadius))
  229. ioCollector.AddHit({ TransformedShape::sGetBodyID(ioCollector.GetContext()), inSubShapeIDCreator.GetID() });
  230. }
  231. void SphereShape::TransformShape(Mat44Arg inCenterOfMassTransform, TransformedShapeCollector &ioCollector) const
  232. {
  233. Vec3 scale;
  234. Mat44 transform = inCenterOfMassTransform.Decompose(scale);
  235. TransformedShape ts(RVec3(transform.GetTranslation()), transform.GetRotation().GetQuaternion(), this, BodyID(), SubShapeIDCreator());
  236. ts.SetShapeScale(ScaleHelpers::MakeUniformScale(scale.Abs()));
  237. ioCollector.AddHit(ts);
  238. }
  239. void SphereShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const
  240. {
  241. float scaled_radius = GetScaledRadius(inScale);
  242. new (&ioContext) GetTrianglesContextVertexList(inPositionCOM, inRotation, Vec3::sReplicate(1.0f), Mat44::sScale(scaled_radius), sUnitSphereTriangles.data(), sUnitSphereTriangles.size(), GetMaterial());
  243. }
  244. int SphereShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const
  245. {
  246. return ((GetTrianglesContextVertexList &)ioContext).GetTrianglesNext(inMaxTrianglesRequested, outTriangleVertices, outMaterials);
  247. }
  248. void SphereShape::SaveBinaryState(StreamOut &inStream) const
  249. {
  250. ConvexShape::SaveBinaryState(inStream);
  251. inStream.Write(mRadius);
  252. }
  253. void SphereShape::RestoreBinaryState(StreamIn &inStream)
  254. {
  255. ConvexShape::RestoreBinaryState(inStream);
  256. inStream.Read(mRadius);
  257. }
  258. bool SphereShape::IsValidScale(Vec3Arg inScale) const
  259. {
  260. return ConvexShape::IsValidScale(inScale) && ScaleHelpers::IsUniformScale(inScale.Abs());
  261. }
  262. void SphereShape::sRegister()
  263. {
  264. ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::Sphere);
  265. f.mConstruct = []() -> Shape * { return new SphereShape; };
  266. f.mColor = Color::sGreen;
  267. }
  268. JPH_NAMESPACE_END