MultithreadedTest.cpp 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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 _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 _DEBUG
  113. const int cMaxRagdolls = 10;
  114. #else
  115. const int cMaxRagdolls = 50;
  116. #endif
  117. // Load ragdoll
  118. Ref<RagdollSettings> ragdoll_settings = RagdollLoader::sLoad("Assets/Human.tof", EMotionType::Dynamic);
  119. if (ragdoll_settings == nullptr)
  120. FatalError("Could not load ragdoll");
  121. // Load animation
  122. Ref<SkeletalAnimation> animation;
  123. if (!ObjectStreamIn::sReadObject("Assets/Human/Dead_Pose1.tof", animation))
  124. FatalError("Could not open animation");
  125. // Create pose
  126. SkeletonPose ragdoll_pose;
  127. ragdoll_pose.SetSkeleton(ragdoll_settings->GetSkeleton());
  128. animation->Sample(0.0f, ragdoll_pose);
  129. default_random_engine random;
  130. uniform_real_distribution<float> from_y(0, 10);
  131. uniform_real_distribution<float> from_xz(-5, 5);
  132. CollisionGroup::GroupID group_id = 1;
  133. Array<Ref<Ragdoll>> ragdolls;
  134. while (!mIsQuitting)
  135. {
  136. // Ensure there are enough objects at all times
  137. if (ragdolls.size() < cMaxRagdolls)
  138. {
  139. // Create ragdoll
  140. Ref<Ragdoll> ragdoll = ragdoll_settings->CreateRagdoll(group_id++, 0, mPhysicsSystem);
  141. // Override root
  142. SkeletonPose::JointState &root = ragdoll_pose.GetJoint(0);
  143. root.mRotation = Quat::sRandom(random);
  144. ragdoll_pose.SetRootOffset(RVec3(from_xz(random), 1.0f + from_y(random), from_xz(random)));
  145. ragdoll_pose.CalculateJointMatrices();
  146. // Drive to pose
  147. ragdoll->SetPose(ragdoll_pose);
  148. ragdoll->DriveToPoseUsingMotors(ragdoll_pose);
  149. Execute(random, "Activate", [ragdoll]() {
  150. // Activate the ragdoll
  151. ragdoll->AddToPhysicsSystem(EActivation::Activate);
  152. });
  153. Execute(random, "Deactivate/Activate", [ragdoll]() {
  154. // Undo/redo add to trigger more race conditions
  155. ragdoll->RemoveFromPhysicsSystem();
  156. ragdoll->AddToPhysicsSystem(EActivation::Activate);
  157. });
  158. ragdolls.push_back(ragdoll);
  159. }
  160. uniform_real_distribution<float> chance(0, 1);
  161. if (ragdolls.size() > 0 && chance(random) < 0.1f)
  162. {
  163. // Pick random body
  164. uniform_int_distribution<size_t> element(0, ragdolls.size() - 1);
  165. size_t index = element(random);
  166. Ref<Ragdoll> ragdoll = ragdolls[index];
  167. ragdolls.erase(ragdolls.begin() + index);
  168. Execute(random, "Deactivate", [ragdoll]() {
  169. // Deactivate it
  170. ragdoll->RemoveFromPhysicsSystem();
  171. });
  172. }
  173. this_thread::sleep_for(1ms);
  174. }
  175. for (Ragdoll *r : ragdolls)
  176. r->RemoveFromPhysicsSystem();
  177. JPH_PROFILE_THREAD_END();
  178. }
  179. void MultithreadedTest::CasterMain()
  180. {
  181. JPH_PROFILE_THREAD_START("CasterMain");
  182. default_random_engine random;
  183. Array<BodyID> bodies;
  184. while (!mIsQuitting)
  185. {
  186. Execute(random, "CastRay", [this, &random]() {
  187. // Cast a random ray
  188. uniform_real_distribution<float> from_y(0, 10);
  189. uniform_real_distribution<float> from_xz(-5, 5);
  190. RVec3 from(from_xz(random), from_y(random), from_xz(random));
  191. RVec3 to(from_xz(random), from_y(random), from_xz(random));
  192. RRayCast ray { from, Vec3(to - from) };
  193. RayCastResult hit;
  194. if (mPhysicsSystem->GetNarrowPhaseQuery().CastRay(ray, hit, SpecifiedBroadPhaseLayerFilter(BroadPhaseLayers::MOVING), SpecifiedObjectLayerFilter(Layers::MOVING)))
  195. {
  196. // Draw hit position
  197. RVec3 hit_position_world = ray.GetPointOnRay(hit.mFraction);
  198. mDebugRenderer->DrawMarker(hit_position_world, Color::sYellow, 0.2f);
  199. BodyLockRead lock(mPhysicsSystem->GetBodyLockInterface(), hit.mBodyID);
  200. if (lock.SucceededAndIsInBroadPhase())
  201. {
  202. // Draw normal
  203. const Body &hit_body = lock.GetBody();
  204. RMat44 inv_com = hit_body.GetInverseCenterOfMassTransform();
  205. Vec3 normal = inv_com.Multiply3x3Transposed(hit_body.GetShape()->GetSurfaceNormal(hit.mSubShapeID2, Vec3(inv_com * hit_position_world))).Normalized();
  206. mDebugRenderer->DrawArrow(hit_position_world, hit_position_world + normal, Color::sGreen, 0.1f);
  207. }
  208. }
  209. });
  210. }
  211. JPH_PROFILE_THREAD_END();
  212. }