HelloWorld.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. // The Jolt headers don't include Jolt.h. Always include Jolt.h before including any other Jolt header.
  4. // You can use Jolt.h in your precompiled header to speed up compilation.
  5. #include <Jolt.h>
  6. // Jolt includes
  7. #include <RegisterTypes.h>
  8. #include <Core/TempAllocator.h>
  9. #include <Core/JobSystemThreadPool.h>
  10. #include <Physics/PhysicsSettings.h>
  11. #include <Physics/PhysicsSystem.h>
  12. #include <Physics/Collision/Shape/BoxShape.h>
  13. #include <Physics/Collision/Shape/SphereShape.h>
  14. #include <Physics/Body/BodyCreationSettings.h>
  15. #include <Physics/Body/BodyActivationListener.h>
  16. // STL includes
  17. #include <iostream>
  18. #include <cstdarg>
  19. #include <thread>
  20. // All Jolt symbols are in the JPH namespace
  21. using namespace JPH;
  22. // We're also using STL classes in this example
  23. using namespace std;
  24. // Callback for traces, connect this to your own trace function if you have one
  25. static void TraceImpl(const char *inFMT, ...)
  26. {
  27. // Format the message
  28. va_list list;
  29. va_start(list, inFMT);
  30. char buffer[1024];
  31. vsnprintf(buffer, sizeof(buffer), inFMT, list);
  32. // Print to the TTY
  33. cout << buffer << endl;
  34. }
  35. #ifdef JPH_ENABLE_ASSERTS
  36. // Callback for asserts, connect this to your own assert handler if you have one
  37. static bool AssertFailedImpl(const char *inExpression, const char *inMessage, const char *inFile, uint inLine)
  38. {
  39. // Print to the TTY
  40. cout << inFile << ":" << inLine << ": (" << inExpression << ") " << (inMessage != nullptr? inMessage : "") << endl;
  41. // Breakpoint
  42. return true;
  43. };
  44. #endif // JPH_ENABLE_ASSERTS
  45. // Layer that objects can be in, determines which other objects it can collide with
  46. // Typically you at least want to have 1 layer for moving bodies and 1 layer for static bodies, but you can have more
  47. // layers if you want. E.g. you could have a layer for high detail collision (which is not used by the physics simulation
  48. // but only if you do collision testing).
  49. namespace Layers
  50. {
  51. static constexpr uint8 NON_MOVING = 0;
  52. static constexpr uint8 MOVING = 1;
  53. static constexpr uint8 NUM_LAYERS = 2;
  54. };
  55. // Function that determines if two object layers can collide
  56. bool MyObjectCanCollide(ObjectLayer inObject1, ObjectLayer inObject2)
  57. {
  58. switch (inObject1)
  59. {
  60. case Layers::NON_MOVING:
  61. return inObject2 == Layers::MOVING; // Non moving only collides with moving
  62. case Layers::MOVING:
  63. return true; // Moving collides with everything
  64. default:
  65. JPH_ASSERT(false);
  66. return false;
  67. }
  68. };
  69. // Each broadphase layer results in a separate bounding volume tree in the broad phase. You at least want to have
  70. // a layer for non-moving and moving objects to avoid having to update a tree full of static objects every frame.
  71. // You can have a 1-on-1 mapping between object layers and broadphase layers (like in this case) but if you have
  72. // many object layers you'll be creating many broad phase trees, which is not efficient. If you want to fine tune
  73. // your broadphase layers define JPH_TRACK_BROADPHASE_STATS and look at the stats reported on the TTY.
  74. namespace BroadPhaseLayers
  75. {
  76. static constexpr BroadPhaseLayer NON_MOVING(0);
  77. static constexpr BroadPhaseLayer MOVING(1);
  78. };
  79. // Function that determines if two broadphase layers can collide
  80. bool MyBroadPhaseCanCollide(ObjectLayer inLayer1, BroadPhaseLayer inLayer2)
  81. {
  82. switch (inLayer1)
  83. {
  84. case Layers::NON_MOVING:
  85. return inLayer2 == BroadPhaseLayers::MOVING;
  86. case Layers::MOVING:
  87. return true;
  88. default:
  89. JPH_ASSERT(false);
  90. return false;
  91. }
  92. }
  93. // An example contact listener
  94. class MyContactListener : public ContactListener
  95. {
  96. public:
  97. // See: ContactListener
  98. virtual ValidateResult OnContactValidate(const Body &inBody1, const Body &inBody2, const CollideShapeResult &inCollisionResult) override
  99. {
  100. cout << "Contact validate callback" << endl;
  101. // Allows you to ignore a contact before it is created (using layers to not make objects collide is cheaper!)
  102. return ValidateResult::AcceptAllContactsForThisBodyPair;
  103. }
  104. virtual void OnContactAdded(const Body &inBody1, const Body &inBody2, const ContactManifold &inManifold, ContactSettings &ioSettings) override
  105. {
  106. cout << "A contact was added" << endl;
  107. }
  108. virtual void OnContactPersisted(const Body &inBody1, const Body &inBody2, const ContactManifold &inManifold, ContactSettings &ioSettings) override
  109. {
  110. cout << "A contact was persisted" << endl;
  111. }
  112. virtual void OnContactRemoved(const SubShapeIDPair &inSubShapePair) override
  113. {
  114. cout << "A contact was removed" << endl;
  115. }
  116. };
  117. // An example activation listener
  118. class MyBodyActivationListener : public BodyActivationListener
  119. {
  120. public:
  121. virtual void OnBodyActivated(const BodyID &inBodyID, void *inBodyUserData) override
  122. {
  123. cout << "A body got activated" << endl;
  124. }
  125. virtual void OnBodyDeactivated(const BodyID &inBodyID, void *inBodyUserData) override
  126. {
  127. cout << "A body went to sleep" << endl;
  128. }
  129. };
  130. // Program entry point
  131. int main(int argc, char** argv)
  132. {
  133. // Install callbacks
  134. Trace = TraceImpl;
  135. JPH_IF_ENABLE_ASSERTS(AssertFailed = AssertFailedImpl;)
  136. // Register all Jolt physics types
  137. RegisterTypes();
  138. // We need a temp allocator for temporary allocations during the physics update. We're
  139. // pre-allocating 10 MB to avoid having to do allocations during the physics update.
  140. // B.t.w. 10 MB is way too much for this example but it is a typical value you can use.
  141. // If you don't want to pre-allocate you can also use TempAllocatorMalloc to fall back to
  142. // malloc / free.
  143. TempAllocatorImpl temp_allocator(10 * 1024 * 1024);
  144. // We need a job system that will execute physics jobs on multiple threads. Typically
  145. // you would implement the JobSystem interface yourself and let Jolt Physics run on top
  146. // of your own job scheduler. JobSystemThreadPool is an example implementation.
  147. JobSystemThreadPool job_system(cMaxPhysicsJobs, cMaxPhysicsBarriers, thread::hardware_concurrency() - 1);
  148. // This is the max amount of rigid bodies that you can add to the physics system. If you try to add more you'll get an error.
  149. // Note: This value is low because this is a simple test. For a real project use something in the order of 65536.
  150. const uint cMaxBodies = 1024;
  151. // This determines how many mutexes to allocate to protect rigid bodies from concurrent access. Set it to 0 for the default settings.
  152. const uint cNumBodyMutexes = 0;
  153. // This is the max amount of body pairs that can be queued at any time (the broad phase will detect overlapping
  154. // body pairs based on their bounding boxes and will insert them into a queue for the narrowphase). If you make this buffer
  155. // too small the queue will fill up and the broad phase jobs will start to do narrow phase work. This is slightly less efficient.
  156. // Note: This value is low because this is a simple test. For a real project use something in the order of 65536.
  157. const uint cMaxBodyPairs = 1024;
  158. // This is the maximum size of the contact constraint buffer. If more contacts (collisions between bodies) are detected than this
  159. // number then these contacts will be ignored and bodies will start interpenetrating / fall through the world.
  160. // Note: This value is low because this is a simple test. For a real project use something in the order of 65536.
  161. const uint cMaxContactConstraints = 1024;
  162. // Create mapping table from object layer to broadphase layer
  163. ObjectToBroadPhaseLayer object_to_broadphase;
  164. object_to_broadphase.resize(Layers::NUM_LAYERS);
  165. object_to_broadphase[Layers::NON_MOVING] = BroadPhaseLayers::NON_MOVING;
  166. object_to_broadphase[Layers::MOVING] = BroadPhaseLayers::MOVING;
  167. // Now we can create the actual physics system.
  168. PhysicsSystem physics_system;
  169. physics_system.Init(cMaxBodies, cNumBodyMutexes, cMaxBodyPairs, cMaxContactConstraints, object_to_broadphase, MyBroadPhaseCanCollide, MyObjectCanCollide);
  170. // A body activation listener gets notified when bodies activate and go to sleep
  171. // Note that this is called from a job so whatever you do here needs to be thread safe.
  172. // Registering one is entirely optional.
  173. MyBodyActivationListener body_activation_listener;
  174. physics_system.SetBodyActivationListener(&body_activation_listener);
  175. // A contact listener gets notified when bodies (are about to) collide, and when they separate again.
  176. // Note that this is called from a job so whatever you do here needs to be thread safe.
  177. // Registering one is entirely optional.
  178. MyContactListener contact_listener;
  179. physics_system.SetContactListener(&contact_listener);
  180. // The main way to interact with the bodies in the physics system is through the body interface. There is a locking and a non-locking
  181. // variant of this. We're going to use the locking version (even though we're not planning to access bodies from multiple threads)
  182. BodyInterface &body_interface = physics_system.GetBodyInterface();
  183. // Next we can create a rigid body to serve as the floor, we make a large box
  184. // Create the settings for the collision volume (the shape).
  185. // Note that for simple shapes (like boxes) you can also directly construct a BoxShape.
  186. BoxShapeSettings floor_shape_settings(Vec3(100.0f, 1.0f, 100.0f));
  187. // Create the shape
  188. ShapeSettings::ShapeResult floor_shape_result = floor_shape_settings.Create();
  189. ShapeRefC floor_shape = floor_shape_result.Get(); // We don't expect an error here, but you can check floor_shape_result for HasError() / GetError()
  190. // Create the settings for the body itself. Note that here you can also set other properties like the restitution / friction.
  191. BodyCreationSettings floor_settings(floor_shape, Vec3(0.0f, -1.0f, 0.0f), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  192. // Create the actual rigid body
  193. Body *floor = body_interface.CreateBody(floor_settings); // Note that if we run out of bodies this can return nullptr
  194. // Add it to the world
  195. body_interface.AddBody(floor->GetID(), EActivation::DontActivate);
  196. // Now create a dynamic body to bounce on the floor
  197. // Note that this uses the shorthand version of creating and adding a body to the world
  198. BodyCreationSettings sphere_settings(new SphereShape(0.5f), Vec3(0.0f, 2.0f, 0.0f), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  199. BodyID sphere_id = body_interface.CreateAndAddBody(sphere_settings, EActivation::Activate);
  200. // Now you can interact with the dynamic body, in this case we're going to give it a velocity.
  201. // (note that if we had used CreateBody then we could have set the velocity straight on the body before adding it to the physics system)
  202. body_interface.SetLinearVelocity(sphere_id, Vec3(0.0f, -5.0f, 0.0f));
  203. // We simulate the physics world in discrete time steps. 60 Hz is a good rate to update the physics system.
  204. const float cDeltaTime = 1.0f / 60.0f;
  205. // Optional step: Before starting the physics simulation you can optimize the broad phase. This improves collision detection performance (it's pointless here because we only have 2 bodies).
  206. // You should definitely not call this every frame or when e.g. streaming in a new level section as it is an expensive operation.
  207. // Instead insert all new objects in batches instead of 1 at a time to keep the broad phase efficient.
  208. physics_system.OptimizeBroadPhase();
  209. // Now we're ready to simulate the body, keep simulating until it goes to sleep
  210. uint step = 0;
  211. while (body_interface.IsActive(sphere_id))
  212. {
  213. // Next step
  214. ++step;
  215. // Output current position and velocity of the sphere
  216. Vec3 position = body_interface.GetCenterOfMassPosition(sphere_id);
  217. Vec3 velocity = body_interface.GetLinearVelocity(sphere_id);
  218. cout << "Step " << step << ": Position = (" << position.GetX() << ", " << position.GetY() << ", " << position.GetZ() << "), Velocity = (" << velocity.GetX() << ", " << velocity.GetY() << ", " << velocity.GetZ() << ")" << endl;
  219. // If you take larger steps than 1 / 60th of a second you need to do multiple collision steps in order to keep the simulation stable. Do 1 collision step per 1 / 60th of a second (round up).
  220. const int cCollisionSteps = 1;
  221. // If you want more accurate step results you can do multiple sub steps within a collision step. Usually you would set this to 1.
  222. const int cIntegrationSubSteps = 1;
  223. // Step the world
  224. physics_system.Update(cDeltaTime, cCollisionSteps, cIntegrationSubSteps, &temp_allocator, &job_system);
  225. }
  226. // Remove the sphere from the physics system. Note that the sphere itself keeps all of its state and can be re-added at any time.
  227. body_interface.RemoveBody(sphere_id);
  228. // Destroy the sphere. After this the sphere ID is no longer valid.
  229. body_interface.DestroyBody(sphere_id);
  230. // Remove and destroy the floor
  231. body_interface.RemoveBody(floor->GetID());
  232. body_interface.DestroyBody(floor->GetID());
  233. return 0;
  234. }