CPhysic.cpp
上传用户:liujun12jf
上传日期:2022-07-12
资源大小:638k
文件大小:2k
源码类别:

OpenGL

开发平台:

Visual C++

  1. #include "CPhysic.h"
  2. int GCBegin(const NewtonMaterial* material, const NewtonBody* body0, const NewtonBody* body1)
  3. {
  4. return 1;
  5. }
  6. int GCProcess(const NewtonMaterial* material, const NewtonContact* contact)
  7. {
  8. return 1;
  9. }
  10. void GCEnd(const NewtonMaterial* material)
  11. {
  12. }
  13. void CPhysic::AddObject(CPhysicObject *o)
  14. {
  15. NewtonCollision *c;
  16. NewtonBody *b;
  17. if (o->isBox) c = NewtonCreateBox(nWorld, o->size[0]*2, o->size[1]*2, o->size[2]*2, NULL); 
  18. else c = NewtonCreateSphere(nWorld, o->size[0]*2, o->size[1]*2, o->size[2]*2, NULL); 
  19. b = NewtonCreateBody(nWorld, c);
  20. NewtonReleaseCollision(nWorld, c);
  21. NewtonBodySetUserData(b, o);
  22. NewtonBodySetMassMatrix(b, o->weight, 1, 1, 1);
  23. NewtonBodySetMatrix(b, &o->mMatrix[0][0]);
  24. NewtonBodySetTransformCallback(b, TransformCallback);
  25. NewtonBodySetForceAndTorqueCallback(b, ForceAndTorqueCallback);
  26. NewtonBodySetAutoactiveCallback(b, AutoactiveCallback);
  27. o->pBody = b;
  28. }
  29. void CPhysic::Frame(float fTime)
  30. {
  31. // update world with timestep
  32. NewtonUpdate(nWorld, fTime*fSpeed);
  33. }
  34. void AutoactiveCallback(const NewtonBody *b, unsigned state)
  35. {
  36. static int iActiveBodies = 0;
  37. if (state == -1)
  38. {
  39. int *p;
  40. p = (int*)b;
  41. *p = iActiveBodies;
  42. }
  43. else
  44. {
  45. // 0*2-1 = -1  &&  1*2-1 = 1  &&  so it will inc or dec count..
  46. iActiveBodies += (state*2)-1;
  47. }
  48. }
  49. void ForceAndTorqueCallback(const NewtonBody* body)
  50. {
  51. float gravity = 9.8f;
  52. float Ixx;
  53. float Iyy;
  54. float Izz;
  55. float mass;
  56. NewtonBodyGetMassMatrix(body, &mass, &Ixx, &Iyy, &Izz);
  57. CVector force(0.0f, -mass * gravity, 0.0f);
  58. NewtonBodySetForce(body, &force[0]);
  59. }
  60. void TransformCallback(const NewtonBody* b, const dFloat* m)
  61. {
  62. CPhysicObject *o;
  63. // get pointer to object, which we saved before
  64. o = (CPhysicObject*) NewtonBodyGetUserData(b);
  65. if (!o)
  66. {
  67. err("NewtonBodyGetUserData returned zero...");
  68. return;
  69. }
  70. // CMatrix& mat = *((dMatrix*)matrix);
  71. CMatrix mat;
  72. // set current matrix
  73. mat = *((CMatrix*)m);
  74. o->SetMatrix(mat);
  75. }
  76. void NewtonBodyUnfreeze(NewtonBody *b)
  77. {
  78. if (!b) return;
  79. NewtonWorld *pNW;
  80. pNW = NewtonBodyGetWorld(b);
  81. if (!pNW) return;
  82. NewtonWorldUnfreezeBody(pNW, b);
  83. }
  84. void NewtonBodyDestroy(NewtonBody *b)
  85. {
  86. if (!b) return;
  87. NewtonWorld *pNW;
  88. pNW = NewtonBodyGetWorld(b);
  89. if (!pNW) return;
  90. NewtonDestroyBody(pNW, b);
  91. }