CollisionShape.cpp 38 KB

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