CollisionShape.cpp 24 KB

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