HelloWorld.cpp 14 KB

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