CollisionShape.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  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. void GetVertexAndIndexData(const Model* model, unsigned lodLevel, SharedArrayPtr<Vector3>& destVertexData, unsigned& destVertexCount,
  56. SharedArrayPtr<unsigned>& destIndexData, unsigned& destIndexCount, const Vector3& scale)
  57. {
  58. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  59. destVertexCount = 0;
  60. destIndexCount = 0;
  61. for (unsigned i = 0; i < geometries.Size(); ++i)
  62. {
  63. unsigned subGeometryLodLevel = lodLevel;
  64. if (subGeometryLodLevel >= geometries[i].Size())
  65. subGeometryLodLevel = geometries[i].Size() / 2;
  66. Geometry* geom = geometries[i][subGeometryLodLevel];
  67. if (!geom)
  68. continue;
  69. destVertexCount += geom->GetVertexCount();
  70. destIndexCount += geom->GetIndexCount();
  71. }
  72. if (!destVertexCount || !destIndexCount)
  73. return;
  74. destVertexData = new Vector3[destVertexCount];
  75. destIndexData = new unsigned[destIndexCount];
  76. unsigned firstVertex = 0;
  77. unsigned firstIndex = 0;
  78. for (unsigned i = 0; i < geometries.Size(); ++i)
  79. {
  80. unsigned subGeometryLodLevel = lodLevel;
  81. if (subGeometryLodLevel >= geometries[i].Size())
  82. subGeometryLodLevel = geometries[i].Size() / 2;
  83. Geometry* geom = geometries[i][subGeometryLodLevel];
  84. if (!geom)
  85. continue;
  86. const unsigned char* vertexData;
  87. const unsigned char* indexData;
  88. unsigned vertexSize;
  89. unsigned indexSize;
  90. geom->GetRawData(vertexData, vertexSize, indexData, indexSize);
  91. if (!vertexData || !indexData)
  92. continue;
  93. unsigned vertexStart = geom->GetVertexStart();
  94. unsigned vertexCount = geom->GetVertexCount();
  95. // Copy vertex data
  96. for (unsigned j = 0; j < vertexCount; ++j)
  97. {
  98. const Vector3& v = *((const Vector3*)(&vertexData[(vertexStart + j) * vertexSize]));
  99. destVertexData[firstVertex + j] = scale * v;
  100. }
  101. unsigned indexStart = geom->GetIndexStart();
  102. unsigned indexCount = geom->GetIndexCount();
  103. // 16-bit indices
  104. if (indexSize == sizeof(unsigned short))
  105. {
  106. const unsigned short* indices = (const unsigned short*)indexData;
  107. for (unsigned j = 0; j < indexCount; j += 3)
  108. {
  109. // Rebase the indices according to our vertex numbering
  110. destIndexData[firstIndex + j] = indices[indexStart + j] - vertexStart + firstVertex;
  111. destIndexData[firstIndex + j + 1] = indices[indexStart + j + 1] - vertexStart + firstVertex;
  112. destIndexData[firstIndex + j + 2] = indices[indexStart + j + 2] - vertexStart + firstVertex;
  113. }
  114. }
  115. // 32-bit indices
  116. else
  117. {
  118. const unsigned* indices = (const unsigned*)indexData;
  119. for (unsigned j = 0; j < indexCount; j += 3)
  120. {
  121. // Rebase the indices according to our vertex numbering
  122. destIndexData[firstIndex + j] = indices[indexStart + j] - vertexStart + firstVertex;
  123. destIndexData[firstIndex + j + 1] = indices[indexStart + j + 1] - vertexStart + firstVertex;
  124. destIndexData[firstIndex + j + 2] = indices[indexStart + j + 2] - vertexStart + firstVertex;
  125. }
  126. }
  127. firstVertex += vertexCount;
  128. firstIndex += indexCount;
  129. }
  130. }
  131. TriangleMeshData::TriangleMeshData(Model* model, bool makeConvexHull, float thickness, unsigned lodLevel, const Vector3& scale) :
  132. triMesh_(0),
  133. indexCount_(0)
  134. {
  135. modelName_ = model->GetName();
  136. unsigned vertexCount;
  137. unsigned indexCount;
  138. if (!makeConvexHull)
  139. GetVertexAndIndexData(model, lodLevel, vertexData_, vertexCount, indexData_, indexCount, scale);
  140. else
  141. {
  142. SharedArrayPtr<Vector3> originalVertices;
  143. SharedArrayPtr<unsigned> originalIndices;
  144. unsigned originalVertexCount;
  145. unsigned originalIndexCount;
  146. GetVertexAndIndexData(model, lodLevel, originalVertices, originalVertexCount, originalIndices, originalIndexCount, scale);
  147. // Build the convex hull from the raw geometry
  148. StanHull::HullDesc desc;
  149. desc.SetHullFlag(StanHull::QF_TRIANGLES);
  150. desc.mVcount = originalVertexCount;
  151. desc.mVertices = (float*)originalVertices.RawPtr();
  152. desc.mVertexStride = 3 * sizeof(float);
  153. desc.mSkinWidth = thickness;
  154. StanHull::HullLibrary lib;
  155. StanHull::HullResult result;
  156. lib.CreateConvexHull(desc, result);
  157. vertexCount = result.mNumOutputVertices;
  158. indexCount = result.mNumIndices;
  159. // Copy vertex data
  160. vertexData_ = new Vector3[vertexCount];
  161. memcpy(vertexData_.RawPtr(), result.mOutputVertices, vertexCount * sizeof(Vector3));
  162. // Copy index data
  163. indexData_ = new unsigned[indexCount];
  164. memcpy(indexData_.RawPtr(), result.mIndices, indexCount * sizeof(unsigned));
  165. lib.ReleaseResult(result);
  166. }
  167. triMesh_ = dGeomTriMeshDataCreate();
  168. dGeomTriMeshDataBuildSingle(triMesh_, vertexData_.RawPtr(), sizeof(Vector3), vertexCount,
  169. indexData_.RawPtr(), indexCount, 3 * sizeof(unsigned));
  170. indexCount_ = indexCount;
  171. }
  172. TriangleMeshData::~TriangleMeshData()
  173. {
  174. if (triMesh_)
  175. {
  176. dGeomTriMeshDataDestroy(triMesh_);
  177. triMesh_ = 0;
  178. }
  179. }
  180. HeightfieldData::HeightfieldData(Model* model, IntVector2 numPoints, float thickness, unsigned lodLevel,
  181. const Vector3& scale) :
  182. heightfield_(0)
  183. {
  184. modelName_ = model->GetName();
  185. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  186. if (!geometries.Size())
  187. return;
  188. lodLevel = Clamp(lodLevel, 0, geometries[0].Size());
  189. Geometry* geom = geometries[0][lodLevel];
  190. if (!geom)
  191. return;
  192. const unsigned char* vertexData;
  193. const unsigned char* indexData;
  194. unsigned vertexSize;
  195. unsigned indexSize;
  196. geom->GetRawData(vertexData, vertexSize, indexData, indexSize);
  197. if (!vertexData || !indexData)
  198. return;
  199. unsigned indexStart = geom->GetIndexStart();
  200. unsigned indexCount = geom->GetIndexCount();
  201. // If X & Z size not specified, try to guess them
  202. if (numPoints == IntVector2::ZERO)
  203. numPoints.x_ = numPoints.y_ = (int)sqrtf((float)geom->GetVertexCount());
  204. unsigned dataSize = numPoints.x_ * numPoints.y_;
  205. // Then allocate the heightfield
  206. BoundingBox box = model->GetBoundingBox();
  207. heightData_ = new float[dataSize];
  208. // Calculate spacing from model's bounding box
  209. float xSpacing = (box.max_.x_ - box.min_.x_) / (numPoints.x_ - 1);
  210. float zSpacing = (box.max_.z_ - box.min_.z_) / (numPoints.y_ - 1);
  211. // Initialize the heightfield with minimum height
  212. for (unsigned i = 0; i < dataSize; ++i)
  213. heightData_[i] = box.min_.y_ * scale.y_;
  214. unsigned vertexStart = geom->GetVertexStart();
  215. unsigned vertexCount = geom->GetVertexCount();
  216. // Now go through vertex data and fit the vertices into the heightfield
  217. for (unsigned i = vertexStart; i < vertexStart + vertexCount; ++i)
  218. {
  219. const Vector3& vertex = *((const Vector3*)(&vertexData[i * vertexSize]));
  220. int x = (int)((vertex.x_ - box.min_.x_) / xSpacing + 0.25f);
  221. int z = (int)((vertex.z_ - box.min_.z_) / zSpacing + 0.25f);
  222. if (x >= numPoints.x_)
  223. x = numPoints.x_ - 1;
  224. if (z >= numPoints.y_)
  225. z = numPoints.y_ - 1;
  226. if (vertex.y_ > heightData_[z * numPoints.x_ + x])
  227. heightData_[z * numPoints.x_ + x] = vertex.y_ * scale.y_;
  228. }
  229. heightfield_ = dGeomHeightfieldDataCreate();
  230. dGeomHeightfieldDataBuildSingle(heightfield_, heightData_.RawPtr(), 0, (box.max_.x_ - box.min_.x_) * scale.x_,
  231. (box.max_.z_ - box.min_.z_) * scale.z_, numPoints.x_, numPoints.y_, 1.0f, 0.0f, thickness, 0);
  232. dGeomHeightfieldDataSetBounds(heightfield_, box.min_.y_ * scale.y_, box.max_.y_ * scale.y_);
  233. }
  234. HeightfieldData::~HeightfieldData()
  235. {
  236. if (heightfield_)
  237. {
  238. dGeomHeightfieldDataDestroy(heightfield_);
  239. heightfield_ = 0;
  240. }
  241. }
  242. OBJECTTYPESTATIC(CollisionShape);
  243. CollisionShape::CollisionShape(Context* context) :
  244. Component(context),
  245. geometry_(0),
  246. shapeType_(SHAPE_NONE),
  247. size_(Vector3::ZERO),
  248. thickness_(0.0f),
  249. lodLevel_(M_MAX_UNSIGNED),
  250. position_(Vector3::ZERO),
  251. rotation_(Quaternion::IDENTITY),
  252. geometryScale_(Vector3::UNITY),
  253. collisionGroup_(M_MAX_UNSIGNED),
  254. collisionMask_(M_MAX_UNSIGNED),
  255. friction_(DEFAULT_FRICTION),
  256. bounce_(DEFAULT_BOUNCE)
  257. {
  258. }
  259. CollisionShape::~CollisionShape()
  260. {
  261. Clear();
  262. }
  263. void CollisionShape::RegisterObject(Context* context)
  264. {
  265. context->RegisterFactory<CollisionShape>();
  266. ENUM_ATTRIBUTE(CollisionShape, "Shape Type", shapeType_, typeNames, SHAPE_NONE, AM_DEFAULT);
  267. ATTRIBUTE(CollisionShape, VAR_VECTOR3, "Size", size_, Vector3::ZERO, AM_DEFAULT);
  268. ATTRIBUTE(CollisionShape, VAR_FLOAT, "Hull Thickness", thickness_, 0.0f, AM_DEFAULT);
  269. ATTRIBUTE(CollisionShape, VAR_INT, "Model LOD Level", lodLevel_, M_MAX_UNSIGNED, AM_DEFAULT);
  270. ATTRIBUTE(CollisionShape, VAR_VECTOR3, "Offset Position", position_, Vector3::ZERO, AM_DEFAULT);
  271. ATTRIBUTE(CollisionShape, VAR_QUATERNION, "Rotation", rotation_, Quaternion::IDENTITY, AM_DEFAULT);
  272. ATTRIBUTE(CollisionShape, VAR_INT, "Collision Group", collisionGroup_, M_MAX_UNSIGNED, AM_DEFAULT);
  273. ATTRIBUTE(CollisionShape, VAR_INT, "Collision Mask", collisionMask_, M_MAX_UNSIGNED, AM_DEFAULT);
  274. ATTRIBUTE(CollisionShape, VAR_FLOAT, "Friction", friction_, DEFAULT_FRICTION, AM_DEFAULT);
  275. ATTRIBUTE(CollisionShape, VAR_FLOAT, "Bounce", bounce_, DEFAULT_BOUNCE, AM_DEFAULT);
  276. ACCESSOR_ATTRIBUTE(CollisionShape, VAR_RESOURCEREF, "Model", GetModelAttr, SetModelAttr, ResourceRef, ResourceRef(Model::GetTypeStatic()), AM_DEFAULT);
  277. }
  278. void CollisionShape::OnFinishUpdate()
  279. {
  280. CreateGeometry();
  281. }
  282. void CollisionShape::Clear()
  283. {
  284. ReleaseGeometry();
  285. shapeType_ = SHAPE_NONE;
  286. }
  287. void CollisionShape::SetSphere(float radius, const Vector3& position, const Quaternion& rotation)
  288. {
  289. ReleaseGeometry();
  290. shapeType_ = SHAPE_SPHERE;
  291. size_ = Vector3(radius, radius, radius);
  292. position_ = position;
  293. rotation_ = rotation;
  294. CreateGeometry();
  295. }
  296. void CollisionShape::SetBox(const Vector3& size, const Vector3& position, const Quaternion& rotation)
  297. {
  298. ReleaseGeometry();
  299. shapeType_ = SHAPE_BOX;
  300. size_ = size;
  301. position_ = position;
  302. rotation_ = rotation;
  303. CreateGeometry();
  304. }
  305. void CollisionShape::SetCapsule(float radius, float height, const Vector3& position, const Quaternion& rotation)
  306. {
  307. ReleaseGeometry();
  308. shapeType_ = SHAPE_CAPSULE;
  309. size_ = Vector3(radius, radius, height);
  310. position_ = position;
  311. rotation_ = rotation;
  312. CreateGeometry();
  313. }
  314. void CollisionShape::SetCylinder(float radius, float height, const Vector3& position, const Quaternion& rotation)
  315. {
  316. ReleaseGeometry();
  317. shapeType_ = SHAPE_CYLINDER;
  318. size_ = Vector3(radius, radius, height);
  319. position_ = position;
  320. rotation_ = rotation;
  321. CreateGeometry();
  322. }
  323. void CollisionShape::SetTriangleMesh(Model* model, unsigned lodLevel, const Vector3& position, const Quaternion& rotation)
  324. {
  325. PROFILE(SetTriangleMeshShape);
  326. if (!model)
  327. {
  328. LOGERROR("Null model, can not set triangle mesh");
  329. return;
  330. }
  331. ReleaseGeometry();
  332. model_ = model;
  333. shapeType_ = SHAPE_TRIANGLEMESH;
  334. lodLevel_ = lodLevel;
  335. size_ = model->GetBoundingBox().Size();
  336. position_ = position;
  337. rotation_ = rotation;
  338. CreateGeometry();
  339. }
  340. void CollisionShape::SetHeightfield(Model* model, const IntVector2& numPoints, float thickness, unsigned lodLevel, const Vector3& position, const Quaternion& rotation)
  341. {
  342. PROFILE(SetHeightFieldShape);
  343. if (!model)
  344. {
  345. LOGERROR("Null model, can not set heightfield");
  346. return;
  347. }
  348. ReleaseGeometry();
  349. model_ = model;
  350. shapeType_ = SHAPE_HEIGHTFIELD;
  351. numPoints_ = numPoints;
  352. thickness_ = thickness;
  353. lodLevel_ = lodLevel;
  354. position_ = position;
  355. rotation_ = rotation;
  356. size_ = model->GetBoundingBox().Size();
  357. CreateGeometry();
  358. }
  359. void CollisionShape::SetConvexHull(Model* model, float thickness, unsigned lodLevel, const Vector3& position, const Quaternion& rotation)
  360. {
  361. PROFILE(SetConvexHullShape);
  362. if (!model)
  363. {
  364. LOGERROR("Null model, can not set convex hull");
  365. return;
  366. }
  367. ReleaseGeometry();
  368. model_ = model;
  369. shapeType_ = SHAPE_CONVEXHULL;
  370. thickness_ = thickness;
  371. lodLevel_ = lodLevel;
  372. size_ = model->GetBoundingBox().Size();
  373. position_ = position;
  374. rotation_ = rotation;
  375. CreateGeometry();
  376. }
  377. void CollisionShape::SetPosition(const Vector3& position)
  378. {
  379. position_ = position;
  380. UpdateTransform();
  381. }
  382. void CollisionShape::SetRotation(const Quaternion& rotation)
  383. {
  384. rotation_ = rotation;
  385. UpdateTransform();
  386. }
  387. void CollisionShape::SetTransform(const Vector3& position, const Quaternion& rotation)
  388. {
  389. position_ = position;
  390. rotation_ = rotation;
  391. UpdateTransform();
  392. }
  393. void CollisionShape::SetCollisionGroup(unsigned group)
  394. {
  395. collisionGroup_ = group;
  396. if (geometry_)
  397. dGeomSetCategoryBits(geometry_, group);
  398. }
  399. void CollisionShape::SetCollisionMask(unsigned mask)
  400. {
  401. collisionMask_ = mask;
  402. if (geometry_)
  403. dGeomSetCollideBits(geometry_, mask);
  404. }
  405. void CollisionShape::SetFriction(float friction)
  406. {
  407. friction_ = Max(friction, 0.0f);
  408. }
  409. void CollisionShape::SetBounce(float bounce)
  410. {
  411. bounce_ = Max(bounce, 0.0f);
  412. }
  413. void CollisionShape::UpdateTransform()
  414. {
  415. if (!geometry_)
  416. return;
  417. // Get the ODE body ID from the RigidBody component, if it exists
  418. dBodyID body = 0;
  419. RigidBody* rigidBody = GetComponent<RigidBody>();
  420. if (rigidBody)
  421. body = rigidBody->GetBody();
  422. // If body already assigned, need to do nothing
  423. if (body)
  424. {
  425. if (dGeomGetBody(geometry_) == body)
  426. return;
  427. // Assign the body, then set offset transform if necessary
  428. dGeomSetBody(geometry_, body);
  429. if (position_ != Vector3::ZERO || rotation_ != Quaternion::IDENTITY)
  430. {
  431. Vector3 offset = geometryScale_ * position_;
  432. dGeomSetOffsetPosition(geometry_, offset.x_, offset.y_, offset.z_);
  433. dGeomSetOffsetQuaternion(geometry_, rotation_.GetData());
  434. }
  435. }
  436. else
  437. {
  438. // No rigid body. Must update the geometry transform manually
  439. Vector3 nodePos = GetWorldPosition();
  440. Quaternion nodeRot = GetWorldRotation();
  441. Vector3 geoposition_ = nodePos + (nodeRot * (geometryScale_ * position_));
  442. Quaternion geomRot = nodeRot * rotation_;
  443. dGeomSetPosition(geometry_, geoposition_.x_, geoposition_.y_, geoposition_.z_);
  444. dGeomSetQuaternion(geometry_, geomRot.GetData());
  445. }
  446. }
  447. void CollisionShape::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  448. {
  449. if (!geometry_)
  450. return;
  451. Color color(0.0f, 1.0f, 0.0f);
  452. RigidBody* rigidBody = GetComponent<RigidBody>();
  453. if (rigidBody && rigidBody->IsActive())
  454. color = Color(1.0f, 1.0f, 1.0f);
  455. // Drawing all the debug geometries of a large world may be expensive (especially triangle meshes)
  456. // so check the geometry AABB against the debug geometry frustum first
  457. float aabb[6];
  458. dGeomGetAABB(geometry_, aabb);
  459. BoundingBox box;
  460. box.min_.x_ = aabb[0];
  461. box.max_.x_ = aabb[1];
  462. box.min_.y_ = aabb[2];
  463. box.max_.y_ = aabb[3];
  464. box.min_.z_ = aabb[4];
  465. box.max_.z_ = aabb[5];
  466. if (!debug->IsInside(box))
  467. return;
  468. const dReal* pos = dGeomGetPosition(geometry_);
  469. dQuaternion quat;
  470. dGeomGetQuaternion(geometry_, quat);
  471. Matrix3x4 transform(Vector3(pos[0], pos[1], pos[2]), Quaternion(quat[0], quat[1], quat[2], quat[3]), 1.0f);
  472. switch (dGeomGetClass(geometry_))
  473. {
  474. case dSphereClass:
  475. {
  476. float radius = dGeomSphereGetRadius(geometry_);
  477. for (unsigned i = 0; i < 360; i += 45)
  478. {
  479. unsigned j = i + 45;
  480. float a = radius * sinf(i * M_DEGTORAD);
  481. float b = radius * cosf(i * M_DEGTORAD);
  482. float c = radius * sinf(j * M_DEGTORAD);
  483. float d = radius * cosf(j * M_DEGTORAD);
  484. Vector3 start, end;
  485. start = transform * Vector3(a, b, 0.0f);
  486. end = transform * Vector3(c, d, 0.0f);
  487. debug->AddLine(start, end, color, depthTest);
  488. start = transform * Vector3(a, 0.0f, b);
  489. end = transform * Vector3(c, 0.0f, d);
  490. debug->AddLine(start, end, color, depthTest);
  491. start = transform * Vector3(0.0f, a, b);
  492. end = transform * Vector3(0.0f, c, d);
  493. debug->AddLine(start, end, color, depthTest);
  494. }
  495. }
  496. break;
  497. case dBoxClass:
  498. {
  499. dVector3 size;
  500. dGeomBoxGetLengths(geometry_, size);
  501. BoundingBox box(0.5f * Vector3(size[0], size[1], size[2]), 0.5f * Vector3(-size[0], -size[1], -size[2]));
  502. debug->AddBoundingBox(box, transform, color, depthTest);
  503. }
  504. break;
  505. case dCapsuleClass:
  506. {
  507. float radius, length;
  508. dGeomCapsuleGetParams(geometry_, &radius, &length);
  509. for (unsigned i = 0; i < 360; i += 45)
  510. {
  511. unsigned j = i + 45;
  512. float a = radius * sinf(i * M_DEGTORAD);
  513. float b = radius * cosf(i * M_DEGTORAD);
  514. float c = radius * sinf(j * M_DEGTORAD);
  515. float d = radius * cosf(j * M_DEGTORAD);
  516. Vector3 start, end;
  517. start = transform * Vector3(a, b, 0.5f * length);
  518. end = transform * Vector3(c, d, 0.5f * length);
  519. debug->AddLine(start, end, color, depthTest);
  520. start = transform * Vector3(a, b, -0.5f * length);
  521. end = transform * Vector3(c, d, -0.5f * length);
  522. debug->AddLine(start, end, color, depthTest);
  523. if (!(i & 1))
  524. {
  525. start = transform * Vector3(a, b, 0.5f * length);
  526. end = transform * Vector3(a, b, -0.5f * length);
  527. debug->AddLine(start, end, color, depthTest);
  528. }
  529. if (b > -M_EPSILON)
  530. {
  531. start = transform * Vector3(a, 0.0f, b + 0.5f * length);
  532. end = transform * Vector3(c, 0.0f, d + 0.5f * length);
  533. debug->AddLine(start, end, color, depthTest);
  534. start = transform * Vector3(0.0f, a, b + 0.5f * length);
  535. end = transform * Vector3(0.0f, c, d + 0.5f * length);
  536. debug->AddLine(start, end, color, depthTest);
  537. start = transform * Vector3(a, 0.0f, -b - 0.5f * length);
  538. end = transform * Vector3(c, 0.0f, -d - 0.5f * length);
  539. debug->AddLine(start, end, color, depthTest);
  540. start = transform * Vector3(0.0f, a, -b - 0.5f * length);
  541. end = transform * Vector3(0.0f, c, -d - 0.5f * length);
  542. debug->AddLine(start, end, color, depthTest);
  543. }
  544. }
  545. }
  546. break;
  547. case dCylinderClass:
  548. {
  549. float radius, length;
  550. dGeomCylinderGetParams(geometry_, &radius, &length);
  551. for (unsigned i = 0; i < 360; i += 45)
  552. {
  553. unsigned j = i + 45;
  554. float a = radius * sinf(i * M_DEGTORAD);
  555. float b = radius * cosf(i * M_DEGTORAD);
  556. float c = radius * sinf(j * M_DEGTORAD);
  557. float d = radius * cosf(j * M_DEGTORAD);
  558. Vector3 start, end;
  559. start = transform * Vector3(a, b, 0.5f * length);
  560. end = transform * Vector3(c, d, 0.5f * length);
  561. debug->AddLine(start, end, color, depthTest);
  562. start = transform * Vector3(a, b, -0.5f * length);
  563. end = transform * Vector3(c, d, -0.5f * length);
  564. debug->AddLine(start, end, color, depthTest);
  565. start = transform * Vector3(a, b, 0.5f * length);
  566. end = transform * Vector3(a, b, -0.5f * length);
  567. debug->AddLine(start, end, color, depthTest);
  568. }
  569. }
  570. break;
  571. case dTriMeshClass:
  572. {
  573. TriangleMeshData* data = static_cast<TriangleMeshData*>(geometryData_.RawPtr());
  574. if (!data)
  575. return;
  576. const Vector3* vertices = data->vertexData_;
  577. const unsigned* indices = data->indexData_;
  578. for (unsigned i = 0; i < data->indexCount_; i += 3)
  579. {
  580. Vector3 v0 = transform * vertices[indices[i]];
  581. Vector3 v1 = transform * vertices[indices[i + 1]];
  582. Vector3 v2 = transform * vertices[indices[i + 2]];
  583. debug->AddLine(v0, v1, color, depthTest);
  584. debug->AddLine(v1, v2, color, depthTest);
  585. debug->AddLine(v2, v0, color, depthTest);
  586. }
  587. }
  588. break;
  589. case dHeightfieldClass:
  590. {
  591. dHeightfieldDataID heightData = dGeomHeightfieldGetHeightfieldData(geometry_);
  592. unsigned xPoints = heightData->m_nWidthSamples;
  593. unsigned zPoints = heightData->m_nDepthSamples;
  594. float xWidth = heightData->m_fWidth;
  595. float zWidth = heightData->m_fDepth;
  596. float xBase = -0.5f * xWidth;
  597. float zBase = -0.5f * zWidth;
  598. float xSpacing = xWidth / (xPoints - 1);
  599. float zSpacing = zWidth / (zPoints - 1);
  600. float* heights = (float*)heightData->m_pHeightData;
  601. for (unsigned z = 0; z < zPoints - 1; ++z)
  602. {
  603. for (unsigned x = 0; x < xPoints - 1; ++x)
  604. {
  605. Vector3 a = transform * Vector3(xBase + x * xSpacing, heights[z * xPoints + x], zBase + z * zSpacing);
  606. Vector3 b = transform * Vector3(xBase + (x + 1) * xSpacing, heights[z * xPoints + x + 1], zBase + z * zSpacing);
  607. Vector3 c = transform * Vector3(xBase + x * xSpacing, heights[(z + 1) * xPoints + x], zBase + (z + 1) * zSpacing);
  608. debug->AddLine(a, b, color, depthTest);
  609. debug->AddLine(a, c, color, depthTest);
  610. }
  611. }
  612. for (unsigned z = 0; z < zPoints - 1; ++z)
  613. {
  614. unsigned x = xPoints - 1;
  615. Vector3 a = transform * Vector3(xBase + x * xSpacing, heights[z * xPoints + x], zBase + z * zSpacing);
  616. Vector3 b = transform * Vector3(xBase + x * xSpacing, heights[(z + 1) * xPoints + x], zBase + (z + 1) * zSpacing);
  617. debug->AddLine(a, b, color, depthTest);
  618. }
  619. for (unsigned x = 0; x < xPoints - 1; ++x)
  620. {
  621. unsigned z = zPoints - 1;
  622. Vector3 a = transform * Vector3(xBase + x * xSpacing, heights[z * xPoints + x], zBase + z * zSpacing);
  623. Vector3 b = transform * Vector3(xBase + (x + 1) * xSpacing, heights[z * xPoints + x + 1], zBase + z * zSpacing);
  624. debug->AddLine(a, b, color, depthTest);
  625. }
  626. }
  627. break;
  628. }
  629. }
  630. void CollisionShape::OnMarkedDirty(Node* node)
  631. {
  632. // If scale has changed, must recreate the geometry
  633. if (GetWorldScale() != geometryScale_)
  634. CreateGeometry();
  635. else
  636. UpdateTransform();
  637. }
  638. void CollisionShape::SetModelAttr(ResourceRef value)
  639. {
  640. ResourceCache* cache = GetSubsystem<ResourceCache>();
  641. model_ = cache->GetResource<Model>(value.id_);
  642. }
  643. ResourceRef CollisionShape::GetModelAttr() const
  644. {
  645. return GetResourceRef(model_, Model::GetTypeStatic());
  646. }
  647. void CollisionShape::OnNodeSet(Node* node)
  648. {
  649. if (node)
  650. {
  651. Scene* scene = node->GetScene();
  652. if (scene)
  653. physicsWorld_ = scene->GetComponent<PhysicsWorld>();
  654. node->AddListener(this);
  655. }
  656. }
  657. void CollisionShape::CreateGeometry()
  658. {
  659. PROFILE(CreateCollisionShape);
  660. if (!physicsWorld_)
  661. {
  662. LOGERROR("Null physics world, can not create collision shape");
  663. return;
  664. }
  665. // Destroy previous geometry if exists
  666. if (geometry_)
  667. {
  668. dGeomDestroy(geometry_);
  669. geometry_ = 0;
  670. }
  671. geometryScale_ = GetWorldScale();
  672. Vector3 size = size_ * geometryScale_;
  673. dSpaceID space = physicsWorld_->GetSpace();
  674. switch (shapeType_)
  675. {
  676. case SHAPE_BOX:
  677. geometry_ = dCreateBox(space, size.x_, size.y_, size.z_);
  678. break;
  679. case SHAPE_SPHERE:
  680. geometry_ = dCreateSphere(space, size.x_);
  681. break;
  682. case SHAPE_CAPSULE:
  683. geometry_ = dCreateCapsule(space, size.x_, size.z_);
  684. break;
  685. case SHAPE_CYLINDER:
  686. geometry_ = dCreateCylinder(space, size.x_, size.z_);
  687. break;
  688. case SHAPE_TRIANGLEMESH:
  689. case SHAPE_CONVEXHULL:
  690. {
  691. // Check the geometry cache
  692. String id = model_->GetName() + "_" + String(geometryScale_) + "_" + String(lodLevel_);
  693. if (shapeType_ == SHAPE_CONVEXHULL)
  694. id += "_" + String(thickness_);
  695. Map<String, SharedPtr<TriangleMeshData> >& cache = physicsWorld_->GetTriangleMeshCache();
  696. Map<String, SharedPtr<TriangleMeshData> >::Iterator j = cache.Find(id);
  697. if (j != cache.End())
  698. {
  699. geometry_ = dCreateTriMesh(space, j->second_->triMesh_, 0, 0, 0);
  700. geometryData_ = StaticCast<CollisionGeometryData>(j->second_);
  701. }
  702. else
  703. {
  704. SharedPtr<TriangleMeshData> newData(new TriangleMeshData(model_, shapeType_ == SHAPE_CONVEXHULL, thickness_,
  705. lodLevel_, geometryScale_));
  706. cache[id] = newData;
  707. geometry_ = dCreateTriMesh(space, newData->triMesh_, 0, 0, 0);
  708. geometryData_ = StaticCast<CollisionGeometryData>(newData);
  709. }
  710. }
  711. break;
  712. case SHAPE_HEIGHTFIELD:
  713. {
  714. // Check the geometry cache
  715. String id = model_->GetName() + "_" + String(numPoints_) + "_" + String(thickness_) + "_" + String(lodLevel_);
  716. Map<String, SharedPtr<HeightfieldData> >& cache = physicsWorld_->GetHeightfieldCache();
  717. Map<String, SharedPtr<HeightfieldData> >::Iterator j = cache.Find(id);
  718. if (j != cache.End())
  719. {
  720. geometry_ = dCreateHeightfield(space, j->second_->heightfield_, 1);
  721. geometryData_ = StaticCast<CollisionGeometryData>(j->second_);
  722. }
  723. else
  724. {
  725. SharedPtr<HeightfieldData> newData(new HeightfieldData(model_, numPoints_, thickness_, lodLevel_, geometryScale_));
  726. cache[id] = newData;
  727. geometry_ = dCreateHeightfield(space, newData->heightfield_, 1);
  728. geometryData_ = StaticCast<CollisionGeometryData>(newData);
  729. }
  730. }
  731. break;
  732. }
  733. // Set collision group and mask & userdata
  734. if (geometry_)
  735. {
  736. dGeomSetCategoryBits(geometry_, collisionGroup_);
  737. dGeomSetCollideBits(geometry_, collisionMask_);
  738. dGeomSetData(geometry_, this);
  739. }
  740. UpdateTransform();
  741. // If rigid body component exists, let it recalculate its mass now
  742. RigidBody* rigidBody = GetComponent<RigidBody>();
  743. if (rigidBody)
  744. rigidBody->UpdateMass();
  745. }
  746. void CollisionShape::ReleaseGeometry(bool notifyBody)
  747. {
  748. if (geometry_)
  749. {
  750. dGeomDestroy(geometry_);
  751. geometry_ = 0;
  752. }
  753. model_.Reset();
  754. geometryData_.Reset();
  755. if (physicsWorld_)
  756. physicsWorld_->CleanupGeometryCache();
  757. // If rigid body component exists, let it recalculate its mass now
  758. if (notifyBody)
  759. {
  760. RigidBody* rigidBody = GetComponent<RigidBody>();
  761. if (rigidBody)
  762. rigidBody->UpdateMass();
  763. }
  764. }