CollisionShape.cpp 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154
  1. //
  2. // Copyright (c) 2008-2015 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 "../Physics/CollisionShape.h"
  24. #include "../Core/Context.h"
  25. #include "../Atomic3D/CustomGeometry.h"
  26. #include "../Graphics/DebugRenderer.h"
  27. #include "../Graphics/DrawableEvents.h"
  28. #include "../Graphics/Geometry.h"
  29. #include "../Graphics/IndexBuffer.h"
  30. #include "../IO/Log.h"
  31. #include "../Atomic3D/Model.h"
  32. #include "../Physics/PhysicsUtils.h"
  33. #include "../Physics/PhysicsWorld.h"
  34. #include "../Core/Profiler.h"
  35. #include "../Resource/ResourceCache.h"
  36. #include "../Resource/ResourceEvents.h"
  37. #include "../Physics/RigidBody.h"
  38. #include "../Scene/Scene.h"
  39. #include "../Atomic3D/Terrain.h"
  40. #include "../Graphics/VertexBuffer.h"
  41. #include <Bullet/src/BulletCollision/CollisionDispatch/btInternalEdgeUtility.h>
  42. #include <Bullet/src/BulletCollision/CollisionShapes/btBoxShape.h>
  43. #include <Bullet/src/BulletCollision/CollisionShapes/btCapsuleShape.h>
  44. #include <Bullet/src/BulletCollision/CollisionShapes/btCompoundShape.h>
  45. #include <Bullet/src/BulletCollision/CollisionShapes/btConeShape.h>
  46. #include <Bullet/src/BulletCollision/CollisionShapes/btConvexHullShape.h>
  47. #include <Bullet/src/BulletCollision/CollisionShapes/btCylinderShape.h>
  48. #include <Bullet/src/BulletCollision/CollisionShapes/btHeightfieldTerrainShape.h>
  49. #include <Bullet/src/BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.h>
  50. #include <Bullet/src/BulletCollision/CollisionShapes/btSphereShape.h>
  51. #include <Bullet/src/BulletCollision/CollisionShapes/btTriangleIndexVertexArray.h>
  52. #include <Bullet/src/BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h>
  53. #include <Bullet/src/BulletCollision/CollisionShapes/btStaticPlaneShape.h>
  54. #include <StanHull/hull.h>
  55. namespace Atomic
  56. {
  57. static const float DEFAULT_COLLISION_MARGIN = 0.04f;
  58. static const btVector3 WHITE(1.0f, 1.0f, 1.0f);
  59. static const btVector3 GREEN(0.0f, 1.0f, 0.0f);
  60. static const char* typeNames[] =
  61. {
  62. "Box",
  63. "Sphere",
  64. "StaticPlane",
  65. "Cylinder",
  66. "Capsule",
  67. "Cone",
  68. "TriangleMesh",
  69. "ConvexHull",
  70. "Terrain",
  71. 0
  72. };
  73. extern const char* PHYSICS_CATEGORY;
  74. class TriangleMeshInterface : public btTriangleIndexVertexArray
  75. {
  76. public:
  77. TriangleMeshInterface(Model* model, unsigned lodLevel) : btTriangleIndexVertexArray()
  78. {
  79. unsigned numGeometries = model->GetNumGeometries();
  80. for (unsigned i = 0; i < numGeometries; ++i)
  81. {
  82. Geometry* geometry = model->GetGeometry(i, lodLevel);
  83. if (!geometry)
  84. {
  85. LOGWARNING("Skipping null geometry for triangle mesh collision");
  86. continue;
  87. }
  88. SharedArrayPtr<unsigned char> vertexData;
  89. SharedArrayPtr<unsigned char> indexData;
  90. unsigned vertexSize;
  91. unsigned indexSize;
  92. unsigned elementMask;
  93. geometry->GetRawDataShared(vertexData, vertexSize, indexData, indexSize, elementMask);
  94. if (!vertexData || !indexData)
  95. {
  96. LOGWARNING("Skipping geometry with no CPU-side geometry data for triangle mesh collision");
  97. continue;
  98. }
  99. // Keep shared pointers to the vertex/index data so that if it's unloaded or changes size, we don't crash
  100. dataArrays_.Push(vertexData);
  101. dataArrays_.Push(indexData);
  102. unsigned indexStart = geometry->GetIndexStart();
  103. unsigned indexCount = geometry->GetIndexCount();
  104. btIndexedMesh meshIndex;
  105. meshIndex.m_numTriangles = indexCount / 3;
  106. meshIndex.m_triangleIndexBase = &indexData[indexStart * indexSize];
  107. meshIndex.m_triangleIndexStride = 3 * indexSize;
  108. meshIndex.m_numVertices = 0;
  109. meshIndex.m_vertexBase = vertexData;
  110. meshIndex.m_vertexStride = vertexSize;
  111. meshIndex.m_indexType = (indexSize == sizeof(unsigned short)) ? PHY_SHORT : PHY_INTEGER;
  112. meshIndex.m_vertexType = PHY_FLOAT;
  113. m_indexedMeshes.push_back(meshIndex);
  114. }
  115. }
  116. TriangleMeshInterface(CustomGeometry* custom) : btTriangleIndexVertexArray()
  117. {
  118. const Vector<PODVector<CustomGeometryVertex> >& srcVertices = custom->GetVertices();
  119. unsigned totalVertexCount = 0;
  120. for (unsigned i = 0; i < srcVertices.Size(); ++i)
  121. totalVertexCount += srcVertices[i].Size();
  122. if (totalVertexCount)
  123. {
  124. // CustomGeometry vertex data is unindexed, so build index data here
  125. SharedArrayPtr<unsigned char> vertexData(new unsigned char[totalVertexCount * sizeof(Vector3)]);
  126. SharedArrayPtr<unsigned char> indexData(new unsigned char[totalVertexCount * sizeof(unsigned)]);
  127. dataArrays_.Push(vertexData);
  128. dataArrays_.Push(indexData);
  129. Vector3* destVertex = reinterpret_cast<Vector3*>(&vertexData[0]);
  130. unsigned* destIndex = reinterpret_cast<unsigned*>(&indexData[0]);
  131. unsigned k = 0;
  132. for (unsigned i = 0; i < srcVertices.Size(); ++i)
  133. {
  134. for (unsigned j = 0; j < srcVertices[i].Size(); ++j)
  135. {
  136. *destVertex++ = srcVertices[i][j].position_;
  137. *destIndex++ = k++;
  138. }
  139. }
  140. btIndexedMesh meshIndex;
  141. meshIndex.m_numTriangles = totalVertexCount / 3;
  142. meshIndex.m_triangleIndexBase = indexData;
  143. meshIndex.m_triangleIndexStride = 3 * sizeof(unsigned);
  144. meshIndex.m_numVertices = totalVertexCount;
  145. meshIndex.m_vertexBase = vertexData;
  146. meshIndex.m_vertexStride = sizeof(Vector3);
  147. meshIndex.m_indexType = PHY_INTEGER;
  148. meshIndex.m_vertexType = PHY_FLOAT;
  149. m_indexedMeshes.push_back(meshIndex);
  150. }
  151. }
  152. private:
  153. /// Shared vertex/index data used in the collision
  154. Vector<SharedArrayPtr<unsigned char> > dataArrays_;
  155. };
  156. TriangleMeshData::TriangleMeshData(Model* model, unsigned lodLevel) :
  157. meshInterface_(0),
  158. shape_(0),
  159. infoMap_(0)
  160. {
  161. meshInterface_ = new TriangleMeshInterface(model, lodLevel);
  162. shape_ = new btBvhTriangleMeshShape(meshInterface_, true, true);
  163. infoMap_ = new btTriangleInfoMap();
  164. btGenerateInternalEdgeInfo(shape_, infoMap_);
  165. }
  166. TriangleMeshData::TriangleMeshData(CustomGeometry* custom) :
  167. meshInterface_(0),
  168. shape_(0),
  169. infoMap_(0)
  170. {
  171. meshInterface_ = new TriangleMeshInterface(custom);
  172. shape_ = new btBvhTriangleMeshShape(meshInterface_, true, true);
  173. infoMap_ = new btTriangleInfoMap();
  174. btGenerateInternalEdgeInfo(shape_, infoMap_);
  175. }
  176. TriangleMeshData::~TriangleMeshData()
  177. {
  178. delete shape_;
  179. shape_ = 0;
  180. delete meshInterface_;
  181. meshInterface_ = 0;
  182. delete infoMap_;
  183. infoMap_ = 0;
  184. }
  185. ConvexData::ConvexData(Model* model, unsigned lodLevel)
  186. {
  187. PODVector<Vector3> vertices;
  188. unsigned numGeometries = model->GetNumGeometries();
  189. for (unsigned i = 0; i < numGeometries; ++i)
  190. {
  191. Geometry* geom = model->GetGeometry(i, lodLevel);
  192. if (!geom)
  193. {
  194. LOGWARNING("Skipping null geometry for convex hull collision");
  195. continue;
  196. };
  197. const unsigned char* vertexData;
  198. const unsigned char* indexData;
  199. unsigned vertexSize;
  200. unsigned indexSize;
  201. unsigned elementMask;
  202. geom->GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask);
  203. if (!vertexData || !indexData)
  204. {
  205. LOGWARNING("Skipping geometry with no CPU-side geometry data for convex hull collision");
  206. continue;
  207. }
  208. unsigned vertexStart = geom->GetVertexStart();
  209. unsigned vertexCount = geom->GetVertexCount();
  210. // Copy vertex data
  211. for (unsigned j = 0; j < vertexCount; ++j)
  212. {
  213. const Vector3& v = *((const Vector3*)(&vertexData[(vertexStart + j) * vertexSize]));
  214. vertices.Push(v);
  215. }
  216. }
  217. BuildHull(vertices);
  218. }
  219. ConvexData::ConvexData(CustomGeometry* custom)
  220. {
  221. const Vector<PODVector<CustomGeometryVertex> >& srcVertices = custom->GetVertices();
  222. PODVector<Vector3> vertices;
  223. for (unsigned i = 0; i < srcVertices.Size(); ++i)
  224. {
  225. for (unsigned j = 0; j < srcVertices[i].Size(); ++j)
  226. vertices.Push(srcVertices[i][j].position_);
  227. }
  228. BuildHull(vertices);
  229. }
  230. void ConvexData::BuildHull(const PODVector<Vector3>& vertices)
  231. {
  232. if (vertices.Size())
  233. {
  234. // Build the convex hull from the raw geometry
  235. StanHull::HullDesc desc;
  236. desc.SetHullFlag(StanHull::QF_TRIANGLES);
  237. desc.mVcount = vertices.Size();
  238. desc.mVertices = vertices[0].Data();
  239. desc.mVertexStride = 3 * sizeof(float);
  240. desc.mSkinWidth = 0.0f;
  241. StanHull::HullLibrary lib;
  242. StanHull::HullResult result;
  243. lib.CreateConvexHull(desc, result);
  244. vertexCount_ = result.mNumOutputVertices;
  245. vertexData_ = new Vector3[vertexCount_];
  246. indexCount_ = result.mNumIndices;
  247. indexData_ = new unsigned[indexCount_];
  248. // Copy vertex data & index data
  249. memcpy(vertexData_.Get(), result.mOutputVertices, vertexCount_ * sizeof(Vector3));
  250. memcpy(indexData_.Get(), result.mIndices, indexCount_ * sizeof(unsigned));
  251. lib.ReleaseResult(result);
  252. }
  253. else
  254. {
  255. vertexCount_ = 0;
  256. indexCount_ = 0;
  257. }
  258. }
  259. ConvexData::~ConvexData()
  260. {
  261. }
  262. HeightfieldData::HeightfieldData(Terrain* terrain, unsigned lodLevel) :
  263. heightData_(terrain->GetHeightData()),
  264. spacing_(terrain->GetSpacing()),
  265. size_(terrain->GetNumVertices()),
  266. minHeight_(0.0f),
  267. maxHeight_(0.0f)
  268. {
  269. if (heightData_)
  270. {
  271. if (lodLevel > 0)
  272. {
  273. IntVector2 lodSize = size_;
  274. Vector3 lodSpacing = spacing_;
  275. unsigned skip = 1;
  276. for (unsigned i = 0; i < lodLevel; ++i)
  277. {
  278. skip *= 2;
  279. lodSpacing.x_ *= 2.0f;
  280. lodSpacing.z_ *= 2.0f;
  281. int rX = lodSize.x_ & 1;
  282. int rY = lodSize.y_ & 1;
  283. lodSize.x_ >>= 1;
  284. lodSize.y_ >>= 1;
  285. lodSize.x_ += rX;
  286. lodSize.y_ += rY;
  287. if (lodSize.x_ <= 2 || lodSize.y_ <= 2)
  288. break;
  289. }
  290. SharedArrayPtr<float> lodHeightData(new float[lodSize.x_ * lodSize.y_]);
  291. for (int y = 0, dY = 0; y < size_.y_ && dY < lodSize.y_; y += skip, ++dY)
  292. {
  293. for (int x = 0, dX = 0; x < size_.x_ && dX < lodSize.x_; x += skip, ++dX)
  294. lodHeightData[dY * lodSize.x_ + dX] = heightData_[y * size_.x_ + x];
  295. }
  296. size_ = lodSize;
  297. spacing_ = lodSpacing;
  298. heightData_ = lodHeightData;
  299. }
  300. unsigned points = size_.x_ * size_.y_;
  301. float* data = heightData_.Get();
  302. minHeight_ = maxHeight_ = data[0];
  303. for (unsigned i = 1; i < points; ++i)
  304. {
  305. minHeight_ = Min(minHeight_, data[i]);
  306. maxHeight_ = Max(maxHeight_, data[i]);
  307. }
  308. }
  309. }
  310. HeightfieldData::~HeightfieldData()
  311. {
  312. }
  313. bool HasDynamicBuffers(Model* model, unsigned lodLevel)
  314. {
  315. unsigned numGeometries = model->GetNumGeometries();
  316. for (unsigned i = 0; i < numGeometries; ++i)
  317. {
  318. Geometry* geometry = model->GetGeometry(i, lodLevel);
  319. if (!geometry)
  320. continue;
  321. unsigned numVertexBuffers = geometry->GetNumVertexBuffers();
  322. for (unsigned j = 0; j < numVertexBuffers; ++j)
  323. {
  324. VertexBuffer* buffer = geometry->GetVertexBuffer(j);
  325. if (!buffer)
  326. continue;
  327. if (buffer->IsDynamic())
  328. return true;
  329. }
  330. IndexBuffer* buffer = geometry->GetIndexBuffer();
  331. if (buffer && buffer->IsDynamic())
  332. return true;
  333. }
  334. return false;
  335. }
  336. CollisionShape::CollisionShape(Context* context) :
  337. Component(context),
  338. shape_(0),
  339. shapeType_(SHAPE_BOX),
  340. position_(Vector3::ZERO),
  341. rotation_(Quaternion::IDENTITY),
  342. size_(Vector3::ONE),
  343. cachedWorldScale_(Vector3::ONE),
  344. lodLevel_(0),
  345. customGeometryID_(0),
  346. margin_(DEFAULT_COLLISION_MARGIN),
  347. recreateShape_(true)
  348. {
  349. }
  350. CollisionShape::~CollisionShape()
  351. {
  352. ReleaseShape();
  353. if (physicsWorld_)
  354. physicsWorld_->RemoveCollisionShape(this);
  355. }
  356. void CollisionShape::RegisterObject(Context* context)
  357. {
  358. context->RegisterFactory<CollisionShape>(PHYSICS_CATEGORY);
  359. ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  360. ENUM_ATTRIBUTE("Shape Type", shapeType_, typeNames, SHAPE_BOX, AM_DEFAULT);
  361. ATTRIBUTE("Size", Vector3, size_, Vector3::ONE, AM_DEFAULT);
  362. ACCESSOR_ATTRIBUTE("Offset Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_DEFAULT);
  363. ACCESSOR_ATTRIBUTE("Offset Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_DEFAULT);
  364. MIXED_ACCESSOR_ATTRIBUTE("Model", GetModelAttr, SetModelAttr, ResourceRef, ResourceRef(Model::GetTypeStatic()), AM_DEFAULT);
  365. ATTRIBUTE("LOD Level", int, lodLevel_, 0, AM_DEFAULT);
  366. ATTRIBUTE("Collision Margin", float, margin_, DEFAULT_COLLISION_MARGIN, AM_DEFAULT);
  367. ATTRIBUTE("CustomGeometry NodeID", int, customGeometryID_, 0, AM_DEFAULT | AM_NODEID);
  368. }
  369. void CollisionShape::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  370. {
  371. Serializable::OnSetAttribute(attr, src);
  372. // Change of any non-accessor attribute requires recreation of the collision shape
  373. if (!attr.accessor_)
  374. recreateShape_ = true;
  375. }
  376. void CollisionShape::ApplyAttributes()
  377. {
  378. if (recreateShape_)
  379. {
  380. UpdateShape();
  381. NotifyRigidBody();
  382. }
  383. }
  384. void CollisionShape::OnSetEnabled()
  385. {
  386. NotifyRigidBody();
  387. }
  388. void CollisionShape::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  389. {
  390. if (debug && physicsWorld_ && shape_ && node_ && IsEnabledEffective())
  391. {
  392. physicsWorld_->SetDebugRenderer(debug);
  393. physicsWorld_->SetDebugDepthTest(depthTest);
  394. // Use the rigid body's world transform if possible, as it may be different from the rendering transform
  395. Matrix3x4 worldTransform;
  396. RigidBody* body = GetComponent<RigidBody>();
  397. bool bodyActive = false;
  398. if (body)
  399. {
  400. worldTransform = Matrix3x4(body->GetPosition(), body->GetRotation(), node_->GetWorldScale());
  401. bodyActive = body->IsActive();
  402. }
  403. else
  404. worldTransform = node_->GetWorldTransform();
  405. Vector3 position = position_;
  406. // For terrains, undo the height centering performed automatically by Bullet
  407. if (shapeType_ == SHAPE_TERRAIN && geometry_)
  408. {
  409. HeightfieldData* heightfield = static_cast<HeightfieldData*>(geometry_.Get());
  410. position.y_ += (heightfield->minHeight_ + heightfield->maxHeight_) * 0.5f;
  411. }
  412. Vector3 worldPosition(worldTransform * position);
  413. Quaternion worldRotation(worldTransform.Rotation() * rotation_);
  414. btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
  415. world->debugDrawObject(btTransform(ToBtQuaternion(worldRotation), ToBtVector3(worldPosition)), shape_, bodyActive ?
  416. WHITE : GREEN);
  417. physicsWorld_->SetDebugRenderer(0);
  418. }
  419. }
  420. void CollisionShape::SetBox(const Vector3& size, const Vector3& position, const Quaternion& rotation)
  421. {
  422. if (model_)
  423. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  424. shapeType_ = SHAPE_BOX;
  425. size_ = size;
  426. position_ = position;
  427. rotation_ = rotation;
  428. model_.Reset();
  429. customGeometryID_ = 0;
  430. UpdateShape();
  431. NotifyRigidBody();
  432. MarkNetworkUpdate();
  433. }
  434. void CollisionShape::SetSphere(float diameter, const Vector3& position, const Quaternion& rotation)
  435. {
  436. if (model_)
  437. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  438. shapeType_ = SHAPE_SPHERE;
  439. size_ = Vector3(diameter, diameter, diameter);
  440. position_ = position;
  441. rotation_ = rotation;
  442. model_.Reset();
  443. customGeometryID_ = 0;
  444. UpdateShape();
  445. NotifyRigidBody();
  446. MarkNetworkUpdate();
  447. }
  448. void CollisionShape::SetStaticPlane(const Vector3& position, const Quaternion& rotation)
  449. {
  450. if (model_)
  451. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  452. shapeType_ = SHAPE_STATICPLANE;
  453. position_ = position;
  454. rotation_ = rotation;
  455. model_.Reset();
  456. customGeometryID_ = 0;
  457. UpdateShape();
  458. NotifyRigidBody();
  459. MarkNetworkUpdate();
  460. }
  461. void CollisionShape::SetCylinder(float diameter, float height, const Vector3& position, const Quaternion& rotation)
  462. {
  463. if (model_)
  464. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  465. shapeType_ = SHAPE_CYLINDER;
  466. size_ = Vector3(diameter, height, diameter);
  467. position_ = position;
  468. rotation_ = rotation;
  469. model_.Reset();
  470. customGeometryID_ = 0;
  471. UpdateShape();
  472. NotifyRigidBody();
  473. MarkNetworkUpdate();
  474. }
  475. void CollisionShape::SetCapsule(float diameter, float height, const Vector3& position, const Quaternion& rotation)
  476. {
  477. if (model_)
  478. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  479. shapeType_ = SHAPE_CAPSULE;
  480. size_ = Vector3(diameter, height, diameter);
  481. position_ = position;
  482. rotation_ = rotation;
  483. model_.Reset();
  484. customGeometryID_ = 0;
  485. UpdateShape();
  486. NotifyRigidBody();
  487. MarkNetworkUpdate();
  488. }
  489. void CollisionShape::SetCone(float diameter, float height, const Vector3& position, const Quaternion& rotation)
  490. {
  491. if (model_)
  492. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  493. shapeType_ = SHAPE_CONE;
  494. size_ = Vector3(diameter, height, diameter);
  495. position_ = position;
  496. rotation_ = rotation;
  497. model_.Reset();
  498. customGeometryID_ = 0;
  499. UpdateShape();
  500. NotifyRigidBody();
  501. MarkNetworkUpdate();
  502. }
  503. void CollisionShape::SetTriangleMesh(Model* model, unsigned lodLevel, const Vector3& scale, const Vector3& position, const Quaternion& rotation)
  504. {
  505. if (!model)
  506. {
  507. LOGERROR("Null model, can not set triangle mesh");
  508. return;
  509. }
  510. if (model_)
  511. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  512. shapeType_ = SHAPE_TRIANGLEMESH;
  513. model_ = model;
  514. lodLevel_ = lodLevel;
  515. size_ = scale;
  516. position_ = position;
  517. rotation_ = rotation;
  518. customGeometryID_ = 0;
  519. UpdateShape();
  520. NotifyRigidBody();
  521. MarkNetworkUpdate();
  522. }
  523. void CollisionShape::SetCustomTriangleMesh(CustomGeometry* custom, const Vector3& scale, const Vector3& position, const Quaternion& rotation)
  524. {
  525. if (!custom)
  526. {
  527. LOGERROR("Null custom geometry, can not set triangle mesh");
  528. return;
  529. }
  530. if (!custom->GetNode())
  531. {
  532. LOGERROR("Custom geometry has null scene node, can not set triangle mesh");
  533. return;
  534. }
  535. if (model_)
  536. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  537. shapeType_ = SHAPE_TRIANGLEMESH;
  538. model_.Reset();
  539. lodLevel_ = 0;
  540. size_ = scale;
  541. position_ = position;
  542. rotation_ = rotation;
  543. customGeometryID_ = custom->GetNode()->GetID();
  544. UpdateShape();
  545. NotifyRigidBody();
  546. MarkNetworkUpdate();
  547. }
  548. void CollisionShape::SetConvexHull(Model* model, unsigned lodLevel, const Vector3& scale, const Vector3& position, const Quaternion& rotation)
  549. {
  550. if (!model)
  551. {
  552. LOGERROR("Null model, can not set convex hull");
  553. return;
  554. }
  555. if (model_)
  556. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  557. shapeType_ = SHAPE_CONVEXHULL;
  558. model_ = model;
  559. lodLevel_ = lodLevel;
  560. size_ = scale;
  561. position_ = position;
  562. rotation_ = rotation;
  563. customGeometryID_ = 0;
  564. UpdateShape();
  565. NotifyRigidBody();
  566. MarkNetworkUpdate();
  567. }
  568. void CollisionShape::SetCustomConvexHull(CustomGeometry* custom, const Vector3& scale, const Vector3& position, const Quaternion& rotation)
  569. {
  570. if (!custom)
  571. {
  572. LOGERROR("Null custom geometry, can not set convex hull");
  573. return;
  574. }
  575. if (!custom->GetNode())
  576. {
  577. LOGERROR("Custom geometry has null scene node, can not set convex hull");
  578. return;
  579. }
  580. if (model_)
  581. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  582. shapeType_ = SHAPE_CONVEXHULL;
  583. model_.Reset();
  584. lodLevel_ = 0;
  585. size_ = scale;
  586. position_ = position;
  587. rotation_ = rotation;
  588. customGeometryID_ = custom->GetNode()->GetID();
  589. UpdateShape();
  590. NotifyRigidBody();
  591. MarkNetworkUpdate();
  592. }
  593. void CollisionShape::SetTerrain(unsigned lodLevel)
  594. {
  595. Terrain* terrain = GetComponent<Terrain>();
  596. if (!terrain)
  597. {
  598. LOGERROR("No terrain component, can not set terrain shape");
  599. return;
  600. }
  601. if (model_)
  602. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  603. shapeType_ = SHAPE_TERRAIN;
  604. lodLevel_ = lodLevel;
  605. UpdateShape();
  606. NotifyRigidBody();
  607. MarkNetworkUpdate();
  608. }
  609. void CollisionShape::SetShapeType(ShapeType type)
  610. {
  611. if (type != shapeType_)
  612. {
  613. shapeType_ = type;
  614. UpdateShape();
  615. NotifyRigidBody();
  616. MarkNetworkUpdate();
  617. }
  618. }
  619. void CollisionShape::SetSize(const Vector3& size)
  620. {
  621. if (size != size_)
  622. {
  623. size_ = size;
  624. UpdateShape();
  625. NotifyRigidBody();
  626. MarkNetworkUpdate();
  627. }
  628. }
  629. void CollisionShape::SetPosition(const Vector3& position)
  630. {
  631. if (position != position_)
  632. {
  633. position_ = position;
  634. NotifyRigidBody();
  635. MarkNetworkUpdate();
  636. }
  637. }
  638. void CollisionShape::SetRotation(const Quaternion& rotation)
  639. {
  640. if (rotation != rotation_)
  641. {
  642. rotation_ = rotation;
  643. NotifyRigidBody();
  644. MarkNetworkUpdate();
  645. }
  646. }
  647. void CollisionShape::SetTransform(const Vector3& position, const Quaternion& rotation)
  648. {
  649. if (position != position_ || rotation != rotation_)
  650. {
  651. position_ = position;
  652. rotation_ = rotation;
  653. NotifyRigidBody();
  654. MarkNetworkUpdate();
  655. }
  656. }
  657. void CollisionShape::SetMargin(float margin)
  658. {
  659. margin = Max(margin, 0.0f);
  660. if (margin != margin_)
  661. {
  662. if (shape_)
  663. shape_->setMargin(margin);
  664. margin_ = margin;
  665. MarkNetworkUpdate();
  666. }
  667. }
  668. void CollisionShape::SetModel(Model* model)
  669. {
  670. if (model != model_)
  671. {
  672. if (model_)
  673. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  674. model_ = model;
  675. if (shapeType_ >= SHAPE_TRIANGLEMESH)
  676. {
  677. UpdateShape();
  678. NotifyRigidBody();
  679. }
  680. MarkNetworkUpdate();
  681. }
  682. }
  683. void CollisionShape::SetLodLevel(unsigned lodLevel)
  684. {
  685. if (lodLevel != lodLevel_)
  686. {
  687. lodLevel_ = lodLevel;
  688. if (shapeType_ >= SHAPE_TRIANGLEMESH)
  689. {
  690. UpdateShape();
  691. NotifyRigidBody();
  692. }
  693. MarkNetworkUpdate();
  694. }
  695. }
  696. BoundingBox CollisionShape::GetWorldBoundingBox() const
  697. {
  698. if (shape_ && node_)
  699. {
  700. // Use the rigid body's world transform if possible, as it may be different from the rendering transform
  701. RigidBody* body = GetComponent<RigidBody>();
  702. Matrix3x4 worldTransform = body ? Matrix3x4(body->GetPosition(), body->GetRotation(), node_->GetWorldScale()) :
  703. node_->GetWorldTransform();
  704. Vector3 worldPosition(worldTransform * position_);
  705. Quaternion worldRotation(worldTransform.Rotation() * rotation_);
  706. btTransform shapeWorldTransform(ToBtQuaternion(worldRotation), ToBtVector3(worldPosition));
  707. btVector3 aabbMin, aabbMax;
  708. shape_->getAabb(shapeWorldTransform, aabbMin, aabbMax);
  709. return BoundingBox(ToVector3(aabbMin), ToVector3(aabbMax));
  710. }
  711. else
  712. return BoundingBox();
  713. }
  714. void CollisionShape::NotifyRigidBody(bool updateMass)
  715. {
  716. btCompoundShape* compound = GetParentCompoundShape();
  717. if (node_ && shape_ && compound)
  718. {
  719. // Remove the shape first to ensure it is not added twice
  720. compound->removeChildShape(shape_);
  721. if (IsEnabledEffective())
  722. {
  723. // Then add with updated offset
  724. Vector3 position = position_;
  725. // For terrains, undo the height centering performed automatically by Bullet
  726. if (shapeType_ == SHAPE_TERRAIN && geometry_)
  727. {
  728. HeightfieldData* heightfield = static_cast<HeightfieldData*>(geometry_.Get());
  729. position.y_ += (heightfield->minHeight_ + heightfield->maxHeight_) * 0.5f;
  730. }
  731. btTransform offset;
  732. offset.setOrigin(ToBtVector3(node_->GetWorldScale() * position));
  733. offset.setRotation(ToBtQuaternion(rotation_));
  734. compound->addChildShape(offset, shape_);
  735. }
  736. // Finally tell the rigid body to update its mass
  737. if (updateMass)
  738. rigidBody_->UpdateMass();
  739. }
  740. }
  741. void CollisionShape::SetModelAttr(const ResourceRef& value)
  742. {
  743. ResourceCache* cache = GetSubsystem<ResourceCache>();
  744. model_ = cache->GetResource<Model>(value.name_);
  745. recreateShape_ = true;
  746. MarkNetworkUpdate();
  747. }
  748. ResourceRef CollisionShape::GetModelAttr() const
  749. {
  750. return GetResourceRef(model_, Model::GetTypeStatic());
  751. }
  752. void CollisionShape::ReleaseShape()
  753. {
  754. btCompoundShape* compound = GetParentCompoundShape();
  755. if (shape_ && compound)
  756. {
  757. compound->removeChildShape(shape_);
  758. rigidBody_->UpdateMass();
  759. }
  760. delete shape_;
  761. shape_ = 0;
  762. geometry_.Reset();
  763. if (physicsWorld_)
  764. physicsWorld_->CleanupGeometryCache();
  765. }
  766. void CollisionShape::OnNodeSet(Node* node)
  767. {
  768. if (node)
  769. {
  770. Scene* scene = GetScene();
  771. if (scene)
  772. {
  773. if (scene == node)
  774. LOGWARNING(GetTypeName() + " should not be created to the root scene node");
  775. physicsWorld_ = scene->GetOrCreateComponent<PhysicsWorld>();
  776. physicsWorld_->AddCollisionShape(this);
  777. }
  778. else
  779. LOGERROR("Node is detached from scene, can not create collision shape");
  780. node->AddListener(this);
  781. cachedWorldScale_ = node->GetWorldScale();
  782. // Terrain collision shape depends on the terrain component's geometry updates. Subscribe to them
  783. SubscribeToEvent(node, E_TERRAINCREATED, HANDLER(CollisionShape, HandleTerrainCreated));
  784. }
  785. }
  786. void CollisionShape::OnMarkedDirty(Node* node)
  787. {
  788. Vector3 newWorldScale = node_->GetWorldScale();
  789. if (HasWorldScaleChanged(cachedWorldScale_, newWorldScale) && shape_)
  790. {
  791. // Physics operations are not safe from worker threads
  792. Scene* scene = GetScene();
  793. if (scene && scene->IsThreadedUpdate())
  794. {
  795. scene->DelayedMarkedDirty(this);
  796. return;
  797. }
  798. switch (shapeType_)
  799. {
  800. case SHAPE_BOX:
  801. case SHAPE_SPHERE:
  802. case SHAPE_CYLINDER:
  803. case SHAPE_CAPSULE:
  804. case SHAPE_CONE:
  805. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  806. break;
  807. case SHAPE_TRIANGLEMESH:
  808. case SHAPE_CONVEXHULL:
  809. shape_->setLocalScaling(ToBtVector3(newWorldScale * size_));
  810. break;
  811. case SHAPE_TERRAIN:
  812. {
  813. HeightfieldData* heightfield = static_cast<HeightfieldData*>(geometry_.Get());
  814. shape_->setLocalScaling(ToBtVector3(Vector3(heightfield->spacing_.x_, 1.0f, heightfield->spacing_.z_) *
  815. newWorldScale * size_));
  816. }
  817. break;
  818. default:
  819. break;
  820. }
  821. NotifyRigidBody();
  822. cachedWorldScale_ = newWorldScale;
  823. }
  824. }
  825. btCompoundShape* CollisionShape::GetParentCompoundShape()
  826. {
  827. if (!rigidBody_)
  828. rigidBody_ = GetComponent<RigidBody>();
  829. return rigidBody_ ? rigidBody_->GetCompoundShape() : 0;
  830. }
  831. void CollisionShape::UpdateShape()
  832. {
  833. PROFILE(UpdateCollisionShape);
  834. ReleaseShape();
  835. if (!physicsWorld_)
  836. return;
  837. if (node_)
  838. {
  839. Vector3 newWorldScale = node_->GetWorldScale();
  840. switch (shapeType_)
  841. {
  842. case SHAPE_BOX:
  843. shape_ = new btBoxShape(ToBtVector3(size_ * 0.5f));
  844. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  845. break;
  846. case SHAPE_SPHERE:
  847. shape_ = new btSphereShape(size_.x_ * 0.5f);
  848. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  849. break;
  850. case SHAPE_STATICPLANE:
  851. shape_ = new btStaticPlaneShape(btVector3(0.0f, 1.0f, 0.0f), 0.0f);
  852. break;
  853. case SHAPE_CYLINDER:
  854. shape_ = new btCylinderShape(btVector3(size_.x_ * 0.5f, size_.y_ * 0.5f, size_.x_ * 0.5f));
  855. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  856. break;
  857. case SHAPE_CAPSULE:
  858. shape_ = new btCapsuleShape(size_.x_ * 0.5f, Max(size_.y_ - size_.x_, 0.0f));
  859. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  860. break;
  861. case SHAPE_CONE:
  862. shape_ = new btConeShape(size_.x_ * 0.5f, size_.y_);
  863. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  864. break;
  865. case SHAPE_TRIANGLEMESH:
  866. size_ = size_.Abs();
  867. if (customGeometryID_ && GetScene())
  868. {
  869. Node* node = GetScene()->GetNode(customGeometryID_);
  870. CustomGeometry* custom = node ? node->GetComponent<CustomGeometry>() : 0;
  871. if (custom)
  872. {
  873. geometry_ = new TriangleMeshData(custom);
  874. TriangleMeshData* triMesh = static_cast<TriangleMeshData*>(geometry_.Get());
  875. shape_ = new btScaledBvhTriangleMeshShape(triMesh->shape_, ToBtVector3(newWorldScale * size_));
  876. }
  877. else
  878. LOGWARNING("Could not find custom geometry component from node ID " + String(customGeometryID_) + " for triangle mesh shape creation");
  879. }
  880. else if (model_ && model_->GetNumGeometries())
  881. {
  882. // Check the geometry cache
  883. Pair<Model*, unsigned> id = MakePair(model_.Get(), lodLevel_);
  884. HashMap<Pair<Model*, unsigned>, SharedPtr<CollisionGeometryData> >& cache = physicsWorld_->GetTriMeshCache();
  885. HashMap<Pair<Model*, unsigned>, SharedPtr<CollisionGeometryData> >::Iterator j = cache.Find(id);
  886. if (j != cache.End())
  887. geometry_ = j->second_;
  888. else
  889. {
  890. geometry_ = new TriangleMeshData(model_, lodLevel_);
  891. // Check if model has dynamic buffers, do not cache in that case
  892. if (!HasDynamicBuffers(model_, lodLevel_))
  893. cache[id] = geometry_;
  894. }
  895. TriangleMeshData* triMesh = static_cast<TriangleMeshData*>(geometry_.Get());
  896. shape_ = new btScaledBvhTriangleMeshShape(triMesh->shape_, ToBtVector3(newWorldScale * size_));
  897. // Watch for live reloads of the collision model to reload the geometry if necessary
  898. SubscribeToEvent(model_, E_RELOADFINISHED, HANDLER(CollisionShape, HandleModelReloadFinished));
  899. }
  900. break;
  901. case SHAPE_CONVEXHULL:
  902. size_ = size_.Abs();
  903. if (customGeometryID_ && GetScene())
  904. {
  905. Node* node = GetScene()->GetNode(customGeometryID_);
  906. CustomGeometry* custom = node ? node->GetComponent<CustomGeometry>() : 0;
  907. if (custom)
  908. {
  909. geometry_ = new ConvexData(custom);
  910. ConvexData* convex = static_cast<ConvexData*>(geometry_.Get());
  911. shape_ = new btConvexHullShape((btScalar*)convex->vertexData_.Get(), convex->vertexCount_, sizeof(Vector3));
  912. shape_->setLocalScaling(ToBtVector3(newWorldScale * size_));
  913. }
  914. else
  915. LOGWARNING("Could not find custom geometry component from node ID " + String(customGeometryID_) + " for convex shape creation");
  916. }
  917. else if (model_ && model_->GetNumGeometries())
  918. {
  919. // Check the geometry cache
  920. Pair<Model*, unsigned> id = MakePair(model_.Get(), lodLevel_);
  921. HashMap<Pair<Model*, unsigned>, SharedPtr<CollisionGeometryData> >& cache = physicsWorld_->GetConvexCache();
  922. HashMap<Pair<Model*, unsigned>, SharedPtr<CollisionGeometryData> >::Iterator j = cache.Find(id);
  923. if (j != cache.End())
  924. geometry_ = j->second_;
  925. else
  926. {
  927. geometry_ = new ConvexData(model_, lodLevel_);
  928. // Check if model has dynamic buffers, do not cache in that case
  929. if (!HasDynamicBuffers(model_, lodLevel_))
  930. cache[id] = geometry_;
  931. }
  932. ConvexData* convex = static_cast<ConvexData*>(geometry_.Get());
  933. shape_ = new btConvexHullShape((btScalar*)convex->vertexData_.Get(), convex->vertexCount_, sizeof(Vector3));
  934. shape_->setLocalScaling(ToBtVector3(newWorldScale * size_));
  935. SubscribeToEvent(model_, E_RELOADFINISHED, HANDLER(CollisionShape, HandleModelReloadFinished));
  936. }
  937. break;
  938. case SHAPE_TERRAIN:
  939. size_ = size_.Abs();
  940. {
  941. Terrain* terrain = GetComponent<Terrain>();
  942. if (terrain && terrain->GetHeightData())
  943. {
  944. geometry_ = new HeightfieldData(terrain, lodLevel_);
  945. HeightfieldData* heightfield = static_cast<HeightfieldData*>(geometry_.Get());
  946. shape_ = new btHeightfieldTerrainShape(heightfield->size_.x_, heightfield->size_.y_,
  947. heightfield->heightData_.Get(), 1.0f, heightfield->minHeight_, heightfield->maxHeight_, 1, PHY_FLOAT,
  948. false);
  949. shape_->setLocalScaling(ToBtVector3(Vector3(heightfield->spacing_.x_, 1.0f, heightfield->spacing_.z_) *
  950. newWorldScale * size_));
  951. }
  952. }
  953. break;
  954. default:
  955. break;
  956. }
  957. if (shape_)
  958. {
  959. shape_->setUserPointer(this);
  960. shape_->setMargin(margin_);
  961. }
  962. cachedWorldScale_ = newWorldScale;
  963. }
  964. if (physicsWorld_)
  965. physicsWorld_->CleanupGeometryCache();
  966. recreateShape_ = false;
  967. }
  968. void CollisionShape::HandleTerrainCreated(StringHash eventType, VariantMap& eventData)
  969. {
  970. if (shapeType_ == SHAPE_TERRAIN)
  971. {
  972. UpdateShape();
  973. NotifyRigidBody();
  974. }
  975. }
  976. void CollisionShape::HandleModelReloadFinished(StringHash eventType, VariantMap& eventData)
  977. {
  978. if (physicsWorld_)
  979. physicsWorld_->RemoveCachedGeometry(model_);
  980. if (shapeType_ == SHAPE_TRIANGLEMESH || shapeType_ == SHAPE_CONVEXHULL)
  981. {
  982. UpdateShape();
  983. NotifyRigidBody();
  984. }
  985. }
  986. }