ForkLiftDemo.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  1. /*
  2. Bullet Continuous Collision Detection and Physics Library
  3. Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
  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. ///September 2006: VehicleDemo is work in progress, this file is mostly just a placeholder
  14. ///This VehicleDemo file is very early in development, please check it later
  15. ///@todo is a basic engine model:
  16. ///A function that maps user input (throttle) into torque/force applied on the wheels
  17. ///with gears etc.
  18. #include "btBulletDynamicsCommon.h"
  19. #include "BulletCollision/CollisionShapes/btHeightfieldTerrainShape.h"
  20. #include "BulletDynamics/MLCPSolvers/btDantzigSolver.h"
  21. #include "BulletDynamics/MLCPSolvers/btSolveProjectedGaussSeidel.h"
  22. #include "BulletDynamics/MLCPSolvers/btMLCPSolver.h"
  23. class btVehicleTuning;
  24. struct btVehicleRaycaster;
  25. class btCollisionShape;
  26. #include "BulletDynamics/Vehicle/btRaycastVehicle.h"
  27. #include "BulletDynamics/ConstraintSolver/btHingeConstraint.h"
  28. #include "BulletDynamics/ConstraintSolver/btSliderConstraint.h"
  29. #include "../CommonInterfaces/CommonExampleInterface.h"
  30. #include "LinearMath/btAlignedObjectArray.h"
  31. #include "btBulletCollisionCommon.h"
  32. #include "../CommonInterfaces/CommonGUIHelperInterface.h"
  33. #include "../CommonInterfaces/CommonRenderInterface.h"
  34. #include "../CommonInterfaces/CommonWindowInterface.h"
  35. #include "../CommonInterfaces/CommonGraphicsAppInterface.h"
  36. ///VehicleDemo shows how to setup and use the built-in raycast vehicle
  37. class ForkLiftDemo : public CommonExampleInterface
  38. {
  39. public:
  40. /* extra stuff*/
  41. btVector3 m_cameraPosition;
  42. class btDiscreteDynamicsWorld* m_dynamicsWorld;
  43. btDiscreteDynamicsWorld* getDynamicsWorld()
  44. {
  45. return m_dynamicsWorld;
  46. }
  47. btRigidBody* m_carChassis;
  48. btRigidBody* localCreateRigidBody(btScalar mass, const btTransform& worldTransform, btCollisionShape* colSape);
  49. GUIHelperInterface* m_guiHelper;
  50. int m_wheelInstances[4];
  51. //----------------------------
  52. btRigidBody* m_liftBody;
  53. btVector3 m_liftStartPos;
  54. btHingeConstraint* m_liftHinge;
  55. btRigidBody* m_forkBody;
  56. btVector3 m_forkStartPos;
  57. btSliderConstraint* m_forkSlider;
  58. btRigidBody* m_loadBody;
  59. btVector3 m_loadStartPos;
  60. void lockLiftHinge(void);
  61. void lockForkSlider(void);
  62. bool m_useDefaultCamera;
  63. //----------------------------
  64. btAlignedObjectArray<btCollisionShape*> m_collisionShapes;
  65. class btBroadphaseInterface* m_overlappingPairCache;
  66. class btCollisionDispatcher* m_dispatcher;
  67. class btConstraintSolver* m_constraintSolver;
  68. class btDefaultCollisionConfiguration* m_collisionConfiguration;
  69. class btTriangleIndexVertexArray* m_indexVertexArrays;
  70. btVector3* m_vertices;
  71. btRaycastVehicle::btVehicleTuning m_tuning;
  72. btVehicleRaycaster* m_vehicleRayCaster;
  73. btRaycastVehicle* m_vehicle;
  74. btCollisionShape* m_wheelShape;
  75. float m_cameraHeight;
  76. float m_minCameraDistance;
  77. float m_maxCameraDistance;
  78. ForkLiftDemo(struct GUIHelperInterface* helper);
  79. virtual ~ForkLiftDemo();
  80. virtual void stepSimulation(float deltaTime);
  81. virtual void resetForklift();
  82. virtual void clientResetScene();
  83. virtual void displayCallback();
  84. virtual void specialKeyboard(int key, int x, int y);
  85. virtual void specialKeyboardUp(int key, int x, int y);
  86. virtual bool mouseMoveCallback(float x,float y)
  87. {
  88. return false;
  89. }
  90. virtual bool mouseButtonCallback(int button, int state, float x, float y)
  91. {
  92. return false;
  93. }
  94. virtual bool keyboardCallback(int key, int state);
  95. virtual void renderScene();
  96. virtual void physicsDebugDraw(int debugFlags);
  97. void initPhysics();
  98. void exitPhysics();
  99. virtual void resetCamera()
  100. {
  101. float dist = 8;
  102. float pitch = -45;
  103. float yaw = 32;
  104. float targetPos[3]={-0.33,-0.72,4.5};
  105. m_guiHelper->resetCamera(dist,pitch,yaw,targetPos[0],targetPos[1],targetPos[2]);
  106. }
  107. /*static DemoApplication* Create()
  108. {
  109. ForkLiftDemo* demo = new ForkLiftDemo();
  110. demo->myinit();
  111. demo->initPhysics();
  112. return demo;
  113. }
  114. */
  115. };
  116. btScalar maxMotorImpulse = 4000.f;
  117. //the sequential impulse solver has difficulties dealing with large mass ratios (differences), between loadMass and the fork parts
  118. btScalar loadMass = 350.f;//
  119. //btScalar loadMass = 10.f;//this should work fine for the SI solver
  120. #ifndef M_PI
  121. #define M_PI 3.14159265358979323846
  122. #endif
  123. #ifndef M_PI_2
  124. #define M_PI_2 1.57079632679489661923
  125. #endif
  126. #ifndef M_PI_4
  127. #define M_PI_4 0.785398163397448309616
  128. #endif
  129. int rightIndex = 0;
  130. int upIndex = 1;
  131. int forwardIndex = 2;
  132. btVector3 wheelDirectionCS0(0,-1,0);
  133. btVector3 wheelAxleCS(-1,0,0);
  134. bool useMCLPSolver = true;
  135. #include <stdio.h> //printf debugging
  136. #include "ForkLiftDemo.h"
  137. const int maxProxies = 32766;
  138. const int maxOverlap = 65535;
  139. ///btRaycastVehicle is the interface for the constraint that implements the raycast vehicle
  140. ///notice that for higher-quality slow-moving vehicles, another approach might be better
  141. ///implementing explicit hinged-wheel constraints with cylinder collision, rather then raycasts
  142. float gEngineForce = 0.f;
  143. float defaultBreakingForce = 10.f;
  144. float gBreakingForce = 100.f;
  145. float maxEngineForce = 1000.f;//this should be engine/velocity dependent
  146. float maxBreakingForce = 100.f;
  147. float gVehicleSteering = 0.f;
  148. float steeringIncrement = 0.04f;
  149. float steeringClamp = 0.3f;
  150. float wheelRadius = 0.5f;
  151. float wheelWidth = 0.4f;
  152. float wheelFriction = 1000;//BT_LARGE_FLOAT;
  153. float suspensionStiffness = 20.f;
  154. float suspensionDamping = 2.3f;
  155. float suspensionCompression = 4.4f;
  156. float rollInfluence = 0.1f;//1.0f;
  157. btScalar suspensionRestLength(0.6);
  158. #define CUBE_HALF_EXTENTS 1
  159. ////////////////////////////////////
  160. ForkLiftDemo::ForkLiftDemo(struct GUIHelperInterface* helper)
  161. :m_guiHelper(helper),
  162. m_carChassis(0),
  163. m_liftBody(0),
  164. m_forkBody(0),
  165. m_loadBody(0),
  166. m_indexVertexArrays(0),
  167. m_vertices(0),
  168. m_cameraHeight(4.f),
  169. m_minCameraDistance(3.f),
  170. m_maxCameraDistance(10.f)
  171. {
  172. helper->setUpAxis(1);
  173. m_vehicle = 0;
  174. m_wheelShape = 0;
  175. m_cameraPosition = btVector3(30,30,30);
  176. m_useDefaultCamera = false;
  177. // setTexturing(true);
  178. // setShadows(true);
  179. }
  180. void ForkLiftDemo::exitPhysics()
  181. {
  182. //cleanup in the reverse order of creation/initialization
  183. //remove the rigidbodies from the dynamics world and delete them
  184. int i;
  185. for (i=m_dynamicsWorld->getNumCollisionObjects()-1; i>=0 ;i--)
  186. {
  187. btCollisionObject* obj = m_dynamicsWorld->getCollisionObjectArray()[i];
  188. btRigidBody* body = btRigidBody::upcast(obj);
  189. if (body && body->getMotionState())
  190. {
  191. while (body->getNumConstraintRefs())
  192. {
  193. btTypedConstraint* constraint = body->getConstraintRef(0);
  194. m_dynamicsWorld->removeConstraint(constraint);
  195. delete constraint;
  196. }
  197. delete body->getMotionState();
  198. m_dynamicsWorld->removeRigidBody(body);
  199. } else
  200. {
  201. m_dynamicsWorld->removeCollisionObject( obj );
  202. }
  203. delete obj;
  204. }
  205. //delete collision shapes
  206. for (int j=0;j<m_collisionShapes.size();j++)
  207. {
  208. btCollisionShape* shape = m_collisionShapes[j];
  209. delete shape;
  210. }
  211. m_collisionShapes.clear();
  212. delete m_indexVertexArrays;
  213. delete m_vertices;
  214. //delete dynamics world
  215. delete m_dynamicsWorld;
  216. m_dynamicsWorld=0;
  217. delete m_vehicleRayCaster;
  218. m_vehicleRayCaster = 0;
  219. delete m_vehicle;
  220. m_vehicle=0;
  221. delete m_wheelShape;
  222. m_wheelShape=0;
  223. //delete solver
  224. delete m_constraintSolver;
  225. m_constraintSolver=0;
  226. //delete broadphase
  227. delete m_overlappingPairCache;
  228. m_overlappingPairCache=0;
  229. //delete dispatcher
  230. delete m_dispatcher;
  231. m_dispatcher=0;
  232. delete m_collisionConfiguration;
  233. m_collisionConfiguration=0;
  234. }
  235. ForkLiftDemo::~ForkLiftDemo()
  236. {
  237. //exitPhysics();
  238. }
  239. void ForkLiftDemo::initPhysics()
  240. {
  241. int upAxis = 1;
  242. m_guiHelper->setUpAxis(upAxis);
  243. btVector3 groundExtents(50,50,50);
  244. groundExtents[upAxis]=3;
  245. btCollisionShape* groundShape = new btBoxShape(groundExtents);
  246. m_collisionShapes.push_back(groundShape);
  247. m_collisionConfiguration = new btDefaultCollisionConfiguration();
  248. m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration);
  249. btVector3 worldMin(-1000,-1000,-1000);
  250. btVector3 worldMax(1000,1000,1000);
  251. m_overlappingPairCache = new btAxisSweep3(worldMin,worldMax);
  252. if (useMCLPSolver)
  253. {
  254. btDantzigSolver* mlcp = new btDantzigSolver();
  255. //btSolveProjectedGaussSeidel* mlcp = new btSolveProjectedGaussSeidel;
  256. btMLCPSolver* sol = new btMLCPSolver(mlcp);
  257. m_constraintSolver = sol;
  258. } else
  259. {
  260. m_constraintSolver = new btSequentialImpulseConstraintSolver();
  261. }
  262. m_dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher,m_overlappingPairCache,m_constraintSolver,m_collisionConfiguration);
  263. if (useMCLPSolver)
  264. {
  265. m_dynamicsWorld ->getSolverInfo().m_minimumSolverBatchSize = 1;//for direct solver it is better to have a small A matrix
  266. } else
  267. {
  268. m_dynamicsWorld ->getSolverInfo().m_minimumSolverBatchSize = 128;//for direct solver, it is better to solve multiple objects together, small batches have high overhead
  269. }
  270. m_dynamicsWorld->getSolverInfo().m_globalCfm = 0.00001;
  271. m_guiHelper->createPhysicsDebugDrawer(m_dynamicsWorld);
  272. //m_dynamicsWorld->setGravity(btVector3(0,0,0));
  273. btTransform tr;
  274. tr.setIdentity();
  275. tr.setOrigin(btVector3(0,-3,0));
  276. //either use heightfield or triangle mesh
  277. //create ground object
  278. localCreateRigidBody(0,tr,groundShape);
  279. btCollisionShape* chassisShape = new btBoxShape(btVector3(1.f,0.5f,2.f));
  280. m_collisionShapes.push_back(chassisShape);
  281. btCompoundShape* compound = new btCompoundShape();
  282. m_collisionShapes.push_back(compound);
  283. btTransform localTrans;
  284. localTrans.setIdentity();
  285. //localTrans effectively shifts the center of mass with respect to the chassis
  286. localTrans.setOrigin(btVector3(0,1,0));
  287. compound->addChildShape(localTrans,chassisShape);
  288. {
  289. btCollisionShape* suppShape = new btBoxShape(btVector3(0.5f,0.1f,0.5f));
  290. btTransform suppLocalTrans;
  291. suppLocalTrans.setIdentity();
  292. //localTrans effectively shifts the center of mass with respect to the chassis
  293. suppLocalTrans.setOrigin(btVector3(0,1.0,2.5));
  294. compound->addChildShape(suppLocalTrans, suppShape);
  295. }
  296. tr.setOrigin(btVector3(0,0.f,0));
  297. m_carChassis = localCreateRigidBody(800,tr,compound);//chassisShape);
  298. //m_carChassis->setDamping(0.2,0.2);
  299. m_wheelShape = new btCylinderShapeX(btVector3(wheelWidth,wheelRadius,wheelRadius));
  300. m_guiHelper->createCollisionShapeGraphicsObject(m_wheelShape);
  301. int wheelGraphicsIndex = m_wheelShape->getUserIndex();
  302. const float position[4]={0,10,10,0};
  303. const float quaternion[4]={0,0,0,1};
  304. const float color[4]={0,1,0,1};
  305. const float scaling[4] = {1,1,1,1};
  306. for (int i=0;i<4;i++)
  307. {
  308. m_wheelInstances[i] = m_guiHelper->registerGraphicsInstance(wheelGraphicsIndex, position, quaternion, color, scaling);
  309. }
  310. {
  311. btCollisionShape* liftShape = new btBoxShape(btVector3(0.5f,2.0f,0.05f));
  312. m_collisionShapes.push_back(liftShape);
  313. btTransform liftTrans;
  314. m_liftStartPos = btVector3(0.0f, 2.5f, 3.05f);
  315. liftTrans.setIdentity();
  316. liftTrans.setOrigin(m_liftStartPos);
  317. m_liftBody = localCreateRigidBody(10,liftTrans, liftShape);
  318. btTransform localA, localB;
  319. localA.setIdentity();
  320. localB.setIdentity();
  321. localA.getBasis().setEulerZYX(0, M_PI_2, 0);
  322. localA.setOrigin(btVector3(0.0, 1.0, 3.05));
  323. localB.getBasis().setEulerZYX(0, M_PI_2, 0);
  324. localB.setOrigin(btVector3(0.0, -1.5, -0.05));
  325. m_liftHinge = new btHingeConstraint(*m_carChassis,*m_liftBody, localA, localB);
  326. // m_liftHinge->setLimit(-LIFT_EPS, LIFT_EPS);
  327. m_liftHinge->setLimit(0.0f, 0.0f);
  328. m_dynamicsWorld->addConstraint(m_liftHinge, true);
  329. btCollisionShape* forkShapeA = new btBoxShape(btVector3(1.0f,0.1f,0.1f));
  330. m_collisionShapes.push_back(forkShapeA);
  331. btCompoundShape* forkCompound = new btCompoundShape();
  332. m_collisionShapes.push_back(forkCompound);
  333. btTransform forkLocalTrans;
  334. forkLocalTrans.setIdentity();
  335. forkCompound->addChildShape(forkLocalTrans, forkShapeA);
  336. btCollisionShape* forkShapeB = new btBoxShape(btVector3(0.1f,0.02f,0.6f));
  337. m_collisionShapes.push_back(forkShapeB);
  338. forkLocalTrans.setIdentity();
  339. forkLocalTrans.setOrigin(btVector3(-0.9f, -0.08f, 0.7f));
  340. forkCompound->addChildShape(forkLocalTrans, forkShapeB);
  341. btCollisionShape* forkShapeC = new btBoxShape(btVector3(0.1f,0.02f,0.6f));
  342. m_collisionShapes.push_back(forkShapeC);
  343. forkLocalTrans.setIdentity();
  344. forkLocalTrans.setOrigin(btVector3(0.9f, -0.08f, 0.7f));
  345. forkCompound->addChildShape(forkLocalTrans, forkShapeC);
  346. btTransform forkTrans;
  347. m_forkStartPos = btVector3(0.0f, 0.6f, 3.2f);
  348. forkTrans.setIdentity();
  349. forkTrans.setOrigin(m_forkStartPos);
  350. m_forkBody = localCreateRigidBody(5, forkTrans, forkCompound);
  351. localA.setIdentity();
  352. localB.setIdentity();
  353. localA.getBasis().setEulerZYX(0, 0, M_PI_2);
  354. localA.setOrigin(btVector3(0.0f, -1.9f, 0.05f));
  355. localB.getBasis().setEulerZYX(0, 0, M_PI_2);
  356. localB.setOrigin(btVector3(0.0, 0.0, -0.1));
  357. m_forkSlider = new btSliderConstraint(*m_liftBody, *m_forkBody, localA, localB, true);
  358. m_forkSlider->setLowerLinLimit(0.1f);
  359. m_forkSlider->setUpperLinLimit(0.1f);
  360. // m_forkSlider->setLowerAngLimit(-LIFT_EPS);
  361. // m_forkSlider->setUpperAngLimit(LIFT_EPS);
  362. m_forkSlider->setLowerAngLimit(0.0f);
  363. m_forkSlider->setUpperAngLimit(0.0f);
  364. m_dynamicsWorld->addConstraint(m_forkSlider, true);
  365. btCompoundShape* loadCompound = new btCompoundShape();
  366. m_collisionShapes.push_back(loadCompound);
  367. btCollisionShape* loadShapeA = new btBoxShape(btVector3(2.0f,0.5f,0.5f));
  368. m_collisionShapes.push_back(loadShapeA);
  369. btTransform loadTrans;
  370. loadTrans.setIdentity();
  371. loadCompound->addChildShape(loadTrans, loadShapeA);
  372. btCollisionShape* loadShapeB = new btBoxShape(btVector3(0.1f,1.0f,1.0f));
  373. m_collisionShapes.push_back(loadShapeB);
  374. loadTrans.setIdentity();
  375. loadTrans.setOrigin(btVector3(2.1f, 0.0f, 0.0f));
  376. loadCompound->addChildShape(loadTrans, loadShapeB);
  377. btCollisionShape* loadShapeC = new btBoxShape(btVector3(0.1f,1.0f,1.0f));
  378. m_collisionShapes.push_back(loadShapeC);
  379. loadTrans.setIdentity();
  380. loadTrans.setOrigin(btVector3(-2.1f, 0.0f, 0.0f));
  381. loadCompound->addChildShape(loadTrans, loadShapeC);
  382. loadTrans.setIdentity();
  383. m_loadStartPos = btVector3(0.0f, 3.5f, 7.0f);
  384. loadTrans.setOrigin(m_loadStartPos);
  385. m_loadBody = localCreateRigidBody(loadMass, loadTrans, loadCompound);
  386. }
  387. /// create vehicle
  388. {
  389. m_vehicleRayCaster = new btDefaultVehicleRaycaster(m_dynamicsWorld);
  390. m_vehicle = new btRaycastVehicle(m_tuning,m_carChassis,m_vehicleRayCaster);
  391. ///never deactivate the vehicle
  392. m_carChassis->setActivationState(DISABLE_DEACTIVATION);
  393. m_dynamicsWorld->addVehicle(m_vehicle);
  394. float connectionHeight = 1.2f;
  395. bool isFrontWheel=true;
  396. //choose coordinate system
  397. m_vehicle->setCoordinateSystem(rightIndex,upIndex,forwardIndex);
  398. btVector3 connectionPointCS0(CUBE_HALF_EXTENTS-(0.3*wheelWidth),connectionHeight,2*CUBE_HALF_EXTENTS-wheelRadius);
  399. m_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxleCS,suspensionRestLength,wheelRadius,m_tuning,isFrontWheel);
  400. connectionPointCS0 = btVector3(-CUBE_HALF_EXTENTS+(0.3*wheelWidth),connectionHeight,2*CUBE_HALF_EXTENTS-wheelRadius);
  401. m_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxleCS,suspensionRestLength,wheelRadius,m_tuning,isFrontWheel);
  402. connectionPointCS0 = btVector3(-CUBE_HALF_EXTENTS+(0.3*wheelWidth),connectionHeight,-2*CUBE_HALF_EXTENTS+wheelRadius);
  403. isFrontWheel = false;
  404. m_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxleCS,suspensionRestLength,wheelRadius,m_tuning,isFrontWheel);
  405. connectionPointCS0 = btVector3(CUBE_HALF_EXTENTS-(0.3*wheelWidth),connectionHeight,-2*CUBE_HALF_EXTENTS+wheelRadius);
  406. m_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxleCS,suspensionRestLength,wheelRadius,m_tuning,isFrontWheel);
  407. for (int i=0;i<m_vehicle->getNumWheels();i++)
  408. {
  409. btWheelInfo& wheel = m_vehicle->getWheelInfo(i);
  410. wheel.m_suspensionStiffness = suspensionStiffness;
  411. wheel.m_wheelsDampingRelaxation = suspensionDamping;
  412. wheel.m_wheelsDampingCompression = suspensionCompression;
  413. wheel.m_frictionSlip = wheelFriction;
  414. wheel.m_rollInfluence = rollInfluence;
  415. }
  416. }
  417. resetForklift();
  418. // setCameraDistance(26.f);
  419. m_guiHelper->autogenerateGraphicsObjects(m_dynamicsWorld);
  420. }
  421. void ForkLiftDemo::physicsDebugDraw(int debugFlags)
  422. {
  423. if (m_dynamicsWorld && m_dynamicsWorld->getDebugDrawer())
  424. {
  425. m_dynamicsWorld->getDebugDrawer()->setDebugMode(debugFlags);
  426. m_dynamicsWorld->debugDrawWorld();
  427. }
  428. }
  429. //to be implemented by the demo
  430. void ForkLiftDemo::renderScene()
  431. {
  432. m_guiHelper->syncPhysicsToGraphics(m_dynamicsWorld);
  433. for (int i=0;i<m_vehicle->getNumWheels();i++)
  434. {
  435. //synchronize the wheels with the (interpolated) chassis worldtransform
  436. m_vehicle->updateWheelTransform(i,true);
  437. CommonRenderInterface* renderer = m_guiHelper->getRenderInterface();
  438. if (renderer)
  439. {
  440. btTransform tr = m_vehicle->getWheelInfo(i).m_worldTransform;
  441. btVector3 pos=tr.getOrigin();
  442. btQuaternion orn = tr.getRotation();
  443. renderer->writeSingleInstanceTransformToCPU(pos,orn,m_wheelInstances[i]);
  444. }
  445. }
  446. m_guiHelper->render(m_dynamicsWorld);
  447. ATTRIBUTE_ALIGNED16(btScalar) m[16];
  448. int i;
  449. btVector3 wheelColor(1,0,0);
  450. btVector3 worldBoundsMin,worldBoundsMax;
  451. getDynamicsWorld()->getBroadphase()->getBroadphaseAabb(worldBoundsMin,worldBoundsMax);
  452. for (i=0;i<m_vehicle->getNumWheels();i++)
  453. {
  454. //synchronize the wheels with the (interpolated) chassis worldtransform
  455. m_vehicle->updateWheelTransform(i,true);
  456. //draw wheels (cylinders)
  457. m_vehicle->getWheelInfo(i).m_worldTransform.getOpenGLMatrix(m);
  458. // m_shapeDrawer->drawOpenGL(m,m_wheelShape,wheelColor,getDebugMode(),worldBoundsMin,worldBoundsMax);
  459. }
  460. #if 0
  461. int lineWidth=400;
  462. int xStart = m_glutScreenWidth - lineWidth;
  463. int yStart = 20;
  464. if((getDebugMode() & btIDebugDraw::DBG_NoHelpText)==0)
  465. {
  466. setOrthographicProjection();
  467. glDisable(GL_LIGHTING);
  468. glColor3f(0, 0, 0);
  469. char buf[124];
  470. sprintf(buf,"SHIFT+Cursor Left/Right - rotate lift");
  471. GLDebugDrawString(xStart,20,buf);
  472. yStart+=20;
  473. sprintf(buf,"SHIFT+Cursor UP/Down - fork up/down");
  474. yStart+=20;
  475. GLDebugDrawString(xStart,yStart,buf);
  476. if (m_useDefaultCamera)
  477. {
  478. sprintf(buf,"F5 - camera mode (free)");
  479. } else
  480. {
  481. sprintf(buf,"F5 - camera mode (follow)");
  482. }
  483. yStart+=20;
  484. GLDebugDrawString(xStart,yStart,buf);
  485. yStart+=20;
  486. if (m_dynamicsWorld->getConstraintSolver()->getSolverType()==BT_MLCP_SOLVER)
  487. {
  488. sprintf(buf,"F6 - solver (direct MLCP)");
  489. } else
  490. {
  491. sprintf(buf,"F6 - solver (sequential impulse)");
  492. }
  493. GLDebugDrawString(xStart,yStart,buf);
  494. btDiscreteDynamicsWorld* world = (btDiscreteDynamicsWorld*) m_dynamicsWorld;
  495. if (world->getLatencyMotionStateInterpolation())
  496. {
  497. sprintf(buf,"F7 - motionstate interpolation (on)");
  498. } else
  499. {
  500. sprintf(buf,"F7 - motionstate interpolation (off)");
  501. }
  502. yStart+=20;
  503. GLDebugDrawString(xStart,yStart,buf);
  504. sprintf(buf,"Click window for keyboard focus");
  505. yStart+=20;
  506. GLDebugDrawString(xStart,yStart,buf);
  507. resetPerspectiveProjection();
  508. glEnable(GL_LIGHTING);
  509. }
  510. #endif
  511. }
  512. void ForkLiftDemo::stepSimulation(float deltaTime)
  513. {
  514. //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  515. {
  516. int wheelIndex = 2;
  517. m_vehicle->applyEngineForce(gEngineForce,wheelIndex);
  518. m_vehicle->setBrake(gBreakingForce,wheelIndex);
  519. wheelIndex = 3;
  520. m_vehicle->applyEngineForce(gEngineForce,wheelIndex);
  521. m_vehicle->setBrake(gBreakingForce,wheelIndex);
  522. wheelIndex = 0;
  523. m_vehicle->setSteeringValue(gVehicleSteering,wheelIndex);
  524. wheelIndex = 1;
  525. m_vehicle->setSteeringValue(gVehicleSteering,wheelIndex);
  526. }
  527. float dt = deltaTime;
  528. if (m_dynamicsWorld)
  529. {
  530. //during idle mode, just run 1 simulation step maximum
  531. int maxSimSubSteps = 2;
  532. int numSimSteps;
  533. numSimSteps = m_dynamicsWorld->stepSimulation(dt,maxSimSubSteps);
  534. if (m_dynamicsWorld->getConstraintSolver()->getSolverType()==BT_MLCP_SOLVER)
  535. {
  536. btMLCPSolver* sol = (btMLCPSolver*) m_dynamicsWorld->getConstraintSolver();
  537. int numFallbacks = sol->getNumFallbacks();
  538. if (numFallbacks)
  539. {
  540. static int totalFailures = 0;
  541. totalFailures+=numFallbacks;
  542. printf("MLCP solver failed %d times, falling back to btSequentialImpulseSolver (SI)\n",totalFailures);
  543. }
  544. sol->setNumFallbacks(0);
  545. }
  546. //#define VERBOSE_FEEDBACK
  547. #ifdef VERBOSE_FEEDBACK
  548. if (!numSimSteps)
  549. printf("Interpolated transforms\n");
  550. else
  551. {
  552. if (numSimSteps > maxSimSubSteps)
  553. {
  554. //detect dropping frames
  555. printf("Dropped (%i) simulation steps out of %i\n",numSimSteps - maxSimSubSteps,numSimSteps);
  556. } else
  557. {
  558. printf("Simulated (%i) steps\n",numSimSteps);
  559. }
  560. }
  561. #endif //VERBOSE_FEEDBACK
  562. }
  563. }
  564. void ForkLiftDemo::displayCallback(void)
  565. {
  566. // glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  567. //renderme();
  568. //optional but useful: debug drawing
  569. if (m_dynamicsWorld)
  570. m_dynamicsWorld->debugDrawWorld();
  571. // glFlush();
  572. // glutSwapBuffers();
  573. }
  574. void ForkLiftDemo::clientResetScene()
  575. {
  576. exitPhysics();
  577. initPhysics();
  578. }
  579. void ForkLiftDemo::resetForklift()
  580. {
  581. gVehicleSteering = 0.f;
  582. gBreakingForce = defaultBreakingForce;
  583. gEngineForce = 0.f;
  584. m_carChassis->setCenterOfMassTransform(btTransform::getIdentity());
  585. m_carChassis->setLinearVelocity(btVector3(0,0,0));
  586. m_carChassis->setAngularVelocity(btVector3(0,0,0));
  587. m_dynamicsWorld->getBroadphase()->getOverlappingPairCache()->cleanProxyFromPairs(m_carChassis->getBroadphaseHandle(),getDynamicsWorld()->getDispatcher());
  588. if (m_vehicle)
  589. {
  590. m_vehicle->resetSuspension();
  591. for (int i=0;i<m_vehicle->getNumWheels();i++)
  592. {
  593. //synchronize the wheels with the (interpolated) chassis worldtransform
  594. m_vehicle->updateWheelTransform(i,true);
  595. }
  596. }
  597. btTransform liftTrans;
  598. liftTrans.setIdentity();
  599. liftTrans.setOrigin(m_liftStartPos);
  600. m_liftBody->activate();
  601. m_liftBody->setCenterOfMassTransform(liftTrans);
  602. m_liftBody->setLinearVelocity(btVector3(0,0,0));
  603. m_liftBody->setAngularVelocity(btVector3(0,0,0));
  604. btTransform forkTrans;
  605. forkTrans.setIdentity();
  606. forkTrans.setOrigin(m_forkStartPos);
  607. m_forkBody->activate();
  608. m_forkBody->setCenterOfMassTransform(forkTrans);
  609. m_forkBody->setLinearVelocity(btVector3(0,0,0));
  610. m_forkBody->setAngularVelocity(btVector3(0,0,0));
  611. // m_liftHinge->setLimit(-LIFT_EPS, LIFT_EPS);
  612. m_liftHinge->setLimit(0.0f, 0.0f);
  613. m_liftHinge->enableAngularMotor(false, 0, 0);
  614. m_forkSlider->setLowerLinLimit(0.1f);
  615. m_forkSlider->setUpperLinLimit(0.1f);
  616. m_forkSlider->setPoweredLinMotor(false);
  617. btTransform loadTrans;
  618. loadTrans.setIdentity();
  619. loadTrans.setOrigin(m_loadStartPos);
  620. m_loadBody->activate();
  621. m_loadBody->setCenterOfMassTransform(loadTrans);
  622. m_loadBody->setLinearVelocity(btVector3(0,0,0));
  623. m_loadBody->setAngularVelocity(btVector3(0,0,0));
  624. }
  625. bool ForkLiftDemo::keyboardCallback(int key, int state)
  626. {
  627. bool handled = false;
  628. bool isShiftPressed = m_guiHelper->getAppInterface()->m_window->isModifierKeyPressed(B3G_SHIFT);
  629. if (state)
  630. {
  631. if (isShiftPressed)
  632. {
  633. switch (key)
  634. {
  635. case B3G_LEFT_ARROW :
  636. {
  637. m_liftHinge->setLimit(-M_PI/16.0f, M_PI/8.0f);
  638. m_liftHinge->enableAngularMotor(true, -0.1, maxMotorImpulse);
  639. handled = true;
  640. break;
  641. }
  642. case B3G_RIGHT_ARROW :
  643. {
  644. m_liftHinge->setLimit(-M_PI/16.0f, M_PI/8.0f);
  645. m_liftHinge->enableAngularMotor(true, 0.1, maxMotorImpulse);
  646. handled = true;
  647. break;
  648. }
  649. case B3G_UP_ARROW :
  650. {
  651. m_forkSlider->setLowerLinLimit(0.1f);
  652. m_forkSlider->setUpperLinLimit(3.9f);
  653. m_forkSlider->setPoweredLinMotor(true);
  654. m_forkSlider->setMaxLinMotorForce(maxMotorImpulse);
  655. m_forkSlider->setTargetLinMotorVelocity(1.0);
  656. handled = true;
  657. break;
  658. }
  659. case B3G_DOWN_ARROW :
  660. {
  661. m_forkSlider->setLowerLinLimit(0.1f);
  662. m_forkSlider->setUpperLinLimit(3.9f);
  663. m_forkSlider->setPoweredLinMotor(true);
  664. m_forkSlider->setMaxLinMotorForce(maxMotorImpulse);
  665. m_forkSlider->setTargetLinMotorVelocity(-1.0);
  666. handled = true;
  667. break;
  668. }
  669. }
  670. } else
  671. {
  672. switch (key)
  673. {
  674. case B3G_LEFT_ARROW :
  675. {
  676. handled = true;
  677. gVehicleSteering += steeringIncrement;
  678. if ( gVehicleSteering > steeringClamp)
  679. gVehicleSteering = steeringClamp;
  680. break;
  681. }
  682. case B3G_RIGHT_ARROW :
  683. {
  684. handled = true;
  685. gVehicleSteering -= steeringIncrement;
  686. if ( gVehicleSteering < -steeringClamp)
  687. gVehicleSteering = -steeringClamp;
  688. break;
  689. }
  690. case B3G_UP_ARROW :
  691. {
  692. handled = true;
  693. gEngineForce = maxEngineForce;
  694. gBreakingForce = 0.f;
  695. break;
  696. }
  697. case B3G_DOWN_ARROW :
  698. {
  699. handled = true;
  700. gEngineForce = -maxEngineForce;
  701. gBreakingForce = 0.f;
  702. break;
  703. }
  704. case B3G_F7:
  705. {
  706. handled = true;
  707. btDiscreteDynamicsWorld* world = (btDiscreteDynamicsWorld*)m_dynamicsWorld;
  708. world->setLatencyMotionStateInterpolation(!world->getLatencyMotionStateInterpolation());
  709. printf("world latencyMotionStateInterpolation = %d\n", world->getLatencyMotionStateInterpolation());
  710. break;
  711. }
  712. case B3G_F6:
  713. {
  714. handled = true;
  715. //switch solver (needs demo restart)
  716. useMCLPSolver = !useMCLPSolver;
  717. printf("switching to useMLCPSolver = %d\n", useMCLPSolver);
  718. delete m_constraintSolver;
  719. if (useMCLPSolver)
  720. {
  721. btDantzigSolver* mlcp = new btDantzigSolver();
  722. //btSolveProjectedGaussSeidel* mlcp = new btSolveProjectedGaussSeidel;
  723. btMLCPSolver* sol = new btMLCPSolver(mlcp);
  724. m_constraintSolver = sol;
  725. } else
  726. {
  727. m_constraintSolver = new btSequentialImpulseConstraintSolver();
  728. }
  729. m_dynamicsWorld->setConstraintSolver(m_constraintSolver);
  730. //exitPhysics();
  731. //initPhysics();
  732. break;
  733. }
  734. case B3G_F5:
  735. handled = true;
  736. m_useDefaultCamera = !m_useDefaultCamera;
  737. break;
  738. default:
  739. break;
  740. }
  741. }
  742. } else
  743. {
  744. switch (key)
  745. {
  746. case B3G_UP_ARROW:
  747. {
  748. lockForkSlider();
  749. gEngineForce = 0.f;
  750. gBreakingForce = defaultBreakingForce;
  751. handled=true;
  752. break;
  753. }
  754. case B3G_DOWN_ARROW:
  755. {
  756. lockForkSlider();
  757. gEngineForce = 0.f;
  758. gBreakingForce = defaultBreakingForce;
  759. handled=true;
  760. break;
  761. }
  762. case B3G_LEFT_ARROW:
  763. case B3G_RIGHT_ARROW:
  764. {
  765. lockLiftHinge();
  766. handled=true;
  767. break;
  768. }
  769. default:
  770. break;
  771. }
  772. }
  773. return handled;
  774. }
  775. void ForkLiftDemo::specialKeyboardUp(int key, int x, int y)
  776. {
  777. #if 0
  778. #endif
  779. }
  780. void ForkLiftDemo::specialKeyboard(int key, int x, int y)
  781. {
  782. #if 0
  783. if (key==GLUT_KEY_END)
  784. return;
  785. // printf("key = %i x=%i y=%i\n",key,x,y);
  786. int state;
  787. state=glutGetModifiers();
  788. if (state & GLUT_ACTIVE_SHIFT)
  789. {
  790. switch (key)
  791. {
  792. case GLUT_KEY_LEFT :
  793. {
  794. m_liftHinge->setLimit(-M_PI/16.0f, M_PI/8.0f);
  795. m_liftHinge->enableAngularMotor(true, -0.1, maxMotorImpulse);
  796. break;
  797. }
  798. case GLUT_KEY_RIGHT :
  799. {
  800. m_liftHinge->setLimit(-M_PI/16.0f, M_PI/8.0f);
  801. m_liftHinge->enableAngularMotor(true, 0.1, maxMotorImpulse);
  802. break;
  803. }
  804. case GLUT_KEY_UP :
  805. {
  806. m_forkSlider->setLowerLinLimit(0.1f);
  807. m_forkSlider->setUpperLinLimit(3.9f);
  808. m_forkSlider->setPoweredLinMotor(true);
  809. m_forkSlider->setMaxLinMotorForce(maxMotorImpulse);
  810. m_forkSlider->setTargetLinMotorVelocity(1.0);
  811. break;
  812. }
  813. case GLUT_KEY_DOWN :
  814. {
  815. m_forkSlider->setLowerLinLimit(0.1f);
  816. m_forkSlider->setUpperLinLimit(3.9f);
  817. m_forkSlider->setPoweredLinMotor(true);
  818. m_forkSlider->setMaxLinMotorForce(maxMotorImpulse);
  819. m_forkSlider->setTargetLinMotorVelocity(-1.0);
  820. break;
  821. }
  822. default:
  823. DemoApplication::specialKeyboard(key,x,y);
  824. break;
  825. }
  826. } else
  827. {
  828. switch (key)
  829. {
  830. case GLUT_KEY_LEFT :
  831. {
  832. gVehicleSteering += steeringIncrement;
  833. if ( gVehicleSteering > steeringClamp)
  834. gVehicleSteering = steeringClamp;
  835. break;
  836. }
  837. case GLUT_KEY_RIGHT :
  838. {
  839. gVehicleSteering -= steeringIncrement;
  840. if ( gVehicleSteering < -steeringClamp)
  841. gVehicleSteering = -steeringClamp;
  842. break;
  843. }
  844. case GLUT_KEY_UP :
  845. {
  846. gEngineForce = maxEngineForce;
  847. gBreakingForce = 0.f;
  848. break;
  849. }
  850. case GLUT_KEY_DOWN :
  851. {
  852. gEngineForce = -maxEngineForce;
  853. gBreakingForce = 0.f;
  854. break;
  855. }
  856. case GLUT_KEY_F7:
  857. {
  858. btDiscreteDynamicsWorld* world = (btDiscreteDynamicsWorld*)m_dynamicsWorld;
  859. world->setLatencyMotionStateInterpolation(!world->getLatencyMotionStateInterpolation());
  860. printf("world latencyMotionStateInterpolation = %d\n", world->getLatencyMotionStateInterpolation());
  861. break;
  862. }
  863. case GLUT_KEY_F6:
  864. {
  865. //switch solver (needs demo restart)
  866. useMCLPSolver = !useMCLPSolver;
  867. printf("switching to useMLCPSolver = %d\n", useMCLPSolver);
  868. delete m_constraintSolver;
  869. if (useMCLPSolver)
  870. {
  871. btDantzigSolver* mlcp = new btDantzigSolver();
  872. //btSolveProjectedGaussSeidel* mlcp = new btSolveProjectedGaussSeidel;
  873. btMLCPSolver* sol = new btMLCPSolver(mlcp);
  874. m_constraintSolver = sol;
  875. } else
  876. {
  877. m_constraintSolver = new btSequentialImpulseConstraintSolver();
  878. }
  879. m_dynamicsWorld->setConstraintSolver(m_constraintSolver);
  880. //exitPhysics();
  881. //initPhysics();
  882. break;
  883. }
  884. case GLUT_KEY_F5:
  885. m_useDefaultCamera = !m_useDefaultCamera;
  886. break;
  887. default:
  888. DemoApplication::specialKeyboard(key,x,y);
  889. break;
  890. }
  891. }
  892. // glutPostRedisplay();
  893. #endif
  894. }
  895. void ForkLiftDemo::lockLiftHinge(void)
  896. {
  897. btScalar hingeAngle = m_liftHinge->getHingeAngle();
  898. btScalar lowLim = m_liftHinge->getLowerLimit();
  899. btScalar hiLim = m_liftHinge->getUpperLimit();
  900. m_liftHinge->enableAngularMotor(false, 0, 0);
  901. if(hingeAngle < lowLim)
  902. {
  903. // m_liftHinge->setLimit(lowLim, lowLim + LIFT_EPS);
  904. m_liftHinge->setLimit(lowLim, lowLim);
  905. }
  906. else if(hingeAngle > hiLim)
  907. {
  908. // m_liftHinge->setLimit(hiLim - LIFT_EPS, hiLim);
  909. m_liftHinge->setLimit(hiLim, hiLim);
  910. }
  911. else
  912. {
  913. // m_liftHinge->setLimit(hingeAngle - LIFT_EPS, hingeAngle + LIFT_EPS);
  914. m_liftHinge->setLimit(hingeAngle, hingeAngle);
  915. }
  916. return;
  917. } // ForkLiftDemo::lockLiftHinge()
  918. void ForkLiftDemo::lockForkSlider(void)
  919. {
  920. btScalar linDepth = m_forkSlider->getLinearPos();
  921. btScalar lowLim = m_forkSlider->getLowerLinLimit();
  922. btScalar hiLim = m_forkSlider->getUpperLinLimit();
  923. m_forkSlider->setPoweredLinMotor(false);
  924. if(linDepth <= lowLim)
  925. {
  926. m_forkSlider->setLowerLinLimit(lowLim);
  927. m_forkSlider->setUpperLinLimit(lowLim);
  928. }
  929. else if(linDepth > hiLim)
  930. {
  931. m_forkSlider->setLowerLinLimit(hiLim);
  932. m_forkSlider->setUpperLinLimit(hiLim);
  933. }
  934. else
  935. {
  936. m_forkSlider->setLowerLinLimit(linDepth);
  937. m_forkSlider->setUpperLinLimit(linDepth);
  938. }
  939. return;
  940. } // ForkLiftDemo::lockForkSlider()
  941. btRigidBody* ForkLiftDemo::localCreateRigidBody(btScalar mass, const btTransform& startTransform, btCollisionShape* shape)
  942. {
  943. btAssert((!shape || shape->getShapeType() != INVALID_SHAPE_PROXYTYPE));
  944. //rigidbody is dynamic if and only if mass is non zero, otherwise static
  945. bool isDynamic = (mass != 0.f);
  946. btVector3 localInertia(0,0,0);
  947. if (isDynamic)
  948. shape->calculateLocalInertia(mass,localInertia);
  949. //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
  950. #define USE_MOTIONSTATE 1
  951. #ifdef USE_MOTIONSTATE
  952. btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
  953. btRigidBody::btRigidBodyConstructionInfo cInfo(mass,myMotionState,shape,localInertia);
  954. btRigidBody* body = new btRigidBody(cInfo);
  955. //body->setContactProcessingThreshold(m_defaultContactProcessingThreshold);
  956. #else
  957. btRigidBody* body = new btRigidBody(mass,0,shape,localInertia);
  958. body->setWorldTransform(startTransform);
  959. #endif//
  960. m_dynamicsWorld->addRigidBody(body);
  961. return body;
  962. }
  963. CommonExampleInterface* ForkLiftCreateFunc(struct CommonExampleOptions& options)
  964. {
  965. return new ForkLiftDemo(options.m_guiHelper);
  966. }