CollisionShape.cpp 38 KB

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