CollisionShape.cpp 31 KB

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