Hinge2Vehicle.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. /*
  2. Bullet Continuous Collision Detection and Physics Library
  3. Copyright (c) 2003-2015 Erwin Coumans http://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. ///May 2015: implemented the wheels using the Hinge2Constraint
  14. ///todo: add controls for the motors etc.
  15. #include "Hinge2Vehicle.h"
  16. #include "btBulletDynamicsCommon.h"
  17. #include "BulletCollision/CollisionShapes/btHeightfieldTerrainShape.h"
  18. #include "BulletDynamics/MLCPSolvers/btDantzigSolver.h"
  19. #include "BulletDynamics/MLCPSolvers/btSolveProjectedGaussSeidel.h"
  20. #include "BulletDynamics/MLCPSolvers/btMLCPSolver.h"
  21. class btVehicleTuning;
  22. class btCollisionShape;
  23. #include "BulletDynamics/ConstraintSolver/btHingeConstraint.h"
  24. #include "BulletDynamics/ConstraintSolver/btSliderConstraint.h"
  25. #include "../CommonInterfaces/CommonExampleInterface.h"
  26. #include "LinearMath/btAlignedObjectArray.h"
  27. #include "btBulletCollisionCommon.h"
  28. #include "../CommonInterfaces/CommonGUIHelperInterface.h"
  29. #include "../CommonInterfaces/CommonRenderInterface.h"
  30. #include "../CommonInterfaces/CommonWindowInterface.h"
  31. #include "../CommonInterfaces/CommonGraphicsAppInterface.h"
  32. #include "../CommonInterfaces/CommonRigidBodyBase.h"
  33. class Hinge2Vehicle : public CommonRigidBodyBase
  34. {
  35. public:
  36. /* extra stuff*/
  37. btVector3 m_cameraPosition;
  38. btRigidBody* m_carChassis;
  39. btRigidBody* localCreateRigidBody(btScalar mass, const btTransform& worldTransform, btCollisionShape* colSape);
  40. GUIHelperInterface* m_guiHelper;
  41. int m_wheelInstances[4];
  42. bool m_useDefaultCamera;
  43. //----------------------------
  44. class btTriangleIndexVertexArray* m_indexVertexArrays;
  45. btVector3* m_vertices;
  46. btCollisionShape* m_wheelShape;
  47. float m_cameraHeight;
  48. float m_minCameraDistance;
  49. float m_maxCameraDistance;
  50. Hinge2Vehicle(struct GUIHelperInterface* helper);
  51. virtual ~Hinge2Vehicle();
  52. virtual void stepSimulation(float deltaTime);
  53. virtual void resetForklift();
  54. virtual void clientResetScene();
  55. virtual void displayCallback();
  56. virtual void specialKeyboard(int key, int x, int y);
  57. virtual void specialKeyboardUp(int key, int x, int y);
  58. virtual bool keyboardCallback(int key, int state);
  59. virtual void renderScene();
  60. virtual void physicsDebugDraw(int debugFlags);
  61. void initPhysics();
  62. void exitPhysics();
  63. virtual void resetCamera()
  64. {
  65. float dist = 8;
  66. float pitch = -32;
  67. float yaw = -45;
  68. float targetPos[3] = {0,0,2};
  69. m_guiHelper->resetCamera(dist, yaw, pitch, targetPos[0], targetPos[1], targetPos[2]);
  70. }
  71. /*static DemoApplication* Create()
  72. {
  73. Hinge2Vehicle* demo = new Hinge2Vehicle();
  74. demo->myinit();
  75. demo->initPhysics();
  76. return demo;
  77. }
  78. */
  79. };
  80. static btScalar maxMotorImpulse = 4000.f;
  81. #ifndef M_PI
  82. #define M_PI 3.14159265358979323846
  83. #endif
  84. #ifndef M_PI_2
  85. #define M_PI_2 1.57079632679489661923
  86. #endif
  87. #ifndef M_PI_4
  88. #define M_PI_4 0.785398163397448309616
  89. #endif
  90. //static int rightIndex = 0;
  91. //static int upIndex = 1;
  92. //static int forwardIndex = 2;
  93. static btVector3 wheelDirectionCS0(0, -1, 0);
  94. static btVector3 wheelAxleCS(-1, 0, 0);
  95. static bool useMCLPSolver = false; //true;
  96. #include <stdio.h> //printf debugging
  97. #include "Hinge2Vehicle.h"
  98. //static const int maxProxies = 32766;
  99. //static const int maxOverlap = 65535;
  100. static float gEngineForce = 0.f;
  101. static float defaultBreakingForce = 10.f;
  102. static float gBreakingForce = 100.f;
  103. static float maxEngineForce = 1000.f; //this should be engine/velocity dependent
  104. //static float maxBreakingForce = 100.f;
  105. static float gVehicleSteering = 0.f;
  106. static float steeringIncrement = 0.04f;
  107. static float steeringClamp = 0.3f;
  108. static float wheelRadius = 0.5f;
  109. static float wheelWidth = 0.4f;
  110. //static float wheelFriction = 1000;//BT_LARGE_FLOAT;
  111. //static float suspensionStiffness = 20.f;
  112. //static float suspensionDamping = 2.3f;
  113. //static float suspensionCompression = 4.4f;
  114. //static float rollInfluence = 0.1f;//1.0f;
  115. //static btScalar suspensionRestLength(0.6);
  116. #define CUBE_HALF_EXTENTS 1
  117. ////////////////////////////////////
  118. Hinge2Vehicle::Hinge2Vehicle(struct GUIHelperInterface* helper)
  119. : CommonRigidBodyBase(helper),
  120. m_carChassis(0),
  121. m_guiHelper(helper),
  122. m_indexVertexArrays(0),
  123. m_vertices(0),
  124. m_cameraHeight(4.f),
  125. m_minCameraDistance(3.f),
  126. m_maxCameraDistance(10.f)
  127. {
  128. helper->setUpAxis(1);
  129. m_wheelShape = 0;
  130. m_cameraPosition = btVector3(30, 30, 30);
  131. m_useDefaultCamera = false;
  132. }
  133. void Hinge2Vehicle::exitPhysics()
  134. {
  135. //cleanup in the reverse order of creation/initialization
  136. //remove the rigidbodies from the dynamics world and delete them
  137. int i;
  138. for (i = m_dynamicsWorld->getNumCollisionObjects() - 1; i >= 0; i--)
  139. {
  140. btCollisionObject* obj = m_dynamicsWorld->getCollisionObjectArray()[i];
  141. btRigidBody* body = btRigidBody::upcast(obj);
  142. if (body && body->getMotionState())
  143. {
  144. while (body->getNumConstraintRefs())
  145. {
  146. btTypedConstraint* constraint = body->getConstraintRef(0);
  147. m_dynamicsWorld->removeConstraint(constraint);
  148. delete constraint;
  149. }
  150. delete body->getMotionState();
  151. m_dynamicsWorld->removeRigidBody(body);
  152. }
  153. else
  154. {
  155. m_dynamicsWorld->removeCollisionObject(obj);
  156. }
  157. delete obj;
  158. }
  159. //delete collision shapes
  160. for (int j = 0; j < m_collisionShapes.size(); j++)
  161. {
  162. btCollisionShape* shape = m_collisionShapes[j];
  163. delete shape;
  164. }
  165. m_collisionShapes.clear();
  166. delete m_indexVertexArrays;
  167. delete m_vertices;
  168. //delete dynamics world
  169. delete m_dynamicsWorld;
  170. m_dynamicsWorld = 0;
  171. delete m_wheelShape;
  172. m_wheelShape = 0;
  173. //delete solver
  174. delete m_solver;
  175. m_solver = 0;
  176. //delete broadphase
  177. delete m_broadphase;
  178. m_broadphase = 0;
  179. //delete dispatcher
  180. delete m_dispatcher;
  181. m_dispatcher = 0;
  182. delete m_collisionConfiguration;
  183. m_collisionConfiguration = 0;
  184. }
  185. Hinge2Vehicle::~Hinge2Vehicle()
  186. {
  187. //exitPhysics();
  188. }
  189. void Hinge2Vehicle::initPhysics()
  190. {
  191. m_guiHelper->setUpAxis(1);
  192. btCollisionShape* groundShape = new btBoxShape(btVector3(50, 3, 50));
  193. m_collisionShapes.push_back(groundShape);
  194. m_collisionConfiguration = new btDefaultCollisionConfiguration();
  195. m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration);
  196. btVector3 worldMin(-1000, -1000, -1000);
  197. btVector3 worldMax(1000, 1000, 1000);
  198. m_broadphase = new btAxisSweep3(worldMin, worldMax);
  199. if (useMCLPSolver)
  200. {
  201. btDantzigSolver* mlcp = new btDantzigSolver();
  202. //btSolveProjectedGaussSeidel* mlcp = new btSolveProjectedGaussSeidel;
  203. btMLCPSolver* sol = new btMLCPSolver(mlcp);
  204. m_solver = sol;
  205. }
  206. else
  207. {
  208. m_solver = new btSequentialImpulseConstraintSolver();
  209. }
  210. m_dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher, m_broadphase, m_solver, m_collisionConfiguration);
  211. if (useMCLPSolver)
  212. {
  213. m_dynamicsWorld->getSolverInfo().m_minimumSolverBatchSize = 1; //for direct solver it is better to have a small A matrix
  214. }
  215. else
  216. {
  217. m_dynamicsWorld->getSolverInfo().m_minimumSolverBatchSize = 128; //for direct solver, it is better to solve multiple objects together, small batches have high overhead
  218. }
  219. m_dynamicsWorld->getSolverInfo().m_numIterations = 100;
  220. m_guiHelper->createPhysicsDebugDrawer(m_dynamicsWorld);
  221. //m_dynamicsWorld->setGravity(btVector3(0,0,0));
  222. btTransform tr;
  223. tr.setIdentity();
  224. tr.setOrigin(btVector3(0, -3, 0));
  225. //either use heightfield or triangle mesh
  226. //create ground object
  227. localCreateRigidBody(0, tr, groundShape);
  228. btCollisionShape* chassisShape = new btBoxShape(btVector3(1.f, 0.5f, 2.f));
  229. m_collisionShapes.push_back(chassisShape);
  230. btCompoundShape* compound = new btCompoundShape();
  231. m_collisionShapes.push_back(compound);
  232. btTransform localTrans;
  233. localTrans.setIdentity();
  234. //localTrans effectively shifts the center of mass with respect to the chassis
  235. localTrans.setOrigin(btVector3(0, 1, 0));
  236. compound->addChildShape(localTrans, chassisShape);
  237. {
  238. btCollisionShape* suppShape = new btBoxShape(btVector3(0.5f, 0.1f, 0.5f));
  239. btTransform suppLocalTrans;
  240. suppLocalTrans.setIdentity();
  241. //localTrans effectively shifts the center of mass with respect to the chassis
  242. suppLocalTrans.setOrigin(btVector3(0, 1.0, 2.5));
  243. compound->addChildShape(suppLocalTrans, suppShape);
  244. }
  245. const btScalar FALLHEIGHT = 5;
  246. tr.setOrigin(btVector3(0, FALLHEIGHT, 0));
  247. const btScalar chassisMass = 2.0f;
  248. const btScalar wheelMass = 1.0f;
  249. m_carChassis = localCreateRigidBody(chassisMass, tr, compound); //chassisShape);
  250. //m_carChassis->setDamping(0.2,0.2);
  251. //m_wheelShape = new btCylinderShapeX(btVector3(wheelWidth,wheelRadius,wheelRadius));
  252. m_wheelShape = new btCylinderShapeX(btVector3(wheelWidth, wheelRadius, wheelRadius));
  253. btVector3 wheelPos[4] = {
  254. btVector3(btScalar(-1.), btScalar(FALLHEIGHT-0.25), btScalar(1.25)),
  255. btVector3(btScalar(1.), btScalar(FALLHEIGHT-0.25), btScalar(1.25)),
  256. btVector3(btScalar(1.), btScalar(FALLHEIGHT-0.25), btScalar(-1.25)),
  257. btVector3(btScalar(-1.), btScalar(FALLHEIGHT-0.25), btScalar(-1.25))};
  258. for (int i = 0; i < 4; i++)
  259. {
  260. // create a Hinge2 joint
  261. // create two rigid bodies
  262. // static bodyA (parent) on top:
  263. btRigidBody* pBodyA = this->m_carChassis;
  264. pBodyA->setActivationState(DISABLE_DEACTIVATION);
  265. // dynamic bodyB (child) below it :
  266. btTransform tr;
  267. tr.setIdentity();
  268. tr.setOrigin(wheelPos[i]);
  269. btRigidBody* pBodyB = createRigidBody(wheelMass, tr, m_wheelShape);
  270. pBodyB->setFriction(1110);
  271. pBodyB->setActivationState(DISABLE_DEACTIVATION);
  272. // add some data to build constraint frames
  273. btVector3 parentAxis(0.f, 1.f, 0.f);
  274. btVector3 childAxis(1.f, 0.f, 0.f);
  275. btVector3 anchor = tr.getOrigin();
  276. btHinge2Constraint* pHinge2 = new btHinge2Constraint(*pBodyA, *pBodyB, anchor, parentAxis, childAxis);
  277. //m_guiHelper->get2dCanvasInterface();
  278. //pHinge2->setLowerLimit(-SIMD_HALF_PI * 0.5f);
  279. //pHinge2->setUpperLimit(SIMD_HALF_PI * 0.5f);
  280. // add constraint to world
  281. m_dynamicsWorld->addConstraint(pHinge2, true);
  282. // Drive engine.
  283. pHinge2->enableMotor(3, true);
  284. pHinge2->setMaxMotorForce(3, 1000);
  285. pHinge2->setTargetVelocity(3, 0);
  286. // Steering engine.
  287. pHinge2->enableMotor(5, true);
  288. pHinge2->setMaxMotorForce(5, 1000);
  289. pHinge2->setTargetVelocity(5, 0);
  290. pHinge2->setParam( BT_CONSTRAINT_CFM, 0.15f, 2 );
  291. pHinge2->setParam( BT_CONSTRAINT_ERP, 0.35f, 2 );
  292. pHinge2->setDamping( 2, 2.0 );
  293. pHinge2->setStiffness( 2, 40.0 );
  294. pHinge2->setDbgDrawSize(btScalar(5.f));
  295. }
  296. resetForklift();
  297. m_guiHelper->autogenerateGraphicsObjects(m_dynamicsWorld);
  298. }
  299. void Hinge2Vehicle::physicsDebugDraw(int debugFlags)
  300. {
  301. if (m_dynamicsWorld && m_dynamicsWorld->getDebugDrawer())
  302. {
  303. m_dynamicsWorld->getDebugDrawer()->setDebugMode(debugFlags);
  304. m_dynamicsWorld->debugDrawWorld();
  305. }
  306. }
  307. //to be implemented by the demo
  308. void Hinge2Vehicle::renderScene()
  309. {
  310. m_guiHelper->syncPhysicsToGraphics(m_dynamicsWorld);
  311. m_guiHelper->render(m_dynamicsWorld);
  312. btVector3 wheelColor(1, 0, 0);
  313. btVector3 worldBoundsMin, worldBoundsMax;
  314. getDynamicsWorld()->getBroadphase()->getBroadphaseAabb(worldBoundsMin, worldBoundsMax);
  315. }
  316. void Hinge2Vehicle::stepSimulation(float deltaTime)
  317. {
  318. float dt = deltaTime;
  319. if (m_dynamicsWorld)
  320. {
  321. //during idle mode, just run 1 simulation step maximum
  322. int maxSimSubSteps = 2;
  323. int numSimSteps;
  324. numSimSteps = m_dynamicsWorld->stepSimulation(dt, maxSimSubSteps);
  325. if (m_dynamicsWorld->getConstraintSolver()->getSolverType() == BT_MLCP_SOLVER)
  326. {
  327. btMLCPSolver* sol = (btMLCPSolver*)m_dynamicsWorld->getConstraintSolver();
  328. int numFallbacks = sol->getNumFallbacks();
  329. if (numFallbacks)
  330. {
  331. static int totalFailures = 0;
  332. totalFailures += numFallbacks;
  333. printf("MLCP solver failed %d times, falling back to btSequentialImpulseSolver (SI)\n", totalFailures);
  334. }
  335. sol->setNumFallbacks(0);
  336. }
  337. //#define VERBOSE_FEEDBACK
  338. #ifdef VERBOSE_FEEDBACK
  339. if (!numSimSteps)
  340. printf("Interpolated transforms\n");
  341. else
  342. {
  343. if (numSimSteps > maxSimSubSteps)
  344. {
  345. //detect dropping frames
  346. printf("Dropped (%i) simulation steps out of %i\n", numSimSteps - maxSimSubSteps, numSimSteps);
  347. }
  348. else
  349. {
  350. printf("Simulated (%i) steps\n", numSimSteps);
  351. }
  352. }
  353. #endif //VERBOSE_FEEDBACK
  354. }
  355. }
  356. void Hinge2Vehicle::displayCallback(void)
  357. {
  358. // glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  359. //renderme();
  360. //optional but useful: debug drawing
  361. if (m_dynamicsWorld)
  362. m_dynamicsWorld->debugDrawWorld();
  363. // glFlush();
  364. // glutSwapBuffers();
  365. }
  366. void Hinge2Vehicle::clientResetScene()
  367. {
  368. exitPhysics();
  369. initPhysics();
  370. }
  371. void Hinge2Vehicle::resetForklift()
  372. {
  373. gVehicleSteering = 0.f;
  374. gBreakingForce = defaultBreakingForce;
  375. gEngineForce = 0.f;
  376. m_carChassis->setCenterOfMassTransform(btTransform::getIdentity());
  377. m_carChassis->setLinearVelocity(btVector3(0, 0, 0));
  378. m_carChassis->setAngularVelocity(btVector3(0, 0, 0));
  379. m_dynamicsWorld->getBroadphase()->getOverlappingPairCache()->cleanProxyFromPairs(m_carChassis->getBroadphaseHandle(), getDynamicsWorld()->getDispatcher());
  380. }
  381. bool Hinge2Vehicle::keyboardCallback(int key, int state)
  382. {
  383. bool handled = false;
  384. bool isShiftPressed = m_guiHelper->getAppInterface()->m_window->isModifierKeyPressed(B3G_SHIFT);
  385. if (state)
  386. {
  387. if (isShiftPressed)
  388. {
  389. }
  390. else
  391. {
  392. switch (key)
  393. {
  394. case B3G_LEFT_ARROW:
  395. {
  396. handled = true;
  397. gVehicleSteering += steeringIncrement;
  398. if (gVehicleSteering > steeringClamp)
  399. gVehicleSteering = steeringClamp;
  400. break;
  401. }
  402. case B3G_RIGHT_ARROW:
  403. {
  404. handled = true;
  405. gVehicleSteering -= steeringIncrement;
  406. if (gVehicleSteering < -steeringClamp)
  407. gVehicleSteering = -steeringClamp;
  408. break;
  409. }
  410. case B3G_UP_ARROW:
  411. {
  412. handled = true;
  413. gEngineForce = maxEngineForce;
  414. gBreakingForce = 0.f;
  415. break;
  416. }
  417. case B3G_DOWN_ARROW:
  418. {
  419. handled = true;
  420. gEngineForce = -maxEngineForce;
  421. gBreakingForce = 0.f;
  422. break;
  423. }
  424. case B3G_F7:
  425. {
  426. handled = true;
  427. btDiscreteDynamicsWorld* world = (btDiscreteDynamicsWorld*)m_dynamicsWorld;
  428. world->setLatencyMotionStateInterpolation(!world->getLatencyMotionStateInterpolation());
  429. printf("world latencyMotionStateInterpolation = %d\n", world->getLatencyMotionStateInterpolation());
  430. break;
  431. }
  432. case B3G_F6:
  433. {
  434. handled = true;
  435. //switch solver (needs demo restart)
  436. useMCLPSolver = !useMCLPSolver;
  437. printf("switching to useMLCPSolver = %d\n", useMCLPSolver);
  438. delete m_solver;
  439. if (useMCLPSolver)
  440. {
  441. btDantzigSolver* mlcp = new btDantzigSolver();
  442. //btSolveProjectedGaussSeidel* mlcp = new btSolveProjectedGaussSeidel;
  443. btMLCPSolver* sol = new btMLCPSolver(mlcp);
  444. m_solver = sol;
  445. }
  446. else
  447. {
  448. m_solver = new btSequentialImpulseConstraintSolver();
  449. }
  450. m_dynamicsWorld->setConstraintSolver(m_solver);
  451. //exitPhysics();
  452. //initPhysics();
  453. break;
  454. }
  455. case B3G_F5:
  456. handled = true;
  457. m_useDefaultCamera = !m_useDefaultCamera;
  458. break;
  459. default:
  460. break;
  461. }
  462. }
  463. }
  464. else
  465. {
  466. }
  467. return handled;
  468. }
  469. void Hinge2Vehicle::specialKeyboardUp(int key, int x, int y)
  470. {
  471. }
  472. void Hinge2Vehicle::specialKeyboard(int key, int x, int y)
  473. {
  474. }
  475. btRigidBody* Hinge2Vehicle::localCreateRigidBody(btScalar mass, const btTransform& startTransform, btCollisionShape* shape)
  476. {
  477. btAssert((!shape || shape->getShapeType() != INVALID_SHAPE_PROXYTYPE));
  478. //rigidbody is dynamic if and only if mass is non zero, otherwise static
  479. bool isDynamic = (mass != 0.f);
  480. btVector3 localInertia(0, 0, 0);
  481. if (isDynamic)
  482. shape->calculateLocalInertia(mass, localInertia);
  483. //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
  484. #define USE_MOTIONSTATE 1
  485. #ifdef USE_MOTIONSTATE
  486. btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
  487. btRigidBody::btRigidBodyConstructionInfo cInfo(mass, myMotionState, shape, localInertia);
  488. btRigidBody* body = new btRigidBody(cInfo);
  489. //body->setContactProcessingThreshold(m_defaultContactProcessingThreshold);
  490. #else
  491. btRigidBody* body = new btRigidBody(mass, 0, shape, localInertia);
  492. body->setWorldTransform(startTransform);
  493. #endif //
  494. m_dynamicsWorld->addRigidBody(body);
  495. return body;
  496. }
  497. CommonExampleInterface* Hinge2VehicleCreateFunc(struct CommonExampleOptions& options)
  498. {
  499. return new Hinge2Vehicle(options.m_guiHelper);
  500. }