2
0

Shape.cpp 9.1 KB

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