MultithreadedTest.cpp 7.2 KB

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