CollisionShape.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  1. //
  2. // Copyright (c) 2008-2014 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. #include "Precompiled.h"
  23. #include "CollisionShape.h"
  24. #include "Context.h"
  25. #include "CustomGeometry.h"
  26. #include "DebugRenderer.h"
  27. #include "DrawableEvents.h"
  28. #include "Geometry.h"
  29. #include "IndexBuffer.h"
  30. #include "Log.h"
  31. #include "Model.h"
  32. #include "PhysicsUtils.h"
  33. #include "PhysicsWorld.h"
  34. #include "Profiler.h"
  35. #include "ResourceCache.h"
  36. #include "ResourceEvents.h"
  37. #include "RigidBody.h"
  38. #include "Scene.h"
  39. #include "Terrain.h"
  40. #include "VertexBuffer.h"
  41. #include <BulletCollision/CollisionDispatch/btInternalEdgeUtility.h>
  42. #include <BulletCollision/CollisionShapes/btBoxShape.h>
  43. #include <BulletCollision/CollisionShapes/btCapsuleShape.h>
  44. #include <BulletCollision/CollisionShapes/btCompoundShape.h>
  45. #include <BulletCollision/CollisionShapes/btConeShape.h>
  46. #include <BulletCollision/CollisionShapes/btConvexHullShape.h>
  47. #include <BulletCollision/CollisionShapes/btCylinderShape.h>
  48. #include <BulletCollision/CollisionShapes/btHeightfieldTerrainShape.h>
  49. #include <BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.h>
  50. #include <BulletCollision/CollisionShapes/btSphereShape.h>
  51. #include <BulletCollision/CollisionShapes/btTriangleIndexVertexArray.h>
  52. #include <BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h>
  53. #include <BulletCollision/CollisionShapes/btStaticPlaneShape.h>
  54. #include <hull.h>
  55. namespace Urho3D
  56. {
  57. static const float DEFAULT_COLLISION_MARGIN = 0.04f;
  58. static const btVector3 WHITE(1.0f, 1.0f, 1.0f);
  59. static const btVector3 GREEN(0.0f, 1.0f, 0.0f);
  60. static const char* typeNames[] =
  61. {
  62. "Box",
  63. "Sphere",
  64. "StaticPlane",
  65. "Cylinder",
  66. "Capsule",
  67. "Cone",
  68. "TriangleMesh",
  69. "ConvexHull",
  70. "Terrain",
  71. 0
  72. };
  73. extern const char* PHYSICS_CATEGORY;
  74. class TriangleMeshInterface : public btTriangleIndexVertexArray
  75. {
  76. public:
  77. TriangleMeshInterface(Model* model, unsigned lodLevel) : btTriangleIndexVertexArray()
  78. {
  79. unsigned numGeometries = model->GetNumGeometries();
  80. for (unsigned i = 0; i < numGeometries; ++i)
  81. {
  82. Geometry* geometry = model->GetGeometry(i, lodLevel);
  83. if (!geometry)
  84. {
  85. LOGWARNING("Skipping null geometry for triangle mesh collision");
  86. continue;
  87. }
  88. SharedArrayPtr<unsigned char> vertexData;
  89. SharedArrayPtr<unsigned char> indexData;
  90. unsigned vertexSize;
  91. unsigned indexSize;
  92. unsigned elementMask;
  93. geometry->GetRawDataShared(vertexData, vertexSize, indexData, indexSize, elementMask);
  94. if (!vertexData || !indexData)
  95. {
  96. LOGWARNING("Skipping geometry with no CPU-side geometry data for triangle mesh collision");
  97. continue;
  98. }
  99. // Keep shared pointers to the vertex/index data so that if it's unloaded or changes size, we don't crash
  100. dataArrays_.Push(vertexData);
  101. dataArrays_.Push(indexData);
  102. unsigned indexStart = geometry->GetIndexStart();
  103. unsigned indexCount = geometry->GetIndexCount();
  104. btIndexedMesh meshIndex;
  105. meshIndex.m_numTriangles = indexCount / 3;
  106. meshIndex.m_triangleIndexBase = &indexData[indexStart * indexSize];
  107. meshIndex.m_triangleIndexStride = 3 * indexSize;
  108. meshIndex.m_numVertices = 0;
  109. meshIndex.m_vertexBase = vertexData;
  110. meshIndex.m_vertexStride = vertexSize;
  111. meshIndex.m_indexType = (indexSize == sizeof(unsigned short)) ? PHY_SHORT : PHY_INTEGER;
  112. meshIndex.m_vertexType = PHY_FLOAT;
  113. m_indexedMeshes.push_back(meshIndex);
  114. }
  115. }
  116. private:
  117. /// Shared vertex/index data used in the collision
  118. Vector<SharedArrayPtr<unsigned char> > dataArrays_;
  119. };
  120. TriangleMeshData::TriangleMeshData(Model* model, unsigned lodLevel) :
  121. meshInterface_(0),
  122. shape_(0),
  123. infoMap_(0)
  124. {
  125. meshInterface_ = new TriangleMeshInterface(model, lodLevel);
  126. shape_ = new btBvhTriangleMeshShape(meshInterface_, true, true);
  127. infoMap_ = new btTriangleInfoMap();
  128. btGenerateInternalEdgeInfo(shape_, infoMap_);
  129. }
  130. TriangleMeshData::~TriangleMeshData()
  131. {
  132. delete shape_;
  133. shape_ = 0;
  134. delete meshInterface_;
  135. meshInterface_ = 0;
  136. delete infoMap_;
  137. infoMap_ = 0;
  138. }
  139. ConvexData::ConvexData(Model* model, unsigned lodLevel)
  140. {
  141. PODVector<Vector3> vertices;
  142. unsigned numGeometries = model->GetNumGeometries();
  143. for (unsigned i = 0; i < numGeometries; ++i)
  144. {
  145. Geometry* geom = model->GetGeometry(i, lodLevel);
  146. if (!geom)
  147. {
  148. LOGWARNING("Skipping null geometry for convex hull collision");
  149. continue;
  150. };
  151. const unsigned char* vertexData;
  152. const unsigned char* indexData;
  153. unsigned vertexSize;
  154. unsigned indexSize;
  155. unsigned elementMask;
  156. geom->GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask);
  157. if (!vertexData || !indexData)
  158. {
  159. LOGWARNING("Skipping geometry with no CPU-side geometry data for convex hull collision");
  160. continue;
  161. }
  162. unsigned vertexStart = geom->GetVertexStart();
  163. unsigned vertexCount = geom->GetVertexCount();
  164. // Copy vertex data
  165. for (unsigned j = 0; j < vertexCount; ++j)
  166. {
  167. const Vector3& v = *((const Vector3*)(&vertexData[(vertexStart + j) * vertexSize]));
  168. vertices.Push(v);
  169. }
  170. }
  171. BuildHull(vertices);
  172. }
  173. ConvexData::ConvexData(CustomGeometry* custom)
  174. {
  175. PODVector<Vector3> vertices;
  176. unsigned numGeometries = custom->GetNumGeometries();
  177. for (unsigned i = 0; i < numGeometries; ++i)
  178. {
  179. Geometry* geom = custom->GetLodGeometry(i, 0);
  180. if (!geom)
  181. {
  182. LOGWARNING("Skipping null geometry for convex hull collision");
  183. continue;
  184. }
  185. const unsigned char* vertexData;
  186. const unsigned char* indexData;
  187. unsigned vertexSize;
  188. unsigned indexSize;
  189. unsigned elementMask;
  190. geom->GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask);
  191. if (!vertexData)
  192. {
  193. LOGWARNING("Skipping geometry with no CPU-side geometry data for convex hull collision - no vertex data");
  194. continue;
  195. }
  196. unsigned vertexStart = geom->GetVertexStart();
  197. unsigned vertexCount = geom->GetVertexCount();
  198. // Copy vertex data
  199. for (unsigned j = 0; j < vertexCount; ++j)
  200. {
  201. const Vector3& v = *((const Vector3*)(&vertexData[(vertexStart + j) * vertexSize]));
  202. vertices.Push(v);
  203. }
  204. }
  205. BuildHull(vertices);
  206. }
  207. void ConvexData::BuildHull(const PODVector<Vector3>& vertices)
  208. {
  209. if (vertices.Size())
  210. {
  211. // Build the convex hull from the raw geometry
  212. StanHull::HullDesc desc;
  213. desc.SetHullFlag(StanHull::QF_TRIANGLES);
  214. desc.mVcount = vertices.Size();
  215. desc.mVertices = vertices[0].Data();
  216. desc.mVertexStride = 3 * sizeof(float);
  217. desc.mSkinWidth = 0.0f;
  218. StanHull::HullLibrary lib;
  219. StanHull::HullResult result;
  220. lib.CreateConvexHull(desc, result);
  221. vertexCount_ = result.mNumOutputVertices;
  222. vertexData_ = new Vector3[vertexCount_];
  223. indexCount_ = result.mNumIndices;
  224. indexData_ = new unsigned[indexCount_];
  225. // Copy vertex data & index data
  226. memcpy(vertexData_.Get(), result.mOutputVertices, vertexCount_ * sizeof(Vector3));
  227. memcpy(indexData_.Get(), result.mIndices, indexCount_ * sizeof(unsigned));
  228. lib.ReleaseResult(result);
  229. }
  230. else
  231. {
  232. vertexCount_ = 0;
  233. indexCount_ = 0;
  234. }
  235. }
  236. ConvexData::~ConvexData()
  237. {
  238. }
  239. HeightfieldData::HeightfieldData(Terrain* terrain) :
  240. heightData_(terrain->GetHeightData()),
  241. spacing_(terrain->GetSpacing()),
  242. size_(terrain->GetNumVertices()),
  243. minHeight_(0.0f),
  244. maxHeight_(0.0f)
  245. {
  246. if (heightData_)
  247. {
  248. unsigned points = size_.x_ * size_.y_;
  249. float* data = heightData_.Get();
  250. minHeight_ = maxHeight_ = data[0];
  251. for (unsigned i = 1; i < points; ++i)
  252. {
  253. minHeight_ = Min(minHeight_, data[i]);
  254. maxHeight_ = Max(maxHeight_, data[i]);
  255. }
  256. }
  257. }
  258. HeightfieldData::~HeightfieldData()
  259. {
  260. }
  261. bool HasDynamicBuffers(Model* model, unsigned lodLevel)
  262. {
  263. unsigned numGeometries = model->GetNumGeometries();
  264. for (unsigned i = 0; i < numGeometries; ++i)
  265. {
  266. Geometry* geometry = model->GetGeometry(i, lodLevel);
  267. if (!geometry)
  268. continue;
  269. unsigned numVertexBuffers = geometry->GetNumVertexBuffers();
  270. for (unsigned j = 0; j < numVertexBuffers; ++j)
  271. {
  272. VertexBuffer* buffer = geometry->GetVertexBuffer(j);
  273. if (!buffer)
  274. continue;
  275. if (buffer->IsDynamic())
  276. return true;
  277. }
  278. IndexBuffer* buffer = geometry->GetIndexBuffer();
  279. if (buffer && buffer->IsDynamic())
  280. return true;
  281. }
  282. return false;
  283. }
  284. CollisionShape::CollisionShape(Context* context) :
  285. Component(context),
  286. shape_(0),
  287. shapeType_(SHAPE_BOX),
  288. position_(Vector3::ZERO),
  289. rotation_(Quaternion::IDENTITY),
  290. size_(Vector3::ONE),
  291. cachedWorldScale_(Vector3::ONE),
  292. lodLevel_(0),
  293. customGeometryID_(0),
  294. margin_(DEFAULT_COLLISION_MARGIN),
  295. recreateShape_(true)
  296. {
  297. }
  298. CollisionShape::~CollisionShape()
  299. {
  300. ReleaseShape();
  301. if (physicsWorld_)
  302. physicsWorld_->RemoveCollisionShape(this);
  303. }
  304. void CollisionShape::RegisterObject(Context* context)
  305. {
  306. context->RegisterFactory<CollisionShape>(PHYSICS_CATEGORY);
  307. ACCESSOR_ATTRIBUTE(CollisionShape, VAR_BOOL, "Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  308. ENUM_ATTRIBUTE(CollisionShape, "Shape Type", shapeType_, typeNames, SHAPE_BOX, AM_DEFAULT);
  309. ATTRIBUTE(CollisionShape, VAR_VECTOR3, "Size", size_, Vector3::ONE, AM_DEFAULT);
  310. REF_ACCESSOR_ATTRIBUTE(CollisionShape, VAR_VECTOR3, "Offset Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_DEFAULT);
  311. REF_ACCESSOR_ATTRIBUTE(CollisionShape, VAR_QUATERNION, "Offset Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_DEFAULT);
  312. ACCESSOR_ATTRIBUTE(CollisionShape, VAR_RESOURCEREF, "Model", GetModelAttr, SetModelAttr, ResourceRef, ResourceRef(Model::GetTypeStatic()), AM_DEFAULT);
  313. ATTRIBUTE(CollisionShape, VAR_INT, "LOD Level", lodLevel_, 0, AM_DEFAULT);
  314. ATTRIBUTE(CollisionShape, VAR_FLOAT, "Collision Margin", margin_, DEFAULT_COLLISION_MARGIN, AM_DEFAULT);
  315. ATTRIBUTE(CollisionShape, VAR_INT, "CustomGeometry NodeID", customGeometryID_, 0, AM_DEFAULT | AM_NODEID);
  316. }
  317. void CollisionShape::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  318. {
  319. Component::OnSetAttribute(attr, src);
  320. // Change of any non-accessor attribute requires recreation of the collision shape
  321. if (!attr.accessor_)
  322. recreateShape_ = true;
  323. }
  324. void CollisionShape::ApplyAttributes()
  325. {
  326. if (recreateShape_)
  327. {
  328. UpdateShape();
  329. NotifyRigidBody();
  330. }
  331. }
  332. void CollisionShape::OnSetEnabled()
  333. {
  334. NotifyRigidBody();
  335. }
  336. void CollisionShape::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  337. {
  338. if (debug && physicsWorld_ && shape_ && node_ && IsEnabledEffective())
  339. {
  340. physicsWorld_->SetDebugRenderer(debug);
  341. physicsWorld_->SetDebugDepthTest(depthTest);
  342. // Use the rigid body's world transform if possible, as it may be different from the rendering transform
  343. Matrix3x4 worldTransform;
  344. RigidBody* body = GetComponent<RigidBody>();
  345. bool bodyActive = false;
  346. if (body)
  347. {
  348. worldTransform = Matrix3x4(body->GetPosition(), body->GetRotation(), node_->GetWorldScale());
  349. bodyActive = body->IsActive();
  350. }
  351. else
  352. worldTransform = node_->GetWorldTransform();
  353. Vector3 position = position_;
  354. // For terrains, undo the height centering performed automatically by Bullet
  355. if (shapeType_ == SHAPE_TERRAIN && geometry_)
  356. {
  357. HeightfieldData* heightfield = static_cast<HeightfieldData*>(geometry_.Get());
  358. position.y_ += (heightfield->minHeight_ + heightfield->maxHeight_) * 0.5f;
  359. }
  360. Vector3 worldPosition(worldTransform * position);
  361. Quaternion worldRotation(worldTransform.Rotation() * rotation_);
  362. btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
  363. world->debugDrawObject(btTransform(ToBtQuaternion(worldRotation), ToBtVector3(worldPosition)), shape_, bodyActive ?
  364. WHITE : GREEN);
  365. physicsWorld_->SetDebugRenderer(0);
  366. }
  367. }
  368. void CollisionShape::SetBox(const Vector3& size, const Vector3& position, const Quaternion& rotation)
  369. {
  370. if (model_)
  371. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  372. shapeType_ = SHAPE_BOX;
  373. size_ = size;
  374. position_ = position;
  375. rotation_ = rotation;
  376. model_.Reset();
  377. customGeometryID_ = 0;
  378. UpdateShape();
  379. NotifyRigidBody();
  380. MarkNetworkUpdate();
  381. }
  382. void CollisionShape::SetSphere(float diameter, const Vector3& position, const Quaternion& rotation)
  383. {
  384. if (model_)
  385. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  386. shapeType_ = SHAPE_SPHERE;
  387. size_ = Vector3(diameter, diameter, diameter);
  388. position_ = position;
  389. rotation_ = rotation;
  390. model_.Reset();
  391. customGeometryID_ = 0;
  392. UpdateShape();
  393. NotifyRigidBody();
  394. MarkNetworkUpdate();
  395. }
  396. void CollisionShape::SetStaticPlane(const Vector3& position, const Quaternion& rotation)
  397. {
  398. if (model_)
  399. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  400. shapeType_ = SHAPE_STATICPLANE;
  401. position_ = position;
  402. rotation_ = rotation;
  403. model_.Reset();
  404. customGeometryID_ = 0;
  405. UpdateShape();
  406. NotifyRigidBody();
  407. MarkNetworkUpdate();
  408. }
  409. void CollisionShape::SetCylinder(float diameter, float height, const Vector3& position, const Quaternion& rotation)
  410. {
  411. if (model_)
  412. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  413. shapeType_ = SHAPE_CYLINDER;
  414. size_ = Vector3(diameter, height, diameter);
  415. position_ = position;
  416. rotation_ = rotation;
  417. model_.Reset();
  418. customGeometryID_ = 0;
  419. UpdateShape();
  420. NotifyRigidBody();
  421. MarkNetworkUpdate();
  422. }
  423. void CollisionShape::SetCapsule(float diameter, float height, const Vector3& position, const Quaternion& rotation)
  424. {
  425. if (model_)
  426. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  427. shapeType_ = SHAPE_CAPSULE;
  428. size_ = Vector3(diameter, height, diameter);
  429. position_ = position;
  430. rotation_ = rotation;
  431. model_.Reset();
  432. customGeometryID_ = 0;
  433. UpdateShape();
  434. NotifyRigidBody();
  435. MarkNetworkUpdate();
  436. }
  437. void CollisionShape::SetCone(float diameter, float height, const Vector3& position, const Quaternion& rotation)
  438. {
  439. if (model_)
  440. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  441. shapeType_ = SHAPE_CONE;
  442. size_ = Vector3(diameter, height, diameter);
  443. position_ = position;
  444. rotation_ = rotation;
  445. model_.Reset();
  446. customGeometryID_ = 0;
  447. UpdateShape();
  448. NotifyRigidBody();
  449. MarkNetworkUpdate();
  450. }
  451. void CollisionShape::SetTriangleMesh(Model* model, unsigned lodLevel, const Vector3& scale, const Vector3& position, const Quaternion& rotation)
  452. {
  453. if (!model)
  454. {
  455. LOGERROR("Null model, can not set triangle mesh");
  456. return;
  457. }
  458. if (model_)
  459. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  460. shapeType_ = SHAPE_TRIANGLEMESH;
  461. model_ = model;
  462. lodLevel_ = lodLevel;
  463. size_ = scale;
  464. position_ = position;
  465. rotation_ = rotation;
  466. customGeometryID_ = 0;
  467. UpdateShape();
  468. NotifyRigidBody();
  469. MarkNetworkUpdate();
  470. }
  471. void CollisionShape::SetConvexHull(Model* model, unsigned lodLevel, const Vector3& scale, const Vector3& position, const Quaternion& rotation)
  472. {
  473. if (!model)
  474. {
  475. LOGERROR("Null model, can not set convex hull");
  476. return;
  477. }
  478. if (model_)
  479. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  480. shapeType_ = SHAPE_CONVEXHULL;
  481. model_ = model;
  482. lodLevel_ = lodLevel;
  483. size_ = scale;
  484. position_ = position;
  485. rotation_ = rotation;
  486. customGeometryID_ = 0;
  487. UpdateShape();
  488. NotifyRigidBody();
  489. MarkNetworkUpdate();
  490. }
  491. void CollisionShape::SetCustomConvexHull(CustomGeometry* custom, const Vector3& scale, const Vector3& position, const Quaternion& rotation)
  492. {
  493. if (!custom)
  494. {
  495. LOGERROR("Null custom geometry, can not set convex hull");
  496. return;
  497. }
  498. if (!custom->GetNode())
  499. {
  500. LOGERROR("Custom geometry has null scene node, can not set convex hull");
  501. return;
  502. }
  503. if (model_)
  504. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  505. shapeType_ = SHAPE_CONVEXHULL;
  506. model_.Reset();
  507. lodLevel_ = 0;
  508. size_ = scale;
  509. position_ = position;
  510. rotation_ = rotation;
  511. customGeometryID_ = custom->GetNode()->GetID();
  512. UpdateShape();
  513. NotifyRigidBody();
  514. MarkNetworkUpdate();
  515. }
  516. void CollisionShape::SetTerrain()
  517. {
  518. Terrain* terrain = GetComponent<Terrain>();
  519. if (!terrain)
  520. {
  521. LOGERROR("No terrain component, can not set terrain shape");
  522. return;
  523. }
  524. if (model_)
  525. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  526. shapeType_ = SHAPE_TERRAIN;
  527. UpdateShape();
  528. NotifyRigidBody();
  529. MarkNetworkUpdate();
  530. }
  531. void CollisionShape::SetShapeType(ShapeType type)
  532. {
  533. if (type != shapeType_)
  534. {
  535. shapeType_ = type;
  536. UpdateShape();
  537. NotifyRigidBody();
  538. MarkNetworkUpdate();
  539. }
  540. }
  541. void CollisionShape::SetSize(const Vector3& size)
  542. {
  543. if (size != size_)
  544. {
  545. size_ = size;
  546. UpdateShape();
  547. NotifyRigidBody();
  548. MarkNetworkUpdate();
  549. }
  550. }
  551. void CollisionShape::SetPosition(const Vector3& position)
  552. {
  553. if (position != position_)
  554. {
  555. position_ = position;
  556. NotifyRigidBody();
  557. MarkNetworkUpdate();
  558. }
  559. }
  560. void CollisionShape::SetRotation(const Quaternion& rotation)
  561. {
  562. if (rotation != rotation_)
  563. {
  564. rotation_ = rotation;
  565. NotifyRigidBody();
  566. MarkNetworkUpdate();
  567. }
  568. }
  569. void CollisionShape::SetTransform(const Vector3& position, const Quaternion& rotation)
  570. {
  571. if (position != position_ || rotation != rotation_)
  572. {
  573. position_ = position;
  574. rotation_ = rotation;
  575. NotifyRigidBody();
  576. MarkNetworkUpdate();
  577. }
  578. }
  579. void CollisionShape::SetMargin(float margin)
  580. {
  581. margin = Max(margin, 0.0f);
  582. if (margin != margin_)
  583. {
  584. if (shape_)
  585. shape_->setMargin(margin);
  586. margin_ = margin;
  587. MarkNetworkUpdate();
  588. }
  589. }
  590. void CollisionShape::SetModel(Model* model)
  591. {
  592. if (model != model_)
  593. {
  594. if (model_)
  595. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  596. model_ = model;
  597. if (shapeType_ >= SHAPE_TRIANGLEMESH)
  598. {
  599. UpdateShape();
  600. NotifyRigidBody();
  601. }
  602. MarkNetworkUpdate();
  603. }
  604. }
  605. void CollisionShape::SetLodLevel(unsigned lodLevel)
  606. {
  607. if (lodLevel != lodLevel_)
  608. {
  609. lodLevel_ = lodLevel;
  610. if (shapeType_ >= SHAPE_TRIANGLEMESH)
  611. {
  612. UpdateShape();
  613. NotifyRigidBody();
  614. }
  615. MarkNetworkUpdate();
  616. }
  617. }
  618. BoundingBox CollisionShape::GetWorldBoundingBox() const
  619. {
  620. if (shape_ && node_)
  621. {
  622. // Use the rigid body's world transform if possible, as it may be different from the rendering transform
  623. RigidBody* body = GetComponent<RigidBody>();
  624. Matrix3x4 worldTransform = body ? Matrix3x4(body->GetPosition(), body->GetRotation(), node_->GetWorldScale()) :
  625. node_->GetWorldTransform();
  626. Vector3 worldPosition(worldTransform * position_);
  627. Quaternion worldRotation(worldTransform.Rotation() * rotation_);
  628. btTransform shapeWorldTransform(ToBtQuaternion(worldRotation), ToBtVector3(worldPosition));
  629. btVector3 aabbMin, aabbMax;
  630. shape_->getAabb(shapeWorldTransform, aabbMin, aabbMax);
  631. return BoundingBox(ToVector3(aabbMin), ToVector3(aabbMax));
  632. }
  633. else
  634. return BoundingBox();
  635. }
  636. void CollisionShape::NotifyRigidBody(bool updateMass)
  637. {
  638. btCompoundShape* compound = GetParentCompoundShape();
  639. if (node_ && shape_ && compound)
  640. {
  641. // Remove the shape first to ensure it is not added twice
  642. compound->removeChildShape(shape_);
  643. if (IsEnabledEffective())
  644. {
  645. // Then add with updated offset
  646. Vector3 position = position_;
  647. // For terrains, undo the height centering performed automatically by Bullet
  648. if (shapeType_ == SHAPE_TERRAIN && geometry_)
  649. {
  650. HeightfieldData* heightfield = static_cast<HeightfieldData*>(geometry_.Get());
  651. position.y_ += (heightfield->minHeight_ + heightfield->maxHeight_) * 0.5f;
  652. }
  653. btTransform offset;
  654. offset.setOrigin(ToBtVector3(node_->GetWorldScale() * position));
  655. offset.setRotation(ToBtQuaternion(rotation_));
  656. compound->addChildShape(offset, shape_);
  657. }
  658. // Finally tell the rigid body to update its mass
  659. if (updateMass)
  660. rigidBody_->UpdateMass();
  661. }
  662. }
  663. void CollisionShape::SetModelAttr(ResourceRef value)
  664. {
  665. ResourceCache* cache = GetSubsystem<ResourceCache>();
  666. model_ = cache->GetResource<Model>(value.name_);
  667. recreateShape_ = true;
  668. MarkNetworkUpdate();
  669. }
  670. ResourceRef CollisionShape::GetModelAttr() const
  671. {
  672. return GetResourceRef(model_, Model::GetTypeStatic());
  673. }
  674. void CollisionShape::ReleaseShape()
  675. {
  676. btCompoundShape* compound = GetParentCompoundShape();
  677. if (shape_ && compound)
  678. {
  679. compound->removeChildShape(shape_);
  680. rigidBody_->UpdateMass();
  681. }
  682. delete shape_;
  683. shape_ = 0;
  684. geometry_.Reset();
  685. if (physicsWorld_)
  686. physicsWorld_->CleanupGeometryCache();
  687. }
  688. void CollisionShape::OnNodeSet(Node* node)
  689. {
  690. if (node)
  691. {
  692. Scene* scene = GetScene();
  693. if (scene)
  694. {
  695. if (scene == node)
  696. LOGWARNING(GetTypeName() + " should not be created to the root scene node");
  697. physicsWorld_ = scene->GetOrCreateComponent<PhysicsWorld>();
  698. physicsWorld_->AddCollisionShape(this);
  699. }
  700. else
  701. LOGERROR("Node is detached from scene, can not create collision shape");
  702. node->AddListener(this);
  703. cachedWorldScale_ = node->GetWorldScale();
  704. // Terrain collision shape depends on the terrain component's geometry updates. Subscribe to them
  705. SubscribeToEvent(node, E_TERRAINCREATED, HANDLER(CollisionShape, HandleTerrainCreated));
  706. }
  707. }
  708. void CollisionShape::OnMarkedDirty(Node* node)
  709. {
  710. Vector3 newWorldScale = node_->GetWorldScale();
  711. if (HasWorldScaleChanged(cachedWorldScale_, newWorldScale) && shape_)
  712. {
  713. // Physics operations are not safe from worker threads
  714. Scene* scene = GetScene();
  715. if (scene && scene->IsThreadedUpdate())
  716. {
  717. scene->DelayedMarkedDirty(this);
  718. return;
  719. }
  720. switch (shapeType_)
  721. {
  722. case SHAPE_BOX:
  723. case SHAPE_SPHERE:
  724. case SHAPE_CYLINDER:
  725. case SHAPE_CAPSULE:
  726. case SHAPE_CONE:
  727. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  728. break;
  729. case SHAPE_TRIANGLEMESH:
  730. case SHAPE_CONVEXHULL:
  731. shape_->setLocalScaling(ToBtVector3(newWorldScale * size_));
  732. break;
  733. case SHAPE_TERRAIN:
  734. {
  735. HeightfieldData* heightfield = static_cast<HeightfieldData*>(geometry_.Get());
  736. shape_->setLocalScaling(ToBtVector3(Vector3(heightfield->spacing_.x_, 1.0f, heightfield->spacing_.z_) *
  737. newWorldScale * size_));
  738. }
  739. break;
  740. default:
  741. break;
  742. }
  743. NotifyRigidBody();
  744. cachedWorldScale_ = newWorldScale;
  745. }
  746. }
  747. btCompoundShape* CollisionShape::GetParentCompoundShape()
  748. {
  749. if (!rigidBody_)
  750. rigidBody_ = GetComponent<RigidBody>();
  751. return rigidBody_ ? rigidBody_->GetCompoundShape() : 0;
  752. }
  753. void CollisionShape::UpdateShape()
  754. {
  755. PROFILE(UpdateCollisionShape);
  756. ReleaseShape();
  757. if (!physicsWorld_)
  758. return;
  759. if (node_)
  760. {
  761. Vector3 newWorldScale = node_->GetWorldScale();
  762. switch (shapeType_)
  763. {
  764. case SHAPE_BOX:
  765. shape_ = new btBoxShape(ToBtVector3(size_ * 0.5f));
  766. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  767. break;
  768. case SHAPE_SPHERE:
  769. shape_ = new btSphereShape(size_.x_ * 0.5f);
  770. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  771. break;
  772. case SHAPE_STATICPLANE:
  773. shape_ = new btStaticPlaneShape(btVector3(0.0f, 1.0f, 0.0f), 0.0f);
  774. break;
  775. case SHAPE_CYLINDER:
  776. shape_ = new btCylinderShape(btVector3(size_.x_ * 0.5f, size_.y_ * 0.5f, size_.x_ * 0.5f));
  777. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  778. break;
  779. case SHAPE_CAPSULE:
  780. shape_ = new btCapsuleShape(size_.x_ * 0.5f, Max(size_.y_ - size_.x_, 0.0f));
  781. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  782. break;
  783. case SHAPE_CONE:
  784. shape_ = new btConeShape(size_.x_ * 0.5f, size_.y_);
  785. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  786. break;
  787. case SHAPE_TRIANGLEMESH:
  788. size_ = size_.Abs();
  789. if (model_ && model_->GetNumGeometries())
  790. {
  791. // Check the geometry cache
  792. Pair<Model*, unsigned> id = MakePair(model_.Get(), lodLevel_);
  793. HashMap<Pair<Model*, unsigned>, SharedPtr<CollisionGeometryData> >& cache = physicsWorld_->GetTriMeshCache();
  794. HashMap<Pair<Model*, unsigned>, SharedPtr<CollisionGeometryData> >::Iterator j = cache.Find(id);
  795. if (j != cache.End())
  796. geometry_ = j->second_;
  797. else
  798. {
  799. geometry_ = new TriangleMeshData(model_, lodLevel_);
  800. // Check if model has dynamic buffers, do not cache in that case
  801. if (!HasDynamicBuffers(model_, lodLevel_))
  802. cache[id] = geometry_;
  803. }
  804. TriangleMeshData* triMesh = static_cast<TriangleMeshData*>(geometry_.Get());
  805. shape_ = new btScaledBvhTriangleMeshShape(triMesh->shape_, ToBtVector3(newWorldScale * size_));
  806. // Watch for live reloads of the collision model to reload the geometry if necessary
  807. SubscribeToEvent(model_, E_RELOADFINISHED, HANDLER(CollisionShape, HandleModelReloadFinished));
  808. }
  809. break;
  810. case SHAPE_CONVEXHULL:
  811. size_ = size_.Abs();
  812. if (customGeometryID_ && GetScene())
  813. {
  814. Node* node = GetScene()->GetNode(customGeometryID_);
  815. CustomGeometry* custom = node ? node->GetComponent<CustomGeometry>() : 0;
  816. if (custom)
  817. {
  818. geometry_ = new ConvexData(custom);
  819. ConvexData* convex = static_cast<ConvexData*>(geometry_.Get());
  820. shape_ = new btConvexHullShape((btScalar*)convex->vertexData_.Get(), convex->vertexCount_, sizeof(Vector3));
  821. shape_->setLocalScaling(ToBtVector3(newWorldScale * size_));
  822. LOGINFO("Set convexhull from customgeometry");
  823. }
  824. else
  825. LOGWARNING("Could not find custom geometry component from node ID " + String(customGeometryID_) + " for convex shape creation");
  826. }
  827. else if (model_ && model_->GetNumGeometries())
  828. {
  829. // Check the geometry cache
  830. Pair<Model*, unsigned> id = MakePair(model_.Get(), lodLevel_);
  831. HashMap<Pair<Model*, unsigned>, SharedPtr<CollisionGeometryData> >& cache = physicsWorld_->GetConvexCache();
  832. HashMap<Pair<Model*, unsigned>, SharedPtr<CollisionGeometryData> >::Iterator j = cache.Find(id);
  833. if (j != cache.End())
  834. geometry_ = j->second_;
  835. else
  836. {
  837. geometry_ = new ConvexData(model_, lodLevel_);
  838. // Check if model has dynamic buffers, do not cache in that case
  839. if (!HasDynamicBuffers(model_, lodLevel_))
  840. cache[id] = geometry_;
  841. }
  842. ConvexData* convex = static_cast<ConvexData*>(geometry_.Get());
  843. shape_ = new btConvexHullShape((btScalar*)convex->vertexData_.Get(), convex->vertexCount_, sizeof(Vector3));
  844. shape_->setLocalScaling(ToBtVector3(newWorldScale * size_));
  845. SubscribeToEvent(model_, E_RELOADFINISHED, HANDLER(CollisionShape, HandleModelReloadFinished));
  846. }
  847. break;
  848. case SHAPE_TERRAIN:
  849. size_ = size_.Abs();
  850. {
  851. Terrain* terrain = GetComponent<Terrain>();
  852. if (terrain && terrain->GetHeightData())
  853. {
  854. geometry_ = new HeightfieldData(terrain);
  855. HeightfieldData* heightfield = static_cast<HeightfieldData*>(geometry_.Get());
  856. shape_ = new btHeightfieldTerrainShape(heightfield->size_.x_, heightfield->size_.y_,
  857. heightfield->heightData_.Get(), 1.0f, heightfield->minHeight_, heightfield->maxHeight_, 1, PHY_FLOAT,
  858. false);
  859. shape_->setLocalScaling(ToBtVector3(Vector3(heightfield->spacing_.x_, 1.0f, heightfield->spacing_.z_) *
  860. newWorldScale * size_));
  861. }
  862. }
  863. break;
  864. default:
  865. break;
  866. }
  867. if (shape_)
  868. {
  869. shape_->setUserPointer(this);
  870. shape_->setMargin(margin_);
  871. }
  872. cachedWorldScale_ = newWorldScale;
  873. }
  874. if (physicsWorld_)
  875. physicsWorld_->CleanupGeometryCache();
  876. recreateShape_ = false;
  877. }
  878. void CollisionShape::HandleTerrainCreated(StringHash eventType, VariantMap& eventData)
  879. {
  880. if (shapeType_ == SHAPE_TERRAIN)
  881. {
  882. UpdateShape();
  883. NotifyRigidBody();
  884. }
  885. }
  886. void CollisionShape::HandleModelReloadFinished(StringHash eventType, VariantMap& eventData)
  887. {
  888. if (physicsWorld_)
  889. physicsWorld_->RemoveCachedGeometry(model_);
  890. if (shapeType_ == SHAPE_TRIANGLEMESH || shapeType_ == SHAPE_CONVEXHULL)
  891. {
  892. UpdateShape();
  893. NotifyRigidBody();
  894. }
  895. }
  896. }