PhysicsWorld.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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. using physx::PxSceneLimits;
  54. namespace crown
  55. {
  56. namespace physics_system
  57. {
  58. using physx::PxFoundation;
  59. using physx::PxPhysics;
  60. using physx::PxAllocatorCallback;
  61. using physx::PxErrorCallback;
  62. using physx::PxErrorCode;
  63. //-----------------------------------------------------------------------------
  64. class PhysXAllocator : public PxAllocatorCallback
  65. {
  66. public:
  67. PhysXAllocator()
  68. : m_backing("physics", default_allocator())
  69. {
  70. }
  71. void* allocate(size_t size, const char*, const char*, int)
  72. {
  73. return m_backing.allocate(size, 16);
  74. }
  75. void deallocate(void* p)
  76. {
  77. m_backing.deallocate(p);
  78. }
  79. private:
  80. ProxyAllocator m_backing;
  81. };
  82. //-----------------------------------------------------------------------------
  83. class PhysXError : public PxErrorCallback
  84. {
  85. public:
  86. void reportError(PxErrorCode::Enum code, const char* message, const char* file, int line)
  87. {
  88. switch (code)
  89. {
  90. case PxErrorCode::eDEBUG_INFO:
  91. {
  92. Log::i("In %s:%d: %s", file, line, message);
  93. break;
  94. }
  95. case PxErrorCode::eDEBUG_WARNING:
  96. case PxErrorCode::ePERF_WARNING:
  97. {
  98. Log::w("In %s:%d: %s", file, line, message);
  99. break;
  100. }
  101. case PxErrorCode::eINVALID_PARAMETER:
  102. case PxErrorCode::eINVALID_OPERATION:
  103. case PxErrorCode::eOUT_OF_MEMORY:
  104. case PxErrorCode::eINTERNAL_ERROR:
  105. case PxErrorCode::eABORT:
  106. {
  107. CE_ASSERT(false, "In %s:%d: %s", file, line, message);
  108. break;
  109. }
  110. default:
  111. {
  112. CE_FATAL("Oops, unknown physx error");
  113. break;
  114. }
  115. }
  116. }
  117. };
  118. static PhysXAllocator* s_px_allocator;
  119. static PhysXError* s_px_error;
  120. static PxFoundation* s_foundation;
  121. static PxPhysics* s_physics;
  122. void init()
  123. {
  124. s_px_allocator = CE_NEW(default_allocator(), PhysXAllocator)();
  125. s_px_error = CE_NEW(default_allocator(), PhysXError)();
  126. s_foundation = PxCreateFoundation(PX_PHYSICS_VERSION, *s_px_allocator, *s_px_error);
  127. CE_ASSERT(s_foundation, "Unable to create PhysX Foundation");
  128. s_physics = PxCreatePhysics(PX_PHYSICS_VERSION, *s_foundation, physx::PxTolerancesScale());
  129. CE_ASSERT(s_physics, "Unable to create PhysX Physics");
  130. bool extension = PxInitExtensions(*s_physics);
  131. CE_ASSERT(extension, "Unable to initialize PhysX Extensions");
  132. }
  133. void shutdown()
  134. {
  135. PxCloseExtensions();
  136. s_physics->release();
  137. s_foundation->release();
  138. CE_DELETE(default_allocator(), s_px_error);
  139. CE_DELETE(default_allocator(), s_px_allocator);
  140. }
  141. } // namespace physics_system
  142. PxFilterFlags PhysicsFilterShader(PxFilterObjectAttributes attributes0, PxFilterData filterData0,
  143. PxFilterObjectAttributes attributes1, PxFilterData filterData1,
  144. PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize)
  145. {
  146. // let triggers through
  147. if(PxFilterObjectIsTrigger(attributes0) || PxFilterObjectIsTrigger(attributes1))
  148. {
  149. pairFlags = PxPairFlag::eTRIGGER_DEFAULT;
  150. return PxFilterFlag::eDEFAULT;
  151. }
  152. // generate contacts for all that were not filtered above
  153. pairFlags = PxPairFlag::eCONTACT_DEFAULT;
  154. // trigger the contact callback for pairs (A,B) where
  155. // the filtermask of A contains the ID of B and vice versa.
  156. if((filterData0.word0 & filterData1.word1) && (filterData1.word0 & filterData0.word1))
  157. {
  158. pairFlags |= PxPairFlag::eNOTIFY_TOUCH_FOUND;
  159. }
  160. return PxFilterFlag::eDEFAULT;
  161. }
  162. static physx::PxSimulationFilterShader g_default_filter_shader = PhysicsFilterShader;
  163. //-----------------------------------------------------------------------------
  164. PhysicsWorld::PhysicsWorld()
  165. : m_scene(NULL)
  166. , m_actors_pool(default_allocator(), MAX_ACTORS, sizeof(Actor), CE_ALIGNOF(Actor))
  167. , m_controllers_pool(default_allocator(), MAX_CONTROLLERS, sizeof(Controller), CE_ALIGNOF(Controller))
  168. , m_triggers_pool(default_allocator(), MAX_TRIGGERS, sizeof(Trigger), CE_ALIGNOF(Trigger))
  169. {
  170. PxSceneLimits scene_limits;
  171. scene_limits.maxNbActors = MAX_ACTORS;
  172. CE_ASSERT(scene_limits.isValid(), "Scene limits is not valid");
  173. PxSceneDesc scene_desc(physics_system::s_physics->getTolerancesScale());
  174. scene_desc.gravity = PxVec3(0.0f, -9.81f, 0.0f);
  175. scene_desc.limits = scene_limits;
  176. if(!scene_desc.cpuDispatcher)
  177. {
  178. m_cpu_dispatcher = physx::PxDefaultCpuDispatcherCreate(1);
  179. CE_ASSERT(m_cpu_dispatcher != NULL, "Failed to create PhysX cpu dispatcher");
  180. scene_desc.cpuDispatcher = m_cpu_dispatcher;
  181. }
  182. // Set filter shader
  183. scene_desc.filterShader = g_default_filter_shader;
  184. scene_desc.flags = PxSceneFlag::eENABLE_ACTIVETRANSFORMS | PxSceneFlag::eENABLE_KINEMATIC_STATIC_PAIRS;
  185. // Set simulation event callback
  186. m_callback = CE_NEW(default_allocator(), PhysicsSimulationCallback)();
  187. scene_desc.simulationEventCallback = m_callback;
  188. CE_ASSERT(scene_desc.isValid(), "Scene is not valid");
  189. // Create scene
  190. m_scene = physics_system::s_physics->createScene(scene_desc);
  191. // Create controller manager
  192. m_controller_manager = PxCreateControllerManager(*physics_system::s_foundation);
  193. CE_ASSERT(m_controller_manager != NULL, "Failed to create PhysX controller manager");
  194. }
  195. //-----------------------------------------------------------------------------
  196. PhysicsWorld::~PhysicsWorld()
  197. {
  198. CE_DELETE(default_allocator(), m_callback);
  199. m_cpu_dispatcher->release();
  200. m_controller_manager->release();
  201. m_scene->release();
  202. }
  203. //-----------------------------------------------------------------------------
  204. ActorId PhysicsWorld::create_actor(const PhysicsResource* res, const uint32_t index, SceneGraph& sg, int32_t node)
  205. {
  206. Actor* actor = CE_NEW(m_actors_pool, Actor)(res, index, physics_system::s_physics, m_scene, sg, node, Vector3::ZERO, Quaternion::IDENTITY);
  207. return m_actors.create(actor);
  208. }
  209. //-----------------------------------------------------------------------------
  210. void PhysicsWorld::destroy_actor(ActorId id)
  211. {
  212. CE_ASSERT(m_actors.has(id), "Actor does not exist");
  213. CE_DELETE(m_actors_pool, m_actors.lookup(id));
  214. m_actors.destroy(id);
  215. }
  216. //-----------------------------------------------------------------------------
  217. ControllerId PhysicsWorld::create_controller(const PhysicsResource* pr, SceneGraph& sg, int32_t node)
  218. {
  219. Controller* controller = CE_NEW(m_controllers_pool, Controller)(pr, sg, node, physics_system::s_physics, m_scene, m_controller_manager);
  220. return m_controllers.create(controller);
  221. }
  222. //-----------------------------------------------------------------------------
  223. void PhysicsWorld::destroy_controller(ControllerId id)
  224. {
  225. CE_ASSERT(m_controllers.has(id), "Controller does not exist");
  226. CE_DELETE(m_controllers_pool, m_controllers.lookup(id));
  227. m_controllers.destroy(id);
  228. }
  229. //-----------------------------------------------------------------------------
  230. TriggerId PhysicsWorld::create_trigger(const Vector3& half_extents, const Vector3& pos, const Quaternion& rot)
  231. {
  232. Trigger* trigger = CE_NEW(m_triggers_pool, Trigger)(physics_system::s_physics, m_scene, half_extents, pos, rot);
  233. return m_triggers.create(trigger);
  234. }
  235. //-----------------------------------------------------------------------------
  236. void PhysicsWorld::destroy_trigger(TriggerId id)
  237. {
  238. CE_ASSERT(m_triggers.has(id), "Trigger does not exist");
  239. CE_DELETE(m_triggers_pool, m_triggers.lookup(id));
  240. m_triggers.destroy(id);
  241. }
  242. //-----------------------------------------------------------------------------
  243. Actor* PhysicsWorld::lookup_actor(ActorId id)
  244. {
  245. CE_ASSERT(m_actors.has(id), "Actor does not exist");
  246. return m_actors.lookup(id);
  247. }
  248. //-----------------------------------------------------------------------------
  249. Controller* PhysicsWorld::lookup_controller(ControllerId id)
  250. {
  251. CE_ASSERT(m_controllers.has(id), "Controller does not exist");
  252. return m_controllers.lookup(id);
  253. }
  254. //-----------------------------------------------------------------------------
  255. Trigger* PhysicsWorld::lookup_trigger(TriggerId id)
  256. {
  257. CE_ASSERT(m_triggers.has(id), "Trigger does not exist");
  258. return m_triggers.lookup(id);
  259. }
  260. //-----------------------------------------------------------------------------
  261. Vector3 PhysicsWorld::gravity() const
  262. {
  263. PxVec3 g = m_scene->getGravity();
  264. return Vector3(g.x, g.y, g.z);
  265. }
  266. //-----------------------------------------------------------------------------
  267. void PhysicsWorld::set_gravity(const Vector3& g)
  268. {
  269. m_scene->setGravity(PxVec3(g.x, g.y, g.z));
  270. }
  271. //-----------------------------------------------------------------------------
  272. void PhysicsWorld::set_filtering(ActorId id, uint32_t group, uint32_t mask)
  273. {
  274. Actor* actor_instance = lookup_actor(id);
  275. PxRigidActor* actor = actor_instance->m_actor;
  276. PxFilterData filter_data;
  277. filter_data.word0 = (PxU32) group; // word0 = own ID
  278. filter_data.word1 = (PxU32) mask; // word1 = ID mask to filter pairs that trigger a contact callback;
  279. const PxU32 num_shapes = actor->getNbShapes();
  280. PxShape** shapes = (PxShape**) default_allocator().allocate((sizeof(PxShape*) * num_shapes));
  281. actor->getShapes(shapes, num_shapes);
  282. for(PxU32 i = 0; i < num_shapes; i++)
  283. {
  284. PxShape* shape = shapes[i];
  285. shape->setSimulationFilterData(filter_data);
  286. }
  287. default_allocator().deallocate(shapes);
  288. }
  289. //-----------------------------------------------------------------------------
  290. void PhysicsWorld::update(float dt)
  291. {
  292. // Update world pose of the actors
  293. for (uint32_t i = 0; i < m_actors.size(); i++)
  294. {
  295. m_actors[i]->update_pose();
  296. }
  297. // Run with fixed timestep
  298. m_scene->simulate(1.0 / 60.0);
  299. while (!m_scene->fetchResults());
  300. // Update transforms
  301. PxU32 num_active_transforms;
  302. PxActiveTransform* active_transforms = m_scene->getActiveTransforms(num_active_transforms);
  303. // Update each actor with its new transform
  304. for (PxU32 i = 0; i < num_active_transforms; i++)
  305. {
  306. const PxTransform tr = active_transforms[i].actor2World;
  307. const Vector3 pos(tr.p.x, tr.p.y, tr.p.z);
  308. const Quaternion rot(tr.q.x, tr.q.y, tr.q.z, tr.q.w);
  309. Actor* actor = static_cast<Actor*>(active_transforms[i].userData);
  310. if (actor != NULL)
  311. {
  312. actor->update(Matrix4x4(rot, pos));
  313. }
  314. }
  315. // Update controllers
  316. for (uint32_t i = 0; i < m_controllers.size(); i++)
  317. {
  318. m_controllers[i]->update();
  319. }
  320. }
  321. } // namespace crown