MultithreadedTest.cpp 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <TestFramework.h>
  5. #include <Tests/General/MultithreadedTest.h>
  6. #include <Jolt/Physics/Collision/Shape/BoxShape.h>
  7. #include <Jolt/Physics/Collision/RayCast.h>
  8. #include <Jolt/Physics/Collision/CastResult.h>
  9. #include <Jolt/Physics/Body/BodyCreationSettings.h>
  10. #include <Jolt/Skeleton/Skeleton.h>
  11. #include <Jolt/Skeleton/SkeletalAnimation.h>
  12. #include <Jolt/Skeleton/SkeletonPose.h>
  13. #include <Jolt/Physics/Ragdoll/Ragdoll.h>
  14. #include <Jolt/ObjectStream/ObjectStreamIn.h>
  15. #include <Layers.h>
  16. #include <Utils/RagdollLoader.h>
  17. #include <Utils/Log.h>
  18. #include <Renderer/DebugRendererImp.h>
  19. JPH_IMPLEMENT_RTTI_VIRTUAL(MultithreadedTest)
  20. {
  21. JPH_ADD_BASE_CLASS(MultithreadedTest, Test)
  22. }
  23. MultithreadedTest::~MultithreadedTest()
  24. {
  25. // Quit the threads
  26. mIsQuitting = true;
  27. mBoxSpawnerThread.join();
  28. mRagdollSpawnerThread.join();
  29. mCasterThread.join();
  30. }
  31. void MultithreadedTest::Initialize()
  32. {
  33. // Floor
  34. CreateFloor();
  35. // Start threads
  36. mBoxSpawnerThread = thread([this]() { BoxSpawner(); });
  37. mRagdollSpawnerThread = thread([this]() { RagdollSpawner(); });
  38. mCasterThread = thread([this]() { CasterMain(); });
  39. }
  40. void MultithreadedTest::Execute(default_random_engine &ioRandom, const char *inName, function<void()> inFunction)
  41. {
  42. uniform_real_distribution<float> chance(0, 1);
  43. if (chance(ioRandom) < 0.5f)
  44. {
  45. // Execute as a job and wait for it
  46. JobHandle handle = mJobSystem->CreateJob(inName, Color::sGreen, inFunction);
  47. while (!handle.IsDone())
  48. this_thread::sleep_for(1ms);
  49. }
  50. else
  51. {
  52. // Execute in this separate thread (not part of the job system)
  53. JPH_PROFILE(inName);
  54. inFunction();
  55. }
  56. }
  57. void MultithreadedTest::BoxSpawner()
  58. {
  59. JPH_PROFILE_THREAD_START("BoxSpawner");
  60. #ifdef JPH_DEBUG
  61. const int cMaxObjects = 100;
  62. #else
  63. const int cMaxObjects = 1000;
  64. #endif
  65. default_random_engine random;
  66. Array<BodyID> bodies;
  67. while (!mIsQuitting)
  68. {
  69. // Ensure there are enough objects at all times
  70. if (bodies.size() < cMaxObjects)
  71. {
  72. BodyID body_id;
  73. Execute(random, "AddBody", [this, &body_id, &random]() {
  74. uniform_real_distribution<float> from_y(0, 10);
  75. uniform_real_distribution<float> from_xz(-5, 5);
  76. RVec3 position(from_xz(random), 1.0f + from_y(random), from_xz(random));
  77. Quat orientation = Quat::sRandom(random);
  78. Vec3 velocity = Vec3::sRandom(random);
  79. Body &body = *mBodyInterface->CreateBody(BodyCreationSettings(new BoxShape(Vec3(0.5f, 0.2f, 0.3f)), position, orientation, EMotionType::Dynamic, Layers::MOVING));
  80. body.SetLinearVelocity(velocity);
  81. body_id = body.GetID();
  82. mBodyInterface->AddBody(body_id, EActivation::Activate);
  83. });
  84. Execute(random, "Remove/AddBody", [this, body_id]() {
  85. // Undo/redo add to trigger more race conditions
  86. mBodyInterface->RemoveBody(body_id);
  87. mBodyInterface->AddBody(body_id, EActivation::Activate);
  88. });
  89. bodies.push_back(body_id);
  90. }
  91. uniform_real_distribution<float> chance(0, 1);
  92. if (bodies.size() > 0 && chance(random) < 0.5f)
  93. {
  94. // Pick random body
  95. uniform_int_distribution<size_t> element(0, bodies.size() - 1);
  96. size_t index = element(random);
  97. BodyID body_id = bodies[index];
  98. bodies.erase(bodies.begin() + index);
  99. Execute(random, "Remove/DestroyBody", [this, body_id]() {
  100. // Remove it
  101. mBodyInterface->RemoveBody(body_id);
  102. mBodyInterface->DestroyBody(body_id);
  103. });
  104. }
  105. this_thread::sleep_for(1ms);
  106. }
  107. JPH_PROFILE_THREAD_END();
  108. }
  109. void MultithreadedTest::RagdollSpawner()
  110. {
  111. JPH_PROFILE_THREAD_START("RagdollSpawner");
  112. #ifdef JPH_DEBUG
  113. const int cMaxRagdolls = 10;
  114. #else
  115. const int cMaxRagdolls = 50;
  116. #endif
  117. #ifdef JPH_OBJECT_STREAM
  118. // Load ragdoll
  119. Ref<RagdollSettings> ragdoll_settings = RagdollLoader::sLoad("Assets/Human.tof", EMotionType::Dynamic);
  120. if (ragdoll_settings == nullptr)
  121. FatalError("Could not load ragdoll");
  122. #else
  123. // Create a ragdoll from code
  124. Ref<RagdollSettings> ragdoll_settings = RagdollLoader::sCreate();
  125. #endif // JPH_OBJECT_STREAM
  126. // Create pose
  127. SkeletonPose ragdoll_pose;
  128. ragdoll_pose.SetSkeleton(ragdoll_settings->GetSkeleton());
  129. {
  130. #ifdef JPH_OBJECT_STREAM
  131. Ref<SkeletalAnimation> animation;
  132. if (!ObjectStreamIn::sReadObject("Assets/Human/Dead_Pose1.tof", animation))
  133. FatalError("Could not open animation");
  134. animation->Sample(0.0f, ragdoll_pose);
  135. #else
  136. Ref<Ragdoll> temp_ragdoll = ragdoll_settings->CreateRagdoll(0, 0, mPhysicsSystem);
  137. temp_ragdoll->GetPose(ragdoll_pose);
  138. ragdoll_pose.CalculateJointStates();
  139. #endif // JPH_OBJECT_STREAM
  140. }
  141. default_random_engine random;
  142. uniform_real_distribution<float> from_y(0, 10);
  143. uniform_real_distribution<float> from_xz(-5, 5);
  144. CollisionGroup::GroupID group_id = 1;
  145. Array<Ref<Ragdoll>> ragdolls;
  146. while (!mIsQuitting)
  147. {
  148. // Ensure there are enough objects at all times
  149. if (ragdolls.size() < cMaxRagdolls)
  150. {
  151. // Create ragdoll
  152. Ref<Ragdoll> ragdoll = ragdoll_settings->CreateRagdoll(group_id++, 0, mPhysicsSystem);
  153. // Override root
  154. SkeletonPose::JointState &root = ragdoll_pose.GetJoint(0);
  155. root.mRotation = Quat::sRandom(random);
  156. ragdoll_pose.SetRootOffset(RVec3(from_xz(random), 1.0f + from_y(random), from_xz(random)));
  157. ragdoll_pose.CalculateJointMatrices();
  158. // Drive to pose
  159. ragdoll->SetPose(ragdoll_pose);
  160. ragdoll->DriveToPoseUsingMotors(ragdoll_pose);
  161. Execute(random, "Activate", [ragdoll]() {
  162. // Activate the ragdoll
  163. ragdoll->AddToPhysicsSystem(EActivation::Activate);
  164. });
  165. Execute(random, "Deactivate/Activate", [ragdoll]() {
  166. // Undo/redo add to trigger more race conditions
  167. ragdoll->RemoveFromPhysicsSystem();
  168. ragdoll->AddToPhysicsSystem(EActivation::Activate);
  169. });
  170. ragdolls.push_back(ragdoll);
  171. }
  172. uniform_real_distribution<float> chance(0, 1);
  173. if (ragdolls.size() > 0 && chance(random) < 0.1f)
  174. {
  175. // Pick random body
  176. uniform_int_distribution<size_t> element(0, ragdolls.size() - 1);
  177. size_t index = element(random);
  178. Ref<Ragdoll> ragdoll = ragdolls[index];
  179. ragdolls.erase(ragdolls.begin() + index);
  180. Execute(random, "Deactivate", [ragdoll]() {
  181. // Deactivate it
  182. ragdoll->RemoveFromPhysicsSystem();
  183. });
  184. }
  185. this_thread::sleep_for(1ms);
  186. }
  187. for (Ragdoll *r : ragdolls)
  188. r->RemoveFromPhysicsSystem();
  189. JPH_PROFILE_THREAD_END();
  190. }
  191. void MultithreadedTest::CasterMain()
  192. {
  193. JPH_PROFILE_THREAD_START("CasterMain");
  194. default_random_engine random;
  195. Array<BodyID> bodies;
  196. while (!mIsQuitting)
  197. {
  198. Execute(random, "CastRay", [this, &random]() {
  199. // Cast a random ray
  200. uniform_real_distribution<float> from_y(0, 10);
  201. uniform_real_distribution<float> from_xz(-5, 5);
  202. RVec3 from(from_xz(random), from_y(random), from_xz(random));
  203. RVec3 to(from_xz(random), from_y(random), from_xz(random));
  204. RRayCast ray { from, Vec3(to - from) };
  205. RayCastResult hit;
  206. if (mPhysicsSystem->GetNarrowPhaseQuery().CastRay(ray, hit, SpecifiedBroadPhaseLayerFilter(BroadPhaseLayers::MOVING), SpecifiedObjectLayerFilter(Layers::MOVING)))
  207. {
  208. // Draw hit position
  209. RVec3 hit_position_world = ray.GetPointOnRay(hit.mFraction);
  210. mDebugRenderer->DrawMarker(hit_position_world, Color::sYellow, 0.2f);
  211. BodyLockRead lock(mPhysicsSystem->GetBodyLockInterface(), hit.mBodyID);
  212. if (lock.SucceededAndIsInBroadPhase())
  213. {
  214. // Draw normal
  215. const Body &hit_body = lock.GetBody();
  216. RMat44 inv_com = hit_body.GetInverseCenterOfMassTransform();
  217. Vec3 normal = inv_com.Multiply3x3Transposed(hit_body.GetShape()->GetSurfaceNormal(hit.mSubShapeID2, Vec3(inv_com * hit_position_world))).Normalized();
  218. mDebugRenderer->DrawArrow(hit_position_world, hit_position_world + normal, Color::sGreen, 0.1f);
  219. }
  220. }
  221. });
  222. }
  223. JPH_PROFILE_THREAD_END();
  224. }