CollisionShape.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. //
  2. // Copyright (c) 2008-2020 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. /// \file
  23. #pragma once
  24. #include "../Container/ArrayPtr.h"
  25. #include "../Math/BoundingBox.h"
  26. #include "../Math/Quaternion.h"
  27. #include "../Scene/Component.h"
  28. class btBvhTriangleMeshShape;
  29. class btCollisionShape;
  30. class btCompoundShape;
  31. class btGImpactMeshShape;
  32. class btTriangleMesh;
  33. struct btTriangleInfoMap;
  34. namespace Urho3D
  35. {
  36. class CustomGeometry;
  37. class Geometry;
  38. class Model;
  39. class PhysicsWorld;
  40. class RigidBody;
  41. class Terrain;
  42. class TriangleMeshInterface;
  43. /// Collision shape type.
  44. enum ShapeType
  45. {
  46. SHAPE_BOX = 0,
  47. SHAPE_SPHERE,
  48. SHAPE_STATICPLANE,
  49. SHAPE_CYLINDER,
  50. SHAPE_CAPSULE,
  51. SHAPE_CONE,
  52. SHAPE_TRIANGLEMESH,
  53. SHAPE_CONVEXHULL,
  54. SHAPE_TERRAIN,
  55. SHAPE_GIMPACTMESH
  56. };
  57. /// Base class for collision shape geometry data.
  58. struct CollisionGeometryData : public RefCounted
  59. {
  60. };
  61. /// Cache of collision geometry data.
  62. /// \todo Remove duplicate declaration
  63. using CollisionGeometryDataCache = HashMap<Pair<Model*, unsigned>, SharedPtr<CollisionGeometryData> >;
  64. /// Triangle mesh geometry data.
  65. struct TriangleMeshData : public CollisionGeometryData
  66. {
  67. /// Construct from a model.
  68. TriangleMeshData(Model* model, unsigned lodLevel);
  69. /// Construct from a custom geometry.
  70. explicit TriangleMeshData(CustomGeometry* custom);
  71. /// Bullet triangle mesh interface.
  72. UniquePtr<TriangleMeshInterface> meshInterface_;
  73. /// Bullet triangle mesh collision shape.
  74. UniquePtr<btBvhTriangleMeshShape> shape_;
  75. /// Bullet triangle info map.
  76. UniquePtr<btTriangleInfoMap> infoMap_;
  77. };
  78. /// Triangle mesh geometry data.
  79. struct GImpactMeshData : public CollisionGeometryData
  80. {
  81. /// Construct from a model.
  82. GImpactMeshData(Model* model, unsigned lodLevel);
  83. /// Construct from a custom geometry.
  84. explicit GImpactMeshData(CustomGeometry* custom);
  85. /// Bullet triangle mesh interface.
  86. UniquePtr<TriangleMeshInterface> meshInterface_;
  87. };
  88. /// Convex hull geometry data.
  89. struct ConvexData : public CollisionGeometryData
  90. {
  91. /// Construct from a model.
  92. ConvexData(Model* model, unsigned lodLevel);
  93. /// Construct from a custom geometry.
  94. explicit ConvexData(CustomGeometry* custom);
  95. /// Build the convex hull from vertices.
  96. void BuildHull(const PODVector<Vector3>& vertices);
  97. /// Vertex data.
  98. SharedArrayPtr<Vector3> vertexData_;
  99. /// Number of vertices.
  100. unsigned vertexCount_{};
  101. /// Index data.
  102. SharedArrayPtr<unsigned> indexData_;
  103. /// Number of indices.
  104. unsigned indexCount_{};
  105. };
  106. /// Heightfield geometry data.
  107. struct HeightfieldData : public CollisionGeometryData
  108. {
  109. /// Construct from a terrain.
  110. HeightfieldData(Terrain* terrain, unsigned lodLevel);
  111. /// Height data. On LOD level 0 the original height data will be used.
  112. SharedArrayPtr<float> heightData_;
  113. /// Vertex spacing.
  114. Vector3 spacing_;
  115. /// Heightmap size.
  116. IntVector2 size_;
  117. /// Minimum height.
  118. float minHeight_;
  119. /// Maximum height.
  120. float maxHeight_;
  121. };
  122. /// Physics collision shape component.
  123. class URHO3D_API CollisionShape : public Component
  124. {
  125. URHO3D_OBJECT(CollisionShape, Component);
  126. public:
  127. /// Construct.
  128. explicit CollisionShape(Context* context);
  129. /// Destruct. Free the geometry data and clean up unused data from the geometry data cache.
  130. ~CollisionShape() override;
  131. /// Register object factory.
  132. static void RegisterObject(Context* context);
  133. /// Apply attribute changes that can not be applied immediately. Called after scene load or a network update.
  134. void ApplyAttributes() override;
  135. /// Handle enabled/disabled state change.
  136. void OnSetEnabled() override;
  137. /// Visualize the component as debug geometry.
  138. void DrawDebugGeometry(DebugRenderer* debug, bool depthTest) override;
  139. /// Set as a box.
  140. void SetBox(const Vector3& size, const Vector3& position = Vector3::ZERO, const Quaternion& rotation = Quaternion::IDENTITY);
  141. /// Set as a sphere.
  142. void SetSphere(float diameter, const Vector3& position = Vector3::ZERO, const Quaternion& rotation = Quaternion::IDENTITY);
  143. /// Set as a static plane.
  144. void SetStaticPlane(const Vector3& position = Vector3::ZERO, const Quaternion& rotation = Quaternion::IDENTITY);
  145. /// Set as a cylinder.
  146. void SetCylinder(float diameter, float height, const Vector3& position = Vector3::ZERO, const Quaternion& rotation = Quaternion::IDENTITY);
  147. /// Set as a capsule.
  148. void SetCapsule(float diameter, float height, const Vector3& position = Vector3::ZERO, const Quaternion& rotation = Quaternion::IDENTITY);
  149. /// Set as a cone.
  150. void SetCone(float diameter, float height, const Vector3& position = Vector3::ZERO, const Quaternion& rotation = Quaternion::IDENTITY);
  151. /// Set as a triangle mesh from Model. If you update a model's geometry and want to reapply the shape, call physicsWorld->RemoveCachedGeometry(model) first.
  152. void SetTriangleMesh(Model* model, unsigned lodLevel = 0, const Vector3& scale = Vector3::ONE, const Vector3& position = Vector3::ZERO,
  153. const Quaternion& rotation = Quaternion::IDENTITY);
  154. /// Set as a triangle mesh from CustomGeometry.
  155. void SetCustomTriangleMesh(CustomGeometry* custom, const Vector3& scale = Vector3::ONE, const Vector3& position = Vector3::ZERO,
  156. const Quaternion& rotation = Quaternion::IDENTITY);
  157. /// Set as a convex hull from Model.
  158. void SetConvexHull(Model* model, unsigned lodLevel = 0, const Vector3& scale = Vector3::ONE, const Vector3& position = Vector3::ZERO,
  159. const Quaternion& rotation = Quaternion::IDENTITY);
  160. /// Set as a convex hull from CustomGeometry.
  161. void SetCustomConvexHull(CustomGeometry* custom, const Vector3& scale = Vector3::ONE, const Vector3& position = Vector3::ZERO,
  162. const Quaternion& rotation = Quaternion::IDENTITY);
  163. /// Set as a triangle mesh from Model. If you update a model's geometry and want to reapply the shape, call physicsWorld->RemoveCachedGeometry(model) first.
  164. void SetGImpactMesh(Model* model, unsigned lodLevel = 0, const Vector3& scale = Vector3::ONE, const Vector3& position = Vector3::ZERO,
  165. const Quaternion& rotation = Quaternion::IDENTITY);
  166. /// Set as a triangle mesh from CustomGeometry.
  167. void SetCustomGImpactMesh(CustomGeometry* custom, const Vector3& scale = Vector3::ONE, const Vector3& position = Vector3::ZERO,
  168. const Quaternion& rotation = Quaternion::IDENTITY);
  169. /// Set as a terrain. Only works if the same scene node contains a Terrain component.
  170. void SetTerrain(unsigned lodLevel = 0);
  171. /// Set shape type.
  172. /// @property
  173. void SetShapeType(ShapeType type);
  174. /// Set shape size.
  175. /// @property
  176. void SetSize(const Vector3& size);
  177. /// Set offset position.
  178. /// @property
  179. void SetPosition(const Vector3& position);
  180. /// Set offset rotation.
  181. /// @property
  182. void SetRotation(const Quaternion& rotation);
  183. /// Set offset transform.
  184. void SetTransform(const Vector3& position, const Quaternion& rotation);
  185. /// Set collision margin.
  186. /// @property
  187. void SetMargin(float margin);
  188. /// Set triangle mesh / convex hull model.
  189. /// @property
  190. void SetModel(Model* model);
  191. /// Set model LOD level.
  192. /// @property
  193. void SetLodLevel(unsigned lodLevel);
  194. /// Return Bullet collision shape.
  195. btCollisionShape* GetCollisionShape() const { return shape_.Get(); }
  196. /// Return the shared geometry data.
  197. CollisionGeometryData* GetGeometryData() const { return geometry_; }
  198. /// Return physics world.
  199. PhysicsWorld* GetPhysicsWorld() const { return physicsWorld_; }
  200. /// Return shape type.
  201. /// @property
  202. ShapeType GetShapeType() const { return shapeType_; }
  203. /// Return shape size.
  204. /// @property
  205. const Vector3& GetSize() const { return size_; }
  206. /// Return offset position.
  207. /// @property
  208. const Vector3& GetPosition() const { return position_; }
  209. /// Return offset rotation.
  210. /// @property
  211. const Quaternion& GetRotation() const { return rotation_; }
  212. /// Return collision margin.
  213. /// @property
  214. float GetMargin() const { return margin_; }
  215. /// Return triangle mesh / convex hull model.
  216. /// @property
  217. Model* GetModel() const { return model_; }
  218. /// Return model LOD level.
  219. /// @property
  220. unsigned GetLodLevel() const { return lodLevel_; }
  221. /// Return world-space bounding box.
  222. /// @property
  223. BoundingBox GetWorldBoundingBox() const;
  224. /// Update the new collision shape to the RigidBody.
  225. void NotifyRigidBody(bool updateMass = true);
  226. /// Set model attribute.
  227. void SetModelAttr(const ResourceRef& value);
  228. /// Return model attribute.
  229. ResourceRef GetModelAttr() const;
  230. /// Release the collision shape.
  231. void ReleaseShape();
  232. protected:
  233. /// Handle node being assigned.
  234. void OnNodeSet(Node* node) override;
  235. /// Handle scene being assigned.
  236. void OnSceneSet(Scene* scene) override;
  237. /// Handle node transform being dirtied.
  238. void OnMarkedDirty(Node* node) override;
  239. /**
  240. * Called when instantiating a collision shape that is not one of ShapeType (default no-op).
  241. *
  242. * Useful for custom shape types that subclass CollisionShape and use a non-standard underlying
  243. * btCollisionShape. UpdateDerivedShape can then be overridden to create the required
  244. * btCollisionShape subclass.
  245. */
  246. virtual btCollisionShape* UpdateDerivedShape(int shapeType, const Vector3& newWorldScale);
  247. private:
  248. /// Find the parent rigid body component and return its compound collision shape.
  249. btCompoundShape* GetParentCompoundShape();
  250. /// Update the collision shape after attribute changes.
  251. void UpdateShape();
  252. /// Update cached geometry collision shape.
  253. void UpdateCachedGeometryShape(CollisionGeometryDataCache& cache);
  254. /// Set as specified shape type using model and LOD.
  255. void SetModelShape(ShapeType shapeType, Model* model, unsigned lodLevel,
  256. const Vector3& scale, const Vector3& position, const Quaternion& rotation);
  257. /// Set as specified shape type using CustomGeometry.
  258. void SetCustomShape(ShapeType shapeType, CustomGeometry* custom,
  259. const Vector3& scale, const Vector3& position, const Quaternion& rotation);
  260. /// Update terrain collision shape from the terrain component.
  261. void HandleTerrainCreated(StringHash eventType, VariantMap& eventData);
  262. /// Update trimesh or convex shape after a model has reloaded itself.
  263. void HandleModelReloadFinished(StringHash eventType, VariantMap& eventData);
  264. /// Mark shape dirty.
  265. void MarkShapeDirty() { recreateShape_ = true; }
  266. /// Physics world.
  267. WeakPtr<PhysicsWorld> physicsWorld_;
  268. /// Rigid body.
  269. WeakPtr<RigidBody> rigidBody_;
  270. /// Model.
  271. SharedPtr<Model> model_;
  272. /// Shared geometry data.
  273. SharedPtr<CollisionGeometryData> geometry_;
  274. /// Bullet collision shape.
  275. UniquePtr<btCollisionShape> shape_;
  276. /// Collision shape type.
  277. ShapeType shapeType_;
  278. /// Offset position.
  279. Vector3 position_;
  280. /// Offset rotation.
  281. Quaternion rotation_;
  282. /// Shape size.
  283. Vector3 size_;
  284. /// Cached world scale for determining if the collision shape needs update.
  285. Vector3 cachedWorldScale_;
  286. /// Model LOD level.
  287. unsigned lodLevel_;
  288. /// CustomGeometry component ID. 0 if not creating the convex hull / triangle mesh from a CustomGeometry.
  289. unsigned customGeometryID_;
  290. /// Collision margin.
  291. float margin_;
  292. /// Recreate collision shape flag.
  293. bool recreateShape_;
  294. /// Shape creation retry flag if attributes initially set without scene.
  295. bool retryCreation_;
  296. };
  297. }