PhysicsWorld.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. /*
  2. Copyright (c) 2013 Daniele Bartolini, Michele Rossi
  3. Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
  4. Permission is hereby granted, free of charge, to any person
  5. obtaining a copy of this software and associated documentation
  6. files (the "Software"), to deal in the Software without
  7. restriction, including without limitation the rights to use,
  8. copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the
  10. Software is furnished to do so, subject to the following
  11. conditions:
  12. The above copyright notice and this permission notice shall be
  13. included in all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  15. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  16. OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  17. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  19. WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  20. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  21. OTHER DEALINGS IN THE SOFTWARE.
  22. */
  23. #include "PhysicsWorld.h"
  24. #include "Vector3.h"
  25. #include "Actor.h"
  26. #include "Device.h"
  27. #include "Quaternion.h"
  28. #include "SceneGraph.h"
  29. #include "Controller.h"
  30. #include "Trigger.h"
  31. #include "PhysicsCallback.h"
  32. #include "ProxyAllocator.h"
  33. #include "PxPhysicsAPI.h"
  34. using physx::PxSceneDesc;
  35. using physx::PxVec3;
  36. using physx::PxTransform;
  37. using physx::PxQuat;
  38. using physx::PxHalfPi;
  39. using physx::PxPlaneGeometry;
  40. using physx::PxMaterial;
  41. using physx::PxShape;
  42. using physx::PxRigidStatic;
  43. using physx::PxActiveTransform;
  44. using physx::PxU32;
  45. using physx::PxSceneFlag;
  46. using physx::PxFilterFlags;
  47. using physx::PxFilterData;
  48. using physx::PxPairFlags;
  49. using physx::PxFilterObjectAttributes;
  50. using physx::PxFilterObjectIsTrigger;
  51. using physx::PxPairFlag;
  52. using physx::PxFilterFlag;
  53. namespace crown
  54. {
  55. namespace physics_system
  56. {
  57. using physx::PxFoundation;
  58. using physx::PxPhysics;
  59. using physx::PxAllocatorCallback;
  60. using physx::PxErrorCallback;
  61. using physx::PxErrorCode;
  62. //-----------------------------------------------------------------------------
  63. class PhysXAllocator : public PxAllocatorCallback
  64. {
  65. public:
  66. PhysXAllocator()
  67. : m_backing("physics", default_allocator())
  68. {
  69. }
  70. void* allocate(size_t size, const char*, const char*, int)
  71. {
  72. return m_backing.allocate(size, 16);
  73. }
  74. void deallocate(void* p)
  75. {
  76. m_backing.deallocate(p);
  77. }
  78. private:
  79. ProxyAllocator m_backing;
  80. };
  81. //-----------------------------------------------------------------------------
  82. class PhysXError : public PxErrorCallback
  83. {
  84. public:
  85. void reportError(PxErrorCode::Enum code, const char* message, const char* file, int line)
  86. {
  87. switch (code)
  88. {
  89. case PxErrorCode::eDEBUG_INFO:
  90. {
  91. Log::i("In %s:%d: %s", file, line, message);
  92. break;
  93. }
  94. case PxErrorCode::eDEBUG_WARNING:
  95. case PxErrorCode::ePERF_WARNING:
  96. {
  97. Log::w("In %s:%d: %s", file, line, message);
  98. break;
  99. }
  100. case PxErrorCode::eINVALID_PARAMETER:
  101. case PxErrorCode::eINVALID_OPERATION:
  102. case PxErrorCode::eOUT_OF_MEMORY:
  103. case PxErrorCode::eINTERNAL_ERROR:
  104. case PxErrorCode::eABORT:
  105. {
  106. CE_ASSERT(false, "In %s:%d: %s", file, line, message);
  107. break;
  108. }
  109. default:
  110. {
  111. CE_FATAL("Oops, unknown physx error");
  112. break;
  113. }
  114. }
  115. }
  116. };
  117. static PhysXAllocator* s_px_allocator;
  118. static PhysXError* s_px_error;
  119. static PxFoundation* s_foundation;
  120. static PxPhysics* s_physics;
  121. void init()
  122. {
  123. s_px_allocator = CE_NEW(default_allocator(), PhysXAllocator)();
  124. s_px_error = CE_NEW(default_allocator(), PhysXError)();
  125. s_foundation = PxCreateFoundation(PX_PHYSICS_VERSION, *s_px_allocator, *s_px_error);
  126. CE_ASSERT(s_foundation, "Unable to create PhysX Foundation");
  127. s_physics = PxCreatePhysics(PX_PHYSICS_VERSION, *s_foundation, physx::PxTolerancesScale());
  128. CE_ASSERT(s_physics, "Unable to create PhysX Physics");
  129. bool extension = PxInitExtensions(*s_physics);
  130. CE_ASSERT(extension, "Unable to initialize PhysX Extensions");
  131. }
  132. void shutdown()
  133. {
  134. PxCloseExtensions();
  135. s_physics->release();
  136. s_foundation->release();
  137. CE_DELETE(default_allocator(), s_px_error);
  138. CE_DELETE(default_allocator(), s_px_allocator);
  139. }
  140. } // namespace physics_system
  141. PxFilterFlags PhysicsFilterShader(PxFilterObjectAttributes attributes0, PxFilterData filterData0,
  142. PxFilterObjectAttributes attributes1, PxFilterData filterData1,
  143. PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize)
  144. {
  145. // let triggers through
  146. if(PxFilterObjectIsTrigger(attributes0) || PxFilterObjectIsTrigger(attributes1))
  147. {
  148. pairFlags = PxPairFlag::eTRIGGER_DEFAULT;
  149. return PxFilterFlag::eDEFAULT;
  150. }
  151. // generate contacts for all that were not filtered above
  152. pairFlags = PxPairFlag::eCONTACT_DEFAULT;
  153. // trigger the contact callback for pairs (A,B) where
  154. // the filtermask of A contains the ID of B and vice versa.
  155. if((filterData0.word0 & filterData1.word1) && (filterData1.word0 & filterData0.word1))
  156. {
  157. pairFlags |= PxPairFlag::eNOTIFY_TOUCH_FOUND;
  158. }
  159. return PxFilterFlag::eDEFAULT;
  160. }
  161. static physx::PxSimulationFilterShader g_default_filter_shader = PhysicsFilterShader;
  162. //-----------------------------------------------------------------------------
  163. PhysicsWorld::PhysicsWorld()
  164. : m_scene(NULL)
  165. , m_actors_pool(default_allocator(), MAX_ACTORS, sizeof(Actor), CE_ALIGNOF(Actor))
  166. , m_controllers_pool(default_allocator(), MAX_CONTROLLERS, sizeof(Controller), CE_ALIGNOF(Controller))
  167. , m_triggers_pool(default_allocator(), MAX_TRIGGERS, sizeof(Trigger), CE_ALIGNOF(Trigger))
  168. {
  169. PxSceneDesc scene_desc(physics_system::s_physics->getTolerancesScale());
  170. scene_desc.gravity = PxVec3(0.0f, -9.81f, 0.0f);
  171. if(!scene_desc.cpuDispatcher)
  172. {
  173. m_cpu_dispatcher = physx::PxDefaultCpuDispatcherCreate(1);
  174. CE_ASSERT(m_cpu_dispatcher != NULL, "Failed to create PhysX cpu dispatcher");
  175. scene_desc.cpuDispatcher = m_cpu_dispatcher;
  176. }
  177. // Set filter shader
  178. scene_desc.filterShader = g_default_filter_shader;
  179. // Enable active transformation
  180. scene_desc.flags = PxSceneFlag::eENABLE_ACTIVETRANSFORMS;
  181. // Set simulation event callback
  182. m_callback = CE_NEW(default_allocator(), PhysicsSimulationCallback)();
  183. scene_desc.simulationEventCallback = m_callback;
  184. // Create scene
  185. m_scene = physics_system::s_physics->createScene(scene_desc);
  186. m_scene->setFlag(PxSceneFlag::eENABLE_KINEMATIC_STATIC_PAIRS, true);
  187. // Create controller manager
  188. m_controller_manager = PxCreateControllerManager(*physics_system::s_foundation);
  189. CE_ASSERT(m_controller_manager != NULL, "Failed to create PhysX controller manager");
  190. }
  191. //-----------------------------------------------------------------------------
  192. PhysicsWorld::~PhysicsWorld()
  193. {
  194. CE_DELETE(default_allocator(), m_callback);
  195. m_cpu_dispatcher->release();
  196. m_controller_manager->release();
  197. m_scene->release();
  198. }
  199. //-----------------------------------------------------------------------------
  200. ActorId PhysicsWorld::create_actor(const PhysicsResource* res, const uint32_t index, SceneGraph& sg, int32_t node)
  201. {
  202. Actor* actor = CE_NEW(m_actors_pool, Actor)(res, index, physics_system::s_physics, m_scene, sg, node, Vector3::ZERO, Quaternion::IDENTITY);
  203. return m_actors.create(actor);
  204. }
  205. //-----------------------------------------------------------------------------
  206. void PhysicsWorld::destroy_actor(ActorId id)
  207. {
  208. CE_ASSERT(m_actors.has(id), "Actor does not exist");
  209. CE_DELETE(m_actors_pool, m_actors.lookup(id));
  210. m_actors.destroy(id);
  211. }
  212. //-----------------------------------------------------------------------------
  213. ControllerId PhysicsWorld::create_controller(const PhysicsResource* pr, SceneGraph& sg, int32_t node)
  214. {
  215. Controller* controller = CE_NEW(m_controllers_pool, Controller)(pr, sg, node, physics_system::s_physics, m_scene, m_controller_manager);
  216. return m_controllers.create(controller);
  217. }
  218. //-----------------------------------------------------------------------------
  219. void PhysicsWorld::destroy_controller(ControllerId id)
  220. {
  221. CE_ASSERT(m_controllers.has(id), "Controller does not exist");
  222. CE_DELETE(m_controllers_pool, m_controllers.lookup(id));
  223. m_controllers.destroy(id);
  224. }
  225. //-----------------------------------------------------------------------------
  226. TriggerId PhysicsWorld::create_trigger(const Vector3& half_extents, const Vector3& pos, const Quaternion& rot)
  227. {
  228. Trigger* trigger = CE_NEW(m_triggers_pool, Trigger)(physics_system::s_physics, m_scene, half_extents, pos, rot);
  229. return m_triggers.create(trigger);
  230. }
  231. //-----------------------------------------------------------------------------
  232. void PhysicsWorld::destroy_trigger(TriggerId id)
  233. {
  234. CE_ASSERT(m_triggers.has(id), "Trigger does not exist");
  235. CE_DELETE(m_triggers_pool, m_triggers.lookup(id));
  236. m_triggers.destroy(id);
  237. }
  238. //-----------------------------------------------------------------------------
  239. Actor* PhysicsWorld::lookup_actor(ActorId id)
  240. {
  241. CE_ASSERT(m_actors.has(id), "Actor does not exist");
  242. return m_actors.lookup(id);
  243. }
  244. //-----------------------------------------------------------------------------
  245. Controller* PhysicsWorld::lookup_controller(ControllerId id)
  246. {
  247. CE_ASSERT(m_controllers.has(id), "Controller does not exist");
  248. return m_controllers.lookup(id);
  249. }
  250. //-----------------------------------------------------------------------------
  251. Trigger* PhysicsWorld::lookup_trigger(TriggerId id)
  252. {
  253. CE_ASSERT(m_triggers.has(id), "Trigger does not exist");
  254. return m_triggers.lookup(id);
  255. }
  256. //-----------------------------------------------------------------------------
  257. Vector3 PhysicsWorld::gravity() const
  258. {
  259. PxVec3 g = m_scene->getGravity();
  260. return Vector3(g.x, g.y, g.z);
  261. }
  262. //-----------------------------------------------------------------------------
  263. void PhysicsWorld::set_gravity(const Vector3& g)
  264. {
  265. m_scene->setGravity(PxVec3(g.x, g.y, g.z));
  266. }
  267. //-----------------------------------------------------------------------------
  268. void PhysicsWorld::set_filtering(ActorId id, uint32_t group, uint32_t mask)
  269. {
  270. Actor* actor_instance = lookup_actor(id);
  271. PxRigidActor* actor = actor_instance->m_actor;
  272. PxFilterData filter_data;
  273. filter_data.word0 = (PxU32) group; // word0 = own ID
  274. filter_data.word1 = (PxU32) mask; // word1 = ID mask to filter pairs that trigger a contact callback;
  275. const PxU32 num_shapes = actor->getNbShapes();
  276. PxShape** shapes = (PxShape**) default_allocator().allocate((sizeof(PxShape*) * num_shapes));
  277. actor->getShapes(shapes, num_shapes);
  278. for(PxU32 i = 0; i < num_shapes; i++)
  279. {
  280. PxShape* shape = shapes[i];
  281. shape->setSimulationFilterData(filter_data);
  282. }
  283. default_allocator().deallocate(shapes);
  284. }
  285. //-----------------------------------------------------------------------------
  286. void PhysicsWorld::update(float dt)
  287. {
  288. // Update world pose of the actors
  289. for (uint32_t i = 0; i < m_actors.size(); i++)
  290. {
  291. m_actors[i]->update_pose();
  292. }
  293. // Run with fixed timestep
  294. m_scene->simulate(1.0 / 60.0);
  295. while (!m_scene->fetchResults());
  296. // Update transforms
  297. PxU32 num_active_transforms;
  298. PxActiveTransform* active_transforms = m_scene->getActiveTransforms(num_active_transforms);
  299. // Update each actor with its new transform
  300. for (PxU32 i = 0; i < num_active_transforms; i++)
  301. {
  302. const PxTransform tr = active_transforms[i].actor2World;
  303. const Vector3 pos(tr.p.x, tr.p.y, tr.p.z);
  304. const Quaternion rot(tr.q.x, tr.q.y, tr.q.z, tr.q.w);
  305. Actor* actor = static_cast<Actor*>(active_transforms[i].userData);
  306. if (actor != NULL)
  307. {
  308. actor->update(Matrix4x4(rot, pos));
  309. }
  310. }
  311. // Update controllers
  312. for (uint32_t i = 0; i < m_controllers.size(); i++)
  313. {
  314. m_controllers[i]->update();
  315. }
  316. }
  317. } // namespace crown