Shape.cpp 8.7 KB

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