CollisionShape.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 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 "PhysicsUtils.h"
  31. #include "PhysicsWorld.h"
  32. #include "RigidBody.h"
  33. #include "Scene.h"
  34. #include <BulletCollision/CollisionShapes/btBvhTriangleMeshShape.h>
  35. #include <BulletCollision/CollisionShapes/btTriangleMesh.h>
  36. #include <hull.h>
  37. TriangleMeshData::TriangleMeshData(Model* model, unsigned lodLevel, const Vector3& scale) :
  38. meshData_(0),
  39. shape_(0)
  40. {
  41. modelName_ = model->GetName();
  42. meshData_ = new btTriangleMesh();
  43. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  44. for (unsigned i = 0; i < geometries.Size(); ++i)
  45. {
  46. unsigned subGeometryLodLevel = lodLevel;
  47. if (subGeometryLodLevel >= geometries[i].Size())
  48. subGeometryLodLevel = geometries[i].Size() - 1;
  49. Geometry* geom = geometries[i][subGeometryLodLevel];
  50. if (!geom)
  51. continue;
  52. const unsigned char* vertexData;
  53. const unsigned char* indexData;
  54. unsigned vertexSize;
  55. unsigned indexSize;
  56. geom->GetRawData(vertexData, vertexSize, indexData, indexSize);
  57. if (!vertexData || !indexData)
  58. continue;
  59. unsigned indexStart = geom->GetIndexStart();
  60. unsigned indexCount = geom->GetIndexCount();
  61. // 16-bit indices
  62. if (indexSize == sizeof(unsigned short))
  63. {
  64. const unsigned short* indices = (const unsigned short*)indexData;
  65. for (unsigned j = indexStart; j < indexStart + indexCount; j += 3)
  66. {
  67. const Vector3& v0 = *((const Vector3*)(&vertexData[indices[j] * vertexSize]));
  68. const Vector3& v1 = *((const Vector3*)(&vertexData[indices[j + 1] * vertexSize]));
  69. const Vector3& v2 = *((const Vector3*)(&vertexData[indices[j + 2] * vertexSize]));
  70. meshData_->addTriangle(ToBtVector3(scale * v0), ToBtVector3(scale * v1), ToBtVector3(scale * v2), true);
  71. }
  72. }
  73. // 32-bit indices
  74. else
  75. {
  76. const unsigned* indices = (const unsigned*)indexData;
  77. for (unsigned j = indexStart; j < indexStart + indexCount; j += 3)
  78. {
  79. const Vector3& v0 = *((const Vector3*)(&vertexData[indices[j] * vertexSize]));
  80. const Vector3& v1 = *((const Vector3*)(&vertexData[indices[j + 1] * vertexSize]));
  81. const Vector3& v2 = *((const Vector3*)(&vertexData[indices[j + 2] * vertexSize]));
  82. meshData_->addTriangle(ToBtVector3(scale * v0), ToBtVector3(scale * v1), ToBtVector3(scale * v2), true);
  83. }
  84. }
  85. }
  86. shape_ = new btBvhTriangleMeshShape(meshData_, true, true);
  87. }
  88. TriangleMeshData::~TriangleMeshData()
  89. {
  90. delete shape_;
  91. shape_ = 0;
  92. delete meshData_;
  93. meshData_ = 0;
  94. }
  95. ConvexHullData::ConvexHullData(Model* model, unsigned lodLevel, float thickness, const Vector3& scale)
  96. {
  97. modelName_ = model->GetName();
  98. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  99. PODVector<Vector3> originalVertices;
  100. for (unsigned i = 0; i < geometries.Size(); ++i)
  101. {
  102. unsigned subGeometryLodLevel = lodLevel;
  103. if (subGeometryLodLevel >= geometries[i].Size())
  104. subGeometryLodLevel = geometries[i].Size() - 1;
  105. Geometry* geom = geometries[i][subGeometryLodLevel];
  106. if (!geom)
  107. continue;
  108. const unsigned char* vertexData;
  109. const unsigned char* indexData;
  110. unsigned vertexSize;
  111. unsigned indexSize;
  112. geom->GetRawData(vertexData, vertexSize, indexData, indexSize);
  113. if (!vertexData || !indexData)
  114. continue;
  115. unsigned vertexStart = geom->GetVertexStart();
  116. unsigned vertexCount = geom->GetVertexCount();
  117. // Copy vertex data
  118. for (unsigned j = 0; j < vertexCount; ++j)
  119. {
  120. const Vector3& v = *((const Vector3*)(&vertexData[(vertexStart + j) * vertexSize]));
  121. originalVertices.Push(scale * v);
  122. }
  123. }
  124. if (originalVertices.Size())
  125. {
  126. // Build the convex hull from the raw geometry
  127. StanHull::HullDesc desc;
  128. desc.SetHullFlag(StanHull::QF_TRIANGLES);
  129. desc.mVcount = originalVertices.Size();
  130. desc.mVertices = originalVertices[0].Data();
  131. desc.mVertexStride = 3 * sizeof(float);
  132. desc.mSkinWidth = thickness;
  133. StanHull::HullLibrary lib;
  134. StanHull::HullResult result;
  135. lib.CreateConvexHull(desc, result);
  136. vertexCount_ = result.mNumOutputVertices;
  137. vertexData_ = new Vector3[vertexCount_];
  138. // Copy vertex data
  139. memcpy(vertexData_.Get(), result.mOutputVertices, vertexCount_ * sizeof(Vector3));
  140. lib.ReleaseResult(result);
  141. }
  142. else
  143. vertexCount_ = 0;
  144. }
  145. ConvexHullData::~ConvexHullData()
  146. {
  147. }
  148. HeightfieldData::HeightfieldData(Model* model, IntVector2 numPoints, float thickness, unsigned lodLevel,
  149. const Vector3& scale)
  150. {
  151. modelName_ = model->GetName();
  152. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  153. if (!geometries.Size())
  154. return;
  155. lodLevel = Clamp(lodLevel, 0, geometries[0].Size());
  156. Geometry* geom = geometries[0][lodLevel];
  157. if (!geom)
  158. return;
  159. const unsigned char* vertexData;
  160. const unsigned char* indexData;
  161. unsigned vertexSize;
  162. unsigned indexSize;
  163. geom->GetRawData(vertexData, vertexSize, indexData, indexSize);
  164. if (!vertexData || !indexData)
  165. return;
  166. unsigned indexStart = geom->GetIndexStart();
  167. unsigned indexCount = geom->GetIndexCount();
  168. // If X & Z size not specified, try to guess them
  169. if (numPoints == IntVector2::ZERO)
  170. numPoints.x_ = numPoints.y_ = (int)sqrtf((float)geom->GetVertexCount());
  171. unsigned dataSize = numPoints.x_ * numPoints.y_;
  172. // Then allocate the heightfield
  173. BoundingBox box = model->GetBoundingBox();
  174. heightData_ = new float[dataSize];
  175. // Calculate spacing from model's bounding box
  176. float xSpacing = (box.max_.x_ - box.min_.x_) / (numPoints.x_ - 1);
  177. float zSpacing = (box.max_.z_ - box.min_.z_) / (numPoints.y_ - 1);
  178. // Initialize the heightfield with minimum height
  179. for (unsigned i = 0; i < dataSize; ++i)
  180. heightData_[i] = box.min_.y_ * scale.y_;
  181. unsigned vertexStart = geom->GetVertexStart();
  182. unsigned vertexCount = geom->GetVertexCount();
  183. // Now go through vertex data and fit the vertices into the heightfield
  184. for (unsigned i = vertexStart; i < vertexStart + vertexCount; ++i)
  185. {
  186. const Vector3& vertex = *((const Vector3*)(&vertexData[i * vertexSize]));
  187. int x = (int)((vertex.x_ - box.min_.x_) / xSpacing + 0.25f);
  188. int z = (int)((vertex.z_ - box.min_.z_) / zSpacing + 0.25f);
  189. if (x >= numPoints.x_)
  190. x = numPoints.x_ - 1;
  191. if (z >= numPoints.y_)
  192. z = numPoints.y_ - 1;
  193. if (vertex.y_ > heightData_[z * numPoints.x_ + x])
  194. heightData_[z * numPoints.x_ + x] = vertex.y_ * scale.y_;
  195. }
  196. }
  197. HeightfieldData::~HeightfieldData()
  198. {
  199. }
  200. OBJECTTYPESTATIC(CollisionShape);
  201. CollisionShape::CollisionShape(Context* context) :
  202. Component(context),
  203. shape_(0),
  204. position_(Vector3::ZERO),
  205. rotation_(Quaternion::IDENTITY),
  206. cachedWorldScale_(Vector3::ONE),
  207. dirty_(false)
  208. {
  209. }
  210. CollisionShape::~CollisionShape()
  211. {
  212. delete shape_;
  213. shape_ = 0;
  214. NotifyRigidBody();
  215. if (physicsWorld_)
  216. physicsWorld_->RemoveCollisionShape(this);
  217. }
  218. void CollisionShape::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  219. {
  220. Serializable::OnSetAttribute(attr, src);
  221. dirty_ = true;
  222. }
  223. void CollisionShape::ApplyAttributes()
  224. {
  225. if (dirty_)
  226. {
  227. UpdateCollisionShape();
  228. NotifyRigidBody();
  229. }
  230. }
  231. void CollisionShape::SetPosition(const Vector3& position)
  232. {
  233. if (position != position_)
  234. {
  235. position_ = position;
  236. NotifyRigidBody();
  237. }
  238. }
  239. void CollisionShape::SetRotation(const Quaternion& rotation)
  240. {
  241. if (rotation != rotation_)
  242. {
  243. rotation_ = rotation;
  244. NotifyRigidBody();
  245. }
  246. }
  247. void CollisionShape::SetTransform(const Vector3& position, const Quaternion& rotation)
  248. {
  249. if (position != position_ || rotation != rotation_)
  250. {
  251. position_ = position;
  252. rotation_ = rotation;
  253. NotifyRigidBody();
  254. }
  255. }
  256. void CollisionShape::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  257. {
  258. /// \todo Implement
  259. }
  260. void CollisionShape::OnNodeSet(Node* node)
  261. {
  262. if (node)
  263. {
  264. Scene* scene = node->GetScene();
  265. if (scene)
  266. {
  267. physicsWorld_ = scene->GetComponent<PhysicsWorld>();
  268. if (physicsWorld_)
  269. physicsWorld_->AddCollisionShape(this);
  270. }
  271. node->AddListener(this);
  272. UpdateCollisionShape();
  273. NotifyRigidBody();
  274. }
  275. }
  276. void CollisionShape::OnMarkedDirty(Node* node)
  277. {
  278. Vector3 newWorldScale = node_->GetWorldScale();
  279. if (newWorldScale != cachedWorldScale_)
  280. {
  281. if (shape_)
  282. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  283. NotifyRigidBody();
  284. cachedWorldScale_ = newWorldScale;
  285. }
  286. }
  287. void CollisionShape::NotifyRigidBody()
  288. {
  289. // We need to notify the rigid body also after having been removed from the node, so maintain a weak pointer to it
  290. if (!rigidBody_)
  291. rigidBody_ = GetComponent<RigidBody>();
  292. if (rigidBody_)
  293. rigidBody_->RefreshCollisionShapes();
  294. dirty_ = false;
  295. }