PerformanceTest.cpp 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. // Jolt includes
  4. #include <Jolt.h>
  5. #include <RegisterTypes.h>
  6. #include <Core/TempAllocator.h>
  7. #include <Core/JobSystemThreadPool.h>
  8. #include <Physics/PhysicsSettings.h>
  9. #include <Physics/PhysicsSystem.h>
  10. #include <Physics/Ragdoll/Ragdoll.h>
  11. #include <Physics/PhysicsScene.h>
  12. #include <Physics/Collision/CastResult.h>
  13. #include <Physics/Collision/RayCast.h>
  14. // STL includes
  15. #include <iostream>
  16. #include <thread>
  17. #include <chrono>
  18. using namespace JPH;
  19. using namespace std;
  20. namespace Layers
  21. {
  22. static constexpr uint8 NON_MOVING = 0;
  23. static constexpr uint8 MOVING = 1;
  24. static constexpr uint8 NUM_LAYERS = 2;
  25. };
  26. bool MyObjectCanCollide(ObjectLayer inObject1, ObjectLayer inObject2)
  27. {
  28. switch (inObject1)
  29. {
  30. case Layers::NON_MOVING:
  31. return inObject2 == Layers::MOVING; // Non moving only collides with moving
  32. case Layers::MOVING:
  33. return true; // Moving collides with everything
  34. default:
  35. JPH_ASSERT(false);
  36. return false;
  37. }
  38. };
  39. namespace BroadPhaseLayers
  40. {
  41. static constexpr BroadPhaseLayer NON_MOVING(0);
  42. static constexpr BroadPhaseLayer MOVING(1);
  43. };
  44. bool MyBroadPhaseCanCollide(ObjectLayer inLayer1, BroadPhaseLayer inLayer2)
  45. {
  46. switch (inLayer1)
  47. {
  48. case Layers::NON_MOVING:
  49. return inLayer2 == BroadPhaseLayers::MOVING;
  50. case Layers::MOVING:
  51. return true;
  52. default:
  53. JPH_ASSERT(false);
  54. return false;
  55. }
  56. }
  57. // Test configuration
  58. const float cHorizontalSeparation = 4.0f;
  59. const float cVerticalSeparation = 0.6f;
  60. #ifdef _DEBUG
  61. const int cPileSize = 5;
  62. const int cNumRows = 2;
  63. const int cNumCols = 2;
  64. #else
  65. const int cPileSize = 10;
  66. const int cNumRows = 4;
  67. const int cNumCols = 4;
  68. #endif
  69. const float cDeltaTime = 1.0f / 60.0f;
  70. // Program entry point
  71. int main(int argc, char** argv)
  72. {
  73. // Register all Jolt physics types
  74. RegisterTypes();
  75. // Create temp allocator
  76. TempAllocatorImpl temp_allocator(10 * 1024 * 1024);
  77. // Load ragdoll
  78. Ref<RagdollSettings> ragdoll_settings;
  79. if (!ObjectStreamIn::sReadObject("Assets/Human.tof", ragdoll_settings))
  80. {
  81. cerr << "Unable to load ragdoll" << endl;
  82. return 1;
  83. }
  84. for (BodyCreationSettings &body : ragdoll_settings->mParts)
  85. body.mObjectLayer = Layers::MOVING;
  86. // Init ragdoll
  87. ragdoll_settings->GetSkeleton()->CalculateParentJointIndices();
  88. ragdoll_settings->Stabilize();
  89. ragdoll_settings->CalculateBodyIndexToConstraintIndex();
  90. ragdoll_settings->CalculateConstraintIndexToBodyIdxPair();
  91. // Load animation
  92. Ref<SkeletalAnimation> animation;
  93. if (!ObjectStreamIn::sReadObject("Assets/Human/dead_pose1.tof", animation))
  94. {
  95. cerr << "Unable to load animation" << endl;
  96. return 1;
  97. }
  98. // Sample pose
  99. SkeletonPose pose;
  100. pose.SetSkeleton(ragdoll_settings->GetSkeleton());
  101. animation->Sample(0.0f, pose);
  102. // Read the scene
  103. Ref<PhysicsScene> scene;
  104. if (!ObjectStreamIn::sReadObject("Assets/terrain2.bof", scene))
  105. {
  106. cerr << "Unable to load terrain" << endl;
  107. return 1;
  108. }
  109. for (BodyCreationSettings &body : scene->GetBodies())
  110. body.mObjectLayer = Layers::NON_MOVING;
  111. scene->FixInvalidScales();
  112. // Create mapping table from object layer to broadphase layer
  113. ObjectToBroadPhaseLayer object_to_broadphase;
  114. object_to_broadphase.resize(Layers::NUM_LAYERS);
  115. object_to_broadphase[Layers::NON_MOVING] = BroadPhaseLayers::NON_MOVING;
  116. object_to_broadphase[Layers::MOVING] = BroadPhaseLayers::MOVING;
  117. // Start profiling this thread
  118. JPH_PROFILE_THREAD_START("Main");
  119. // Trace header
  120. cout << "Motion Quality, Thread Count, Time (s), Hash" << endl;
  121. // Iterate motion qualities
  122. for (uint mq = 0; mq < 2; ++mq)
  123. {
  124. // Determine motion quality
  125. EMotionQuality motion_quality = mq == 0? EMotionQuality::Discrete : EMotionQuality::LinearCast;
  126. string motion_quality_str = mq == 0? "Discrete" : "LinearCast";
  127. // Set motion quality on ragdoll
  128. for (BodyCreationSettings &body : ragdoll_settings->mParts)
  129. body.mMotionQuality = motion_quality;
  130. // Test thread permutations
  131. for (uint num_threads = 0; num_threads < thread::hardware_concurrency(); ++num_threads)
  132. {
  133. // Create job system with desired number of threads
  134. JobSystemThreadPool job_system(cMaxPhysicsJobs, cMaxPhysicsBarriers, num_threads);
  135. // Create physics system
  136. PhysicsSystem physics_system;
  137. physics_system.Init(10240, 0, 65536, 10240, object_to_broadphase, MyBroadPhaseCanCollide, MyObjectCanCollide);
  138. // Add background geometry
  139. scene->CreateBodies(&physics_system);
  140. // Create ragdoll piles
  141. vector<Ref<Ragdoll>> ragdolls;
  142. mt19937 random;
  143. uniform_real_distribution<float> angle(0.0f, JPH_PI);
  144. CollisionGroup::GroupID group_id = 1;
  145. for (int row = 0; row < cNumRows; ++row)
  146. for (int col = 0; col < cNumCols; ++col)
  147. {
  148. // Determine start location of ray
  149. Vec3 start = Vec3(cHorizontalSeparation * (col - (cNumCols - 1) / 2.0f), 100, cHorizontalSeparation * (row - (cNumRows - 1) / 2.0f));
  150. // Cast ray down to terrain
  151. RayCastResult hit;
  152. Vec3 ray_direction(0, -200, 0);
  153. RayCast ray { start, ray_direction };
  154. if (physics_system.GetNarrowPhaseQuery().CastRay(ray, hit, SpecifiedBroadPhaseLayerFilter(BroadPhaseLayers::NON_MOVING), SpecifiedObjectLayerFilter(Layers::NON_MOVING)))
  155. start = start + hit.mFraction * ray_direction;
  156. for (int i = 0; i < cPileSize; ++i)
  157. {
  158. // Create ragdoll
  159. Ref<Ragdoll> ragdoll = ragdoll_settings->CreateRagdoll(group_id++, nullptr, &physics_system);
  160. // Override root
  161. SkeletonPose pose_copy = pose;
  162. SkeletonPose::JointState &root = pose_copy.GetJoint(0);
  163. root.mTranslation = start + Vec3(0, cVerticalSeparation * (i + 1), 0);
  164. root.mRotation = Quat::sRotation(Vec3::sAxisY(), angle(random)) * root.mRotation;
  165. pose_copy.CalculateJointMatrices();
  166. // Drive to pose
  167. ragdoll->SetPose(pose_copy);
  168. ragdoll->DriveToPoseUsingMotors(pose_copy);
  169. ragdoll->AddToPhysicsSystem(EActivation::Activate);
  170. // Keep reference
  171. ragdolls.push_back(ragdoll);
  172. }
  173. }
  174. chrono::nanoseconds total_duration(0);
  175. // Step the world for a fixed amount of iterations
  176. for (uint iterations = 0; iterations < 500; ++iterations)
  177. {
  178. JPH_PROFILE_NEXTFRAME();
  179. // Start measuring
  180. chrono::high_resolution_clock::time_point clock_start = chrono::high_resolution_clock::now();
  181. // Do a physics step
  182. physics_system.Update(cDeltaTime, 1, 1, &temp_allocator, &job_system);
  183. // Stop measuring
  184. chrono::high_resolution_clock::time_point clock_end = chrono::high_resolution_clock::now();
  185. total_duration += chrono::duration_cast<chrono::nanoseconds>(clock_end - clock_start);
  186. // Dump profile information every 100 iterations
  187. if (iterations % 100 == 0)
  188. {
  189. JPH_PROFILE_DUMP();
  190. }
  191. }
  192. // Calculate hash of all positions and rotations of the bodies
  193. size_t hash = 0;
  194. BodyInterface &bi = physics_system.GetBodyInterfaceNoLock();
  195. for (Ragdoll *ragdoll : ragdolls)
  196. for (BodyID id : ragdoll->GetBodyIDs())
  197. {
  198. Vec3 pos = bi.GetPosition(id);
  199. Quat rot = bi.GetRotation(id);
  200. hash_combine(hash, pos.GetX(), pos.GetY(), pos.GetZ(), rot.GetX(), rot.GetY(), rot.GetZ(), rot.GetW());
  201. }
  202. // Remove ragdolls
  203. for (Ragdoll *ragdoll : ragdolls)
  204. ragdoll->RemoveFromPhysicsSystem();
  205. // Trace stat line
  206. cout << motion_quality_str << ", " << num_threads + 1 << ", " << 1.0e-9 * total_duration.count() << ", " << hash << endl;
  207. }
  208. }
  209. // End profiling this thread
  210. JPH_PROFILE_THREAD_END();
  211. return 0;
  212. }