btSoftMultiBodyDynamicsWorld.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. /*
  2. Bullet Continuous Collision Detection and Physics Library
  3. Copyright (c) 2003-2006 Erwin Coumans https://bulletphysics.org
  4. This software is provided 'as-is', without any express or implied warranty.
  5. In no event will the authors be held liable for any damages arising from the use of this software.
  6. Permission is granted to anyone to use this software for any purpose,
  7. including commercial applications, and to alter it and redistribute it freely,
  8. subject to the following restrictions:
  9. 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
  10. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  11. 3. This notice may not be removed or altered from any source distribution.
  12. */
  13. #include "btSoftMultiBodyDynamicsWorld.h"
  14. #include "LinearMath/btQuickprof.h"
  15. //softbody & helpers
  16. #include "BulletSoftBody/btSoftBody.h"
  17. #include "BulletSoftBody/btSoftBodyHelpers.h"
  18. #include "BulletSoftBody/btSoftBodySolvers.h"
  19. #include "BulletSoftBody/btDefaultSoftBodySolver.h"
  20. #include "LinearMath/btSerializer.h"
  21. btSoftMultiBodyDynamicsWorld::btSoftMultiBodyDynamicsWorld(
  22. btDispatcher* dispatcher,
  23. btBroadphaseInterface* pairCache,
  24. btMultiBodyConstraintSolver* constraintSolver,
  25. btCollisionConfiguration* collisionConfiguration,
  26. btSoftBodySolver* softBodySolver) : btMultiBodyDynamicsWorld(dispatcher, pairCache, constraintSolver, collisionConfiguration),
  27. m_softBodySolver(softBodySolver),
  28. m_ownsSolver(false)
  29. {
  30. if (!m_softBodySolver)
  31. {
  32. void* ptr = btAlignedAlloc(sizeof(btDefaultSoftBodySolver), 16);
  33. m_softBodySolver = new (ptr) btDefaultSoftBodySolver();
  34. m_ownsSolver = true;
  35. }
  36. m_drawFlags = fDrawFlags::Std;
  37. m_drawNodeTree = true;
  38. m_drawFaceTree = false;
  39. m_drawClusterTree = false;
  40. m_sbi.m_broadphase = pairCache;
  41. m_sbi.m_dispatcher = dispatcher;
  42. m_sbi.m_sparsesdf.Initialize();
  43. m_sbi.m_sparsesdf.Reset();
  44. m_sbi.air_density = (btScalar)1.2;
  45. m_sbi.water_density = 0;
  46. m_sbi.water_offset = 0;
  47. m_sbi.water_normal = btVector3(0, 0, 0);
  48. m_sbi.m_gravity.setValue(0, -10, 0);
  49. m_sbi.m_sparsesdf.Initialize();
  50. }
  51. btSoftMultiBodyDynamicsWorld::~btSoftMultiBodyDynamicsWorld()
  52. {
  53. if (m_ownsSolver)
  54. {
  55. m_softBodySolver->~btSoftBodySolver();
  56. btAlignedFree(m_softBodySolver);
  57. }
  58. }
  59. void btSoftMultiBodyDynamicsWorld::predictUnconstraintMotion(btScalar timeStep)
  60. {
  61. btDiscreteDynamicsWorld::predictUnconstraintMotion(timeStep);
  62. {
  63. BT_PROFILE("predictUnconstraintMotionSoftBody");
  64. m_softBodySolver->predictMotion(float(timeStep));
  65. }
  66. }
  67. void btSoftMultiBodyDynamicsWorld::internalSingleStepSimulation(btScalar timeStep)
  68. {
  69. // Let the solver grab the soft bodies and if necessary optimize for it
  70. m_softBodySolver->optimize(getSoftBodyArray());
  71. if (!m_softBodySolver->checkInitialized())
  72. {
  73. btAssert("Solver initialization failed\n");
  74. }
  75. btDiscreteDynamicsWorld::internalSingleStepSimulation(timeStep);
  76. ///solve soft bodies constraints
  77. solveSoftBodiesConstraints(timeStep);
  78. //self collisions
  79. for (int i = 0; i < m_softBodies.size(); i++)
  80. {
  81. btSoftBody* psb = (btSoftBody*)m_softBodies[i];
  82. psb->defaultCollisionHandler(psb);
  83. }
  84. ///update soft bodies
  85. m_softBodySolver->updateSoftBodies();
  86. for (int i = 0; i < m_softBodies.size(); i++)
  87. {
  88. btSoftBody* psb = (btSoftBody*)m_softBodies[i];
  89. psb->interpolateRenderMesh();
  90. }
  91. // End solver-wise simulation step
  92. // ///////////////////////////////
  93. }
  94. void btSoftMultiBodyDynamicsWorld::solveSoftBodiesConstraints(btScalar timeStep)
  95. {
  96. BT_PROFILE("solveSoftConstraints");
  97. if (m_softBodies.size())
  98. {
  99. btSoftBody::solveClusters(m_softBodies);
  100. }
  101. // Solve constraints solver-wise
  102. m_softBodySolver->solveConstraints(timeStep * m_softBodySolver->getTimeScale());
  103. }
  104. void btSoftMultiBodyDynamicsWorld::addSoftBody(btSoftBody* body, int collisionFilterGroup, int collisionFilterMask)
  105. {
  106. m_softBodies.push_back(body);
  107. // Set the soft body solver that will deal with this body
  108. // to be the world's solver
  109. body->setSoftBodySolver(m_softBodySolver);
  110. btCollisionWorld::addCollisionObject(body,
  111. collisionFilterGroup,
  112. collisionFilterMask);
  113. }
  114. void btSoftMultiBodyDynamicsWorld::removeSoftBody(btSoftBody* body)
  115. {
  116. m_softBodies.remove(body);
  117. btCollisionWorld::removeCollisionObject(body);
  118. }
  119. void btSoftMultiBodyDynamicsWorld::removeCollisionObject(btCollisionObject* collisionObject)
  120. {
  121. btSoftBody* body = btSoftBody::upcast(collisionObject);
  122. if (body)
  123. removeSoftBody(body);
  124. else
  125. btDiscreteDynamicsWorld::removeCollisionObject(collisionObject);
  126. }
  127. void btSoftMultiBodyDynamicsWorld::debugDrawWorld()
  128. {
  129. btMultiBodyDynamicsWorld::debugDrawWorld();
  130. if (getDebugDrawer())
  131. {
  132. int i;
  133. for (i = 0; i < this->m_softBodies.size(); i++)
  134. {
  135. btSoftBody* psb = (btSoftBody*)this->m_softBodies[i];
  136. if (getDebugDrawer() && (getDebugDrawer()->getDebugMode() & (btIDebugDraw::DBG_DrawWireframe)))
  137. {
  138. btSoftBodyHelpers::DrawFrame(psb, m_debugDrawer);
  139. btSoftBodyHelpers::Draw(psb, m_debugDrawer, m_drawFlags);
  140. }
  141. if (m_debugDrawer && (m_debugDrawer->getDebugMode() & btIDebugDraw::DBG_DrawAabb))
  142. {
  143. if (m_drawNodeTree) btSoftBodyHelpers::DrawNodeTree(psb, m_debugDrawer);
  144. if (m_drawFaceTree) btSoftBodyHelpers::DrawFaceTree(psb, m_debugDrawer);
  145. if (m_drawClusterTree) btSoftBodyHelpers::DrawClusterTree(psb, m_debugDrawer);
  146. }
  147. }
  148. }
  149. }
  150. struct btSoftSingleRayCallback : public btBroadphaseRayCallback
  151. {
  152. btVector3 m_rayFromWorld;
  153. btVector3 m_rayToWorld;
  154. btTransform m_rayFromTrans;
  155. btTransform m_rayToTrans;
  156. btVector3 m_hitNormal;
  157. const btSoftMultiBodyDynamicsWorld* m_world;
  158. btCollisionWorld::RayResultCallback& m_resultCallback;
  159. btSoftSingleRayCallback(const btVector3& rayFromWorld, const btVector3& rayToWorld, const btSoftMultiBodyDynamicsWorld* world, btCollisionWorld::RayResultCallback& resultCallback)
  160. : m_rayFromWorld(rayFromWorld),
  161. m_rayToWorld(rayToWorld),
  162. m_world(world),
  163. m_resultCallback(resultCallback)
  164. {
  165. m_rayFromTrans.setIdentity();
  166. m_rayFromTrans.setOrigin(m_rayFromWorld);
  167. m_rayToTrans.setIdentity();
  168. m_rayToTrans.setOrigin(m_rayToWorld);
  169. btVector3 rayDir = (rayToWorld - rayFromWorld);
  170. rayDir.normalize();
  171. ///what about division by zero? --> just set rayDirection[i] to INF/1e30
  172. m_rayDirectionInverse[0] = rayDir[0] == btScalar(0.0) ? btScalar(1e30) : btScalar(1.0) / rayDir[0];
  173. m_rayDirectionInverse[1] = rayDir[1] == btScalar(0.0) ? btScalar(1e30) : btScalar(1.0) / rayDir[1];
  174. m_rayDirectionInverse[2] = rayDir[2] == btScalar(0.0) ? btScalar(1e30) : btScalar(1.0) / rayDir[2];
  175. m_signs[0] = m_rayDirectionInverse[0] < 0.0;
  176. m_signs[1] = m_rayDirectionInverse[1] < 0.0;
  177. m_signs[2] = m_rayDirectionInverse[2] < 0.0;
  178. m_lambda_max = rayDir.dot(m_rayToWorld - m_rayFromWorld);
  179. }
  180. virtual bool process(const btBroadphaseProxy* proxy)
  181. {
  182. ///terminate further ray tests, once the closestHitFraction reached zero
  183. if (m_resultCallback.m_closestHitFraction == btScalar(0.f))
  184. return false;
  185. btCollisionObject* collisionObject = (btCollisionObject*)proxy->m_clientObject;
  186. //only perform raycast if filterMask matches
  187. if (m_resultCallback.needsCollision(collisionObject->getBroadphaseHandle()))
  188. {
  189. //RigidcollisionObject* collisionObject = ctrl->GetRigidcollisionObject();
  190. //btVector3 collisionObjectAabbMin,collisionObjectAabbMax;
  191. #if 0
  192. #ifdef RECALCULATE_AABB
  193. btVector3 collisionObjectAabbMin,collisionObjectAabbMax;
  194. collisionObject->getCollisionShape()->getAabb(collisionObject->getWorldTransform(),collisionObjectAabbMin,collisionObjectAabbMax);
  195. #else
  196. //getBroadphase()->getAabb(collisionObject->getBroadphaseHandle(),collisionObjectAabbMin,collisionObjectAabbMax);
  197. const btVector3& collisionObjectAabbMin = collisionObject->getBroadphaseHandle()->m_aabbMin;
  198. const btVector3& collisionObjectAabbMax = collisionObject->getBroadphaseHandle()->m_aabbMax;
  199. #endif
  200. #endif
  201. //btScalar hitLambda = m_resultCallback.m_closestHitFraction;
  202. //culling already done by broadphase
  203. //if (btRayAabb(m_rayFromWorld,m_rayToWorld,collisionObjectAabbMin,collisionObjectAabbMax,hitLambda,m_hitNormal))
  204. {
  205. m_world->rayTestSingle(m_rayFromTrans, m_rayToTrans,
  206. collisionObject,
  207. collisionObject->getCollisionShape(),
  208. collisionObject->getWorldTransform(),
  209. m_resultCallback);
  210. }
  211. }
  212. return true;
  213. }
  214. };
  215. void btSoftMultiBodyDynamicsWorld::rayTest(const btVector3& rayFromWorld, const btVector3& rayToWorld, RayResultCallback& resultCallback) const
  216. {
  217. BT_PROFILE("rayTest");
  218. /// use the broadphase to accelerate the search for objects, based on their aabb
  219. /// and for each object with ray-aabb overlap, perform an exact ray test
  220. btSoftSingleRayCallback rayCB(rayFromWorld, rayToWorld, this, resultCallback);
  221. #ifndef USE_BRUTEFORCE_RAYBROADPHASE
  222. m_broadphasePairCache->rayTest(rayFromWorld, rayToWorld, rayCB);
  223. #else
  224. for (int i = 0; i < this->getNumCollisionObjects(); i++)
  225. {
  226. rayCB.process(m_collisionObjects[i]->getBroadphaseHandle());
  227. }
  228. #endif //USE_BRUTEFORCE_RAYBROADPHASE
  229. }
  230. void btSoftMultiBodyDynamicsWorld::rayTestSingle(const btTransform& rayFromTrans, const btTransform& rayToTrans,
  231. btCollisionObject* collisionObject,
  232. const btCollisionShape* collisionShape,
  233. const btTransform& colObjWorldTransform,
  234. RayResultCallback& resultCallback)
  235. {
  236. if (collisionShape->isSoftBody())
  237. {
  238. btSoftBody* softBody = btSoftBody::upcast(collisionObject);
  239. if (softBody)
  240. {
  241. btSoftBody::sRayCast softResult;
  242. if (softBody->rayTest(rayFromTrans.getOrigin(), rayToTrans.getOrigin(), softResult))
  243. {
  244. if (softResult.fraction <= resultCallback.m_closestHitFraction)
  245. {
  246. btCollisionWorld::LocalShapeInfo shapeInfo;
  247. shapeInfo.m_shapePart = 0;
  248. shapeInfo.m_triangleIndex = softResult.index;
  249. // get the normal
  250. btVector3 rayDir = rayToTrans.getOrigin() - rayFromTrans.getOrigin();
  251. btVector3 normal = -rayDir;
  252. normal.normalize();
  253. if (softResult.feature == btSoftBody::eFeature::Face)
  254. {
  255. normal = softBody->m_faces[softResult.index].m_normal;
  256. if (normal.dot(rayDir) > 0)
  257. {
  258. // normal always point toward origin of the ray
  259. normal = -normal;
  260. }
  261. }
  262. btCollisionWorld::LocalRayResult rayResult(collisionObject,
  263. &shapeInfo,
  264. normal,
  265. softResult.fraction);
  266. bool normalInWorldSpace = true;
  267. resultCallback.addSingleResult(rayResult, normalInWorldSpace);
  268. }
  269. }
  270. }
  271. }
  272. else
  273. {
  274. btCollisionWorld::rayTestSingle(rayFromTrans, rayToTrans, collisionObject, collisionShape, colObjWorldTransform, resultCallback);
  275. }
  276. }
  277. void btSoftMultiBodyDynamicsWorld::serializeSoftBodies(btSerializer* serializer)
  278. {
  279. int i;
  280. //serialize all collision objects
  281. for (i = 0; i < m_collisionObjects.size(); i++)
  282. {
  283. btCollisionObject* colObj = m_collisionObjects[i];
  284. if (colObj->getInternalType() & btCollisionObject::CO_SOFT_BODY)
  285. {
  286. int len = colObj->calculateSerializeBufferSize();
  287. btChunk* chunk = serializer->allocate(len, 1);
  288. const char* structType = colObj->serialize(chunk->m_oldPtr, serializer);
  289. serializer->finalizeChunk(chunk, structType, BT_SOFTBODY_CODE, colObj);
  290. }
  291. }
  292. }
  293. void btSoftMultiBodyDynamicsWorld::serialize(btSerializer* serializer)
  294. {
  295. serializer->startSerialization();
  296. serializeDynamicsWorldInfo(serializer);
  297. serializeSoftBodies(serializer);
  298. serializeMultiBodies(serializer);
  299. serializeRigidBodies(serializer);
  300. serializeCollisionObjects(serializer);
  301. serializeContactManifolds(serializer);
  302. serializer->finishSerialization();
  303. }