CollisionShape.cpp 39 KB

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