MultiDofDemo.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. #include "MultiDofDemo.h"
  2. #include "../OpenGLWindow/SimpleOpenGL3App.h"
  3. #include "btBulletDynamicsCommon.h"
  4. #include "BulletDynamics/MLCPSolvers/btDantzigSolver.h"
  5. #include "BulletDynamics/MLCPSolvers/btLemkeSolver.h"
  6. #include "BulletDynamics/MLCPSolvers/btSolveProjectedGaussSeidel.h"
  7. #include "BulletDynamics/Featherstone/btMultiBody.h"
  8. #include "BulletDynamics/Featherstone/btMultiBodyConstraintSolver.h"
  9. #include "BulletDynamics/Featherstone/btMultiBodyMLCPConstraintSolver.h"
  10. #include "BulletDynamics/Featherstone/btMultiBodyDynamicsWorld.h"
  11. #include "BulletDynamics/Featherstone/btMultiBodyLinkCollider.h"
  12. #include "BulletDynamics/Featherstone/btMultiBodyLink.h"
  13. #include "BulletDynamics/Featherstone/btMultiBodyJointLimitConstraint.h"
  14. #include "BulletDynamics/Featherstone/btMultiBodyJointMotor.h"
  15. #include "BulletDynamics/Featherstone/btMultiBodyPoint2Point.h"
  16. #include "BulletDynamics/Featherstone/btMultiBodyFixedConstraint.h"
  17. #include "BulletDynamics/Featherstone/btMultiBodySliderConstraint.h"
  18. #include "../OpenGLWindow/GLInstancingRenderer.h"
  19. #include "BulletCollision/CollisionShapes/btShapeHull.h"
  20. #include "../CommonInterfaces/CommonMultiBodyBase.h"
  21. class MultiDofDemo : public CommonMultiBodyBase
  22. {
  23. public:
  24. MultiDofDemo(GUIHelperInterface* helper);
  25. virtual ~MultiDofDemo();
  26. virtual void initPhysics();
  27. virtual void stepSimulation(float deltaTime);
  28. virtual void resetCamera()
  29. {
  30. float dist = 1;
  31. float pitch = -35;
  32. float yaw = 50;
  33. float targetPos[3] = {-3, 2.8, -2.5};
  34. m_guiHelper->resetCamera(dist, yaw, pitch, targetPos[0], targetPos[1], targetPos[2]);
  35. }
  36. btMultiBody* createFeatherstoneMultiBody_testMultiDof(class btMultiBodyDynamicsWorld* world, int numLinks, const btVector3& basePosition, const btVector3& baseHalfExtents, const btVector3& linkHalfExtents, bool spherical = false, bool floating = false);
  37. void addColliders_testMultiDof(btMultiBody* pMultiBody, btMultiBodyDynamicsWorld* pWorld, const btVector3& baseHalfExtents, const btVector3& linkHalfExtents);
  38. void addBoxes_testMultiDof();
  39. };
  40. static bool g_floatingBase = false;
  41. static bool g_firstInit = true;
  42. static float scaling = 0.4f;
  43. static float friction = 1.;
  44. static int g_constraintSolverType = 0;
  45. #define ARRAY_SIZE_X 5
  46. #define ARRAY_SIZE_Y 5
  47. #define ARRAY_SIZE_Z 5
  48. //maximum number of objects (and allow user to shoot additional boxes)
  49. #define MAX_PROXIES (ARRAY_SIZE_X * ARRAY_SIZE_Y * ARRAY_SIZE_Z + 1024)
  50. #define START_POS_X -5
  51. //#define START_POS_Y 12
  52. #define START_POS_Y 2
  53. #define START_POS_Z -3
  54. MultiDofDemo::MultiDofDemo(GUIHelperInterface* helper)
  55. : CommonMultiBodyBase(helper)
  56. {
  57. m_guiHelper->setUpAxis(1);
  58. }
  59. MultiDofDemo::~MultiDofDemo()
  60. {
  61. }
  62. void MultiDofDemo::stepSimulation(float deltaTime)
  63. {
  64. //use a smaller internal timestep, there are stability issues
  65. float internalTimeStep = 1. / 240.f;
  66. m_dynamicsWorld->stepSimulation(deltaTime, 10, internalTimeStep);
  67. }
  68. void MultiDofDemo::initPhysics()
  69. {
  70. m_guiHelper->setUpAxis(1);
  71. if (g_firstInit)
  72. {
  73. m_guiHelper->getRenderInterface()->getActiveCamera()->setCameraDistance(btScalar(10. * scaling));
  74. m_guiHelper->getRenderInterface()->getActiveCamera()->setCameraPitch(50);
  75. g_firstInit = false;
  76. }
  77. ///collision configuration contains default setup for memory, collision setup
  78. m_collisionConfiguration = new btDefaultCollisionConfiguration();
  79. ///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded)
  80. m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration);
  81. m_broadphase = new btDbvtBroadphase();
  82. if (g_constraintSolverType == 4)
  83. {
  84. g_constraintSolverType = 0;
  85. g_floatingBase = !g_floatingBase;
  86. }
  87. btMultiBodyConstraintSolver* sol;
  88. btMLCPSolverInterface* mlcp;
  89. switch (g_constraintSolverType++)
  90. {
  91. case 0:
  92. sol = new btMultiBodyConstraintSolver;
  93. b3Printf("Constraint Solver: Sequential Impulse");
  94. break;
  95. case 1:
  96. mlcp = new btSolveProjectedGaussSeidel();
  97. sol = new btMultiBodyMLCPConstraintSolver(mlcp);
  98. b3Printf("Constraint Solver: MLCP + PGS");
  99. break;
  100. case 2:
  101. mlcp = new btDantzigSolver();
  102. sol = new btMultiBodyMLCPConstraintSolver(mlcp);
  103. b3Printf("Constraint Solver: MLCP + Dantzig");
  104. break;
  105. default:
  106. mlcp = new btLemkeSolver();
  107. sol = new btMultiBodyMLCPConstraintSolver(mlcp);
  108. b3Printf("Constraint Solver: MLCP + Lemke");
  109. break;
  110. }
  111. m_solver = sol;
  112. //use btMultiBodyDynamicsWorld for Featherstone btMultiBody support
  113. btMultiBodyDynamicsWorld* world = new btMultiBodyDynamicsWorld(m_dispatcher, m_broadphase, sol, m_collisionConfiguration);
  114. m_dynamicsWorld = world;
  115. // m_dynamicsWorld->setDebugDrawer(&gDebugDraw);
  116. m_guiHelper->createPhysicsDebugDrawer(m_dynamicsWorld);
  117. m_dynamicsWorld->setGravity(btVector3(0, -10, 0));
  118. m_dynamicsWorld->getSolverInfo().m_globalCfm = 1e-3;
  119. ///create a few basic rigid bodies
  120. btVector3 groundHalfExtents(50, 50, 50);
  121. btCollisionShape* groundShape = new btBoxShape(groundHalfExtents);
  122. //groundShape->initializePolyhedralFeatures();
  123. // btCollisionShape* groundShape = new btStaticPlaneShape(btVector3(0,1,0),50);
  124. m_collisionShapes.push_back(groundShape);
  125. btTransform groundTransform;
  126. groundTransform.setIdentity();
  127. groundTransform.setOrigin(btVector3(0, -50, 00));
  128. /////////////////////////////////////////////////////////////////
  129. /////////////////////////////////////////////////////////////////
  130. bool damping = true;
  131. bool gyro = true;
  132. int numLinks = 5;
  133. bool spherical = true; //set it ot false -to use 1DoF hinges instead of 3DoF sphericals
  134. bool multibodyOnly = false;
  135. bool canSleep = false;
  136. bool selfCollide = true;
  137. bool multibodyConstraint = false;
  138. btVector3 linkHalfExtents(0.05, 0.37, 0.1);
  139. btVector3 baseHalfExtents(0.05, 0.37, 0.1);
  140. btMultiBody* mbC = createFeatherstoneMultiBody_testMultiDof(world, numLinks, btVector3(-0.4f, 3.f, 0.f), baseHalfExtents, linkHalfExtents, spherical, g_floatingBase);
  141. //mbC->forceMultiDof(); //if !spherical, you can comment this line to check the 1DoF algorithm
  142. mbC->setCanSleep(canSleep);
  143. mbC->setHasSelfCollision(selfCollide);
  144. mbC->setUseGyroTerm(gyro);
  145. //
  146. if (!damping)
  147. {
  148. mbC->setLinearDamping(0.f);
  149. mbC->setAngularDamping(0.f);
  150. }
  151. else
  152. {
  153. mbC->setLinearDamping(0.1f);
  154. mbC->setAngularDamping(0.9f);
  155. }
  156. //
  157. m_dynamicsWorld->setGravity(btVector3(0, -9.81, 0));
  158. //m_dynamicsWorld->getSolverInfo().m_numIterations = 100;
  159. //////////////////////////////////////////////
  160. if (numLinks > 0)
  161. {
  162. btScalar q0 = 45.f * SIMD_PI / 180.f;
  163. if (!spherical)
  164. {
  165. mbC->setJointPosMultiDof(0, &q0);
  166. }
  167. else
  168. {
  169. btQuaternion quat0(btVector3(1, 1, 0).normalized(), q0);
  170. quat0.normalize();
  171. mbC->setJointPosMultiDof(0, quat0);
  172. }
  173. }
  174. ///
  175. addColliders_testMultiDof(mbC, world, baseHalfExtents, linkHalfExtents);
  176. /////////////////////////////////////////////////////////////////
  177. btScalar groundHeight = -51.55;
  178. if (!multibodyOnly)
  179. {
  180. btScalar mass(0.);
  181. //rigidbody is dynamic if and only if mass is non zero, otherwise static
  182. bool isDynamic = (mass != 0.f);
  183. btVector3 localInertia(0, 0, 0);
  184. if (isDynamic)
  185. groundShape->calculateLocalInertia(mass, localInertia);
  186. //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
  187. groundTransform.setIdentity();
  188. groundTransform.setOrigin(btVector3(0, groundHeight, 0));
  189. btDefaultMotionState* myMotionState = new btDefaultMotionState(groundTransform);
  190. btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, groundShape, localInertia);
  191. btRigidBody* body = new btRigidBody(rbInfo);
  192. //add the body to the dynamics world
  193. m_dynamicsWorld->addRigidBody(body, 1, 1 + 2); //,1,1+2);
  194. }
  195. /////////////////////////////////////////////////////////////////
  196. if (!multibodyOnly)
  197. {
  198. btVector3 halfExtents(.5, .5, .5);
  199. btBoxShape* colShape = new btBoxShape(halfExtents);
  200. //btCollisionShape* colShape = new btSphereShape(btScalar(1.));
  201. m_collisionShapes.push_back(colShape);
  202. /// Create Dynamic Objects
  203. btTransform startTransform;
  204. startTransform.setIdentity();
  205. btScalar mass(1.f);
  206. //rigidbody is dynamic if and only if mass is non zero, otherwise static
  207. bool isDynamic = (mass != 0.f);
  208. btVector3 localInertia(0, 0, 0);
  209. if (isDynamic)
  210. colShape->calculateLocalInertia(mass, localInertia);
  211. startTransform.setOrigin(btVector3(
  212. btScalar(0.0),
  213. 0.0,
  214. btScalar(0.0)));
  215. //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
  216. btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
  217. btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, colShape, localInertia);
  218. btRigidBody* body = new btRigidBody(rbInfo);
  219. m_dynamicsWorld->addRigidBody(body); //,1,1+2);
  220. if (multibodyConstraint)
  221. {
  222. btVector3 pointInA = -linkHalfExtents;
  223. // btVector3 pointInB = halfExtents;
  224. btMatrix3x3 frameInA;
  225. btMatrix3x3 frameInB;
  226. frameInA.setIdentity();
  227. frameInB.setIdentity();
  228. btVector3 jointAxis(1.0, 0.0, 0.0);
  229. //btMultiBodySliderConstraint* p2p = new btMultiBodySliderConstraint(mbC,numLinks-1,body,pointInA,pointInB,frameInA,frameInB,jointAxis);
  230. btMultiBodyFixedConstraint* p2p = new btMultiBodyFixedConstraint(mbC, numLinks - 1, mbC, numLinks - 4, pointInA, pointInA, frameInA, frameInB);
  231. p2p->setMaxAppliedImpulse(2.0);
  232. m_dynamicsWorld->addMultiBodyConstraint(p2p);
  233. }
  234. }
  235. m_guiHelper->autogenerateGraphicsObjects(m_dynamicsWorld);
  236. /////////////////////////////////////////////////////////////////
  237. }
  238. btMultiBody* MultiDofDemo::createFeatherstoneMultiBody_testMultiDof(btMultiBodyDynamicsWorld* pWorld, int numLinks, const btVector3& basePosition, const btVector3& baseHalfExtents, const btVector3& linkHalfExtents, bool spherical, bool floating)
  239. {
  240. //init the base
  241. btVector3 baseInertiaDiag(0.f, 0.f, 0.f);
  242. float baseMass = 1.f;
  243. if (baseMass)
  244. {
  245. btCollisionShape* pTempBox = new btBoxShape(btVector3(baseHalfExtents[0], baseHalfExtents[1], baseHalfExtents[2]));
  246. pTempBox->calculateLocalInertia(baseMass, baseInertiaDiag);
  247. delete pTempBox;
  248. }
  249. bool canSleep = false;
  250. btMultiBody* pMultiBody = new btMultiBody(numLinks, baseMass, baseInertiaDiag, !floating, canSleep);
  251. btQuaternion baseOriQuat(0.f, 0.f, 0.f, 1.f);
  252. pMultiBody->setBasePos(basePosition);
  253. pMultiBody->setWorldToBaseRot(baseOriQuat);
  254. btVector3 vel(0, 0, 0);
  255. // pMultiBody->setBaseVel(vel);
  256. //init the links
  257. btVector3 hingeJointAxis(1, 0, 0);
  258. float linkMass = 1.f;
  259. btVector3 linkInertiaDiag(0.f, 0.f, 0.f);
  260. btCollisionShape* pTempBox = new btBoxShape(btVector3(linkHalfExtents[0], linkHalfExtents[1], linkHalfExtents[2]));
  261. pTempBox->calculateLocalInertia(linkMass, linkInertiaDiag);
  262. delete pTempBox;
  263. //y-axis assumed up
  264. btVector3 parentComToCurrentCom(0, -linkHalfExtents[1] * 2.f, 0); //par body's COM to cur body's COM offset
  265. btVector3 currentPivotToCurrentCom(0, -linkHalfExtents[1], 0); //cur body's COM to cur body's PIV offset
  266. btVector3 parentComToCurrentPivot = parentComToCurrentCom - currentPivotToCurrentCom; //par body's COM to cur body's PIV offset
  267. //////
  268. btScalar q0 = 0.f * SIMD_PI / 180.f;
  269. btQuaternion quat0(btVector3(0, 1, 0).normalized(), q0);
  270. quat0.normalize();
  271. /////
  272. for (int i = 0; i < numLinks; ++i)
  273. {
  274. if (!spherical)
  275. pMultiBody->setupRevolute(i, linkMass, linkInertiaDiag, i - 1, btQuaternion(0.f, 0.f, 0.f, 1.f), hingeJointAxis, parentComToCurrentPivot, currentPivotToCurrentCom, true);
  276. else
  277. //pMultiBody->setupPlanar(i, linkMass, linkInertiaDiag, i - 1, btQuaternion(0.f, 0.f, 0.f, 1.f)/*quat0*/, btVector3(1, 0, 0), parentComToCurrentPivot*2, false);
  278. pMultiBody->setupSpherical(i, linkMass, linkInertiaDiag, i - 1, btQuaternion(0.f, 0.f, 0.f, 1.f), parentComToCurrentPivot, currentPivotToCurrentCom, true);
  279. }
  280. pMultiBody->finalizeMultiDof();
  281. ///
  282. pWorld->addMultiBody(pMultiBody);
  283. ///
  284. return pMultiBody;
  285. }
  286. void MultiDofDemo::addColliders_testMultiDof(btMultiBody* pMultiBody, btMultiBodyDynamicsWorld* pWorld, const btVector3& baseHalfExtents, const btVector3& linkHalfExtents)
  287. {
  288. btAlignedObjectArray<btQuaternion> world_to_local;
  289. world_to_local.resize(pMultiBody->getNumLinks() + 1);
  290. btAlignedObjectArray<btVector3> local_origin;
  291. local_origin.resize(pMultiBody->getNumLinks() + 1);
  292. world_to_local[0] = pMultiBody->getWorldToBaseRot();
  293. local_origin[0] = pMultiBody->getBasePos();
  294. {
  295. // float pos[4]={local_origin[0].x(),local_origin[0].y(),local_origin[0].z(),1};
  296. btScalar quat[4] = {-world_to_local[0].x(), -world_to_local[0].y(), -world_to_local[0].z(), world_to_local[0].w()};
  297. if (1)
  298. {
  299. btCollisionShape* box = new btBoxShape(baseHalfExtents);
  300. btMultiBodyLinkCollider* col = new btMultiBodyLinkCollider(pMultiBody, -1);
  301. col->setCollisionShape(box);
  302. btTransform tr;
  303. tr.setIdentity();
  304. tr.setOrigin(local_origin[0]);
  305. tr.setRotation(btQuaternion(quat[0], quat[1], quat[2], quat[3]));
  306. col->setWorldTransform(tr);
  307. pWorld->addCollisionObject(col, 2, 1 + 2);
  308. col->setFriction(friction);
  309. pMultiBody->setBaseCollider(col);
  310. }
  311. }
  312. for (int i = 0; i < pMultiBody->getNumLinks(); ++i)
  313. {
  314. const int parent = pMultiBody->getParent(i);
  315. world_to_local[i + 1] = pMultiBody->getParentToLocalRot(i) * world_to_local[parent + 1];
  316. local_origin[i + 1] = local_origin[parent + 1] + (quatRotate(world_to_local[i + 1].inverse(), pMultiBody->getRVector(i)));
  317. }
  318. for (int i = 0; i < pMultiBody->getNumLinks(); ++i)
  319. {
  320. btVector3 posr = local_origin[i + 1];
  321. // float pos[4]={posr.x(),posr.y(),posr.z(),1};
  322. btScalar quat[4] = {-world_to_local[i + 1].x(), -world_to_local[i + 1].y(), -world_to_local[i + 1].z(), world_to_local[i + 1].w()};
  323. btCollisionShape* box = new btBoxShape(linkHalfExtents);
  324. btMultiBodyLinkCollider* col = new btMultiBodyLinkCollider(pMultiBody, i);
  325. col->setCollisionShape(box);
  326. btTransform tr;
  327. tr.setIdentity();
  328. tr.setOrigin(posr);
  329. tr.setRotation(btQuaternion(quat[0], quat[1], quat[2], quat[3]));
  330. col->setWorldTransform(tr);
  331. col->setFriction(friction);
  332. pWorld->addCollisionObject(col, 2, 1 + 2);
  333. pMultiBody->getLink(i).m_collider = col;
  334. }
  335. }
  336. void MultiDofDemo::addBoxes_testMultiDof()
  337. {
  338. //create a few dynamic rigidbodies
  339. // Re-using the same collision is better for memory usage and performance
  340. btBoxShape* colShape = new btBoxShape(btVector3(1, 1, 1));
  341. //btCollisionShape* colShape = new btSphereShape(btScalar(1.));
  342. m_collisionShapes.push_back(colShape);
  343. /// Create Dynamic Objects
  344. btTransform startTransform;
  345. startTransform.setIdentity();
  346. btScalar mass(1.f);
  347. //rigidbody is dynamic if and only if mass is non zero, otherwise static
  348. bool isDynamic = (mass != 0.f);
  349. btVector3 localInertia(0, 0, 0);
  350. if (isDynamic)
  351. colShape->calculateLocalInertia(mass, localInertia);
  352. float start_x = START_POS_X - ARRAY_SIZE_X / 2;
  353. float start_y = START_POS_Y;
  354. float start_z = START_POS_Z - ARRAY_SIZE_Z / 2;
  355. for (int k = 0; k < ARRAY_SIZE_Y; k++)
  356. {
  357. for (int i = 0; i < ARRAY_SIZE_X; i++)
  358. {
  359. for (int j = 0; j < ARRAY_SIZE_Z; j++)
  360. {
  361. startTransform.setOrigin(btVector3(
  362. btScalar(3.0 * i + start_x),
  363. btScalar(3.0 * k + start_y),
  364. btScalar(3.0 * j + start_z)));
  365. //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
  366. btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
  367. btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, colShape, localInertia);
  368. btRigidBody* body = new btRigidBody(rbInfo);
  369. m_dynamicsWorld->addRigidBody(body); //,1,1+2);
  370. }
  371. }
  372. }
  373. }
  374. class CommonExampleInterface* MultiDofCreateFunc(struct CommonExampleOptions& options)
  375. {
  376. return new MultiDofDemo(options.m_guiHelper);
  377. }