PerformanceTest.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. // Jolt includes
  4. #include <Jolt/Jolt.h>
  5. #include <Jolt/RegisterTypes.h>
  6. #include <Jolt/Core/TempAllocator.h>
  7. #include <Jolt/Core/JobSystemThreadPool.h>
  8. #include <Jolt/Physics/PhysicsSettings.h>
  9. #include <Jolt/Physics/PhysicsSystem.h>
  10. #include <Jolt/Physics/Collision/NarrowPhaseStats.h>
  11. #ifdef JPH_DEBUG_RENDERER
  12. #include <Jolt/Renderer/DebugRendererRecorder.h>
  13. #include <Jolt/Core/StreamWrapper.h>
  14. #endif // JPH_DEBUG_RENDERER
  15. // STL includes
  16. #include <iostream>
  17. #include <thread>
  18. #include <chrono>
  19. #include <memory>
  20. #include <cstdarg>
  21. using namespace JPH;
  22. using namespace std;
  23. // Disable common warnings triggered by Jolt
  24. JPH_SUPPRESS_WARNINGS
  25. // Local includes
  26. #include "RagdollScene.h"
  27. #include "ConvexVsMeshScene.h"
  28. // Time step for physics
  29. constexpr float cDeltaTime = 1.0f / 60.0f;
  30. static void TraceImpl(const char *inFMT, ...)
  31. {
  32. // Format the message
  33. va_list list;
  34. va_start(list, inFMT);
  35. char buffer[1024];
  36. vsnprintf(buffer, sizeof(buffer), inFMT, list);
  37. // Print to the TTY
  38. cout << buffer << endl;
  39. }
  40. // Program entry point
  41. int main(int argc, char** argv)
  42. {
  43. // Parse command line parameters
  44. int specified_quality = -1;
  45. int specified_threads = -1;
  46. uint max_iterations = 500;
  47. bool disable_sleep = false;
  48. bool enable_profiler = false;
  49. #ifdef JPH_DEBUG_RENDERER
  50. bool enable_debug_renderer = false;
  51. #endif // JPH_DEBUG_RENDERER
  52. bool enable_per_frame_recording = false;
  53. unique_ptr<PerformanceTestScene> scene;
  54. for (int argidx = 1; argidx < argc; ++argidx)
  55. {
  56. const char *arg = argv[argidx];
  57. if (strncmp(arg, "-s=", 3) == 0)
  58. {
  59. // Parse scene
  60. if (strcmp(arg + 3, "Ragdoll") == 0)
  61. scene = unique_ptr<PerformanceTestScene>(new RagdollScene);
  62. else if (strcmp(arg + 3, "ConvexVsMesh") == 0)
  63. scene = unique_ptr<PerformanceTestScene>(new ConvexVsMeshScene);
  64. else
  65. {
  66. cerr << "Invalid scene" << endl;
  67. return 1;
  68. }
  69. }
  70. else if (strncmp(arg, "-i=", 3) == 0)
  71. {
  72. // Parse max iterations
  73. max_iterations = (uint)atoi(arg + 3);
  74. }
  75. else if (strncmp(arg, "-q=", 3) == 0)
  76. {
  77. // Parse quality
  78. if (strcmp(arg + 3, "Discrete") == 0)
  79. specified_quality = 0;
  80. else if (strcmp(arg + 3, "LinearCast") == 0)
  81. specified_quality = 1;
  82. else
  83. {
  84. cerr << "Invalid quality" << endl;
  85. return 1;
  86. }
  87. }
  88. else if (strncmp(arg, "-t=", 3) == 0)
  89. {
  90. // Parse threads
  91. specified_threads = atoi(arg + 3);
  92. }
  93. else if (strcmp(arg, "-no_sleep") == 0)
  94. {
  95. disable_sleep = true;
  96. }
  97. else if (strcmp(arg, "-p") == 0)
  98. {
  99. enable_profiler = true;
  100. }
  101. #ifdef JPH_DEBUG_RENDERER
  102. else if (strcmp(arg, "-r") == 0)
  103. {
  104. enable_debug_renderer = true;
  105. }
  106. #endif // JPH_DEBUG_RENDERER
  107. else if (strcmp(arg, "-f") == 0)
  108. {
  109. enable_per_frame_recording = true;
  110. }
  111. else if (strcmp(arg, "-h") == 0)
  112. {
  113. // Print usage
  114. cerr << "Usage:" << endl
  115. << "-s=<scene>: Select scene (Ragdoll, ConvexVsMesh)" << endl
  116. << "-i=<num physics steps>: Number of physics steps to simulate (default 500)" << endl
  117. << "-q=<quality>: Test only with specified quality (Discrete, LinearCast)" << endl
  118. << "-t=<num threads>: Test only with N threads (default is to iterate over 1 .. num hardware threads)" << endl
  119. << "-p: Write out profiles" << endl
  120. << "-r: Record debug renderer output for JoltViewer" << endl
  121. << "-f: Record per frame timings" << endl
  122. << "-no_sleep: Disable sleeping" << endl;
  123. return 0;
  124. }
  125. }
  126. // Install callbacks
  127. Trace = TraceImpl;
  128. // Register all Jolt physics types
  129. RegisterTypes();
  130. // Create temp allocator
  131. TempAllocatorImpl temp_allocator(10 * 1024 * 1024);
  132. // Load the scene
  133. if (scene == nullptr)
  134. scene = unique_ptr<PerformanceTestScene>(new RagdollScene);
  135. if (!scene->Load())
  136. return 1;
  137. // Output scene we're running
  138. cout << "Running scene: " << scene->GetName() << endl;
  139. // Create mapping table from object layer to broadphase layer
  140. BPLayerInterfaceImpl broad_phase_layer_interface;
  141. // Start profiling this thread
  142. JPH_PROFILE_THREAD_START("Main");
  143. // Trace header
  144. cout << "Motion Quality, Thread Count, Steps / Second, Hash" << endl;
  145. // Iterate motion qualities
  146. for (uint mq = 0; mq < 2; ++mq)
  147. {
  148. // Skip quality if another was specified
  149. if (specified_quality != -1 && mq != (uint)specified_quality)
  150. continue;
  151. // Determine motion quality
  152. EMotionQuality motion_quality = mq == 0? EMotionQuality::Discrete : EMotionQuality::LinearCast;
  153. string motion_quality_str = mq == 0? "Discrete" : "LinearCast";
  154. // Determine which thread counts to test
  155. vector<uint> thread_permutations;
  156. if (specified_threads > 0)
  157. thread_permutations.push_back((uint)specified_threads - 1);
  158. else
  159. for (uint num_threads = 0; num_threads < thread::hardware_concurrency(); ++num_threads)
  160. thread_permutations.push_back(num_threads);
  161. // Test thread permutations
  162. for (uint num_threads : thread_permutations)
  163. {
  164. // Create job system with desired number of threads
  165. JobSystemThreadPool job_system(cMaxPhysicsJobs, cMaxPhysicsBarriers, num_threads);
  166. // Create physics system
  167. PhysicsSystem physics_system;
  168. physics_system.Init(10240, 0, 65536, 10240, broad_phase_layer_interface, BroadPhaseCanCollide, ObjectCanCollide);
  169. // Start test scene
  170. scene->StartTest(physics_system, motion_quality);
  171. // Disable sleeping if requested
  172. if (disable_sleep)
  173. {
  174. const BodyLockInterface &bli = physics_system.GetBodyLockInterfaceNoLock();
  175. BodyIDVector body_ids;
  176. physics_system.GetBodies(body_ids);
  177. for (BodyID id : body_ids)
  178. {
  179. BodyLockWrite lock(bli, id);
  180. if (lock.Succeeded())
  181. {
  182. Body &body = lock.GetBody();
  183. if (!body.IsStatic())
  184. body.SetAllowSleeping(false);
  185. }
  186. }
  187. }
  188. // Optimize the broadphase to prevent an expensive first frame
  189. physics_system.OptimizeBroadPhase();
  190. // A tag used to identify the test
  191. string tag = ToLower(motion_quality_str) + "_th" + ConvertToString(num_threads + 1);
  192. #ifdef JPH_DEBUG_RENDERER
  193. // Open renderer output
  194. ofstream renderer_file;
  195. if (enable_debug_renderer)
  196. renderer_file.open(("performance_test_" + tag + ".jor").c_str(), ofstream::out | ofstream::binary | ofstream::trunc);
  197. StreamOutWrapper renderer_stream(renderer_file);
  198. DebugRendererRecorder renderer(renderer_stream);
  199. #endif // JPH_DEBUG_RENDERER
  200. // Open per frame timing output
  201. ofstream per_frame_file;
  202. if (enable_per_frame_recording)
  203. {
  204. per_frame_file.open(("per_frame_" + tag + ".csv").c_str(), ofstream::out | ofstream::trunc);
  205. per_frame_file << "Frame, Time (ms)" << endl;
  206. }
  207. chrono::nanoseconds total_duration(0);
  208. // Step the world for a fixed amount of iterations
  209. for (uint iterations = 0; iterations < max_iterations; ++iterations)
  210. {
  211. JPH_PROFILE_NEXTFRAME();
  212. // Start measuring
  213. chrono::high_resolution_clock::time_point clock_start = chrono::high_resolution_clock::now();
  214. // Do a physics step
  215. physics_system.Update(cDeltaTime, 1, 1, &temp_allocator, &job_system);
  216. // Stop measuring
  217. chrono::high_resolution_clock::time_point clock_end = chrono::high_resolution_clock::now();
  218. chrono::nanoseconds duration = chrono::duration_cast<chrono::nanoseconds>(clock_end - clock_start);
  219. total_duration += duration;
  220. #ifdef JPH_DEBUG_RENDERER
  221. if (enable_debug_renderer)
  222. {
  223. // Draw the state of the world
  224. BodyManager::DrawSettings settings;
  225. physics_system.DrawBodies(settings, &renderer);
  226. // Mark end of frame
  227. renderer.EndFrame();
  228. }
  229. #endif // JPH_DEBUG_RENDERER
  230. // Record time taken this iteration
  231. if (enable_per_frame_recording)
  232. per_frame_file << iterations << ", " << (1.0e-6 * duration.count()) << endl;
  233. // Dump profile information every 100 iterations
  234. if (enable_profiler && iterations % 100 == 0)
  235. {
  236. JPH_PROFILE_DUMP(tag + "_it" + ConvertToString(iterations));
  237. }
  238. }
  239. // Calculate hash of all positions and rotations of the bodies
  240. size_t hash = 0;
  241. BodyInterface &bi = physics_system.GetBodyInterfaceNoLock();
  242. BodyIDVector body_ids;
  243. physics_system.GetBodies(body_ids);
  244. for (BodyID id : body_ids)
  245. {
  246. Vec3 pos = bi.GetPosition(id);
  247. Quat rot = bi.GetRotation(id);
  248. hash_combine(hash, pos.GetX(), pos.GetY(), pos.GetZ(), rot.GetX(), rot.GetY(), rot.GetZ(), rot.GetW());
  249. }
  250. // Stop test scene
  251. scene->StopTest(physics_system);
  252. // Trace stat line
  253. cout << motion_quality_str << ", " << num_threads + 1 << ", " << double(max_iterations) / (1.0e-9 * total_duration.count()) << ", " << hash << endl;
  254. }
  255. }
  256. #ifdef JPH_TRACK_NARROWPHASE_STATS
  257. NarrowPhaseStat::sReportStats();
  258. #endif // JPH_TRACK_NARROWPHASE_STATS
  259. // End profiling this thread
  260. JPH_PROFILE_THREAD_END();
  261. return 0;
  262. }