CollisionShape.cpp 39 KB

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