CollisionShape.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "CollisionShape.h"
  25. #include "Context.h"
  26. #include "DebugRenderer.h"
  27. #include "Geometry.h"
  28. #include "Log.h"
  29. #include "Model.h"
  30. #include "PhysicsWorld.h"
  31. #include "Profiler.h"
  32. #include "ResourceCache.h"
  33. #include "RigidBody.h"
  34. #include "Scene.h"
  35. #include "XMLFile.h"
  36. #include <ode/ode.h>
  37. #include <../ode/src/heightfield.h>
  38. #include <../ode/src/collision_std.h>
  39. #include <hull.h>
  40. #include "DebugNew.h"
  41. static const String typeNames[] =
  42. {
  43. "None",
  44. "Box",
  45. "Sphere",
  46. "Capsule",
  47. "Cylinder",
  48. "TriangleMesh",
  49. "Heightfield",
  50. "ConvexHull",
  51. ""
  52. };
  53. static const float DEFAULT_FRICTION = 0.5f;
  54. static const float DEFAULT_BOUNCE = 0.0f;
  55. static const Quaternion CYLINDER_ROTATION(90.0f, 0.0f, 0.0f);
  56. void GetVertexAndIndexData(const Model* model, unsigned lodLevel, SharedArrayPtr<Vector3>& destVertexData, unsigned& destVertexCount,
  57. SharedArrayPtr<unsigned>& destIndexData, unsigned& destIndexCount, const Vector3& scale)
  58. {
  59. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  60. destVertexCount = 0;
  61. destIndexCount = 0;
  62. for (unsigned i = 0; i < geometries.Size(); ++i)
  63. {
  64. unsigned subGeometryLodLevel = lodLevel;
  65. if (subGeometryLodLevel >= geometries[i].Size())
  66. subGeometryLodLevel = geometries[i].Size() / 2;
  67. Geometry* geom = geometries[i][subGeometryLodLevel];
  68. if (!geom)
  69. continue;
  70. destVertexCount += geom->GetVertexCount();
  71. destIndexCount += geom->GetIndexCount();
  72. }
  73. if (!destVertexCount || !destIndexCount)
  74. return;
  75. destVertexData = new Vector3[destVertexCount];
  76. destIndexData = new unsigned[destIndexCount];
  77. unsigned firstVertex = 0;
  78. unsigned firstIndex = 0;
  79. for (unsigned i = 0; i < geometries.Size(); ++i)
  80. {
  81. unsigned subGeometryLodLevel = lodLevel;
  82. if (subGeometryLodLevel >= geometries[i].Size())
  83. subGeometryLodLevel = geometries[i].Size() / 2;
  84. Geometry* geom = geometries[i][subGeometryLodLevel];
  85. if (!geom)
  86. continue;
  87. const unsigned char* vertexData;
  88. const unsigned char* indexData;
  89. unsigned vertexSize;
  90. unsigned indexSize;
  91. geom->GetRawData(vertexData, vertexSize, indexData, indexSize);
  92. if (!vertexData || !indexData)
  93. continue;
  94. unsigned vertexStart = geom->GetVertexStart();
  95. unsigned vertexCount = geom->GetVertexCount();
  96. // Copy vertex data
  97. for (unsigned j = 0; j < vertexCount; ++j)
  98. {
  99. const Vector3& v = *((const Vector3*)(&vertexData[(vertexStart + j) * vertexSize]));
  100. destVertexData[firstVertex + j] = scale * v;
  101. }
  102. unsigned indexStart = geom->GetIndexStart();
  103. unsigned indexCount = geom->GetIndexCount();
  104. // 16-bit indices
  105. if (indexSize == sizeof(unsigned short))
  106. {
  107. const unsigned short* indices = (const unsigned short*)indexData;
  108. for (unsigned j = 0; j < indexCount; j += 3)
  109. {
  110. // Rebase the indices according to our vertex numbering
  111. destIndexData[firstIndex + j] = indices[indexStart + j] - vertexStart + firstVertex;
  112. destIndexData[firstIndex + j + 1] = indices[indexStart + j + 1] - vertexStart + firstVertex;
  113. destIndexData[firstIndex + j + 2] = indices[indexStart + j + 2] - vertexStart + firstVertex;
  114. }
  115. }
  116. // 32-bit indices
  117. else
  118. {
  119. const unsigned* indices = (const unsigned*)indexData;
  120. for (unsigned j = 0; j < indexCount; j += 3)
  121. {
  122. // Rebase the indices according to our vertex numbering
  123. destIndexData[firstIndex + j] = indices[indexStart + j] - vertexStart + firstVertex;
  124. destIndexData[firstIndex + j + 1] = indices[indexStart + j + 1] - vertexStart + firstVertex;
  125. destIndexData[firstIndex + j + 2] = indices[indexStart + j + 2] - vertexStart + firstVertex;
  126. }
  127. }
  128. firstVertex += vertexCount;
  129. firstIndex += indexCount;
  130. }
  131. }
  132. TriangleMeshData::TriangleMeshData(Model* model, bool makeConvexHull, float thickness, unsigned lodLevel, const Vector3& scale) :
  133. triMesh_(0),
  134. indexCount_(0)
  135. {
  136. modelName_ = model->GetName();
  137. unsigned vertexCount;
  138. unsigned indexCount;
  139. if (!makeConvexHull)
  140. GetVertexAndIndexData(model, lodLevel, vertexData_, vertexCount, indexData_, indexCount, scale);
  141. else
  142. {
  143. SharedArrayPtr<Vector3> originalVertices;
  144. SharedArrayPtr<unsigned> originalIndices;
  145. unsigned originalVertexCount;
  146. unsigned originalIndexCount;
  147. GetVertexAndIndexData(model, lodLevel, originalVertices, originalVertexCount, originalIndices, originalIndexCount, scale);
  148. // Build the convex hull from the raw geometry
  149. StanHull::HullDesc desc;
  150. desc.SetHullFlag(StanHull::QF_TRIANGLES);
  151. desc.mVcount = originalVertexCount;
  152. desc.mVertices = (float*)originalVertices.Get();
  153. desc.mVertexStride = 3 * sizeof(float);
  154. desc.mSkinWidth = thickness;
  155. StanHull::HullLibrary lib;
  156. StanHull::HullResult result;
  157. lib.CreateConvexHull(desc, result);
  158. vertexCount = result.mNumOutputVertices;
  159. indexCount = result.mNumIndices;
  160. // Copy vertex data
  161. vertexData_ = new Vector3[vertexCount];
  162. memcpy(vertexData_.Get(), result.mOutputVertices, vertexCount * sizeof(Vector3));
  163. // Copy index data
  164. indexData_ = new unsigned[indexCount];
  165. memcpy(indexData_.Get(), result.mIndices, indexCount * sizeof(unsigned));
  166. lib.ReleaseResult(result);
  167. }
  168. triMesh_ = dGeomTriMeshDataCreate();
  169. dGeomTriMeshDataBuildSingle(triMesh_, vertexData_.Get(), sizeof(Vector3), vertexCount,
  170. indexData_.Get(), indexCount, 3 * sizeof(unsigned));
  171. indexCount_ = indexCount;
  172. }
  173. TriangleMeshData::~TriangleMeshData()
  174. {
  175. if (triMesh_)
  176. {
  177. dGeomTriMeshDataDestroy(triMesh_);
  178. triMesh_ = 0;
  179. }
  180. }
  181. HeightfieldData::HeightfieldData(Model* model, IntVector2 numPoints, float thickness, unsigned lodLevel,
  182. const Vector3& scale) :
  183. heightfield_(0)
  184. {
  185. modelName_ = model->GetName();
  186. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  187. if (!geometries.Size())
  188. return;
  189. lodLevel = Clamp(lodLevel, 0, geometries[0].Size());
  190. Geometry* geom = geometries[0][lodLevel];
  191. if (!geom)
  192. return;
  193. const unsigned char* vertexData;
  194. const unsigned char* indexData;
  195. unsigned vertexSize;
  196. unsigned indexSize;
  197. geom->GetRawData(vertexData, vertexSize, indexData, indexSize);
  198. if (!vertexData || !indexData)
  199. return;
  200. unsigned indexStart = geom->GetIndexStart();
  201. unsigned indexCount = geom->GetIndexCount();
  202. // If X & Z size not specified, try to guess them
  203. if (numPoints == IntVector2::ZERO)
  204. numPoints.x_ = numPoints.y_ = (int)sqrtf((float)geom->GetVertexCount());
  205. unsigned dataSize = numPoints.x_ * numPoints.y_;
  206. // Then allocate the heightfield
  207. BoundingBox box = model->GetBoundingBox();
  208. heightData_ = new float[dataSize];
  209. // Calculate spacing from model's bounding box
  210. float xSpacing = (box.max_.x_ - box.min_.x_) / (numPoints.x_ - 1);
  211. float zSpacing = (box.max_.z_ - box.min_.z_) / (numPoints.y_ - 1);
  212. // Initialize the heightfield with minimum height
  213. for (unsigned i = 0; i < dataSize; ++i)
  214. heightData_[i] = box.min_.y_ * scale.y_;
  215. unsigned vertexStart = geom->GetVertexStart();
  216. unsigned vertexCount = geom->GetVertexCount();
  217. // Now go through vertex data and fit the vertices into the heightfield
  218. for (unsigned i = vertexStart; i < vertexStart + vertexCount; ++i)
  219. {
  220. const Vector3& vertex = *((const Vector3*)(&vertexData[i * vertexSize]));
  221. int x = (int)((vertex.x_ - box.min_.x_) / xSpacing + 0.25f);
  222. int z = (int)((vertex.z_ - box.min_.z_) / zSpacing + 0.25f);
  223. if (x >= numPoints.x_)
  224. x = numPoints.x_ - 1;
  225. if (z >= numPoints.y_)
  226. z = numPoints.y_ - 1;
  227. if (vertex.y_ > heightData_[z * numPoints.x_ + x])
  228. heightData_[z * numPoints.x_ + x] = vertex.y_ * scale.y_;
  229. }
  230. heightfield_ = dGeomHeightfieldDataCreate();
  231. dGeomHeightfieldDataBuildSingle(heightfield_, heightData_.Get(), 0, (box.max_.x_ - box.min_.x_) * scale.x_,
  232. (box.max_.z_ - box.min_.z_) * scale.z_, numPoints.x_, numPoints.y_, 1.0f, 0.0f, thickness, 0);
  233. dGeomHeightfieldDataSetBounds(heightfield_, box.min_.y_ * scale.y_, box.max_.y_ * scale.y_);
  234. }
  235. HeightfieldData::~HeightfieldData()
  236. {
  237. if (heightfield_)
  238. {
  239. dGeomHeightfieldDataDestroy(heightfield_);
  240. heightfield_ = 0;
  241. }
  242. }
  243. OBJECTTYPESTATIC(CollisionShape);
  244. CollisionShape::CollisionShape(Context* context) :
  245. Component(context),
  246. geometry_(0),
  247. shapeType_(SHAPE_NONE),
  248. size_(Vector3::ONE),
  249. thickness_(0.0f),
  250. lodLevel_(0),
  251. position_(Vector3::ZERO),
  252. rotation_(Quaternion::IDENTITY),
  253. geometryScale_(Vector3::ONE),
  254. collisionLayer_(M_MAX_UNSIGNED),
  255. collisionMask_(M_MAX_UNSIGNED),
  256. friction_(DEFAULT_FRICTION),
  257. bounce_(DEFAULT_BOUNCE),
  258. phantom_(false),
  259. recreateGeometry_(false)
  260. {
  261. }
  262. CollisionShape::~CollisionShape()
  263. {
  264. Clear();
  265. if (physicsWorld_)
  266. physicsWorld_->RemoveCollisionShape(this);
  267. }
  268. void CollisionShape::RegisterObject(Context* context)
  269. {
  270. context->RegisterFactory<CollisionShape>();
  271. ENUM_ATTRIBUTE(CollisionShape, "Shape Type", shapeType_, typeNames, SHAPE_NONE, AM_DEFAULT);
  272. ATTRIBUTE(CollisionShape, VAR_VECTOR3, "Size", size_, Vector3::ONE, AM_DEFAULT);
  273. REF_ACCESSOR_ATTRIBUTE(CollisionShape, VAR_VECTOR3, "Offset Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_DEFAULT);
  274. REF_ACCESSOR_ATTRIBUTE(CollisionShape, VAR_QUATERNION, "Offset Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_DEFAULT);
  275. ACCESSOR_ATTRIBUTE(CollisionShape, VAR_RESOURCEREF, "Model", GetModelAttr, SetModelAttr, ResourceRef, ResourceRef(Model::GetTypeStatic()), AM_DEFAULT);
  276. ATTRIBUTE(CollisionShape, VAR_INT, "LOD Level", lodLevel_, 0, AM_DEFAULT);
  277. ATTRIBUTE(CollisionShape, VAR_FLOAT, "Hull Thickness", thickness_, 0.0f, AM_DEFAULT);
  278. ACCESSOR_ATTRIBUTE(CollisionShape, VAR_FLOAT, "Friction", GetFriction, SetFriction, float, DEFAULT_FRICTION, AM_DEFAULT);
  279. ACCESSOR_ATTRIBUTE(CollisionShape, VAR_FLOAT, "Bounce", GetBounce, SetBounce, float, DEFAULT_BOUNCE, AM_DEFAULT);
  280. ACCESSOR_ATTRIBUTE(CollisionShape, VAR_INT, "Collision Group", GetCollisionLayer, SetCollisionLayer, unsigned, M_MAX_UNSIGNED, AM_DEFAULT);
  281. ACCESSOR_ATTRIBUTE(CollisionShape, VAR_INT, "Collision Mask", GetCollisionMask, SetCollisionMask, unsigned, M_MAX_UNSIGNED, AM_DEFAULT);
  282. ATTRIBUTE(CollisionShape, VAR_BOOL, "Is Phantom", phantom_, false, AM_DEFAULT);
  283. }
  284. void CollisionShape::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  285. {
  286. Serializable::OnSetAttribute(attr, src);
  287. // Change of some attributes requires the geometry to be recreated
  288. switch (attr.offset_)
  289. {
  290. case offsetof(CollisionShape, size_):
  291. size_ = size_.Abs(); // Negative size is not allowed
  292. recreateGeometry_ = true;
  293. break;
  294. case offsetof(CollisionShape, shapeType_):
  295. case offsetof(CollisionShape, thickness_):
  296. case offsetof(CollisionShape, lodLevel_):
  297. recreateGeometry_ = true;
  298. break;
  299. }
  300. }
  301. void CollisionShape::ApplyAttributes()
  302. {
  303. if (recreateGeometry_)
  304. {
  305. CreateGeometry();
  306. recreateGeometry_ = false;
  307. }
  308. }
  309. void CollisionShape::Clear()
  310. {
  311. ReleaseGeometry();
  312. shapeType_ = SHAPE_NONE;
  313. }
  314. void CollisionShape::SetSphere(float diameter, const Vector3& position, const Quaternion& rotation)
  315. {
  316. ReleaseGeometry();
  317. shapeType_ = SHAPE_SPHERE;
  318. size_ = Vector3(diameter, diameter, diameter);
  319. position_ = position;
  320. rotation_ = rotation;
  321. CreateGeometry();
  322. }
  323. void CollisionShape::SetBox(const Vector3& size, const Vector3& position, const Quaternion& rotation)
  324. {
  325. ReleaseGeometry();
  326. shapeType_ = SHAPE_BOX;
  327. size_ = size;
  328. position_ = position;
  329. rotation_ = rotation;
  330. CreateGeometry();
  331. }
  332. void CollisionShape::SetCapsule(float diameter, float height, const Vector3& position, const Quaternion& rotation)
  333. {
  334. ReleaseGeometry();
  335. shapeType_ = SHAPE_CAPSULE;
  336. size_ = Vector3(diameter, height, diameter);
  337. position_ = position;
  338. rotation_ = rotation;
  339. CreateGeometry();
  340. }
  341. void CollisionShape::SetCylinder(float diameter, float height, const Vector3& position, const Quaternion& rotation)
  342. {
  343. ReleaseGeometry();
  344. shapeType_ = SHAPE_CYLINDER;
  345. size_ = Vector3(diameter, height, diameter);
  346. position_ = position;
  347. rotation_ = rotation;
  348. CreateGeometry();
  349. }
  350. void CollisionShape::SetTriangleMesh(Model* model, unsigned lodLevel, const Vector3& size, const Vector3& position, const Quaternion& rotation)
  351. {
  352. PROFILE(SetTriangleMeshShape);
  353. if (!model)
  354. {
  355. LOGERROR("Null model, can not set triangle mesh");
  356. return;
  357. }
  358. ReleaseGeometry();
  359. model_ = model;
  360. shapeType_ = SHAPE_TRIANGLEMESH;
  361. lodLevel_ = lodLevel;
  362. size_ = size.Abs();
  363. position_ = position;
  364. rotation_ = rotation;
  365. CreateGeometry();
  366. }
  367. void CollisionShape::SetHeightfield(Model* model, unsigned xPoints, unsigned zPoints, float thickness, unsigned lodLevel, const Vector3& size, const Vector3& position, const Quaternion& rotation)
  368. {
  369. PROFILE(SetHeightFieldShape);
  370. if (!model)
  371. {
  372. LOGERROR("Null model, can not set heightfield");
  373. return;
  374. }
  375. ReleaseGeometry();
  376. model_ = model;
  377. shapeType_ = SHAPE_HEIGHTFIELD;
  378. numPoints_ = IntVector2(xPoints, zPoints);
  379. thickness_ = thickness;
  380. lodLevel_ = lodLevel;
  381. size_ = size.Abs();
  382. position_ = position;
  383. rotation_ = rotation;
  384. CreateGeometry();
  385. }
  386. void CollisionShape::SetConvexHull(Model* model, float thickness, unsigned lodLevel, const Vector3& size, const Vector3& position, const Quaternion& rotation)
  387. {
  388. PROFILE(SetConvexHullShape);
  389. if (!model)
  390. {
  391. LOGERROR("Null model, can not set convex hull");
  392. return;
  393. }
  394. ReleaseGeometry();
  395. model_ = model;
  396. shapeType_ = SHAPE_CONVEXHULL;
  397. thickness_ = thickness;
  398. lodLevel_ = lodLevel;
  399. size_ = size.Abs();
  400. position_ = position;
  401. rotation_ = rotation;
  402. CreateGeometry();
  403. }
  404. void CollisionShape::SetPosition(const Vector3& position)
  405. {
  406. position_ = position;
  407. UpdateTransform();
  408. }
  409. void CollisionShape::SetRotation(const Quaternion& rotation)
  410. {
  411. rotation_ = rotation;
  412. UpdateTransform();
  413. }
  414. void CollisionShape::SetTransform(const Vector3& position, const Quaternion& rotation)
  415. {
  416. position_ = position;
  417. rotation_ = rotation;
  418. UpdateTransform();
  419. }
  420. void CollisionShape::SetCollisionLayer(unsigned group)
  421. {
  422. collisionLayer_ = group;
  423. if (geometry_)
  424. dGeomSetCategoryBits(geometry_, group);
  425. }
  426. void CollisionShape::SetCollisionMask(unsigned mask)
  427. {
  428. collisionMask_ = mask;
  429. if (geometry_)
  430. dGeomSetCollideBits(geometry_, mask);
  431. }
  432. void CollisionShape::SetFriction(float friction)
  433. {
  434. friction_ = Max(friction, 0.0f);
  435. }
  436. void CollisionShape::SetBounce(float bounce)
  437. {
  438. bounce_ = Max(bounce, 0.0f);
  439. }
  440. void CollisionShape::SetPhantom(bool enable)
  441. {
  442. phantom_ = enable;
  443. }
  444. BoundingBox CollisionShape::GetWorldBoundingBox() const
  445. {
  446. if (!geometry_)
  447. return BoundingBox(0.0f, 0.0f);
  448. float aabb[6];
  449. dGeomGetAABB(geometry_, aabb);
  450. BoundingBox box;
  451. box.min_.x_ = aabb[0];
  452. box.max_.x_ = aabb[1];
  453. box.min_.y_ = aabb[2];
  454. box.max_.y_ = aabb[3];
  455. box.min_.z_ = aabb[4];
  456. box.max_.z_ = aabb[5];
  457. box.defined_ = true;
  458. return box;
  459. }
  460. void CollisionShape::UpdateTransform(bool nodeUpdate)
  461. {
  462. if (!geometry_)
  463. return;
  464. // Get the ODE body ID from the RigidBody component, if it exists
  465. RigidBody* rigidBody = GetComponent<RigidBody>();
  466. dBodyID body = rigidBody ? rigidBody->GetBody() : 0;
  467. // Apply an adjustment to the cylinder and capsule shapes to make them upright by default
  468. Quaternion offsetQuaternion = (shapeType_ == SHAPE_CYLINDER || shapeType_ == SHAPE_CAPSULE) ? CYLINDER_ROTATION * rotation_ : rotation_;
  469. if (body)
  470. {
  471. // Assign body now if necessary
  472. if (dGeomGetBody(geometry_) != body)
  473. dGeomSetBody(geometry_, body);
  474. else
  475. {
  476. // If the body is already assigned, and this is a node dirtying update, need to do nothing
  477. if (nodeUpdate)
  478. return;
  479. }
  480. // Update the offset transform
  481. if (position_ != Vector3::ZERO || offsetQuaternion != Quaternion::IDENTITY)
  482. {
  483. Vector3 offset(geometryScale_ * position_);
  484. dGeomSetOffsetPosition(geometry_, offset.x_, offset.y_, offset.z_);
  485. dGeomSetOffsetQuaternion(geometry_, offsetQuaternion.GetData());
  486. }
  487. else
  488. dGeomClearOffset(geometry_);
  489. }
  490. else
  491. {
  492. // No rigid body. Must update the geometry transform manually
  493. // Use the target transform in case the node has smoothed motion enabled
  494. Matrix3x4 transform(node_->GetWorldTargetTransform());
  495. Vector3 nodePos(transform.Translation());
  496. Quaternion nodeRot(transform.Rotation());
  497. Vector3 geomPos(nodePos + (nodeRot * (geometryScale_ * position_)));
  498. Quaternion geomRot(nodeRot * offsetQuaternion);
  499. dGeomSetPosition(geometry_, geomPos.x_, geomPos.y_, geomPos.z_);
  500. dGeomSetQuaternion(geometry_, geomRot.GetData());
  501. }
  502. }
  503. void CollisionShape::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  504. {
  505. if (!geometry_)
  506. return;
  507. const Color* color;
  508. RigidBody* rigidBody = GetComponent<RigidBody>();
  509. if (rigidBody && rigidBody->IsActive())
  510. color = &Color::WHITE;
  511. else
  512. color = &Color::GREEN;
  513. unsigned uintColor = color->ToUInt();
  514. // Drawing all the debug geometries of a large world may be expensive (especially triangle meshes)
  515. // so cull the geometry AABB against the debug geometry frustum first
  516. if (!debug->IsInside(GetWorldBoundingBox()))
  517. return;
  518. const Vector3& position = *reinterpret_cast<const Vector3*>(dGeomGetPosition(geometry_));
  519. Quaternion rotation;
  520. dGeomGetQuaternion(geometry_, const_cast<float*>(rotation.GetData()));
  521. Matrix3x4 transform(position, rotation, 1.0f);
  522. switch (dGeomGetClass(geometry_))
  523. {
  524. case dSphereClass:
  525. {
  526. float radius = dGeomSphereGetRadius(geometry_);
  527. for (unsigned i = 0; i < 360; i += 45)
  528. {
  529. unsigned j = i + 45;
  530. float a = radius * sinf(i * M_DEGTORAD);
  531. float b = radius * cosf(i * M_DEGTORAD);
  532. float c = radius * sinf(j * M_DEGTORAD);
  533. float d = radius * cosf(j * M_DEGTORAD);
  534. Vector3 start, end;
  535. start = transform * Vector3(a, b, 0.0f);
  536. end = transform * Vector3(c, d, 0.0f);
  537. debug->AddLine(start, end, uintColor, depthTest);
  538. start = transform * Vector3(a, 0.0f, b);
  539. end = transform * Vector3(c, 0.0f, d);
  540. debug->AddLine(start, end, uintColor, depthTest);
  541. start = transform * Vector3(0.0f, a, b);
  542. end = transform * Vector3(0.0f, c, d);
  543. debug->AddLine(start, end, uintColor, depthTest);
  544. }
  545. }
  546. break;
  547. case dBoxClass:
  548. {
  549. dVector3 size;
  550. dGeomBoxGetLengths(geometry_, size);
  551. BoundingBox box(0.5f * Vector3(size[0], size[1], size[2]), 0.5f * Vector3(-size[0], -size[1], -size[2]));
  552. debug->AddBoundingBox(box, transform, *color, depthTest);
  553. }
  554. break;
  555. case dCapsuleClass:
  556. {
  557. float radius, length;
  558. dGeomCapsuleGetParams(geometry_, &radius, &length);
  559. for (unsigned i = 0; i < 360; i += 45)
  560. {
  561. unsigned j = i + 45;
  562. float a = radius * sinf(i * M_DEGTORAD);
  563. float b = radius * cosf(i * M_DEGTORAD);
  564. float c = radius * sinf(j * M_DEGTORAD);
  565. float d = radius * cosf(j * M_DEGTORAD);
  566. Vector3 start, end;
  567. start = transform * Vector3(a, b, 0.5f * length);
  568. end = transform * Vector3(c, d, 0.5f * length);
  569. debug->AddLine(start, end, uintColor, depthTest);
  570. start = transform * Vector3(a, b, -0.5f * length);
  571. end = transform * Vector3(c, d, -0.5f * length);
  572. debug->AddLine(start, end, uintColor, depthTest);
  573. if (!(i & 1))
  574. {
  575. start = transform * Vector3(a, b, 0.5f * length);
  576. end = transform * Vector3(a, b, -0.5f * length);
  577. debug->AddLine(start, end, uintColor, depthTest);
  578. }
  579. if (b > -M_EPSILON)
  580. {
  581. start = transform * Vector3(a, 0.0f, b + 0.5f * length);
  582. end = transform * Vector3(c, 0.0f, d + 0.5f * length);
  583. debug->AddLine(start, end, uintColor, depthTest);
  584. start = transform * Vector3(0.0f, a, b + 0.5f * length);
  585. end = transform * Vector3(0.0f, c, d + 0.5f * length);
  586. debug->AddLine(start, end, uintColor, depthTest);
  587. start = transform * Vector3(a, 0.0f, -b - 0.5f * length);
  588. end = transform * Vector3(c, 0.0f, -d - 0.5f * length);
  589. debug->AddLine(start, end, uintColor, depthTest);
  590. start = transform * Vector3(0.0f, a, -b - 0.5f * length);
  591. end = transform * Vector3(0.0f, c, -d - 0.5f * length);
  592. debug->AddLine(start, end, uintColor, depthTest);
  593. }
  594. }
  595. }
  596. break;
  597. case dCylinderClass:
  598. {
  599. float radius, length;
  600. dGeomCylinderGetParams(geometry_, &radius, &length);
  601. for (unsigned i = 0; i < 360; i += 45)
  602. {
  603. unsigned j = i + 45;
  604. float a = radius * sinf(i * M_DEGTORAD);
  605. float b = radius * cosf(i * M_DEGTORAD);
  606. float c = radius * sinf(j * M_DEGTORAD);
  607. float d = radius * cosf(j * M_DEGTORAD);
  608. Vector3 start, end;
  609. start = transform * Vector3(a, b, 0.5f * length);
  610. end = transform * Vector3(c, d, 0.5f * length);
  611. debug->AddLine(start, end, uintColor, depthTest);
  612. start = transform * Vector3(a, b, -0.5f * length);
  613. end = transform * Vector3(c, d, -0.5f * length);
  614. debug->AddLine(start, end, uintColor, depthTest);
  615. start = transform * Vector3(a, b, 0.5f * length);
  616. end = transform * Vector3(a, b, -0.5f * length);
  617. debug->AddLine(start, end, uintColor, depthTest);
  618. }
  619. }
  620. break;
  621. case dTriMeshClass:
  622. {
  623. TriangleMeshData* data = static_cast<TriangleMeshData*>(geometryData_.Get());
  624. if (data)
  625. {
  626. debug->AddTriangleMesh(data->vertexData_.Get(), sizeof(Vector3), data->indexData_.Get(), sizeof(unsigned), 0,
  627. data->indexCount_, transform, *color, depthTest);
  628. }
  629. }
  630. break;
  631. case dHeightfieldClass:
  632. {
  633. dHeightfieldDataID heightData = dGeomHeightfieldGetHeightfieldData(geometry_);
  634. unsigned xPoints = heightData->m_nWidthSamples;
  635. unsigned zPoints = heightData->m_nDepthSamples;
  636. float xWidth = heightData->m_fWidth;
  637. float zWidth = heightData->m_fDepth;
  638. float xBase = -0.5f * xWidth;
  639. float zBase = -0.5f * zWidth;
  640. float xSpacing = xWidth / (xPoints - 1);
  641. float zSpacing = zWidth / (zPoints - 1);
  642. float* heights = (float*)heightData->m_pHeightData;
  643. for (unsigned z = 0; z < zPoints - 1; ++z)
  644. {
  645. for (unsigned x = 0; x < xPoints - 1; ++x)
  646. {
  647. Vector3 a = transform * Vector3(xBase + x * xSpacing, heights[z * xPoints + x], zBase + z * zSpacing);
  648. Vector3 b = transform * Vector3(xBase + (x + 1) * xSpacing, heights[z * xPoints + x + 1], zBase + z * zSpacing);
  649. Vector3 c = transform * Vector3(xBase + x * xSpacing, heights[(z + 1) * xPoints + x], zBase + (z + 1) * zSpacing);
  650. debug->AddLine(a, b, uintColor, depthTest);
  651. debug->AddLine(a, c, uintColor, depthTest);
  652. }
  653. }
  654. for (unsigned z = 0; z < zPoints - 1; ++z)
  655. {
  656. unsigned x = xPoints - 1;
  657. Vector3 a = transform * Vector3(xBase + x * xSpacing, heights[z * xPoints + x], zBase + z * zSpacing);
  658. Vector3 b = transform * Vector3(xBase + x * xSpacing, heights[(z + 1) * xPoints + x], zBase + (z + 1) * zSpacing);
  659. debug->AddLine(a, b, uintColor, depthTest);
  660. }
  661. for (unsigned x = 0; x < xPoints - 1; ++x)
  662. {
  663. unsigned z = zPoints - 1;
  664. Vector3 a = transform * Vector3(xBase + x * xSpacing, heights[z * xPoints + x], zBase + z * zSpacing);
  665. Vector3 b = transform * Vector3(xBase + (x + 1) * xSpacing, heights[z * xPoints + x + 1], zBase + z * zSpacing);
  666. debug->AddLine(a, b, uintColor, depthTest);
  667. }
  668. }
  669. break;
  670. }
  671. }
  672. void CollisionShape::OnMarkedDirty(Node* node)
  673. {
  674. // Physics operations are not safe from worker threads
  675. Scene* scene = node->GetScene();
  676. if (scene && scene->IsThreadedUpdate())
  677. {
  678. scene->DelayedMarkedDirty(this);
  679. return;
  680. }
  681. // If scale has changed, must recreate the geometry
  682. if (node->GetWorldScale() != geometryScale_)
  683. CreateGeometry();
  684. else
  685. UpdateTransform(true);
  686. }
  687. void CollisionShape::SetModelAttr(ResourceRef value)
  688. {
  689. ResourceCache* cache = GetSubsystem<ResourceCache>();
  690. model_ = cache->GetResource<Model>(value.id_);
  691. recreateGeometry_ = true;
  692. }
  693. ResourceRef CollisionShape::GetModelAttr() const
  694. {
  695. return GetResourceRef(model_, Model::GetTypeStatic());
  696. }
  697. void CollisionShape::OnNodeSet(Node* node)
  698. {
  699. if (node)
  700. {
  701. Scene* scene = node->GetScene();
  702. if (scene)
  703. {
  704. physicsWorld_ = scene->GetComponent<PhysicsWorld>();
  705. if (physicsWorld_)
  706. physicsWorld_->AddCollisionShape(this);
  707. }
  708. node->AddListener(this);
  709. }
  710. }
  711. void CollisionShape::CreateGeometry()
  712. {
  713. PROFILE(CreateCollisionShape);
  714. if (!physicsWorld_)
  715. {
  716. LOGERROR("Null physics world, can not create collision shape");
  717. return;
  718. }
  719. // Destroy previous geometry if exists
  720. if (geometry_)
  721. {
  722. dGeomDestroy(geometry_);
  723. geometry_ = 0;
  724. }
  725. geometryScale_ = node_->GetWorldScale();
  726. Vector3 size = size_ * geometryScale_;
  727. dSpaceID space = physicsWorld_->GetSpace();
  728. switch (shapeType_)
  729. {
  730. case SHAPE_BOX:
  731. geometry_ = dCreateBox(space, size.x_, size.y_, size.z_);
  732. break;
  733. case SHAPE_SPHERE:
  734. geometry_ = dCreateSphere(space, 0.5f * size.x_);
  735. break;
  736. case SHAPE_CAPSULE:
  737. geometry_ = dCreateCapsule(space, 0.5f * size.x_, Max(size.y_ - size.x_, 0.0f));
  738. break;
  739. case SHAPE_CYLINDER:
  740. geometry_ = dCreateCylinder(space, 0.5f * size.x_, size.y_);
  741. break;
  742. case SHAPE_TRIANGLEMESH:
  743. case SHAPE_CONVEXHULL:
  744. {
  745. // For mesh cache lookup purposes, quantize size to 3 decimals only. Otherwise floating point inaccuracy from world
  746. // matrix multiplications and rotation/scale decomposing causes several slightly differing meshes to be created
  747. char sizeText[CONVERSION_BUFFER_LENGTH];
  748. sprintf(sizeText, "%.3f%.3f%.3f", size.x_, size.y_, size.z_);
  749. // Check the geometry cache
  750. String id = model_->GetName() + "_" + String(sizeText) + "_" + String(lodLevel_);
  751. if (shapeType_ == SHAPE_CONVEXHULL)
  752. id += "_" + String(thickness_);
  753. Map<String, SharedPtr<TriangleMeshData> >& cache = physicsWorld_->GetTriangleMeshCache();
  754. Map<String, SharedPtr<TriangleMeshData> >::Iterator j = cache.Find(id);
  755. if (j != cache.End())
  756. {
  757. geometry_ = dCreateTriMesh(space, j->second_->triMesh_, 0, 0, 0);
  758. geometryData_ = StaticCast<CollisionGeometryData>(j->second_);
  759. }
  760. else
  761. {
  762. SharedPtr<TriangleMeshData> newData(new TriangleMeshData(model_, shapeType_ == SHAPE_CONVEXHULL, thickness_,
  763. lodLevel_, size));
  764. cache[id] = newData;
  765. geometry_ = dCreateTriMesh(space, newData->triMesh_, 0, 0, 0);
  766. geometryData_ = StaticCast<CollisionGeometryData>(newData);
  767. }
  768. }
  769. break;
  770. case SHAPE_HEIGHTFIELD:
  771. {
  772. char sizeText[CONVERSION_BUFFER_LENGTH];
  773. sprintf(sizeText, "%.3f%.3f%.3f", size.x_, size.y_, size.z_);
  774. // Check the geometry cache
  775. String id = model_->GetName() + "_" + String(sizeText) + "_" + String(numPoints_) + "_" + String(thickness_) + "_" +
  776. String(lodLevel_);
  777. Map<String, SharedPtr<HeightfieldData> >& cache = physicsWorld_->GetHeightfieldCache();
  778. Map<String, SharedPtr<HeightfieldData> >::Iterator j = cache.Find(id);
  779. if (j != cache.End())
  780. {
  781. geometry_ = dCreateHeightfield(space, j->second_->heightfield_, 1);
  782. geometryData_ = StaticCast<CollisionGeometryData>(j->second_);
  783. }
  784. else
  785. {
  786. SharedPtr<HeightfieldData> newData(new HeightfieldData(model_, numPoints_, thickness_, lodLevel_, size));
  787. cache[id] = newData;
  788. geometry_ = dCreateHeightfield(space, newData->heightfield_, 1);
  789. geometryData_ = StaticCast<CollisionGeometryData>(newData);
  790. }
  791. }
  792. break;
  793. }
  794. // Set collision group and mask & userdata
  795. if (geometry_)
  796. {
  797. dGeomSetCategoryBits(geometry_, collisionLayer_);
  798. dGeomSetCollideBits(geometry_, collisionMask_);
  799. dGeomSetData(geometry_, this);
  800. }
  801. UpdateTransform();
  802. // If rigid body component exists, let it recalculate its mass now
  803. RigidBody* rigidBody = GetComponent<RigidBody>();
  804. if (rigidBody)
  805. rigidBody->UpdateMass();
  806. }
  807. void CollisionShape::ReleaseGeometry(bool notifyBody)
  808. {
  809. if (!physicsWorld_)
  810. return;
  811. if (geometry_)
  812. {
  813. dGeomDestroy(geometry_);
  814. geometry_ = 0;
  815. }
  816. model_.Reset();
  817. geometryData_.Reset();
  818. physicsWorld_->CleanupGeometryCache();
  819. // If rigid body component exists, let it recalculate its mass now
  820. if (notifyBody)
  821. {
  822. RigidBody* rigidBody = GetComponent<RigidBody>();
  823. if (rigidBody)
  824. rigidBody->UpdateMass();
  825. }
  826. }