CollisionShape.cpp 27 KB

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