You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BtPhysTest.cpp 15 KiB

12 years ago
12 years ago
12 years ago
12 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. //
  2. // BtPhysTest
  3. //
  4. // Copyright: (c) 2009-2012 Benjamin Huet <huet.benjamin@gmail.com>
  5. // (c) 2012 Sam Hocevar <sam@hocevar.net>
  6. //
  7. #if defined HAVE_CONFIG_H
  8. # include "config.h"
  9. #endif
  10. #if defined _WIN32
  11. # include <direct.h>
  12. #endif
  13. #if defined _XBOX
  14. # define _USE_MATH_DEFINES /* for M_PI */
  15. # include <xtl.h>
  16. # undef near /* Fuck Microsoft */
  17. # undef far /* Fuck Microsoft again */
  18. #elif defined _WIN32
  19. # define _USE_MATH_DEFINES /* for M_PI */
  20. # define WIN32_LEAN_AND_MEAN
  21. # include <windows.h>
  22. # undef near /* Fuck Microsoft */
  23. # undef far /* Fuck Microsoft again */
  24. #else
  25. # include <cmath>
  26. #endif
  27. #include "core.h"
  28. #include "loldebug.h"
  29. using namespace lol;
  30. #ifndef HAVE_PHYS_USE_BULLET
  31. #define HAVE_PHYS_USE_BULLET
  32. #endif /* HAVE_PHYS_USE_BULLET */
  33. #include "Physics/LolPhysics.h"
  34. #include "Physics/EasyPhysics.h"
  35. #include "PhysicObject.h"
  36. #include "BtPhysTest.h"
  37. using namespace lol::phys;
  38. #define CUBE_HALF_EXTENTS .5f
  39. #define EXTRA_HEIGHT 1.f
  40. int gNumObjects = 64;
  41. BtPhysTest::BtPhysTest(bool editor)
  42. {
  43. /* Create a camera that matches the settings of XNA BtPhysTest */
  44. m_camera = new Camera(vec3(0.f, 600.f, 0.f),
  45. vec3(0.f, 0.f, 0.f),
  46. vec3(0, 1, 0));
  47. m_camera->SetRotation(quat::fromeuler_xyz(0.f, 0.f, 0.f));
  48. m_camera->SetPerspective(45.f, 1280.f, 960.f, .1f, 1000.f);
  49. //m_camera->SetOrtho(1280.f / 6, 960.f / 6, -1000.f, 1000.f);
  50. Ticker::Ref(m_camera);
  51. m_ready = false;
  52. m_simulation = new Simulation();
  53. m_simulation->Init();
  54. vec3 NewGravity = vec3(.0f, -10.0f, .0f);
  55. m_simulation->SetGravity(NewGravity);
  56. m_simulation->SetContinuousDetection(true);
  57. m_simulation->SetTimestep(1.f / 120.f);
  58. Ticker::Ref(m_simulation);
  59. float offset = 29.5f;
  60. vec3 pos_offset = vec3(.0f, 30.f, .0f);
  61. for (int i=0; i < 6; i++)
  62. {
  63. vec3 NewPosition = vec3(.0f);
  64. quat NewRotation = quat(1.f);
  65. PhysicsObject* NewPhyobj = new PhysicsObject(m_simulation, NewPosition, NewRotation);
  66. int idx = i/2;
  67. NewPosition = pos_offset;
  68. NewPosition[idx] += offset;
  69. offset *= -1.f;
  70. if (idx != 1)
  71. {
  72. vec3 axis = vec3(.0f);
  73. axis[2 - idx] = 1;
  74. NewRotation = quat::rotate(90.f, axis);
  75. }
  76. NewPhyobj->SetTransform(NewPosition, NewRotation);
  77. Ticker::Ref(NewPhyobj);
  78. m_ground_list << NewPhyobj;
  79. }
  80. {
  81. quat NewRotation = quat(1.f);
  82. vec3 NewPosition = pos_offset + vec3(5.0f, -20.0f, -15.0f);
  83. PhysicsObject* NewPhyobj = new PhysicsObject(m_simulation, NewPosition, NewRotation, 0);
  84. m_platform_list << NewPhyobj;
  85. Ticker::Ref(NewPhyobj);
  86. NewPosition = pos_offset + vec3(-20.0f, -25.0f, 5.0f);
  87. NewPhyobj = new PhysicsObject(m_simulation, NewPosition, NewRotation, 0);
  88. m_platform_list << NewPhyobj;
  89. Ticker::Ref(NewPhyobj);
  90. }
  91. if (1)
  92. {
  93. for (int x=0; x < 6; x++)
  94. {
  95. for (int y=0; y < 6; y++)
  96. {
  97. for (int z=0; z < 5; z++)
  98. {
  99. PhysicsObject* new_physobj = new PhysicsObject(m_simulation, 1000.f,
  100. vec3(-20.f, 15.f, -20.f) +
  101. vec3(8.f * (float)x, 8.f * (float)y, 8.f * (float)z));
  102. m_physobj_list << new_physobj;
  103. Ticker::Ref(new_physobj);
  104. }
  105. }
  106. }
  107. }
  108. if (1)
  109. {
  110. Array<PhysicsObject*> RopeElements;
  111. for (int i = 0; i < 14; i++)
  112. {
  113. PhysicsObject* new_physobj = new PhysicsObject(m_simulation, 1000.f,
  114. vec3(0.f, 15.f, -20.f) +
  115. vec3(0.f, 0.f, 2.f * (float)i), 1);
  116. RopeElements << new_physobj;
  117. m_physobj_list << new_physobj;
  118. Ticker::Ref(new_physobj);
  119. if (RopeElements.Count() > 1)
  120. {
  121. EasyConstraint* new_constraint = new EasyConstraint();
  122. vec3 A2B = .5f * (RopeElements[i]->GetPhysic()->GetTransform().v3.xyz -
  123. RopeElements[i - 1]->GetPhysic()->GetTransform().v3.xyz);
  124. new_constraint->SetPhysObjA(RopeElements[i - 1]->GetPhysic(), lol::mat4::translate(A2B));
  125. new_constraint->SetPhysObjB(RopeElements[i]->GetPhysic(), lol::mat4::translate(-A2B));
  126. new_constraint->InitConstraintToPoint2Point();
  127. new_constraint->DisableCollisionBetweenObjs(true);
  128. new_constraint->AddToSimulation(m_simulation);
  129. m_constraint_list << new_constraint;
  130. }
  131. }
  132. }
  133. #if 0
  134. //init Physics
  135. {
  136. m_bt_ccd_mode = USE_CCD;
  137. //collision configuration contains default setup for memory, collision setup
  138. m_bt_collision_config = new btDefaultCollisionConfiguration();
  139. //use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded)
  140. m_bt_dispatcher = new btCollisionDispatcher(m_bt_collision_config);
  141. m_bt_dispatcher->registerCollisionCreateFunc(BOX_SHAPE_PROXYTYPE,
  142. BOX_SHAPE_PROXYTYPE,
  143. m_bt_collision_config->getCollisionAlgorithmCreateFunc(CONVEX_SHAPE_PROXYTYPE,
  144. CONVEX_SHAPE_PROXYTYPE));
  145. m_bt_broadphase = new btDbvtBroadphase();
  146. ///the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded)
  147. m_bt_solver = new btSequentialImpulseConstraintSolver;
  148. m_bt_world = new btDiscreteDynamicsWorld(m_bt_dispatcher, m_bt_broadphase, m_bt_solver, m_bt_collision_config);
  149. //m_bt_world->setDebugDrawer(&sDebugDrawer);
  150. m_bt_world->getSolverInfo().m_splitImpulse = true;
  151. m_bt_world->getSolverInfo().m_numIterations = 20;
  152. m_bt_world->getDispatchInfo().m_useContinuous = (m_bt_ccd_mode == USE_CCD);
  153. m_bt_world->setGravity(btVector3(0,-10,0));
  154. ///create a few basic rigid bodies
  155. btBoxShape* box = new btBoxShape(btVector3(btScalar(110.),btScalar(1.),btScalar(110.)));
  156. btCollisionShape* groundShape = box;
  157. m_bt_collision_shapes << groundShape;
  158. m_ground_mesh.Compile("[sc#ddd afcb220 2 220 -1]");
  159. //m_bt_collision_shapes << new btCylinderShape(btVector3(.5f,.5f,.5f));
  160. btTransform groundTransform;
  161. groundTransform.setIdentity();
  162. //We can also use DemoApplication::localCreateRigidBody, but for clarity it is provided here:
  163. {
  164. btScalar mass(0.);
  165. //rigidbody is dynamic if and only if mass is non zero, otherwise static
  166. bool isDynamic = (mass != 0.f);
  167. btVector3 localInertia(0,0,0);
  168. if (isDynamic)
  169. groundShape->calculateLocalInertia(mass,localInertia);
  170. //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
  171. btDefaultMotionState* myMotionState = new btDefaultMotionState(groundTransform);
  172. btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,groundShape,localInertia);
  173. btRigidBody* body = new btRigidBody(rbInfo);
  174. //add the body to the dynamics world
  175. m_bt_world->addRigidBody(body);
  176. }
  177. //Adding Shapes
  178. {
  179. //create a few dynamic rigidbodies
  180. // Re-using the same collision is better for memory usage and performance
  181. btCollisionShape* colShape = new btBoxShape(btVector3(1,1,1));
  182. m_rigid_mesh[0].Compile("[sc#add afcb2 2 2 -.1]");
  183. m_rigid_mesh[1].Compile("[sc#dad afcb2 2 2 -.1]");
  184. m_rigid_mesh[2].Compile("[sc#dda afcb2 2 2 -.1]");
  185. m_rigid_mesh[3].Compile("[sc#daa afcb2 2 2 -.1]");
  186. m_rigid_mesh[4].Compile("[sc#ada afcb2 2 2 -.1]");
  187. m_rigid_mesh[5].Compile("[sc#aad afcb2 2 2 -.1]");
  188. m_bt_collision_shapes << colShape;
  189. m_bt_dynamic_shapes << colShape;
  190. /// Create Dynamic Objects
  191. btTransform startTransform;
  192. startTransform.setIdentity();
  193. btScalar mass(1.f);
  194. //rigidbody is dynamic if and only if mass is non zero, otherwise static
  195. bool isDynamic = (mass != 0.f);
  196. btVector3 localInertia(0,0,0);
  197. if (isDynamic)
  198. colShape->calculateLocalInertia(mass,localInertia);
  199. int i;
  200. for (i=0;i<gNumObjects;i++)
  201. {
  202. btCollisionShape* shape = colShape;
  203. btTransform trans;
  204. trans.setIdentity();
  205. //stack them
  206. int colsize = 10;
  207. int row = int(((float)i*CUBE_HALF_EXTENTS*2.0f)/((float)colsize*2.0f*CUBE_HALF_EXTENTS));
  208. int row2 = row;
  209. int col = (i)%(colsize)-colsize/2;
  210. if (col>3)
  211. {
  212. col=11;
  213. row2 |=1;
  214. }
  215. btVector3 pos(((row+col+row2) % 4)*CUBE_HALF_EXTENTS,
  216. 20.0f + row*8*CUBE_HALF_EXTENTS+CUBE_HALF_EXTENTS+EXTRA_HEIGHT,
  217. col*8*CUBE_HALF_EXTENTS + 2 * (row2%2)*CUBE_HALF_EXTENTS);
  218. trans.setOrigin(pos);
  219. float mass = 1.f;
  220. btAssert((!shape || shape->getShapeType() != INVALID_SHAPE_PROXYTYPE));
  221. //rigidbody is dynamic if and only if mass is non zero, otherwise static
  222. bool isDynamic = (mass != 0.f);
  223. btVector3 localInertia(0,0,0);
  224. if (isDynamic)
  225. shape->calculateLocalInertia(mass,localInertia);
  226. //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
  227. btDefaultMotionState* myMotionState = new btDefaultMotionState(trans);
  228. btRigidBody::btRigidBodyConstructionInfo cInfo(mass,myMotionState,shape,localInertia);
  229. btRigidBody* body = new btRigidBody(cInfo);
  230. body->setContactProcessingThreshold(BT_LARGE_FLOAT);
  231. m_bt_world->addRigidBody(body);
  232. ///when using m_ccdMode
  233. if (m_bt_ccd_mode == USE_CCD)
  234. {
  235. body->setCcdMotionThreshold(CUBE_HALF_EXTENTS);
  236. body->setCcdSweptSphereRadius(0.9*CUBE_HALF_EXTENTS);
  237. }
  238. }
  239. }
  240. }
  241. #endif
  242. }
  243. void BtPhysTest::TickGame(float seconds)
  244. {
  245. WorldEntity::TickGame(seconds);
  246. if (Input::GetButtonState(27 /*SDLK_ESCAPE*/))
  247. Ticker::Shutdown();
  248. vec3 GroundBarycenter = vec3(.0f);
  249. vec3 PhysObjBarycenter = vec3(.0f);
  250. float factor = .0f;
  251. for (int i = 0; i < m_ground_list.Count(); i++)
  252. {
  253. PhysicsObject* PhysObj = m_ground_list[i];
  254. mat4 GroundMat = PhysObj->GetTransform();
  255. GroundBarycenter += GroundMat.v3.xyz;
  256. factor += 1.f;
  257. }
  258. GroundBarycenter /= factor;
  259. for (int i = 0; i < m_ground_list.Count(); i++)
  260. {
  261. PhysicsObject* PhysObj = m_ground_list[i];
  262. mat4 GroundMat = PhysObj->GetTransform();
  263. vec3 CenterToGround = GroundMat.v3.xyz - GroundBarycenter;
  264. vec3 CenterToCam = m_camera->m_position - GroundBarycenter;
  265. if (dot(normalize(CenterToCam - CenterToGround),
  266. normalize(CenterToGround)) > 0.f)
  267. PhysObj->SetRender(false);
  268. else
  269. PhysObj->SetRender(true);
  270. }
  271. if (0)
  272. {
  273. for (int i = 0; i < m_ground_list.Count(); i++)
  274. {
  275. PhysicsObject* PhysObj = m_ground_list[i];
  276. mat4 GroundMat = PhysObj->GetTransform();
  277. mat4 CenterMx = mat4::translate(GroundBarycenter);
  278. GroundMat = inverse(CenterMx) * GroundMat;
  279. GroundMat = CenterMx *
  280. mat4(quat::fromeuler_xyz(vec3(.0f, 20.f, 20.0f) * seconds))
  281. * GroundMat;
  282. PhysObj->SetTransform(GroundMat.v3.xyz, quat(GroundMat));
  283. }
  284. }
  285. {
  286. for (int i = 0; i < m_platform_list.Count(); i++)
  287. {
  288. PhysicsObject* PhysObj = m_platform_list[i];
  289. mat4 GroundMat = PhysObj->GetTransform();
  290. if (i == 0)
  291. {
  292. GroundMat = GroundMat * mat4(quat::fromeuler_xyz(vec3(20.f, .0f, .0f) * seconds));
  293. PhysObj->SetTransform(GroundMat.v3.xyz, quat(GroundMat));
  294. }
  295. else
  296. {
  297. GroundMat = GroundMat * mat4::translate(vec3(.0f, .0f, 10.0f) * seconds);
  298. if (GroundMat.v3.z > 40.0f)
  299. GroundMat = GroundMat * mat4::translate(vec3(.0f, .0f, -80.0f));
  300. PhysObj->SetTransform(GroundMat.v3.xyz, quat(GroundMat));
  301. }
  302. }
  303. }
  304. PhysObjBarycenter = vec3(.0f);
  305. for (int i = 0; i < m_physobj_list.Count(); i++)
  306. {
  307. PhysicsObject* PhysObj = m_physobj_list[i];
  308. mat4 GroundMat = PhysObj->GetTransform();
  309. PhysObjBarycenter += GroundMat.v3.xyz;
  310. factor += 1.f;
  311. }
  312. PhysObjBarycenter /= factor;
  313. m_camera->SetTarget(PhysObjBarycenter);
  314. m_camera->SetPosition(GroundBarycenter + normalize(GroundBarycenter - PhysObjBarycenter) * 60.0f);
  315. #if 0
  316. ///step the simulation
  317. if (m_bt_world)
  318. {
  319. //int steps = (int)(seconds / 0.005f);
  320. //for (int i = 0; i < steps; i++)
  321. m_bt_world->stepSimulation(seconds /*/ steps*/);
  322. //optional but useful: debug drawing
  323. //m_bt_world->debugDrawWorld();
  324. }
  325. #endif
  326. }
  327. void BtPhysTest::TickDraw(float seconds)
  328. {
  329. WorldEntity::TickDraw(seconds);
  330. if (!m_ready)
  331. {
  332. #if 0
  333. m_ground_mesh.MeshConvert();
  334. m_rigid_mesh[0].MeshConvert();
  335. m_rigid_mesh[1].MeshConvert();
  336. m_rigid_mesh[2].MeshConvert();
  337. m_rigid_mesh[3].MeshConvert();
  338. m_rigid_mesh[4].MeshConvert();
  339. m_rigid_mesh[5].MeshConvert();
  340. #endif
  341. /* FIXME: this object never cleans up */
  342. m_ready = true;
  343. }
  344. Video::SetClearColor(vec4(0.0f, 0.0f, 0.12f, 1.0f));
  345. #if 0
  346. vec3 BarycenterLocation = vec3(.0f);
  347. float BarycenterFactor = 0.0f;
  348. for(int i=0;i<gNumObjects;i++)
  349. {
  350. mat4 m(1.0f);
  351. btMatrix3x3 rot; rot.setIdentity();
  352. btCollisionObject* colObj = m_bt_world->getCollisionObjectArray()[i];
  353. btRigidBody* body = btRigidBody::upcast(colObj);
  354. if(body && body->getMotionState())
  355. {
  356. btDefaultMotionState* myMotionState = (btDefaultMotionState*)body->getMotionState();
  357. myMotionState->m_graphicsWorldTrans.getOpenGLMatrix(&m[0][0]);
  358. rot = myMotionState->m_graphicsWorldTrans.getBasis();
  359. }
  360. else
  361. {
  362. colObj->getWorldTransform().getOpenGLMatrix(&m[0][0]);
  363. rot = colObj->getWorldTransform().getBasis();
  364. }
  365. if (i > 0)
  366. {
  367. BarycenterLocation += m.v3.xyz;
  368. BarycenterFactor += 1.0f;
  369. }
  370. if (i == 0)
  371. m_ground_mesh.Render(m);
  372. else
  373. m_rigid_mesh[i % 6].Render(m);
  374. }
  375. if (BarycenterFactor > .0f)
  376. {
  377. BarycenterLocation /= BarycenterFactor;
  378. m_camera->SetTarget(BarycenterLocation);
  379. m_camera->SetPosition(BarycenterLocation + vec3(-20.0f, 8.0f, .0f));
  380. }
  381. #endif
  382. }
  383. BtPhysTest::~BtPhysTest()
  384. {
  385. Ticker::Unref(m_camera);
  386. while (m_constraint_list.Count())
  387. {
  388. EasyConstraint* CurPop = m_constraint_list.Last();
  389. m_constraint_list.Pop();
  390. CurPop->RemoveFromSimulation(m_simulation);
  391. delete CurPop;
  392. }
  393. while (m_ground_list.Count())
  394. {
  395. PhysicsObject* CurPop = m_ground_list.Last();
  396. m_ground_list.Pop();
  397. CurPop->GetPhysic()->RemoveFromSimulation(m_simulation);
  398. Ticker::Unref(CurPop);
  399. }
  400. while (m_platform_list.Count())
  401. {
  402. PhysicsObject* CurPop = m_platform_list.Last();
  403. m_platform_list.Pop();
  404. CurPop->GetPhysic()->RemoveFromSimulation(m_simulation);
  405. Ticker::Unref(CurPop);
  406. }
  407. while (m_physobj_list.Count())
  408. {
  409. PhysicsObject* CurPop = m_physobj_list.Last();
  410. m_physobj_list.Pop();
  411. CurPop->GetPhysic()->RemoveFromSimulation(m_simulation);
  412. Ticker::Unref(CurPop);
  413. }
  414. Ticker::Unref(m_simulation);
  415. #if 0
  416. //Exit Physics
  417. {
  418. //cleanup in the reverse order of creation/initialization
  419. //remove the rigidbodies from the dynamics world and delete them
  420. for (int i = m_bt_world->getNumCollisionObjects() - 1; i >= 0 ;i--)
  421. {
  422. btCollisionObject* obj = m_bt_world->getCollisionObjectArray()[i];
  423. btRigidBody* body = btRigidBody::upcast(obj);
  424. if (body && body->getMotionState())
  425. delete body->getMotionState();
  426. m_bt_world->removeCollisionObject(obj);
  427. delete obj;
  428. }
  429. //delete collision shapes
  430. for (int j = 0; j < m_bt_collision_shapes.Count(); j++)
  431. {
  432. btCollisionShape* shape = m_bt_collision_shapes[j];
  433. delete shape;
  434. }
  435. m_bt_collision_shapes.Empty();
  436. delete m_bt_world;
  437. delete m_bt_solver;
  438. delete m_bt_broadphase;
  439. delete m_bt_dispatcher;
  440. delete m_bt_collision_config;
  441. }
  442. #endif
  443. }
  444. int main(int argc, char **argv)
  445. {
  446. Application app("BtPhysTest", ivec2(1280, 720), 60.0f);
  447. #if defined _MSC_VER && !defined _XBOX
  448. _chdir("..");
  449. #elif defined _WIN32 && !defined _XBOX
  450. _chdir("../..");
  451. #endif
  452. new BtPhysTest(argc > 1);
  453. app.ShowPointer(false);
  454. app.Run();
  455. return EXIT_SUCCESS;
  456. }