CollisionShape.cpp 30 KB

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