CollisionShape.cpp 25 KB

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