CollisionShape.cpp 39 KB

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