CollisionShape.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  1. //
  2. // Copyright (c) 2008-2013 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 "DebugRenderer.h"
  26. #include "DrawableEvents.h"
  27. #include "Geometry.h"
  28. #include "Log.h"
  29. #include "Model.h"
  30. #include "PhysicsUtils.h"
  31. #include "PhysicsWorld.h"
  32. #include "Profiler.h"
  33. #include "ResourceCache.h"
  34. #include "RigidBody.h"
  35. #include "Scene.h"
  36. #include "Terrain.h"
  37. #include <BulletCollision/CollisionShapes/btBoxShape.h>
  38. #include <BulletCollision/CollisionShapes/btCapsuleShape.h>
  39. #include <BulletCollision/CollisionShapes/btCompoundShape.h>
  40. #include <BulletCollision/CollisionShapes/btConeShape.h>
  41. #include <BulletCollision/CollisionShapes/btConvexHullShape.h>
  42. #include <BulletCollision/CollisionShapes/btCylinderShape.h>
  43. #include <BulletCollision/CollisionShapes/btHeightfieldTerrainShape.h>
  44. #include <BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.h>
  45. #include <BulletCollision/CollisionShapes/btSphereShape.h>
  46. #include <BulletCollision/CollisionShapes/btTriangleMesh.h>
  47. #include <BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h>
  48. #include <BulletCollision/CollisionShapes/btStaticPlaneShape.h>
  49. #include <hull.h>
  50. namespace Urho3D
  51. {
  52. static const float DEFAULT_COLLISION_MARGIN = 0.04f;
  53. static const btVector3 WHITE(1.0f, 1.0f, 1.0f);
  54. static const btVector3 GREEN(0.0f, 1.0f, 0.0f);
  55. static const char* typeNames[] =
  56. {
  57. "Box",
  58. "Sphere",
  59. "StaticPlane",
  60. "Cylinder",
  61. "Capsule",
  62. "Cone",
  63. "TriangleMesh",
  64. "ConvexHull",
  65. "Terrain",
  66. 0
  67. };
  68. TriangleMeshData::TriangleMeshData(Model* model, unsigned lodLevel) :
  69. meshData_(0),
  70. shape_(0)
  71. {
  72. modelName_ = model->GetName();
  73. meshData_ = new btTriangleMesh();
  74. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  75. for (unsigned i = 0; i < geometries.Size(); ++i)
  76. {
  77. unsigned subGeometryLodLevel = lodLevel;
  78. if (subGeometryLodLevel >= geometries[i].Size())
  79. subGeometryLodLevel = geometries[i].Size() - 1;
  80. Geometry* geom = geometries[i][subGeometryLodLevel];
  81. if (!geom)
  82. {
  83. LOGWARNING("Skipping null geometry for triangle mesh collision");
  84. continue;
  85. }
  86. const unsigned char* vertexData;
  87. const unsigned char* indexData;
  88. unsigned vertexSize;
  89. unsigned indexSize;
  90. unsigned elementMask;
  91. geom->GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask);
  92. if (!vertexData || !indexData)
  93. {
  94. LOGWARNING("Skipping geometry with no CPU-side geometry data for triangle mesh collision");
  95. continue;
  96. }
  97. unsigned indexStart = geom->GetIndexStart();
  98. unsigned indexCount = geom->GetIndexCount();
  99. // 16-bit indices
  100. if (indexSize == sizeof(unsigned short))
  101. {
  102. const unsigned short* indices = (const unsigned short*)indexData;
  103. for (unsigned j = indexStart; j < indexStart + indexCount; j += 3)
  104. {
  105. const Vector3& v0 = *((const Vector3*)(&vertexData[indices[j] * vertexSize]));
  106. const Vector3& v1 = *((const Vector3*)(&vertexData[indices[j + 1] * vertexSize]));
  107. const Vector3& v2 = *((const Vector3*)(&vertexData[indices[j + 2] * vertexSize]));
  108. meshData_->addTriangle(ToBtVector3(v0), ToBtVector3(v1), ToBtVector3(v2), true);
  109. }
  110. }
  111. // 32-bit indices
  112. else
  113. {
  114. const unsigned* indices = (const unsigned*)indexData;
  115. for (unsigned j = indexStart; j < indexStart + indexCount; j += 3)
  116. {
  117. const Vector3& v0 = *((const Vector3*)(&vertexData[indices[j] * vertexSize]));
  118. const Vector3& v1 = *((const Vector3*)(&vertexData[indices[j + 1] * vertexSize]));
  119. const Vector3& v2 = *((const Vector3*)(&vertexData[indices[j + 2] * vertexSize]));
  120. meshData_->addTriangle(ToBtVector3(v0), ToBtVector3(v1), ToBtVector3(v2), true);
  121. }
  122. }
  123. }
  124. shape_ = new btBvhTriangleMeshShape(meshData_, true, true);
  125. }
  126. TriangleMeshData::~TriangleMeshData()
  127. {
  128. delete shape_;
  129. shape_ = 0;
  130. delete meshData_;
  131. meshData_ = 0;
  132. }
  133. ConvexData::ConvexData(Model* model, unsigned lodLevel)
  134. {
  135. modelName_ = model->GetName();
  136. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  137. PODVector<Vector3> originalVertices;
  138. for (unsigned i = 0; i < geometries.Size(); ++i)
  139. {
  140. unsigned subGeometryLodLevel = lodLevel;
  141. if (subGeometryLodLevel >= geometries[i].Size())
  142. subGeometryLodLevel = geometries[i].Size() - 1;
  143. Geometry* geom = geometries[i][subGeometryLodLevel];
  144. if (!geom)
  145. {
  146. LOGWARNING("Skipping null geometry for convex hull collision");
  147. continue;
  148. };
  149. const unsigned char* vertexData;
  150. const unsigned char* indexData;
  151. unsigned vertexSize;
  152. unsigned indexSize;
  153. unsigned elementMask;
  154. geom->GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask);
  155. if (!vertexData || !indexData)
  156. {
  157. LOGWARNING("Skipping geometry with no CPU-side geometry data for convex hull collision");
  158. continue;
  159. }
  160. unsigned vertexStart = geom->GetVertexStart();
  161. unsigned vertexCount = geom->GetVertexCount();
  162. // Copy vertex data
  163. for (unsigned j = 0; j < vertexCount; ++j)
  164. {
  165. const Vector3& v = *((const Vector3*)(&vertexData[(vertexStart + j) * vertexSize]));
  166. originalVertices.Push(v);
  167. }
  168. }
  169. if (originalVertices.Size())
  170. {
  171. // Build the convex hull from the raw geometry
  172. StanHull::HullDesc desc;
  173. desc.SetHullFlag(StanHull::QF_TRIANGLES);
  174. desc.mVcount = originalVertices.Size();
  175. desc.mVertices = originalVertices[0].Data();
  176. desc.mVertexStride = 3 * sizeof(float);
  177. desc.mSkinWidth = 0.0f;
  178. StanHull::HullLibrary lib;
  179. StanHull::HullResult result;
  180. lib.CreateConvexHull(desc, result);
  181. vertexCount_ = result.mNumOutputVertices;
  182. vertexData_ = new Vector3[vertexCount_];
  183. indexCount_ = result.mNumIndices;
  184. indexData_ = new unsigned[indexCount_];
  185. // Copy vertex data & index data
  186. memcpy(vertexData_.Get(), result.mOutputVertices, vertexCount_ * sizeof(Vector3));
  187. memcpy(indexData_.Get(), result.mIndices, indexCount_ * sizeof(unsigned));
  188. lib.ReleaseResult(result);
  189. }
  190. else
  191. vertexCount_ = 0;
  192. }
  193. ConvexData::~ConvexData()
  194. {
  195. }
  196. HeightfieldData::HeightfieldData(Terrain* terrain) :
  197. heightData_(terrain->GetHeightData()),
  198. spacing_(terrain->GetSpacing()),
  199. size_(terrain->GetNumVertices()),
  200. minHeight_(0.0f),
  201. maxHeight_(0.0f)
  202. {
  203. if (heightData_)
  204. {
  205. unsigned points = size_.x_ * size_.y_;
  206. float* data = heightData_.Get();
  207. minHeight_ = maxHeight_ = data[0];
  208. for (unsigned i = 1; i < points; ++i)
  209. {
  210. minHeight_ = Min(minHeight_, data[i]);
  211. maxHeight_ = Max(maxHeight_, data[i]);
  212. }
  213. }
  214. }
  215. HeightfieldData::~HeightfieldData()
  216. {
  217. }
  218. OBJECTTYPESTATIC(CollisionShape);
  219. CollisionShape::CollisionShape(Context* context) :
  220. Component(context),
  221. shape_(0),
  222. shapeType_(SHAPE_BOX),
  223. position_(Vector3::ZERO),
  224. rotation_(Quaternion::IDENTITY),
  225. size_(Vector3::ONE),
  226. cachedWorldScale_(Vector3::ONE),
  227. lodLevel_(0),
  228. margin_(DEFAULT_COLLISION_MARGIN),
  229. recreateShape_(true)
  230. {
  231. }
  232. CollisionShape::~CollisionShape()
  233. {
  234. ReleaseShape();
  235. if (physicsWorld_)
  236. physicsWorld_->RemoveCollisionShape(this);
  237. }
  238. void CollisionShape::RegisterObject(Context* context)
  239. {
  240. context->RegisterFactory<CollisionShape>();
  241. ACCESSOR_ATTRIBUTE(CollisionShape, VAR_BOOL, "Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  242. ENUM_ATTRIBUTE(CollisionShape, "Shape Type", shapeType_, typeNames, SHAPE_BOX, AM_DEFAULT);
  243. ATTRIBUTE(CollisionShape, VAR_VECTOR3, "Size", size_, Vector3::ONE, AM_DEFAULT);
  244. REF_ACCESSOR_ATTRIBUTE(CollisionShape, VAR_VECTOR3, "Offset Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_DEFAULT);
  245. REF_ACCESSOR_ATTRIBUTE(CollisionShape, VAR_QUATERNION, "Offset Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_DEFAULT);
  246. ACCESSOR_ATTRIBUTE(CollisionShape, VAR_RESOURCEREF, "Model", GetModelAttr, SetModelAttr, ResourceRef, ResourceRef(Model::GetTypeStatic()), AM_DEFAULT);
  247. ATTRIBUTE(CollisionShape, VAR_INT, "LOD Level", lodLevel_, 0, AM_DEFAULT);
  248. ATTRIBUTE(CollisionShape, VAR_FLOAT, "Collision Margin", margin_, DEFAULT_COLLISION_MARGIN, AM_DEFAULT);
  249. }
  250. void CollisionShape::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  251. {
  252. Component::OnSetAttribute(attr, src);
  253. // Change of any non-accessor attribute requires recreation of the collision shape
  254. if (!attr.accessor_)
  255. recreateShape_ = true;
  256. }
  257. void CollisionShape::ApplyAttributes()
  258. {
  259. if (recreateShape_)
  260. {
  261. UpdateShape();
  262. NotifyRigidBody();
  263. }
  264. }
  265. void CollisionShape::OnSetEnabled()
  266. {
  267. NotifyRigidBody();
  268. }
  269. void CollisionShape::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  270. {
  271. if (debug && physicsWorld_ && shape_ && node_ && IsEnabledEffective())
  272. {
  273. physicsWorld_->SetDebugRenderer(debug);
  274. physicsWorld_->SetDebugDepthTest(depthTest);
  275. // Use the rigid body's world transform if possible, as it may be different from the rendering transform
  276. Matrix3x4 worldTransform;
  277. RigidBody* body = GetComponent<RigidBody>();
  278. bool bodyActive = false;
  279. if (body)
  280. {
  281. worldTransform = Matrix3x4(body->GetPosition(), body->GetRotation(), node_->GetWorldScale());
  282. bodyActive = body->IsActive();
  283. }
  284. else
  285. worldTransform = node_->GetWorldTransform();
  286. Vector3 position = position_;
  287. // For terrains, undo the height centering performed automatically by Bullet
  288. if (shapeType_ == SHAPE_TERRAIN && geometry_)
  289. {
  290. HeightfieldData* heightfield = static_cast<HeightfieldData*>(geometry_.Get());
  291. position.y_ += (heightfield->minHeight_ + heightfield->maxHeight_) * 0.5f;
  292. }
  293. Vector3 worldPosition = worldTransform * position;
  294. Quaternion worldRotation = worldTransform.Rotation() * rotation_;
  295. btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
  296. world->debugDrawObject(btTransform(ToBtQuaternion(worldRotation), ToBtVector3(worldPosition)), shape_, bodyActive ?
  297. WHITE : GREEN);
  298. physicsWorld_->SetDebugRenderer(0);
  299. }
  300. }
  301. void CollisionShape::SetBox(const Vector3& size, const Vector3& position, const Quaternion& rotation)
  302. {
  303. shapeType_ = SHAPE_BOX;
  304. size_ = size;
  305. position_ = position;
  306. rotation_ = rotation;
  307. model_.Reset();
  308. UpdateShape();
  309. NotifyRigidBody();
  310. MarkNetworkUpdate();
  311. }
  312. void CollisionShape::SetSphere(float diameter, const Vector3& position, const Quaternion& rotation)
  313. {
  314. shapeType_ = SHAPE_SPHERE;
  315. size_ = Vector3(diameter, diameter, diameter);
  316. position_ = position;
  317. rotation_ = rotation;
  318. model_.Reset();
  319. UpdateShape();
  320. NotifyRigidBody();
  321. MarkNetworkUpdate();
  322. }
  323. void CollisionShape::SetCylinder(float diameter, float height, const Vector3& position, const Quaternion& rotation)
  324. {
  325. shapeType_ = SHAPE_CYLINDER;
  326. size_ = Vector3(diameter, height, diameter);
  327. position_ = position;
  328. rotation_ = rotation;
  329. model_.Reset();
  330. UpdateShape();
  331. NotifyRigidBody();
  332. MarkNetworkUpdate();
  333. }
  334. void CollisionShape::SetCapsule(float diameter, float height, const Vector3& position, const Quaternion& rotation)
  335. {
  336. shapeType_ = SHAPE_CAPSULE;
  337. size_ = Vector3(diameter, height, diameter);
  338. position_ = position;
  339. rotation_ = rotation;
  340. model_.Reset();
  341. UpdateShape();
  342. NotifyRigidBody();
  343. MarkNetworkUpdate();
  344. }
  345. void CollisionShape::SetCone(float diameter, float height, const Vector3& position, const Quaternion& rotation)
  346. {
  347. shapeType_ = SHAPE_CONE;
  348. size_ = Vector3(diameter, height, diameter);
  349. position_ = position;
  350. rotation_ = rotation;
  351. model_.Reset();
  352. UpdateShape();
  353. NotifyRigidBody();
  354. MarkNetworkUpdate();
  355. }
  356. void CollisionShape::SetTriangleMesh(Model* model, unsigned lodLevel, const Vector3& scale, const Vector3& position, const Quaternion& rotation)
  357. {
  358. if (!model)
  359. {
  360. LOGERROR("Null model, can not set triangle mesh");
  361. return;
  362. }
  363. shapeType_ = SHAPE_TRIANGLEMESH;
  364. model_ = model;
  365. lodLevel_ = lodLevel;
  366. size_ = scale;
  367. position_ = position;
  368. rotation_ = rotation;
  369. UpdateShape();
  370. NotifyRigidBody();
  371. MarkNetworkUpdate();
  372. }
  373. void CollisionShape::SetConvexHull(Model* model, unsigned lodLevel, const Vector3& scale, const Vector3& position, const Quaternion& rotation)
  374. {
  375. if (!model)
  376. {
  377. LOGERROR("Null model, can not set convex hull");
  378. return;
  379. }
  380. shapeType_ = SHAPE_CONVEXHULL;
  381. model_ = model;
  382. lodLevel_ = lodLevel;
  383. size_ = scale;
  384. position_ = position;
  385. rotation_ = rotation;
  386. UpdateShape();
  387. NotifyRigidBody();
  388. MarkNetworkUpdate();
  389. }
  390. void CollisionShape::SetTerrain()
  391. {
  392. Terrain* terrain = GetComponent<Terrain>();
  393. if (!terrain)
  394. {
  395. LOGERROR("No terrain component, can not set terrain shape");
  396. return;
  397. }
  398. shapeType_ = SHAPE_TERRAIN;
  399. UpdateShape();
  400. NotifyRigidBody();
  401. MarkNetworkUpdate();
  402. }
  403. void CollisionShape::SetShapeType(ShapeType type)
  404. {
  405. if (type != shapeType_)
  406. {
  407. shapeType_ = type;
  408. UpdateShape();
  409. NotifyRigidBody();
  410. MarkNetworkUpdate();
  411. }
  412. }
  413. void CollisionShape::SetSize(const Vector3& size)
  414. {
  415. if (size != size_)
  416. {
  417. size_ = size;
  418. UpdateShape();
  419. NotifyRigidBody();
  420. MarkNetworkUpdate();
  421. }
  422. }
  423. void CollisionShape::SetPosition(const Vector3& position)
  424. {
  425. if (position != position_)
  426. {
  427. position_ = position;
  428. NotifyRigidBody();
  429. MarkNetworkUpdate();
  430. }
  431. }
  432. void CollisionShape::SetRotation(const Quaternion& rotation)
  433. {
  434. if (rotation != rotation_)
  435. {
  436. rotation_ = rotation;
  437. NotifyRigidBody();
  438. MarkNetworkUpdate();
  439. }
  440. }
  441. void CollisionShape::SetTransform(const Vector3& position, const Quaternion& rotation)
  442. {
  443. if (position != position_ || rotation != rotation_)
  444. {
  445. position_ = position;
  446. rotation_ = rotation;
  447. NotifyRigidBody();
  448. MarkNetworkUpdate();
  449. }
  450. }
  451. void CollisionShape::SetMargin(float margin)
  452. {
  453. margin = Max(margin, 0.0f);
  454. if (margin != margin_)
  455. {
  456. if (shape_)
  457. shape_->setMargin(margin);
  458. margin_ = margin;
  459. MarkNetworkUpdate();
  460. }
  461. }
  462. void CollisionShape::SetModel(Model* model)
  463. {
  464. if (model != model_)
  465. {
  466. model_ = model;
  467. if (shapeType_ >= SHAPE_TRIANGLEMESH)
  468. {
  469. UpdateShape();
  470. NotifyRigidBody();
  471. }
  472. MarkNetworkUpdate();
  473. }
  474. }
  475. void CollisionShape::SetLodLevel(unsigned lodLevel)
  476. {
  477. if (lodLevel != lodLevel_)
  478. {
  479. lodLevel_ = lodLevel;
  480. if (shapeType_ >= SHAPE_TRIANGLEMESH)
  481. {
  482. UpdateShape();
  483. NotifyRigidBody();
  484. }
  485. MarkNetworkUpdate();
  486. }
  487. }
  488. void CollisionShape::NotifyRigidBody()
  489. {
  490. btCompoundShape* compound = GetParentCompoundShape();
  491. if (node_ && shape_ && compound)
  492. {
  493. // Remove the shape first to ensure it is not added twice
  494. compound->removeChildShape(shape_);
  495. if (IsEnabledEffective())
  496. {
  497. // Then add with updated offset
  498. Vector3 position = position_;
  499. // For terrains, undo the height centering performed automatically by Bullet
  500. if (shapeType_ == SHAPE_TERRAIN && geometry_)
  501. {
  502. HeightfieldData* heightfield = static_cast<HeightfieldData*>(geometry_.Get());
  503. position.y_ += (heightfield->minHeight_ + heightfield->maxHeight_) * 0.5f;
  504. }
  505. btTransform offset;
  506. offset.setOrigin(ToBtVector3(node_->GetWorldScale() * position));
  507. offset.setRotation(ToBtQuaternion(rotation_));
  508. compound->addChildShape(offset, shape_);
  509. }
  510. // Finally tell the rigid body to update its mass
  511. rigidBody_->UpdateMass();
  512. }
  513. }
  514. void CollisionShape::SetModelAttr(ResourceRef value)
  515. {
  516. ResourceCache* cache = GetSubsystem<ResourceCache>();
  517. model_ = cache->GetResource<Model>(value.id_);
  518. recreateShape_ = true;
  519. MarkNetworkUpdate();
  520. }
  521. ResourceRef CollisionShape::GetModelAttr() const
  522. {
  523. return GetResourceRef(model_, Model::GetTypeStatic());
  524. }
  525. void CollisionShape::ReleaseShape()
  526. {
  527. btCompoundShape* compound = GetParentCompoundShape();
  528. if (shape_ && compound)
  529. {
  530. compound->removeChildShape(shape_);
  531. rigidBody_->UpdateMass();
  532. }
  533. delete shape_;
  534. shape_ = 0;
  535. geometry_.Reset();
  536. if (physicsWorld_)
  537. physicsWorld_->CleanupGeometryCache();
  538. }
  539. void CollisionShape::OnNodeSet(Node* node)
  540. {
  541. if (node)
  542. {
  543. Scene* scene = GetScene();
  544. if (scene)
  545. {
  546. if (scene == node)
  547. LOGWARNING(GetTypeName() + " should not be created to the root scene node");
  548. physicsWorld_ = scene->GetComponent<PhysicsWorld>();
  549. if (physicsWorld_)
  550. physicsWorld_->AddCollisionShape(this);
  551. else
  552. LOGERROR("No physics world component in scene, can not create collision shape");
  553. }
  554. node->AddListener(this);
  555. cachedWorldScale_ = node->GetWorldScale();
  556. // Terrain collision shape depends on the terrain component's geometry updates. Subscribe to them
  557. SubscribeToEvent(node, E_TERRAINCREATED, HANDLER(CollisionShape, HandleTerrainCreated));
  558. }
  559. }
  560. void CollisionShape::OnMarkedDirty(Node* node)
  561. {
  562. Vector3 newWorldScale = node_->GetWorldScale();
  563. if (!newWorldScale.Equals(cachedWorldScale_) && shape_)
  564. {
  565. // Physics operations are not safe from worker threads
  566. Scene* scene = GetScene();
  567. if (scene && scene->IsThreadedUpdate())
  568. {
  569. scene->DelayedMarkedDirty(this);
  570. return;
  571. }
  572. switch (shapeType_)
  573. {
  574. case SHAPE_BOX:
  575. case SHAPE_SPHERE:
  576. case SHAPE_CYLINDER:
  577. case SHAPE_CAPSULE:
  578. case SHAPE_CONE:
  579. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  580. break;
  581. case SHAPE_TRIANGLEMESH:
  582. case SHAPE_CONVEXHULL:
  583. shape_->setLocalScaling(ToBtVector3(newWorldScale * size_));
  584. break;
  585. case SHAPE_TERRAIN:
  586. {
  587. HeightfieldData* heightfield = static_cast<HeightfieldData*>(geometry_.Get());
  588. shape_->setLocalScaling(ToBtVector3(Vector3(heightfield->spacing_.x_, 1.0f, heightfield->spacing_.z_) *
  589. newWorldScale * size_));
  590. }
  591. break;
  592. default:
  593. break;
  594. }
  595. NotifyRigidBody();
  596. cachedWorldScale_ = newWorldScale;
  597. }
  598. }
  599. btCompoundShape* CollisionShape::GetParentCompoundShape()
  600. {
  601. if (!rigidBody_)
  602. rigidBody_ = GetComponent<RigidBody>();
  603. return rigidBody_ ? rigidBody_->GetCompoundShape() : 0;
  604. }
  605. void CollisionShape::UpdateShape()
  606. {
  607. PROFILE(UpdateCollisionShape);
  608. ReleaseShape();
  609. if (!physicsWorld_)
  610. return;
  611. if (node_)
  612. {
  613. Vector3 newWorldScale = node_->GetWorldScale();
  614. switch (shapeType_)
  615. {
  616. case SHAPE_BOX:
  617. shape_ = new btBoxShape(ToBtVector3(size_ * 0.5f));
  618. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  619. break;
  620. case SHAPE_SPHERE:
  621. shape_ = new btSphereShape(size_.x_ * 0.5f);
  622. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  623. break;
  624. case SHAPE_STATICPLANE:
  625. shape_ = new btStaticPlaneShape(btVector3(0.0f, 1.0f, 0.0f), 0.0f);
  626. break;
  627. case SHAPE_CYLINDER:
  628. shape_ = new btCylinderShape(btVector3(size_.x_ * 0.5f, size_.y_ * 0.5f, size_.x_ * 0.5f));
  629. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  630. break;
  631. case SHAPE_CAPSULE:
  632. shape_ = new btCapsuleShape(size_.x_ * 0.5f, Max(size_.y_ - size_.x_, 0.0f));
  633. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  634. break;
  635. case SHAPE_CONE:
  636. shape_ = new btConeShape(size_.x_ * 0.5f, size_.y_);
  637. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  638. break;
  639. case SHAPE_TRIANGLEMESH:
  640. size_ = size_.Abs();
  641. if (model_)
  642. {
  643. // Check the geometry cache
  644. String id = "TriMesh_" + model_->GetName() + "_" + String(lodLevel_);
  645. HashMap<String, SharedPtr<CollisionGeometryData> >& cache = physicsWorld_->GetGeometryCache();
  646. HashMap<String, SharedPtr<CollisionGeometryData> >::Iterator j = cache.Find(id);
  647. if (j != cache.End())
  648. geometry_ = j->second_;
  649. else
  650. {
  651. geometry_ = new TriangleMeshData(model_, lodLevel_);
  652. cache[id] = geometry_;
  653. }
  654. TriangleMeshData* triMesh = static_cast<TriangleMeshData*>(geometry_.Get());
  655. shape_ = new btScaledBvhTriangleMeshShape(triMesh->shape_, ToBtVector3(newWorldScale * size_));
  656. }
  657. break;
  658. case SHAPE_CONVEXHULL:
  659. size_ = size_.Abs();
  660. if (model_)
  661. {
  662. // Check the geometry cache
  663. String id = "Convex_" + model_->GetName() + "_" + String(lodLevel_);
  664. HashMap<String, SharedPtr<CollisionGeometryData> >& cache = physicsWorld_->GetGeometryCache();
  665. HashMap<String, SharedPtr<CollisionGeometryData> >::Iterator j = cache.Find(id);
  666. if (j != cache.End())
  667. geometry_ = j->second_;
  668. else
  669. {
  670. geometry_ = new ConvexData(model_, lodLevel_);
  671. cache[id] = geometry_;
  672. }
  673. ConvexData* convex = static_cast<ConvexData*>(geometry_.Get());
  674. shape_ = new btConvexHullShape((btScalar*)convex->vertexData_.Get(), convex->vertexCount_, sizeof(Vector3));
  675. shape_->setLocalScaling(ToBtVector3(newWorldScale * size_));
  676. }
  677. break;
  678. case SHAPE_TERRAIN:
  679. size_ = size_.Abs();
  680. {
  681. Terrain* terrain = GetComponent<Terrain>();
  682. if (terrain && terrain->GetHeightData())
  683. {
  684. geometry_ = new HeightfieldData(terrain);
  685. HeightfieldData* heightfield = static_cast<HeightfieldData*>(geometry_.Get());
  686. shape_ = new btHeightfieldTerrainShape(heightfield->size_.x_, heightfield->size_.y_,
  687. heightfield->heightData_.Get(), 1.0f, heightfield->minHeight_, heightfield->maxHeight_, 1, PHY_FLOAT,
  688. false);
  689. shape_->setLocalScaling(ToBtVector3(Vector3(heightfield->spacing_.x_, 1.0f, heightfield->spacing_.z_) *
  690. newWorldScale * size_));
  691. }
  692. }
  693. break;
  694. default:
  695. break;
  696. }
  697. if (shape_)
  698. {
  699. shape_->setUserPointer(this);
  700. shape_->setMargin(margin_);
  701. }
  702. cachedWorldScale_ = newWorldScale;
  703. }
  704. if (physicsWorld_)
  705. physicsWorld_->CleanupGeometryCache();
  706. recreateShape_ = false;
  707. }
  708. void CollisionShape::HandleTerrainCreated(StringHash eventType, VariantMap& eventData)
  709. {
  710. if (shapeType_ == SHAPE_TERRAIN)
  711. {
  712. UpdateShape();
  713. NotifyRigidBody();
  714. }
  715. }
  716. }