MotorDemo.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. /*
  2. Bullet Continuous Collision Detection and Physics Library Copyright (c) 2007 Erwin Coumans
  3. Motor Demo
  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 "btBulletDynamicsCommon.h"
  14. #include "LinearMath/btIDebugDraw.h"
  15. #include "MotorDemo.h"
  16. #include <cmath>
  17. #include "LinearMath/btAlignedObjectArray.h"
  18. class btBroadphaseInterface;
  19. class btCollisionShape;
  20. class btOverlappingPairCache;
  21. class btCollisionDispatcher;
  22. class btConstraintSolver;
  23. struct btCollisionAlgorithmCreateFunc;
  24. class btDefaultCollisionConfiguration;
  25. #include "../CommonInterfaces/CommonRigidBodyBase.h"
  26. class MotorDemo : public CommonRigidBodyBase
  27. {
  28. float m_Time;
  29. float m_fCyclePeriod; // in milliseconds
  30. float m_fMuscleStrength;
  31. btAlignedObjectArray<class TestRig*> m_rigs;
  32. public:
  33. MotorDemo(struct GUIHelperInterface* helper)
  34. : CommonRigidBodyBase(helper)
  35. {
  36. }
  37. void initPhysics();
  38. void exitPhysics();
  39. virtual ~MotorDemo()
  40. {
  41. }
  42. void spawnTestRig(const btVector3& startOffset, bool bFixed);
  43. // virtual void keyboardCallback(unsigned char key, int x, int y);
  44. void setMotorTargets(btScalar deltaTime);
  45. void resetCamera()
  46. {
  47. float dist = 11;
  48. float pitch = -35;
  49. float yaw = 52;
  50. float targetPos[3] = {0, 0.46, 0};
  51. m_guiHelper->resetCamera(dist, yaw, pitch, targetPos[0], targetPos[1], targetPos[2]);
  52. }
  53. };
  54. #ifndef M_PI
  55. #define M_PI 3.14159265358979323846
  56. #endif
  57. #ifndef M_PI_2
  58. #define M_PI_2 1.57079632679489661923
  59. #endif
  60. #ifndef M_PI_4
  61. #define M_PI_4 0.785398163397448309616
  62. #endif
  63. #ifndef M_PI_8
  64. #define M_PI_8 0.5 * M_PI_4
  65. #endif
  66. // /LOCAL FUNCTIONS
  67. #define NUM_LEGS 6
  68. #define BODYPART_COUNT 2 * NUM_LEGS + 1
  69. #define JOINT_COUNT BODYPART_COUNT - 1
  70. class TestRig
  71. {
  72. btDynamicsWorld* m_ownerWorld;
  73. btCollisionShape* m_shapes[BODYPART_COUNT];
  74. btRigidBody* m_bodies[BODYPART_COUNT];
  75. btTypedConstraint* m_joints[JOINT_COUNT];
  76. btRigidBody* localCreateRigidBody(btScalar mass, const btTransform& startTransform, btCollisionShape* shape)
  77. {
  78. bool isDynamic = (mass != 0.f);
  79. btVector3 localInertia(0, 0, 0);
  80. if (isDynamic)
  81. shape->calculateLocalInertia(mass, localInertia);
  82. btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
  83. btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, shape, localInertia);
  84. btRigidBody* body = new btRigidBody(rbInfo);
  85. m_ownerWorld->addRigidBody(body);
  86. return body;
  87. }
  88. public:
  89. TestRig(btDynamicsWorld* ownerWorld, const btVector3& positionOffset, bool bFixed)
  90. : m_ownerWorld(ownerWorld)
  91. {
  92. btVector3 vUp(0, 1, 0);
  93. //
  94. // Setup geometry
  95. //
  96. float fBodySize = 0.25f;
  97. float fLegLength = 0.45f;
  98. float fForeLegLength = 0.75f;
  99. m_shapes[0] = new btCapsuleShape(btScalar(fBodySize), btScalar(0.10));
  100. int i;
  101. for (i = 0; i < NUM_LEGS; i++)
  102. {
  103. m_shapes[1 + 2 * i] = new btCapsuleShape(btScalar(0.10), btScalar(fLegLength));
  104. m_shapes[2 + 2 * i] = new btCapsuleShape(btScalar(0.08), btScalar(fForeLegLength));
  105. }
  106. //
  107. // Setup rigid bodies
  108. //
  109. float fHeight = 0.5;
  110. btTransform offset;
  111. offset.setIdentity();
  112. offset.setOrigin(positionOffset);
  113. // root
  114. btVector3 vRoot = btVector3(btScalar(0.), btScalar(fHeight), btScalar(0.));
  115. btTransform transform;
  116. transform.setIdentity();
  117. transform.setOrigin(vRoot);
  118. if (bFixed)
  119. {
  120. m_bodies[0] = localCreateRigidBody(btScalar(0.), offset * transform, m_shapes[0]);
  121. }
  122. else
  123. {
  124. m_bodies[0] = localCreateRigidBody(btScalar(1.), offset * transform, m_shapes[0]);
  125. }
  126. // legs
  127. for (i = 0; i < NUM_LEGS; i++)
  128. {
  129. float fAngle = 2 * M_PI * i / NUM_LEGS;
  130. float fSin = std::sin(fAngle);
  131. float fCos = std::cos(fAngle);
  132. transform.setIdentity();
  133. btVector3 vBoneOrigin = btVector3(btScalar(fCos * (fBodySize + 0.5 * fLegLength)), btScalar(fHeight), btScalar(fSin * (fBodySize + 0.5 * fLegLength)));
  134. transform.setOrigin(vBoneOrigin);
  135. // thigh
  136. btVector3 vToBone = (vBoneOrigin - vRoot).normalize();
  137. btVector3 vAxis = vToBone.cross(vUp);
  138. transform.setRotation(btQuaternion(vAxis, M_PI_2));
  139. m_bodies[1 + 2 * i] = localCreateRigidBody(btScalar(1.), offset * transform, m_shapes[1 + 2 * i]);
  140. // shin
  141. transform.setIdentity();
  142. transform.setOrigin(btVector3(btScalar(fCos * (fBodySize + fLegLength)), btScalar(fHeight - 0.5 * fForeLegLength), btScalar(fSin * (fBodySize + fLegLength))));
  143. m_bodies[2 + 2 * i] = localCreateRigidBody(btScalar(1.), offset * transform, m_shapes[2 + 2 * i]);
  144. }
  145. // Setup some damping on the m_bodies
  146. for (i = 0; i < BODYPART_COUNT; ++i)
  147. {
  148. m_bodies[i]->setDamping(0.05, 0.85);
  149. m_bodies[i]->setDeactivationTime(0.8);
  150. //m_bodies[i]->setSleepingThresholds(1.6, 2.5);
  151. m_bodies[i]->setSleepingThresholds(0.5f, 0.5f);
  152. }
  153. //
  154. // Setup the constraints
  155. //
  156. btHingeConstraint* hingeC;
  157. //btConeTwistConstraint* coneC;
  158. btTransform localA, localB, localC;
  159. for (i = 0; i < NUM_LEGS; i++)
  160. {
  161. float fAngle = 2 * M_PI * i / NUM_LEGS;
  162. float fSin = std::sin(fAngle);
  163. float fCos = std::cos(fAngle);
  164. // hip joints
  165. localA.setIdentity();
  166. localB.setIdentity();
  167. localA.getBasis().setEulerZYX(0, -fAngle, 0);
  168. localA.setOrigin(btVector3(btScalar(fCos * fBodySize), btScalar(0.), btScalar(fSin * fBodySize)));
  169. localB = m_bodies[1 + 2 * i]->getWorldTransform().inverse() * m_bodies[0]->getWorldTransform() * localA;
  170. hingeC = new btHingeConstraint(*m_bodies[0], *m_bodies[1 + 2 * i], localA, localB);
  171. hingeC->setLimit(btScalar(-0.75 * M_PI_4), btScalar(M_PI_8));
  172. //hingeC->setLimit(btScalar(-0.1), btScalar(0.1));
  173. m_joints[2 * i] = hingeC;
  174. m_ownerWorld->addConstraint(m_joints[2 * i], true);
  175. // knee joints
  176. localA.setIdentity();
  177. localB.setIdentity();
  178. localC.setIdentity();
  179. localA.getBasis().setEulerZYX(0, -fAngle, 0);
  180. localA.setOrigin(btVector3(btScalar(fCos * (fBodySize + fLegLength)), btScalar(0.), btScalar(fSin * (fBodySize + fLegLength))));
  181. localB = m_bodies[1 + 2 * i]->getWorldTransform().inverse() * m_bodies[0]->getWorldTransform() * localA;
  182. localC = m_bodies[2 + 2 * i]->getWorldTransform().inverse() * m_bodies[0]->getWorldTransform() * localA;
  183. hingeC = new btHingeConstraint(*m_bodies[1 + 2 * i], *m_bodies[2 + 2 * i], localB, localC);
  184. //hingeC->setLimit(btScalar(-0.01), btScalar(0.01));
  185. hingeC->setLimit(btScalar(-M_PI_8), btScalar(0.2));
  186. m_joints[1 + 2 * i] = hingeC;
  187. m_ownerWorld->addConstraint(m_joints[1 + 2 * i], true);
  188. }
  189. }
  190. virtual ~TestRig()
  191. {
  192. int i;
  193. // Remove all constraints
  194. for (i = 0; i < JOINT_COUNT; ++i)
  195. {
  196. m_ownerWorld->removeConstraint(m_joints[i]);
  197. delete m_joints[i];
  198. m_joints[i] = 0;
  199. }
  200. // Remove all bodies and shapes
  201. for (i = 0; i < BODYPART_COUNT; ++i)
  202. {
  203. m_ownerWorld->removeRigidBody(m_bodies[i]);
  204. delete m_bodies[i]->getMotionState();
  205. delete m_bodies[i];
  206. m_bodies[i] = 0;
  207. delete m_shapes[i];
  208. m_shapes[i] = 0;
  209. }
  210. }
  211. btTypedConstraint** GetJoints() { return &m_joints[0]; }
  212. };
  213. void motorPreTickCallback(btDynamicsWorld* world, btScalar timeStep)
  214. {
  215. MotorDemo* motorDemo = (MotorDemo*)world->getWorldUserInfo();
  216. motorDemo->setMotorTargets(timeStep);
  217. }
  218. void MotorDemo::initPhysics()
  219. {
  220. m_guiHelper->setUpAxis(1);
  221. // Setup the basic world
  222. m_Time = 0;
  223. m_fCyclePeriod = 2000.f; // in milliseconds
  224. // m_fMuscleStrength = 0.05f;
  225. // new SIMD solver for joints clips accumulated impulse, so the new limits for the motor
  226. // should be (numberOfsolverIterations * oldLimits)
  227. // currently solver uses 10 iterations, so:
  228. m_fMuscleStrength = 0.5f;
  229. m_collisionConfiguration = new btDefaultCollisionConfiguration();
  230. m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration);
  231. btVector3 worldAabbMin(-10000, -10000, -10000);
  232. btVector3 worldAabbMax(10000, 10000, 10000);
  233. m_broadphase = new btAxisSweep3(worldAabbMin, worldAabbMax);
  234. m_solver = new btSequentialImpulseConstraintSolver;
  235. m_dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher, m_broadphase, m_solver, m_collisionConfiguration);
  236. m_dynamicsWorld->setInternalTickCallback(motorPreTickCallback, this, true);
  237. m_guiHelper->createPhysicsDebugDrawer(m_dynamicsWorld);
  238. // Setup a big ground box
  239. {
  240. btCollisionShape* groundShape = new btBoxShape(btVector3(btScalar(200.), btScalar(10.), btScalar(200.)));
  241. m_collisionShapes.push_back(groundShape);
  242. btTransform groundTransform;
  243. groundTransform.setIdentity();
  244. groundTransform.setOrigin(btVector3(0, -10, 0));
  245. createRigidBody(btScalar(0.), groundTransform, groundShape);
  246. }
  247. // Spawn one ragdoll
  248. btVector3 startOffset(1, 0.5, 0);
  249. spawnTestRig(startOffset, false);
  250. startOffset.setValue(-2, 0.5, 0);
  251. spawnTestRig(startOffset, true);
  252. m_guiHelper->autogenerateGraphicsObjects(m_dynamicsWorld);
  253. }
  254. void MotorDemo::spawnTestRig(const btVector3& startOffset, bool bFixed)
  255. {
  256. TestRig* rig = new TestRig(m_dynamicsWorld, startOffset, bFixed);
  257. m_rigs.push_back(rig);
  258. }
  259. void PreStep()
  260. {
  261. }
  262. void MotorDemo::setMotorTargets(btScalar deltaTime)
  263. {
  264. float ms = deltaTime * 1000000.;
  265. float minFPS = 1000000.f / 60.f;
  266. if (ms > minFPS)
  267. ms = minFPS;
  268. m_Time += ms;
  269. //
  270. // set per-frame sinusoidal position targets using angular motor (hacky?)
  271. //
  272. for (int r = 0; r < m_rigs.size(); r++)
  273. {
  274. for (int i = 0; i < 2 * NUM_LEGS; i++)
  275. {
  276. btHingeConstraint* hingeC = static_cast<btHingeConstraint*>(m_rigs[r]->GetJoints()[i]);
  277. btScalar fCurAngle = hingeC->getHingeAngle();
  278. btScalar fTargetPercent = (int(m_Time / 1000) % int(m_fCyclePeriod)) / m_fCyclePeriod;
  279. btScalar fTargetAngle = 0.5 * (1 + sin(2 * M_PI * fTargetPercent));
  280. btScalar fTargetLimitAngle = hingeC->getLowerLimit() + fTargetAngle * (hingeC->getUpperLimit() - hingeC->getLowerLimit());
  281. btScalar fAngleError = fTargetLimitAngle - fCurAngle;
  282. btScalar fDesiredAngularVel = 1000000.f * fAngleError / ms;
  283. hingeC->enableAngularMotor(true, fDesiredAngularVel, m_fMuscleStrength);
  284. }
  285. }
  286. }
  287. #if 0
  288. void MotorDemo::keyboardCallback(unsigned char key, int x, int y)
  289. {
  290. switch (key)
  291. {
  292. case '+': case '=':
  293. m_fCyclePeriod /= 1.1f;
  294. if (m_fCyclePeriod < 1.f)
  295. m_fCyclePeriod = 1.f;
  296. break;
  297. case '-': case '_':
  298. m_fCyclePeriod *= 1.1f;
  299. break;
  300. case '[':
  301. m_fMuscleStrength /= 1.1f;
  302. break;
  303. case ']':
  304. m_fMuscleStrength *= 1.1f;
  305. break;
  306. default:
  307. DemoApplication::keyboardCallback(key, x, y);
  308. }
  309. }
  310. #endif
  311. void MotorDemo::exitPhysics()
  312. {
  313. int i;
  314. for (i = 0; i < m_rigs.size(); i++)
  315. {
  316. TestRig* rig = m_rigs[i];
  317. delete rig;
  318. }
  319. //cleanup in the reverse order of creation/initialization
  320. //remove the rigidbodies from the dynamics world and delete them
  321. for (i = m_dynamicsWorld->getNumCollisionObjects() - 1; i >= 0; i--)
  322. {
  323. btCollisionObject* obj = m_dynamicsWorld->getCollisionObjectArray()[i];
  324. btRigidBody* body = btRigidBody::upcast(obj);
  325. if (body && body->getMotionState())
  326. {
  327. delete body->getMotionState();
  328. }
  329. m_dynamicsWorld->removeCollisionObject(obj);
  330. delete obj;
  331. }
  332. //delete collision shapes
  333. for (int j = 0; j < m_collisionShapes.size(); j++)
  334. {
  335. btCollisionShape* shape = m_collisionShapes[j];
  336. delete shape;
  337. }
  338. //delete dynamics world
  339. delete m_dynamicsWorld;
  340. //delete solver
  341. delete m_solver;
  342. //delete broadphase
  343. delete m_broadphase;
  344. //delete dispatcher
  345. delete m_dispatcher;
  346. delete m_collisionConfiguration;
  347. }
  348. class CommonExampleInterface* MotorControlCreateFunc(struct CommonExampleOptions& options)
  349. {
  350. return new MotorDemo(options.m_guiHelper);
  351. }