CollisionShape.cpp 25 KB

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