Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 

474 řádky
13 KiB

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