CollisionShape.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  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 "VertexBuffer.h"
  39. #include <BulletCollision/CollisionDispatch/btInternalEdgeUtility.h>
  40. #include <BulletCollision/CollisionShapes/btBoxShape.h>
  41. #include <BulletCollision/CollisionShapes/btCapsuleShape.h>
  42. #include <BulletCollision/CollisionShapes/btCompoundShape.h>
  43. #include <BulletCollision/CollisionShapes/btConeShape.h>
  44. #include <BulletCollision/CollisionShapes/btConvexHullShape.h>
  45. #include <BulletCollision/CollisionShapes/btCylinderShape.h>
  46. #include <BulletCollision/CollisionShapes/btHeightfieldTerrainShape.h>
  47. #include <BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.h>
  48. #include <BulletCollision/CollisionShapes/btSphereShape.h>
  49. #include <BulletCollision/CollisionShapes/btTriangleIndexVertexArray.h>
  50. #include <BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h>
  51. #include <BulletCollision/CollisionShapes/btStaticPlaneShape.h>
  52. #include <hull.h>
  53. namespace Urho3D
  54. {
  55. static const float DEFAULT_COLLISION_MARGIN = 0.04f;
  56. static const btVector3 WHITE(1.0f, 1.0f, 1.0f);
  57. static const btVector3 GREEN(0.0f, 1.0f, 0.0f);
  58. static const char* typeNames[] =
  59. {
  60. "Box",
  61. "Sphere",
  62. "StaticPlane",
  63. "Cylinder",
  64. "Capsule",
  65. "Cone",
  66. "TriangleMesh",
  67. "ConvexHull",
  68. "Terrain",
  69. 0
  70. };
  71. extern const char* PHYSICS_CATEGORY;
  72. class TriangleMeshInterface : public btTriangleIndexVertexArray
  73. {
  74. public:
  75. TriangleMeshInterface(Model* model, unsigned lodLevel) : btTriangleIndexVertexArray()
  76. {
  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. // Keep a shared pointer to the referred geometry
  98. /// \todo Model live reload is not handled properly, but at least we will not crash due to holding a pointer
  99. /// to the original geometry
  100. geometries_.Push(SharedPtr<Geometry>(geometry));
  101. unsigned indexStart = geometry->GetIndexStart();
  102. unsigned indexCount = geometry->GetIndexCount();
  103. btIndexedMesh meshIndex;
  104. meshIndex.m_numTriangles = indexCount / 3;
  105. meshIndex.m_triangleIndexBase = &indexData[indexStart * indexSize];
  106. meshIndex.m_triangleIndexStride = 3 * indexSize;
  107. meshIndex.m_numVertices = 0;
  108. meshIndex.m_vertexBase = vertexData;
  109. meshIndex.m_vertexStride = vertexSize;
  110. meshIndex.m_indexType = (indexSize == sizeof(unsigned short)) ? PHY_SHORT : PHY_INTEGER;
  111. meshIndex.m_vertexType = PHY_FLOAT;
  112. m_indexedMeshes.push_back(meshIndex);
  113. }
  114. }
  115. private:
  116. /// Geometries used in the collision
  117. Vector<SharedPtr<Geometry> > geometries_;
  118. };
  119. TriangleMeshData::TriangleMeshData(Model* model, unsigned lodLevel) :
  120. meshInterface_(0),
  121. shape_(0),
  122. infoMap_(0)
  123. {
  124. modelName_ = model->GetName();
  125. meshInterface_ = new TriangleMeshInterface(model, lodLevel);
  126. shape_ = new btBvhTriangleMeshShape(meshInterface_, true, true);
  127. infoMap_ = new btTriangleInfoMap();
  128. btGenerateInternalEdgeInfo(shape_, infoMap_);
  129. }
  130. TriangleMeshData::~TriangleMeshData()
  131. {
  132. delete shape_;
  133. shape_ = 0;
  134. delete meshInterface_;
  135. meshInterface_ = 0;
  136. delete infoMap_;
  137. infoMap_ = 0;
  138. }
  139. ConvexData::ConvexData(Model* model, unsigned lodLevel)
  140. {
  141. modelName_ = model->GetName();
  142. PODVector<Vector3> vertices;
  143. unsigned numGeometries = model->GetNumGeometries();
  144. for (unsigned i = 0; i < numGeometries; ++i)
  145. {
  146. Geometry* geom = model->GetGeometry(i, lodLevel);
  147. if (!geom)
  148. {
  149. LOGWARNING("Skipping null geometry for convex hull collision");
  150. continue;
  151. };
  152. const unsigned char* vertexData;
  153. const unsigned char* indexData;
  154. unsigned vertexSize;
  155. unsigned indexSize;
  156. unsigned elementMask;
  157. geom->GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask);
  158. if (!vertexData || !indexData)
  159. {
  160. LOGWARNING("Skipping geometry with no CPU-side geometry data for convex hull collision");
  161. continue;
  162. }
  163. unsigned vertexStart = geom->GetVertexStart();
  164. unsigned vertexCount = geom->GetVertexCount();
  165. // Copy vertex data
  166. for (unsigned j = 0; j < vertexCount; ++j)
  167. {
  168. const Vector3& v = *((const Vector3*)(&vertexData[(vertexStart + j) * vertexSize]));
  169. vertices.Push(v);
  170. }
  171. }
  172. BuildHull(vertices);
  173. }
  174. ConvexData::ConvexData(CustomGeometry* custom)
  175. {
  176. PODVector<Vector3> vertices;
  177. unsigned numGeometries = custom->GetNumGeometries();
  178. for (unsigned i = 0; i < numGeometries; ++i)
  179. {
  180. Geometry* geom = custom->GetLodGeometry(i, 0);
  181. if (!geom)
  182. {
  183. LOGWARNING("Skipping null geometry for convex hull collision");
  184. continue;
  185. }
  186. const unsigned char* vertexData;
  187. const unsigned char* indexData;
  188. unsigned vertexSize;
  189. unsigned indexSize;
  190. unsigned elementMask;
  191. geom->GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask);
  192. if (!vertexData)
  193. {
  194. LOGWARNING("Skipping geometry with no CPU-side geometry data for convex hull collision - no vertex data");
  195. continue;
  196. }
  197. unsigned vertexStart = geom->GetVertexStart();
  198. unsigned vertexCount = geom->GetVertexCount();
  199. // Copy vertex data
  200. for (unsigned j = 0; j < vertexCount; ++j)
  201. {
  202. const Vector3& v = *((const Vector3*)(&vertexData[(vertexStart + j) * vertexSize]));
  203. vertices.Push(v);
  204. }
  205. }
  206. BuildHull(vertices);
  207. }
  208. void ConvexData::BuildHull(const PODVector<Vector3>& vertices)
  209. {
  210. if (vertices.Size())
  211. {
  212. // Build the convex hull from the raw geometry
  213. StanHull::HullDesc desc;
  214. desc.SetHullFlag(StanHull::QF_TRIANGLES);
  215. desc.mVcount = vertices.Size();
  216. desc.mVertices = vertices[0].Data();
  217. desc.mVertexStride = 3 * sizeof(float);
  218. desc.mSkinWidth = 0.0f;
  219. StanHull::HullLibrary lib;
  220. StanHull::HullResult result;
  221. lib.CreateConvexHull(desc, result);
  222. vertexCount_ = result.mNumOutputVertices;
  223. vertexData_ = new Vector3[vertexCount_];
  224. indexCount_ = result.mNumIndices;
  225. indexData_ = new unsigned[indexCount_];
  226. // Copy vertex data & index data
  227. memcpy(vertexData_.Get(), result.mOutputVertices, vertexCount_ * sizeof(Vector3));
  228. memcpy(indexData_.Get(), result.mIndices, indexCount_ * sizeof(unsigned));
  229. lib.ReleaseResult(result);
  230. }
  231. else
  232. {
  233. vertexCount_ = 0;
  234. indexCount_ = 0;
  235. }
  236. }
  237. ConvexData::~ConvexData()
  238. {
  239. }
  240. HeightfieldData::HeightfieldData(Terrain* terrain) :
  241. heightData_(terrain->GetHeightData()),
  242. spacing_(terrain->GetSpacing()),
  243. size_(terrain->GetNumVertices()),
  244. minHeight_(0.0f),
  245. maxHeight_(0.0f)
  246. {
  247. if (heightData_)
  248. {
  249. unsigned points = size_.x_ * size_.y_;
  250. float* data = heightData_.Get();
  251. minHeight_ = maxHeight_ = data[0];
  252. for (unsigned i = 1; i < points; ++i)
  253. {
  254. minHeight_ = Min(minHeight_, data[i]);
  255. maxHeight_ = Max(maxHeight_, data[i]);
  256. }
  257. }
  258. }
  259. HeightfieldData::~HeightfieldData()
  260. {
  261. }
  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.name_);
  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. // Check if any geometry has a dynamic vertex buffer
  760. bool dynamic = false;
  761. unsigned numGeometries = model_->GetNumGeometries();
  762. for (unsigned i = 0; i < numGeometries; ++i)
  763. {
  764. Geometry* geometry = model_->GetGeometry(i, lodLevel_);
  765. if (!geometry)
  766. continue;
  767. unsigned numVertexBuffers = geometry->GetNumVertexBuffers();
  768. for(unsigned j = 0; j < numVertexBuffers; ++j)
  769. {
  770. VertexBuffer* buffer = geometry->GetVertexBuffer(j);
  771. if(!buffer)
  772. continue;
  773. if(buffer->IsDynamic())
  774. dynamic = true;
  775. }
  776. }
  777. // Don't cache geometry with dynamic vertex buffers
  778. if(!dynamic)
  779. {
  780. cache[id] = geometry_;
  781. }
  782. }
  783. TriangleMeshData* triMesh = static_cast<TriangleMeshData*>(geometry_.Get());
  784. shape_ = new btScaledBvhTriangleMeshShape(triMesh->shape_, ToBtVector3(newWorldScale * size_));
  785. }
  786. break;
  787. case SHAPE_CONVEXHULL:
  788. size_ = size_.Abs();
  789. if (customGeometryID_ && GetScene())
  790. {
  791. Node* node = GetScene()->GetNode(customGeometryID_);
  792. CustomGeometry* custom = node ? node->GetComponent<CustomGeometry>() : 0;
  793. if (custom)
  794. {
  795. geometry_ = new ConvexData(custom);
  796. ConvexData* convex = static_cast<ConvexData*>(geometry_.Get());
  797. shape_ = new btConvexHullShape((btScalar*)convex->vertexData_.Get(), convex->vertexCount_, sizeof(Vector3));
  798. shape_->setLocalScaling(ToBtVector3(newWorldScale * size_));
  799. LOGINFO("Set convexhull from customgeometry");
  800. }
  801. else
  802. LOGWARNING("Could not find custom geometry component from node ID " + String(customGeometryID_) + " for convex shape creation");
  803. }
  804. else if (model_)
  805. {
  806. // Check the geometry cache
  807. String id = "Convex_" + model_->GetName() + "_" + String(lodLevel_);
  808. HashMap<String, SharedPtr<CollisionGeometryData> >& cache = physicsWorld_->GetGeometryCache();
  809. HashMap<String, SharedPtr<CollisionGeometryData> >::Iterator j = cache.Find(id);
  810. if (j != cache.End())
  811. geometry_ = j->second_;
  812. else
  813. {
  814. geometry_ = new ConvexData(model_, lodLevel_);
  815. // Check if any geometry has a dynamic vertex buffer
  816. bool dynamic = false;
  817. unsigned numGeometries = model_->GetNumGeometries();
  818. for (unsigned i = 0; i < numGeometries; ++i)
  819. {
  820. Geometry* geometry = model_->GetGeometry(i, lodLevel_);
  821. if (!geometry)
  822. continue;
  823. unsigned numVertexBuffers = geometry->GetNumVertexBuffers();
  824. for(unsigned j = 0; j < numVertexBuffers; ++j)
  825. {
  826. VertexBuffer* buffer = geometry->GetVertexBuffer(j);
  827. if(!buffer)
  828. continue;
  829. if(buffer->IsDynamic())
  830. dynamic = true;
  831. }
  832. }
  833. // Don't cache geometry with dynamic vertex buffers
  834. if(!dynamic)
  835. {
  836. cache[id] = geometry_;
  837. }
  838. }
  839. ConvexData* convex = static_cast<ConvexData*>(geometry_.Get());
  840. shape_ = new btConvexHullShape((btScalar*)convex->vertexData_.Get(), convex->vertexCount_, sizeof(Vector3));
  841. shape_->setLocalScaling(ToBtVector3(newWorldScale * size_));
  842. }
  843. break;
  844. case SHAPE_TERRAIN:
  845. size_ = size_.Abs();
  846. {
  847. Terrain* terrain = GetComponent<Terrain>();
  848. if (terrain && terrain->GetHeightData())
  849. {
  850. geometry_ = new HeightfieldData(terrain);
  851. HeightfieldData* heightfield = static_cast<HeightfieldData*>(geometry_.Get());
  852. shape_ = new btHeightfieldTerrainShape(heightfield->size_.x_, heightfield->size_.y_,
  853. heightfield->heightData_.Get(), 1.0f, heightfield->minHeight_, heightfield->maxHeight_, 1, PHY_FLOAT,
  854. false);
  855. shape_->setLocalScaling(ToBtVector3(Vector3(heightfield->spacing_.x_, 1.0f, heightfield->spacing_.z_) *
  856. newWorldScale * size_));
  857. }
  858. }
  859. break;
  860. default:
  861. break;
  862. }
  863. if (shape_)
  864. {
  865. shape_->setUserPointer(this);
  866. shape_->setMargin(margin_);
  867. }
  868. cachedWorldScale_ = newWorldScale;
  869. }
  870. if (physicsWorld_)
  871. physicsWorld_->CleanupGeometryCache();
  872. recreateShape_ = false;
  873. }
  874. void CollisionShape::HandleTerrainCreated(StringHash eventType, VariantMap& eventData)
  875. {
  876. if (shapeType_ == SHAPE_TERRAIN)
  877. {
  878. UpdateShape();
  879. NotifyRigidBody();
  880. }
  881. }
  882. }