Shape.cpp 9.1 KB

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