CollisionShape.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  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. // Copy vertex data
  184. memcpy(vertexData_.Get(), result.mOutputVertices, vertexCount_ * sizeof(Vector3));
  185. lib.ReleaseResult(result);
  186. }
  187. else
  188. vertexCount_ = 0;
  189. }
  190. ConvexData::~ConvexData()
  191. {
  192. }
  193. HeightfieldData::HeightfieldData(Terrain* terrain) :
  194. heightData_(terrain->GetHeightData()),
  195. spacing_(terrain->GetSpacing()),
  196. size_(terrain->GetNumVertices()),
  197. minHeight_(0.0f),
  198. maxHeight_(0.0f)
  199. {
  200. if (heightData_)
  201. {
  202. unsigned points = size_.x_ * size_.y_;
  203. float* data = heightData_.Get();
  204. minHeight_ = maxHeight_ = data[0];
  205. for (unsigned i = 1; i < points; ++i)
  206. {
  207. minHeight_ = Min(minHeight_, data[i]);
  208. maxHeight_ = Max(maxHeight_, data[i]);
  209. }
  210. }
  211. }
  212. HeightfieldData::~HeightfieldData()
  213. {
  214. }
  215. OBJECTTYPESTATIC(CollisionShape);
  216. CollisionShape::CollisionShape(Context* context) :
  217. Component(context),
  218. shape_(0),
  219. shapeType_(SHAPE_BOX),
  220. position_(Vector3::ZERO),
  221. rotation_(Quaternion::IDENTITY),
  222. size_(Vector3::ONE),
  223. cachedWorldScale_(Vector3::ONE),
  224. lodLevel_(0),
  225. margin_(DEFAULT_COLLISION_MARGIN),
  226. recreateShape_(true)
  227. {
  228. }
  229. CollisionShape::~CollisionShape()
  230. {
  231. ReleaseShape();
  232. if (physicsWorld_)
  233. physicsWorld_->RemoveCollisionShape(this);
  234. }
  235. void CollisionShape::RegisterObject(Context* context)
  236. {
  237. context->RegisterFactory<CollisionShape>();
  238. ACCESSOR_ATTRIBUTE(CollisionShape, VAR_BOOL, "Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  239. ENUM_ATTRIBUTE(CollisionShape, "Shape Type", shapeType_, typeNames, SHAPE_BOX, AM_DEFAULT);
  240. ATTRIBUTE(CollisionShape, VAR_VECTOR3, "Size", size_, Vector3::ONE, AM_DEFAULT);
  241. REF_ACCESSOR_ATTRIBUTE(CollisionShape, VAR_VECTOR3, "Offset Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_DEFAULT);
  242. REF_ACCESSOR_ATTRIBUTE(CollisionShape, VAR_QUATERNION, "Offset Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_DEFAULT);
  243. ACCESSOR_ATTRIBUTE(CollisionShape, VAR_RESOURCEREF, "Model", GetModelAttr, SetModelAttr, ResourceRef, ResourceRef(Model::GetTypeStatic()), AM_DEFAULT);
  244. ATTRIBUTE(CollisionShape, VAR_INT, "LOD Level", lodLevel_, 0, AM_DEFAULT);
  245. ATTRIBUTE(CollisionShape, VAR_FLOAT, "Collision Margin", margin_, DEFAULT_COLLISION_MARGIN, AM_DEFAULT);
  246. }
  247. void CollisionShape::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  248. {
  249. Component::OnSetAttribute(attr, src);
  250. // Change of any non-accessor attribute requires recreation of the collision shape
  251. if (!attr.accessor_)
  252. recreateShape_ = true;
  253. }
  254. void CollisionShape::ApplyAttributes()
  255. {
  256. if (recreateShape_)
  257. {
  258. UpdateShape();
  259. NotifyRigidBody();
  260. }
  261. }
  262. void CollisionShape::OnSetEnabled()
  263. {
  264. NotifyRigidBody();
  265. }
  266. void CollisionShape::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  267. {
  268. if (debug && physicsWorld_ && shape_ && node_ && IsEnabledEffective())
  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. bool bodyActive = false;
  276. if (body)
  277. {
  278. worldTransform = Matrix3x4(body->GetPosition(), body->GetRotation(), node_->GetWorldScale());
  279. bodyActive = body->IsActive();
  280. }
  281. else
  282. worldTransform = node_->GetWorldTransform();
  283. Vector3 position = position_;
  284. // For terrains, undo the height centering performed automatically by Bullet
  285. if (shapeType_ == SHAPE_TERRAIN && geometry_)
  286. {
  287. HeightfieldData* heightfield = static_cast<HeightfieldData*>(geometry_.Get());
  288. position.y_ += (heightfield->minHeight_ + heightfield->maxHeight_) * 0.5f;
  289. }
  290. Vector3 worldPosition = worldTransform * position;
  291. Quaternion worldRotation = worldTransform.Rotation() * rotation_;
  292. btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
  293. world->debugDrawObject(btTransform(ToBtQuaternion(worldRotation), ToBtVector3(worldPosition)), shape_, bodyActive ?
  294. WHITE : GREEN);
  295. physicsWorld_->SetDebugRenderer(0);
  296. }
  297. }
  298. void CollisionShape::SetBox(const Vector3& size, const Vector3& position, const Quaternion& rotation)
  299. {
  300. shapeType_ = SHAPE_BOX;
  301. size_ = size;
  302. position_ = position;
  303. rotation_ = rotation;
  304. model_.Reset();
  305. UpdateShape();
  306. NotifyRigidBody();
  307. MarkNetworkUpdate();
  308. }
  309. void CollisionShape::SetSphere(float diameter, const Vector3& position, const Quaternion& rotation)
  310. {
  311. shapeType_ = SHAPE_SPHERE;
  312. size_ = Vector3(diameter, diameter, diameter);
  313. position_ = position;
  314. rotation_ = rotation;
  315. model_.Reset();
  316. UpdateShape();
  317. NotifyRigidBody();
  318. MarkNetworkUpdate();
  319. }
  320. void CollisionShape::SetCylinder(float diameter, float height, const Vector3& position, const Quaternion& rotation)
  321. {
  322. shapeType_ = SHAPE_CYLINDER;
  323. size_ = Vector3(diameter, height, diameter);
  324. position_ = position;
  325. rotation_ = rotation;
  326. model_.Reset();
  327. UpdateShape();
  328. NotifyRigidBody();
  329. MarkNetworkUpdate();
  330. }
  331. void CollisionShape::SetCapsule(float diameter, float height, const Vector3& position, const Quaternion& rotation)
  332. {
  333. shapeType_ = SHAPE_CAPSULE;
  334. size_ = Vector3(diameter, height, diameter);
  335. position_ = position;
  336. rotation_ = rotation;
  337. model_.Reset();
  338. UpdateShape();
  339. NotifyRigidBody();
  340. MarkNetworkUpdate();
  341. }
  342. void CollisionShape::SetCone(float diameter, float height, const Vector3& position, const Quaternion& rotation)
  343. {
  344. shapeType_ = SHAPE_CONE;
  345. size_ = Vector3(diameter, height, diameter);
  346. position_ = position;
  347. rotation_ = rotation;
  348. model_.Reset();
  349. UpdateShape();
  350. NotifyRigidBody();
  351. MarkNetworkUpdate();
  352. }
  353. void CollisionShape::SetTriangleMesh(Model* model, unsigned lodLevel, const Vector3& scale, const Vector3& position, const Quaternion& rotation)
  354. {
  355. if (!model)
  356. {
  357. LOGERROR("Null model, can not set triangle mesh");
  358. return;
  359. }
  360. shapeType_ = SHAPE_TRIANGLEMESH;
  361. model_ = model;
  362. lodLevel_ = lodLevel;
  363. size_ = scale;
  364. position_ = position;
  365. rotation_ = rotation;
  366. UpdateShape();
  367. NotifyRigidBody();
  368. MarkNetworkUpdate();
  369. }
  370. void CollisionShape::SetConvexHull(Model* model, unsigned lodLevel, const Vector3& scale, const Vector3& position, const Quaternion& rotation)
  371. {
  372. if (!model)
  373. {
  374. LOGERROR("Null model, can not set convex hull");
  375. return;
  376. }
  377. shapeType_ = SHAPE_CONVEXHULL;
  378. model_ = model;
  379. lodLevel_ = lodLevel;
  380. size_ = scale;
  381. position_ = position;
  382. rotation_ = rotation;
  383. UpdateShape();
  384. NotifyRigidBody();
  385. MarkNetworkUpdate();
  386. }
  387. void CollisionShape::SetTerrain()
  388. {
  389. Terrain* terrain = GetComponent<Terrain>();
  390. if (!terrain)
  391. {
  392. LOGERROR("No terrain component, can not set terrain shape");
  393. return;
  394. }
  395. shapeType_ = SHAPE_TERRAIN;
  396. UpdateShape();
  397. NotifyRigidBody();
  398. MarkNetworkUpdate();
  399. }
  400. void CollisionShape::SetShapeType(ShapeType type)
  401. {
  402. if (type != shapeType_)
  403. {
  404. shapeType_ = type;
  405. UpdateShape();
  406. NotifyRigidBody();
  407. MarkNetworkUpdate();
  408. }
  409. }
  410. void CollisionShape::SetSize(const Vector3& size)
  411. {
  412. if (size != size_)
  413. {
  414. size_ = size;
  415. UpdateShape();
  416. NotifyRigidBody();
  417. MarkNetworkUpdate();
  418. }
  419. }
  420. void CollisionShape::SetPosition(const Vector3& position)
  421. {
  422. if (position != position_)
  423. {
  424. position_ = position;
  425. NotifyRigidBody();
  426. MarkNetworkUpdate();
  427. }
  428. }
  429. void CollisionShape::SetRotation(const Quaternion& rotation)
  430. {
  431. if (rotation != rotation_)
  432. {
  433. rotation_ = rotation;
  434. NotifyRigidBody();
  435. MarkNetworkUpdate();
  436. }
  437. }
  438. void CollisionShape::SetTransform(const Vector3& position, const Quaternion& rotation)
  439. {
  440. if (position != position_ || rotation != rotation_)
  441. {
  442. position_ = position;
  443. rotation_ = rotation;
  444. NotifyRigidBody();
  445. MarkNetworkUpdate();
  446. }
  447. }
  448. void CollisionShape::SetMargin(float margin)
  449. {
  450. margin = Max(margin, 0.0f);
  451. if (margin != margin_)
  452. {
  453. if (shape_)
  454. shape_->setMargin(margin);
  455. margin_ = margin;
  456. MarkNetworkUpdate();
  457. }
  458. }
  459. void CollisionShape::SetModel(Model* model)
  460. {
  461. if (model != model_)
  462. {
  463. model_ = model;
  464. if (shapeType_ >= SHAPE_TRIANGLEMESH)
  465. {
  466. UpdateShape();
  467. NotifyRigidBody();
  468. }
  469. MarkNetworkUpdate();
  470. }
  471. }
  472. void CollisionShape::SetLodLevel(unsigned lodLevel)
  473. {
  474. if (lodLevel != lodLevel_)
  475. {
  476. lodLevel_ = lodLevel;
  477. if (shapeType_ >= SHAPE_TRIANGLEMESH)
  478. {
  479. UpdateShape();
  480. NotifyRigidBody();
  481. }
  482. MarkNetworkUpdate();
  483. }
  484. }
  485. void CollisionShape::NotifyRigidBody()
  486. {
  487. btCompoundShape* compound = GetParentCompoundShape();
  488. if (node_ && shape_ && compound)
  489. {
  490. // Remove the shape first to ensure it is not added twice
  491. compound->removeChildShape(shape_);
  492. if (IsEnabledEffective())
  493. {
  494. // Then add with updated offset
  495. Vector3 position = position_;
  496. // For terrains, undo the height centering performed automatically by Bullet
  497. if (shapeType_ == SHAPE_TERRAIN && geometry_)
  498. {
  499. HeightfieldData* heightfield = static_cast<HeightfieldData*>(geometry_.Get());
  500. position.y_ += (heightfield->minHeight_ + heightfield->maxHeight_) * 0.5f;
  501. }
  502. btTransform offset;
  503. offset.setOrigin(ToBtVector3(node_->GetWorldScale() * position));
  504. offset.setRotation(ToBtQuaternion(rotation_));
  505. compound->addChildShape(offset, shape_);
  506. }
  507. // Finally tell the rigid body to update its mass
  508. rigidBody_->UpdateMass();
  509. }
  510. }
  511. void CollisionShape::SetModelAttr(ResourceRef value)
  512. {
  513. ResourceCache* cache = GetSubsystem<ResourceCache>();
  514. model_ = cache->GetResource<Model>(value.id_);
  515. recreateShape_ = true;
  516. MarkNetworkUpdate();
  517. }
  518. ResourceRef CollisionShape::GetModelAttr() const
  519. {
  520. return GetResourceRef(model_, Model::GetTypeStatic());
  521. }
  522. void CollisionShape::ReleaseShape()
  523. {
  524. btCompoundShape* compound = GetParentCompoundShape();
  525. if (shape_ && compound)
  526. {
  527. compound->removeChildShape(shape_);
  528. rigidBody_->UpdateMass();
  529. }
  530. delete shape_;
  531. shape_ = 0;
  532. geometry_.Reset();
  533. if (physicsWorld_)
  534. physicsWorld_->CleanupGeometryCache();
  535. }
  536. void CollisionShape::OnNodeSet(Node* node)
  537. {
  538. if (node)
  539. {
  540. Scene* scene = GetScene();
  541. if (scene)
  542. {
  543. if (scene == node)
  544. LOGWARNING(GetTypeName() + " should not be created to the root scene node");
  545. physicsWorld_ = scene->GetComponent<PhysicsWorld>();
  546. if (physicsWorld_)
  547. physicsWorld_->AddCollisionShape(this);
  548. else
  549. LOGERROR("No physics world component in scene, can not create collision shape");
  550. }
  551. node->AddListener(this);
  552. cachedWorldScale_ = node->GetWorldScale();
  553. // Terrain collision shape depends on the terrain component's geometry updates. Subscribe to them
  554. SubscribeToEvent(node, E_TERRAINCREATED, HANDLER(CollisionShape, HandleTerrainCreated));
  555. }
  556. }
  557. void CollisionShape::OnMarkedDirty(Node* node)
  558. {
  559. Vector3 newWorldScale = node_->GetWorldScale();
  560. if (!newWorldScale.Equals(cachedWorldScale_) && shape_)
  561. {
  562. // Physics operations are not safe from worker threads
  563. Scene* scene = GetScene();
  564. if (scene && scene->IsThreadedUpdate())
  565. {
  566. scene->DelayedMarkedDirty(this);
  567. return;
  568. }
  569. switch (shapeType_)
  570. {
  571. case SHAPE_BOX:
  572. case SHAPE_SPHERE:
  573. case SHAPE_CYLINDER:
  574. case SHAPE_CAPSULE:
  575. case SHAPE_CONE:
  576. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  577. break;
  578. case SHAPE_TRIANGLEMESH:
  579. case SHAPE_CONVEXHULL:
  580. shape_->setLocalScaling(ToBtVector3(newWorldScale * size_));
  581. break;
  582. case SHAPE_TERRAIN:
  583. {
  584. HeightfieldData* heightfield = static_cast<HeightfieldData*>(geometry_.Get());
  585. shape_->setLocalScaling(ToBtVector3(Vector3(heightfield->spacing_.x_, 1.0f, heightfield->spacing_.z_) *
  586. newWorldScale * size_));
  587. }
  588. break;
  589. default:
  590. break;
  591. }
  592. NotifyRigidBody();
  593. cachedWorldScale_ = newWorldScale;
  594. }
  595. }
  596. btCompoundShape* CollisionShape::GetParentCompoundShape()
  597. {
  598. if (!rigidBody_)
  599. rigidBody_ = GetComponent<RigidBody>();
  600. return rigidBody_ ? rigidBody_->GetCompoundShape() : 0;
  601. }
  602. void CollisionShape::UpdateShape()
  603. {
  604. PROFILE(UpdateCollisionShape);
  605. ReleaseShape();
  606. if (!physicsWorld_)
  607. return;
  608. if (node_)
  609. {
  610. Vector3 newWorldScale = node_->GetWorldScale();
  611. switch (shapeType_)
  612. {
  613. case SHAPE_BOX:
  614. shape_ = new btBoxShape(ToBtVector3(size_ * 0.5f));
  615. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  616. break;
  617. case SHAPE_SPHERE:
  618. shape_ = new btSphereShape(size_.x_ * 0.5f);
  619. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  620. break;
  621. case SHAPE_STATICPLANE:
  622. shape_ = new btStaticPlaneShape(btVector3(0.0f, 1.0f, 0.0f), 0.0f);
  623. break;
  624. case SHAPE_CYLINDER:
  625. shape_ = new btCylinderShape(btVector3(size_.x_ * 0.5f, size_.y_ * 0.5f, size_.x_ * 0.5f));
  626. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  627. break;
  628. case SHAPE_CAPSULE:
  629. shape_ = new btCapsuleShape(size_.x_ * 0.5f, Max(size_.y_ - size_.x_, 0.0f));
  630. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  631. break;
  632. case SHAPE_CONE:
  633. shape_ = new btConeShape(size_.x_ * 0.5f, size_.y_);
  634. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  635. break;
  636. case SHAPE_TRIANGLEMESH:
  637. size_ = size_.Abs();
  638. if (model_)
  639. {
  640. // Check the geometry cache
  641. String id = "TriMesh_" + model_->GetName() + "_" + String(lodLevel_);
  642. HashMap<String, SharedPtr<CollisionGeometryData> >& cache = physicsWorld_->GetGeometryCache();
  643. HashMap<String, SharedPtr<CollisionGeometryData> >::Iterator j = cache.Find(id);
  644. if (j != cache.End())
  645. geometry_ = j->second_;
  646. else
  647. {
  648. geometry_ = new TriangleMeshData(model_, lodLevel_);
  649. cache[id] = geometry_;
  650. }
  651. TriangleMeshData* triMesh = static_cast<TriangleMeshData*>(geometry_.Get());
  652. shape_ = new btScaledBvhTriangleMeshShape(triMesh->shape_, ToBtVector3(newWorldScale * size_));
  653. }
  654. break;
  655. case SHAPE_CONVEXHULL:
  656. size_ = size_.Abs();
  657. if (model_)
  658. {
  659. // Check the geometry cache
  660. String id = "Convex_" + model_->GetName() + "_" + String(lodLevel_);
  661. HashMap<String, SharedPtr<CollisionGeometryData> >& cache = physicsWorld_->GetGeometryCache();
  662. HashMap<String, SharedPtr<CollisionGeometryData> >::Iterator j = cache.Find(id);
  663. if (j != cache.End())
  664. geometry_ = j->second_;
  665. else
  666. {
  667. geometry_ = new ConvexData(model_, lodLevel_);
  668. cache[id] = geometry_;
  669. }
  670. ConvexData* convex = static_cast<ConvexData*>(geometry_.Get());
  671. shape_ = new btConvexHullShape((btScalar*)convex->vertexData_.Get(), convex->vertexCount_, sizeof(Vector3));
  672. shape_->setLocalScaling(ToBtVector3(newWorldScale * size_));
  673. }
  674. break;
  675. case SHAPE_TERRAIN:
  676. size_ = size_.Abs();
  677. {
  678. Terrain* terrain = GetComponent<Terrain>();
  679. if (terrain && terrain->GetHeightData())
  680. {
  681. geometry_ = new HeightfieldData(terrain);
  682. HeightfieldData* heightfield = static_cast<HeightfieldData*>(geometry_.Get());
  683. shape_ = new btHeightfieldTerrainShape(heightfield->size_.x_, heightfield->size_.y_,
  684. heightfield->heightData_.Get(), 1.0f, heightfield->minHeight_, heightfield->maxHeight_, 1, PHY_FLOAT,
  685. false);
  686. shape_->setLocalScaling(ToBtVector3(Vector3(heightfield->spacing_.x_, 1.0f, heightfield->spacing_.z_) *
  687. newWorldScale * size_));
  688. }
  689. }
  690. break;
  691. default:
  692. break;
  693. }
  694. if (shape_)
  695. {
  696. shape_->setUserPointer(this);
  697. shape_->setMargin(margin_);
  698. }
  699. cachedWorldScale_ = newWorldScale;
  700. }
  701. if (physicsWorld_)
  702. physicsWorld_->CleanupGeometryCache();
  703. recreateShape_ = false;
  704. }
  705. void CollisionShape::HandleTerrainCreated(StringHash eventType, VariantMap& eventData)
  706. {
  707. if (shapeType_ == SHAPE_TERRAIN)
  708. {
  709. UpdateShape();
  710. NotifyRigidBody();
  711. }
  712. }
  713. }