您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 

471 行
12 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 "core.h"
  31. #include "loldebug.h"
  32. using namespace lol;
  33. #ifndef HAVE_PHYS_USE_BULLET
  34. #define HAVE_PHYS_USE_BULLET
  35. #endif /* HAVE_PHYS_USE_BULLET */
  36. #include "Physics/LolPhysics.h"
  37. #include "Physics/EasyPhysics.h"
  38. #include "PhysicObject.h"
  39. #include "BtPhysTest.h"
  40. using namespace lol::phys;
  41. #define CUBE_HALF_EXTENTS .5f
  42. #define EXTRA_HEIGHT 1.f
  43. int gNumObjects = 64;
  44. BtPhysTest::BtPhysTest(bool editor)
  45. {
  46. /* Create a camera that matches the settings of XNA BtPhysTest */
  47. m_camera = new Camera(vec3(0.f, 600.f, 0.f),
  48. vec3(0.f, 0.f, 0.f),
  49. vec3(0, 1, 0));
  50. m_camera->SetRotation(quat::fromeuler_xyz(0.f, 0.f, 0.f));
  51. m_camera->SetPerspective(45.f, 1280.f, 960.f, .1f, 1000.f);
  52. //m_camera->SetOrtho(1280.f / 6, 960.f / 6, -1000.f, 1000.f);
  53. Ticker::Ref(m_camera);
  54. m_ready = false;
  55. m_simulation = new Simulation();
  56. m_simulation->Init();
  57. vec3 NewGravity = vec3(.0f, -10.0f, .0f);
  58. m_simulation->SetGravity(NewGravity);
  59. m_simulation->SetContinuousDetection(true);
  60. m_simulation->SetTimestep(1.f / 120.f);
  61. Ticker::Ref(m_simulation);
  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, 1000.f,
  90. vec3(-20.f, 15.f, -20.f) +
  91. vec3(8.f * (float)x, 8.f * (float)y, 8.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. vec3 GroundBarycenter = vec3(.0f);
  213. vec3 PhysObjBarycenter = vec3(.0f);
  214. float factor = .0f;
  215. for (int i = 0; i < m_ground_list.Count(); i++)
  216. {
  217. PhysicsObject* PhysObj = m_ground_list[i];
  218. mat4 GroundMat = PhysObj->GetTransform();
  219. GroundBarycenter += GroundMat.v3.xyz;
  220. factor += 1.f;
  221. }
  222. GroundBarycenter /= factor;
  223. for (int i = 0; i < m_ground_list.Count(); i++)
  224. {
  225. PhysicsObject* PhysObj = m_ground_list[i];
  226. mat4 GroundMat = PhysObj->GetTransform();
  227. vec3 CenterToGround = GroundMat.v3.xyz - GroundBarycenter;
  228. vec3 CenterToCam = m_camera->m_position - GroundBarycenter;
  229. if (dot(normalize(CenterToCam - CenterToGround),
  230. normalize(CenterToGround)) > 0.f)
  231. PhysObj->SetRender(false);
  232. else
  233. PhysObj->SetRender(true);
  234. }
  235. for (int i = 0; i < m_ground_list.Count(); i++)
  236. {
  237. PhysicsObject* PhysObj = m_ground_list[i];
  238. mat4 GroundMat = PhysObj->GetTransform();
  239. mat4 CenterMx = mat4::translate(GroundBarycenter);
  240. GroundMat = inverse(CenterMx) * GroundMat;
  241. GroundMat = CenterMx *
  242. mat4(quat::fromeuler_xyz(vec3(.0f, 20.f, 20.0f) * seconds))
  243. * GroundMat;
  244. PhysObj->SetTransform(GroundMat.v3.xyz, quat(GroundMat));
  245. }
  246. PhysObjBarycenter = vec3(.0f);
  247. for (int i = 0; i < m_physobj_list.Count(); i++)
  248. {
  249. PhysicsObject* PhysObj = m_physobj_list[i];
  250. mat4 GroundMat = PhysObj->GetTransform();
  251. PhysObjBarycenter += GroundMat.v3.xyz;
  252. factor += 1.f;
  253. }
  254. PhysObjBarycenter /= factor;
  255. m_camera->SetTarget(PhysObjBarycenter);
  256. m_camera->SetPosition(GroundBarycenter + normalize(GroundBarycenter - PhysObjBarycenter) * 60.0f);
  257. #if 0
  258. ///step the simulation
  259. if (m_bt_world)
  260. {
  261. //int steps = (int)(seconds / 0.005f);
  262. //for (int i = 0; i < steps; i++)
  263. m_bt_world->stepSimulation(seconds /*/ steps*/);
  264. //optional but useful: debug drawing
  265. //m_bt_world->debugDrawWorld();
  266. }
  267. #endif
  268. }
  269. void BtPhysTest::TickDraw(float seconds)
  270. {
  271. WorldEntity::TickDraw(seconds);
  272. if (!m_ready)
  273. {
  274. #if 0
  275. m_ground_mesh.MeshConvert();
  276. m_rigid_mesh[0].MeshConvert();
  277. m_rigid_mesh[1].MeshConvert();
  278. m_rigid_mesh[2].MeshConvert();
  279. m_rigid_mesh[3].MeshConvert();
  280. m_rigid_mesh[4].MeshConvert();
  281. m_rigid_mesh[5].MeshConvert();
  282. #endif
  283. /* FIXME: this object never cleans up */
  284. m_ready = true;
  285. }
  286. Video::SetClearColor(vec4(0.0f, 0.0f, 0.12f, 1.0f));
  287. #if 0
  288. vec3 BarycenterLocation = vec3(.0f);
  289. float BarycenterFactor = 0.0f;
  290. for(int i=0;i<gNumObjects;i++)
  291. {
  292. mat4 m(1.0f);
  293. btMatrix3x3 rot; rot.setIdentity();
  294. btCollisionObject* colObj = m_bt_world->getCollisionObjectArray()[i];
  295. btRigidBody* body = btRigidBody::upcast(colObj);
  296. if(body && body->getMotionState())
  297. {
  298. btDefaultMotionState* myMotionState = (btDefaultMotionState*)body->getMotionState();
  299. myMotionState->m_graphicsWorldTrans.getOpenGLMatrix(&m[0][0]);
  300. rot = myMotionState->m_graphicsWorldTrans.getBasis();
  301. }
  302. else
  303. {
  304. colObj->getWorldTransform().getOpenGLMatrix(&m[0][0]);
  305. rot = colObj->getWorldTransform().getBasis();
  306. }
  307. if (i > 0)
  308. {
  309. BarycenterLocation += m.v3.xyz;
  310. BarycenterFactor += 1.0f;
  311. }
  312. if (i == 0)
  313. m_ground_mesh.Render(m);
  314. else
  315. m_rigid_mesh[i % 6].Render(m);
  316. }
  317. if (BarycenterFactor > .0f)
  318. {
  319. BarycenterLocation /= BarycenterFactor;
  320. m_camera->SetTarget(BarycenterLocation);
  321. m_camera->SetPosition(BarycenterLocation + vec3(-20.0f, 8.0f, .0f));
  322. }
  323. #endif
  324. }
  325. BtPhysTest::~BtPhysTest()
  326. {
  327. Ticker::Unref(m_camera);
  328. while (m_ground_list.Count())
  329. {
  330. PhysicsObject* CurPop = m_ground_list.Last();
  331. m_ground_list.Pop();
  332. Ticker::Unref(CurPop);
  333. }
  334. while (m_physobj_list.Count())
  335. {
  336. PhysicsObject* CurPop = m_physobj_list.Last();
  337. m_physobj_list.Pop();
  338. Ticker::Unref(CurPop);
  339. }
  340. Ticker::Unref(m_simulation);
  341. #if 0
  342. //Exit Physics
  343. {
  344. //cleanup in the reverse order of creation/initialization
  345. //remove the rigidbodies from the dynamics world and delete them
  346. for (int i = m_bt_world->getNumCollisionObjects() - 1; i >= 0 ;i--)
  347. {
  348. btCollisionObject* obj = m_bt_world->getCollisionObjectArray()[i];
  349. btRigidBody* body = btRigidBody::upcast(obj);
  350. if (body && body->getMotionState())
  351. delete body->getMotionState();
  352. m_bt_world->removeCollisionObject(obj);
  353. delete obj;
  354. }
  355. //delete collision shapes
  356. for (int j = 0; j < m_bt_collision_shapes.Count(); j++)
  357. {
  358. btCollisionShape* shape = m_bt_collision_shapes[j];
  359. delete shape;
  360. }
  361. m_bt_collision_shapes.Empty();
  362. delete m_bt_world;
  363. delete m_bt_solver;
  364. delete m_bt_broadphase;
  365. delete m_bt_dispatcher;
  366. delete m_bt_collision_config;
  367. }
  368. #endif
  369. }
  370. int main(int argc, char **argv)
  371. {
  372. Application app("BtPhysTest", ivec2(1280, 720), 60.0f);
  373. #if defined _MSC_VER && !defined _XBOX
  374. _chdir("..");
  375. #elif defined _WIN32 && !defined _XBOX
  376. _chdir("../..");
  377. #endif
  378. new BtPhysTest(argc > 1);
  379. app.ShowPointer(false);
  380. app.Run();
  381. return EXIT_SUCCESS;
  382. }