CollisionShape.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. //
  2. // Copyright (c) 2008-2017 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. #pragma once
  23. #include "../Container/ArrayPtr.h"
  24. #include "../Math/BoundingBox.h"
  25. #include "../Math/Quaternion.h"
  26. #include "../Scene/Component.h"
  27. class btBvhTriangleMeshShape;
  28. class btCollisionShape;
  29. class btCompoundShape;
  30. class btTriangleMesh;
  31. struct btTriangleInfoMap;
  32. namespace Urho3D
  33. {
  34. class CustomGeometry;
  35. class Geometry;
  36. class Model;
  37. class PhysicsWorld;
  38. class RigidBody;
  39. class Terrain;
  40. class TriangleMeshInterface;
  41. /// Collision shape type.
  42. enum ShapeType
  43. {
  44. SHAPE_BOX = 0,
  45. SHAPE_SPHERE,
  46. SHAPE_STATICPLANE,
  47. SHAPE_CYLINDER,
  48. SHAPE_CAPSULE,
  49. SHAPE_CONE,
  50. SHAPE_TRIANGLEMESH,
  51. SHAPE_CONVEXHULL,
  52. SHAPE_TERRAIN
  53. };
  54. /// Base class for collision shape geometry data.
  55. struct CollisionGeometryData : public RefCounted
  56. {
  57. };
  58. /// Triangle mesh geometry data.
  59. struct TriangleMeshData : public CollisionGeometryData
  60. {
  61. /// Construct from a model.
  62. TriangleMeshData(Model* model, unsigned lodLevel);
  63. /// Construct from a custom geometry.
  64. TriangleMeshData(CustomGeometry* custom);
  65. /// Destruct. Free geometry data.
  66. ~TriangleMeshData();
  67. /// Bullet triangle mesh interface.
  68. UniquePtr<TriangleMeshInterface> meshInterface_;
  69. /// Bullet triangle mesh collision shape.
  70. UniquePtr<btBvhTriangleMeshShape> shape_;
  71. /// Bullet triangle info map.
  72. UniquePtr<btTriangleInfoMap> infoMap_;
  73. };
  74. /// Convex hull geometry data.
  75. struct ConvexData : public CollisionGeometryData
  76. {
  77. /// Construct from a model.
  78. ConvexData(Model* model, unsigned lodLevel);
  79. /// Construct from a custom geometry.
  80. ConvexData(CustomGeometry* custom);
  81. /// Destruct. Free geometry data.
  82. ~ConvexData();
  83. /// Build the convex hull from vertices.
  84. void BuildHull(const PODVector<Vector3>& vertices);
  85. /// Vertex data.
  86. SharedArrayPtr<Vector3> vertexData_;
  87. /// Number of vertices.
  88. unsigned vertexCount_;
  89. /// Index data.
  90. SharedArrayPtr<unsigned> indexData_;
  91. /// Number of indices.
  92. unsigned indexCount_;
  93. };
  94. /// Heightfield geometry data.
  95. struct HeightfieldData : public CollisionGeometryData
  96. {
  97. /// Construct from a terrain.
  98. HeightfieldData(Terrain* terrain, unsigned lodLevel);
  99. /// Destruct. Free geometry data.
  100. ~HeightfieldData();
  101. /// Height data. On LOD level 0 the original height data will be used.
  102. SharedArrayPtr<float> heightData_;
  103. /// Vertex spacing.
  104. Vector3 spacing_;
  105. /// Heightmap size.
  106. IntVector2 size_;
  107. /// Minimum height.
  108. float minHeight_;
  109. /// Maximum height.
  110. float maxHeight_;
  111. };
  112. /// Physics collision shape component.
  113. class URHO3D_API CollisionShape : public Component
  114. {
  115. URHO3D_OBJECT(CollisionShape, Component);
  116. public:
  117. /// Construct.
  118. CollisionShape(Context* context);
  119. /// Destruct. Free the geometry data and clean up unused data from the geometry data cache.
  120. virtual ~CollisionShape();
  121. /// Register object factory.
  122. static void RegisterObject(Context* context);
  123. /// Handle attribute write access.
  124. virtual void OnSetAttribute(const AttributeInfo& attr, const Variant& src);
  125. /// Apply attribute changes that can not be applied immediately. Called after scene load or a network update.
  126. virtual void ApplyAttributes();
  127. /// Handle enabled/disabled state change.
  128. virtual void OnSetEnabled();
  129. /// Visualize the component as debug geometry.
  130. virtual void DrawDebugGeometry(DebugRenderer* debug, bool depthTest);
  131. /// Set as a box.
  132. void SetBox(const Vector3& size, const Vector3& position = Vector3::ZERO, const Quaternion& rotation = Quaternion::IDENTITY);
  133. /// Set as a sphere.
  134. void SetSphere(float diameter, const Vector3& position = Vector3::ZERO, const Quaternion& rotation = Quaternion::IDENTITY);
  135. /// Set as a static plane.
  136. void SetStaticPlane(const Vector3& position = Vector3::ZERO, const Quaternion& rotation = Quaternion::IDENTITY);
  137. /// Set as a cylinder.
  138. void SetCylinder
  139. (float diameter, float height, const Vector3& position = Vector3::ZERO, const Quaternion& rotation = Quaternion::IDENTITY);
  140. /// Set as a capsule.
  141. void SetCapsule
  142. (float diameter, float height, const Vector3& position = Vector3::ZERO, const Quaternion& rotation = Quaternion::IDENTITY);
  143. /// Set as a cone.
  144. void SetCone
  145. (float diameter, float height, const Vector3& position = Vector3::ZERO, const Quaternion& rotation = Quaternion::IDENTITY);
  146. /// 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.
  147. void SetTriangleMesh
  148. (Model* model, unsigned lodLevel = 0, const Vector3& scale = Vector3::ONE, const Vector3& position = Vector3::ZERO,
  149. const Quaternion& rotation = Quaternion::IDENTITY);
  150. /// Set as a triangle mesh from CustomGeometry.
  151. void SetCustomTriangleMesh(CustomGeometry* custom, const Vector3& scale = Vector3::ONE, const Vector3& position = Vector3::ZERO,
  152. const Quaternion& rotation = Quaternion::IDENTITY);
  153. /// Set as a convex hull from Model.
  154. void SetConvexHull
  155. (Model* model, unsigned lodLevel = 0, const Vector3& scale = Vector3::ONE, const Vector3& position = Vector3::ZERO,
  156. const Quaternion& rotation = Quaternion::IDENTITY);
  157. /// Set as a convex hull from CustomGeometry.
  158. void SetCustomConvexHull(CustomGeometry* custom, const Vector3& scale = Vector3::ONE, const Vector3& position = Vector3::ZERO,
  159. const Quaternion& rotation = Quaternion::IDENTITY);
  160. /// Set as a terrain. Only works if the same scene node contains a Terrain component.
  161. void SetTerrain(unsigned lodLevel = 0);
  162. /// Set shape type.
  163. void SetShapeType(ShapeType type);
  164. /// Set shape size.
  165. void SetSize(const Vector3& size);
  166. /// Set offset position.
  167. void SetPosition(const Vector3& position);
  168. /// Set offset rotation.
  169. void SetRotation(const Quaternion& rotation);
  170. /// Set offset transform.
  171. void SetTransform(const Vector3& position, const Quaternion& rotation);
  172. /// Set collision margin.
  173. void SetMargin(float margin);
  174. /// Set triangle mesh / convex hull model.
  175. void SetModel(Model* model);
  176. /// Set model LOD level.
  177. void SetLodLevel(unsigned lodLevel);
  178. /// Return Bullet collision shape.
  179. btCollisionShape* GetCollisionShape() const { return shape_.Get(); }
  180. /// Return the shared geometry data.
  181. CollisionGeometryData* GetGeometryData() const { return geometry_; }
  182. /// Return physics world.
  183. PhysicsWorld* GetPhysicsWorld() const { return physicsWorld_; }
  184. /// Return shape type.
  185. ShapeType GetShapeType() const { return shapeType_; }
  186. /// Return shape size.
  187. const Vector3& GetSize() const { return size_; }
  188. /// Return offset position.
  189. const Vector3& GetPosition() const { return position_; }
  190. /// Return offset rotation.
  191. const Quaternion& GetRotation() const { return rotation_; }
  192. /// Return collision margin.
  193. float GetMargin() const { return margin_; }
  194. /// Return triangle mesh / convex hull model.
  195. Model* GetModel() const { return model_; }
  196. /// Return model LOD level.
  197. unsigned GetLodLevel() const { return lodLevel_; }
  198. /// Return world-space bounding box.
  199. BoundingBox GetWorldBoundingBox() const;
  200. /// Update the new collision shape to the RigidBody.
  201. void NotifyRigidBody(bool updateMass = true);
  202. /// Set model attribute.
  203. void SetModelAttr(const ResourceRef& value);
  204. /// Return model attribute.
  205. ResourceRef GetModelAttr() const;
  206. /// Release the collision shape.
  207. void ReleaseShape();
  208. protected:
  209. /// Handle node being assigned.
  210. virtual void OnNodeSet(Node* node);
  211. /// Handle scene being assigned.
  212. virtual void OnSceneSet(Scene* scene);
  213. /// Handle node transform being dirtied.
  214. virtual void OnMarkedDirty(Node* node);
  215. /**
  216. * Called when instantiating a collision shape that is not one of ShapeType (default no-op).
  217. *
  218. * Useful for custom shape types that subclass CollisionShape and use a non-standard underlying
  219. * btCollisionShape. UpdateDerivedShape can then be overridden to create the required
  220. * btCollisionShape subclass.
  221. */
  222. virtual btCollisionShape* UpdateDerivedShape(int shapeType, const Vector3& newWorldScale);
  223. private:
  224. /// Find the parent rigid body component and return its compound collision shape.
  225. btCompoundShape* GetParentCompoundShape();
  226. /// Update the collision shape after attribute changes.
  227. void UpdateShape();
  228. /// Update terrain collision shape from the terrain component.
  229. void HandleTerrainCreated(StringHash eventType, VariantMap& eventData);
  230. /// Update trimesh or convex shape after a model has reloaded itself.
  231. void HandleModelReloadFinished(StringHash eventType, VariantMap& eventData);
  232. /// Physics world.
  233. WeakPtr<PhysicsWorld> physicsWorld_;
  234. /// Rigid body.
  235. WeakPtr<RigidBody> rigidBody_;
  236. /// Model.
  237. SharedPtr<Model> model_;
  238. /// Shared geometry data.
  239. SharedPtr<CollisionGeometryData> geometry_;
  240. /// Bullet collision shape.
  241. UniquePtr<btCollisionShape> shape_;
  242. /// Collision shape type.
  243. ShapeType shapeType_;
  244. /// Offset position.
  245. Vector3 position_;
  246. /// Offset rotation.
  247. Quaternion rotation_;
  248. /// Shape size.
  249. Vector3 size_;
  250. /// Cached world scale for determining if the collision shape needs update.
  251. Vector3 cachedWorldScale_;
  252. /// Model LOD level.
  253. unsigned lodLevel_;
  254. /// CustomGeometry component ID. 0 if not creating the convex hull / triangle mesh from a CustomGeometry.
  255. unsigned customGeometryID_;
  256. /// Collision margin.
  257. float margin_;
  258. /// Recreate collision shape flag.
  259. bool recreateShape_;
  260. /// Shape creation retry flag if attributes initially set without scene.
  261. bool retryCreation_;
  262. };
  263. }