Shape.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <Jolt/Jolt.h>
  5. #include <Jolt/Physics/Collision/Shape/Shape.h>
  6. #include <Jolt/Physics/Collision/Shape/ScaledShape.h>
  7. #include <Jolt/Physics/Collision/Shape/StaticCompoundShape.h>
  8. #include <Jolt/Physics/Collision/TransformedShape.h>
  9. #include <Jolt/Physics/Collision/PhysicsMaterial.h>
  10. #include <Jolt/Physics/Collision/RayCast.h>
  11. #include <Jolt/Physics/Collision/CastResult.h>
  12. #include <Jolt/Physics/Collision/CollidePointResult.h>
  13. #include <Jolt/Core/StreamIn.h>
  14. #include <Jolt/Core/StreamOut.h>
  15. #include <Jolt/Core/Factory.h>
  16. #include <Jolt/ObjectStream/TypeDeclarations.h>
  17. JPH_NAMESPACE_BEGIN
  18. JPH_IMPLEMENT_SERIALIZABLE_ABSTRACT_BASE(ShapeSettings)
  19. {
  20. JPH_ADD_BASE_CLASS(ShapeSettings, SerializableObject)
  21. JPH_ADD_ATTRIBUTE(ShapeSettings, mUserData)
  22. }
  23. #ifdef JPH_DEBUG_RENDERER
  24. bool Shape::sDrawSubmergedVolumes = false;
  25. #endif // JPH_DEBUG_RENDERER
  26. ShapeFunctions ShapeFunctions::sRegistry[NumSubShapeTypes];
  27. TransformedShape Shape::GetSubShapeTransformedShape(const SubShapeID &inSubShapeID, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale, SubShapeID &outRemainder) const
  28. {
  29. // We have reached the leaf shape so there is no remainder
  30. outRemainder = SubShapeID();
  31. // Just return the transformed shape for this shape
  32. TransformedShape ts(RVec3(inPositionCOM), inRotation, this, BodyID());
  33. ts.SetShapeScale(inScale);
  34. return ts;
  35. }
  36. void Shape::CollectTransformedShapes(const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale, const SubShapeIDCreator &inSubShapeIDCreator, TransformedShapeCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  37. {
  38. // Test shape filter
  39. if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))
  40. return;
  41. TransformedShape ts(RVec3(inPositionCOM), inRotation, this, TransformedShape::sGetBodyID(ioCollector.GetContext()), inSubShapeIDCreator);
  42. ts.SetShapeScale(inScale);
  43. ioCollector.AddHit(ts);
  44. }
  45. void Shape::TransformShape(Mat44Arg inCenterOfMassTransform, TransformedShapeCollector &ioCollector) const
  46. {
  47. Vec3 scale;
  48. Mat44 transform = inCenterOfMassTransform.Decompose(scale);
  49. TransformedShape ts(RVec3(transform.GetTranslation()), transform.GetQuaternion(), this, BodyID(), SubShapeIDCreator());
  50. ts.SetShapeScale(MakeScaleValid(scale));
  51. ioCollector.AddHit(ts);
  52. }
  53. void Shape::SaveBinaryState(StreamOut &inStream) const
  54. {
  55. inStream.Write(mShapeSubType);
  56. inStream.Write(mUserData);
  57. }
  58. void Shape::RestoreBinaryState(StreamIn &inStream)
  59. {
  60. // Type hash read by sRestoreFromBinaryState
  61. inStream.Read(mUserData);
  62. }
  63. Shape::ShapeResult Shape::sRestoreFromBinaryState(StreamIn &inStream)
  64. {
  65. ShapeResult result;
  66. // Read the type of the shape
  67. EShapeSubType shape_sub_type;
  68. inStream.Read(shape_sub_type);
  69. if (inStream.IsEOF() || inStream.IsFailed())
  70. {
  71. result.SetError("Failed to read type id");
  72. return result;
  73. }
  74. // Construct and read the data of the shape
  75. Ref<Shape> shape = ShapeFunctions::sGet(shape_sub_type).mConstruct();
  76. shape->RestoreBinaryState(inStream);
  77. if (inStream.IsEOF() || inStream.IsFailed())
  78. {
  79. result.SetError("Failed to restore shape");
  80. return result;
  81. }
  82. result.Set(shape);
  83. return result;
  84. }
  85. void Shape::SaveWithChildren(StreamOut &inStream, ShapeToIDMap &ioShapeMap, MaterialToIDMap &ioMaterialMap) const
  86. {
  87. ShapeToIDMap::const_iterator shape_id_iter = ioShapeMap.find(this);
  88. if (shape_id_iter == ioShapeMap.end())
  89. {
  90. // Write shape ID of this shape
  91. uint32 shape_id = (uint32)ioShapeMap.size();
  92. ioShapeMap[this] = shape_id;
  93. inStream.Write(shape_id);
  94. // Write the shape itself
  95. SaveBinaryState(inStream);
  96. // Write the ID's of all sub shapes
  97. ShapeList sub_shapes;
  98. SaveSubShapeState(sub_shapes);
  99. inStream.Write(uint32(sub_shapes.size()));
  100. for (const Shape *shape : sub_shapes)
  101. {
  102. if (shape == nullptr)
  103. inStream.Write(~uint32(0));
  104. else
  105. shape->SaveWithChildren(inStream, ioShapeMap, ioMaterialMap);
  106. }
  107. // Write the materials
  108. PhysicsMaterialList materials;
  109. SaveMaterialState(materials);
  110. StreamUtils::SaveObjectArray(inStream, materials, &ioMaterialMap);
  111. }
  112. else
  113. {
  114. // Known shape, just write the ID
  115. inStream.Write(shape_id_iter->second);
  116. }
  117. }
  118. Shape::ShapeResult Shape::sRestoreWithChildren(StreamIn &inStream, IDToShapeMap &ioShapeMap, IDToMaterialMap &ioMaterialMap)
  119. {
  120. ShapeResult result;
  121. // Read ID of this shape
  122. uint32 shape_id;
  123. inStream.Read(shape_id);
  124. if (inStream.IsEOF() || inStream.IsFailed())
  125. {
  126. result.SetError("Failed to read shape id");
  127. return result;
  128. }
  129. // Check nullptr shape
  130. if (shape_id == ~uint32(0))
  131. {
  132. result.Set(nullptr);
  133. return result;
  134. }
  135. // Check if we already read this shape
  136. if (shape_id < ioShapeMap.size())
  137. {
  138. result.Set(ioShapeMap[shape_id]);
  139. return result;
  140. }
  141. // Read the shape
  142. result = sRestoreFromBinaryState(inStream);
  143. if (result.HasError())
  144. return result;
  145. JPH_ASSERT(ioShapeMap.size() == shape_id); // Assert that this is the next ID in the map
  146. ioShapeMap.push_back(result.Get());
  147. // Read the sub shapes
  148. uint32 len;
  149. inStream.Read(len);
  150. if (inStream.IsEOF() || inStream.IsFailed())
  151. {
  152. result.SetError("Failed to read stream");
  153. return result;
  154. }
  155. ShapeList sub_shapes;
  156. sub_shapes.reserve(len);
  157. for (size_t i = 0; i < len; ++i)
  158. {
  159. ShapeResult sub_shape_result = sRestoreWithChildren(inStream, ioShapeMap, ioMaterialMap);
  160. if (sub_shape_result.HasError())
  161. return sub_shape_result;
  162. sub_shapes.push_back(sub_shape_result.Get());
  163. }
  164. result.Get()->RestoreSubShapeState(sub_shapes.data(), (uint)sub_shapes.size());
  165. // Read the materials
  166. Result mlresult = StreamUtils::RestoreObjectArray<PhysicsMaterialList>(inStream, ioMaterialMap);
  167. if (mlresult.HasError())
  168. {
  169. result.SetError(mlresult.GetError());
  170. return result;
  171. }
  172. const PhysicsMaterialList &materials = mlresult.Get();
  173. result.Get()->RestoreMaterialState(materials.data(), (uint)materials.size());
  174. return result;
  175. }
  176. Shape::Stats Shape::GetStatsRecursive(VisitedShapes &ioVisitedShapes) const
  177. {
  178. Stats stats = GetStats();
  179. // If shape is already visited, don't count its size again
  180. if (!ioVisitedShapes.insert(this).second)
  181. stats.mSizeBytes = 0;
  182. return stats;
  183. }
  184. bool Shape::IsValidScale(Vec3Arg inScale) const
  185. {
  186. return !ScaleHelpers::IsZeroScale(inScale);
  187. }
  188. Vec3 Shape::MakeScaleValid(Vec3Arg inScale) const
  189. {
  190. return ScaleHelpers::MakeNonZeroScale(inScale);
  191. }
  192. Shape::ShapeResult Shape::ScaleShape(Vec3Arg inScale) const
  193. {
  194. const Vec3 unit_scale = Vec3::sReplicate(1.0f);
  195. if (inScale.IsNearZero())
  196. {
  197. ShapeResult result;
  198. result.SetError("Can't use zero scale!");
  199. return result;
  200. }
  201. // First test if we can just wrap this shape in a scaled shape
  202. if (IsValidScale(inScale))
  203. {
  204. // Test if the scale is near unit
  205. ShapeResult result;
  206. if (inScale.IsClose(unit_scale))
  207. result.Set(const_cast<Shape *>(this));
  208. else
  209. result.Set(new ScaledShape(this, inScale));
  210. return result;
  211. }
  212. // Collect the leaf shapes and their transforms
  213. struct Collector : TransformedShapeCollector
  214. {
  215. virtual void AddHit(const ResultType &inResult) override
  216. {
  217. mShapes.push_back(inResult);
  218. }
  219. Array<TransformedShape> mShapes;
  220. };
  221. Collector collector;
  222. TransformShape(Mat44::sScale(inScale) * Mat44::sTranslation(GetCenterOfMass()), collector);
  223. // Construct a compound shape
  224. StaticCompoundShapeSettings compound;
  225. compound.mSubShapes.reserve(collector.mShapes.size());
  226. for (const TransformedShape &ts : collector.mShapes)
  227. {
  228. const Shape *shape = ts.mShape;
  229. // Construct a scaled shape if scale is not unit
  230. Vec3 scale = ts.GetShapeScale();
  231. if (!scale.IsClose(unit_scale))
  232. shape = new ScaledShape(shape, scale);
  233. // Add the shape
  234. compound.AddShape(Vec3(ts.mShapePositionCOM) - ts.mShapeRotation * shape->GetCenterOfMass(), ts.mShapeRotation, shape);
  235. }
  236. return compound.Create();
  237. }
  238. void Shape::sCollidePointUsingRayCast(const Shape &inShape, Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter)
  239. {
  240. // First test if we're inside our bounding box
  241. AABox bounds = inShape.GetLocalBounds();
  242. if (bounds.Contains(inPoint))
  243. {
  244. // A collector that just counts the number of hits
  245. class HitCountCollector : public CastRayCollector
  246. {
  247. public:
  248. virtual void AddHit(const RayCastResult &inResult) override
  249. {
  250. // Store the last sub shape ID so that we can provide something to our outer hit collector
  251. mSubShapeID = inResult.mSubShapeID2;
  252. ++mHitCount;
  253. }
  254. int mHitCount = 0;
  255. SubShapeID mSubShapeID;
  256. };
  257. HitCountCollector collector;
  258. // Configure the raycast
  259. RayCastSettings settings;
  260. settings.mBackFaceMode = EBackFaceMode::CollideWithBackFaces;
  261. // Cast a ray that's 10% longer than the height of our bounding box
  262. inShape.CastRay(RayCast { inPoint, 1.1f * bounds.GetSize().GetY() * Vec3::sAxisY() }, settings, inSubShapeIDCreator, collector, inShapeFilter);
  263. // Odd amount of hits means inside
  264. if ((collector.mHitCount & 1) == 1)
  265. ioCollector.AddHit({ TransformedShape::sGetBodyID(ioCollector.GetContext()), collector.mSubShapeID });
  266. }
  267. }
  268. JPH_NAMESPACE_END