PerformanceTest.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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/Factory.h>
  7. #include <Jolt/Core/TempAllocator.h>
  8. #include <Jolt/Core/JobSystemThreadPool.h>
  9. #include <Jolt/Physics/PhysicsSettings.h>
  10. #include <Jolt/Physics/PhysicsSystem.h>
  11. #include <Jolt/Physics/Collision/NarrowPhaseStats.h>
  12. #include <Jolt/Physics/StateRecorderImpl.h>
  13. #ifdef JPH_DEBUG_RENDERER
  14. #include <Jolt/Renderer/DebugRendererRecorder.h>
  15. #include <Jolt/Core/StreamWrapper.h>
  16. #endif // JPH_DEBUG_RENDERER
  17. // STL includes
  18. #include <iostream>
  19. #include <thread>
  20. #include <chrono>
  21. #include <memory>
  22. #include <cstdarg>
  23. using namespace JPH;
  24. using namespace std;
  25. // Disable common warnings triggered by Jolt
  26. JPH_SUPPRESS_WARNINGS
  27. // Local includes
  28. #include "RagdollScene.h"
  29. #include "ConvexVsMeshScene.h"
  30. // Time step for physics
  31. constexpr float cDeltaTime = 1.0f / 60.0f;
  32. static void TraceImpl(const char *inFMT, ...)
  33. {
  34. // Format the message
  35. va_list list;
  36. va_start(list, inFMT);
  37. char buffer[1024];
  38. vsnprintf(buffer, sizeof(buffer), inFMT, list);
  39. // Print to the TTY
  40. cout << buffer << endl;
  41. }
  42. // Program entry point
  43. int main(int argc, char** argv)
  44. {
  45. // Register allocation hook
  46. RegisterDefaultAllocator();
  47. // Parse command line parameters
  48. int specified_quality = -1;
  49. int specified_threads = -1;
  50. uint max_iterations = 500;
  51. bool disable_sleep = false;
  52. bool enable_profiler = false;
  53. #ifdef JPH_DEBUG_RENDERER
  54. bool enable_debug_renderer = false;
  55. #endif // JPH_DEBUG_RENDERER
  56. bool enable_per_frame_recording = false;
  57. bool record_state = false;
  58. bool validate_state = false;
  59. unique_ptr<PerformanceTestScene> scene;
  60. const char *validate_hash = nullptr;
  61. for (int argidx = 1; argidx < argc; ++argidx)
  62. {
  63. const char *arg = argv[argidx];
  64. if (strncmp(arg, "-s=", 3) == 0)
  65. {
  66. // Parse scene
  67. if (strcmp(arg + 3, "Ragdoll") == 0)
  68. scene = unique_ptr<PerformanceTestScene>(new RagdollScene);
  69. else if (strcmp(arg + 3, "ConvexVsMesh") == 0)
  70. scene = unique_ptr<PerformanceTestScene>(new ConvexVsMeshScene);
  71. else
  72. {
  73. cerr << "Invalid scene" << endl;
  74. return 1;
  75. }
  76. }
  77. else if (strncmp(arg, "-i=", 3) == 0)
  78. {
  79. // Parse max iterations
  80. max_iterations = (uint)atoi(arg + 3);
  81. }
  82. else if (strncmp(arg, "-q=", 3) == 0)
  83. {
  84. // Parse quality
  85. if (strcmp(arg + 3, "Discrete") == 0)
  86. specified_quality = 0;
  87. else if (strcmp(arg + 3, "LinearCast") == 0)
  88. specified_quality = 1;
  89. else
  90. {
  91. cerr << "Invalid quality" << endl;
  92. return 1;
  93. }
  94. }
  95. else if (strncmp(arg, "-t=", 3) == 0)
  96. {
  97. // Parse threads
  98. specified_threads = atoi(arg + 3);
  99. }
  100. else if (strcmp(arg, "-no_sleep") == 0)
  101. {
  102. disable_sleep = true;
  103. }
  104. else if (strcmp(arg, "-p") == 0)
  105. {
  106. enable_profiler = true;
  107. }
  108. #ifdef JPH_DEBUG_RENDERER
  109. else if (strcmp(arg, "-r") == 0)
  110. {
  111. enable_debug_renderer = true;
  112. }
  113. #endif // JPH_DEBUG_RENDERER
  114. else if (strcmp(arg, "-f") == 0)
  115. {
  116. enable_per_frame_recording = true;
  117. }
  118. else if (strcmp(arg, "-rs") == 0)
  119. {
  120. record_state = true;
  121. }
  122. else if (strcmp(arg, "-vs") == 0)
  123. {
  124. validate_state = true;
  125. }
  126. else if (strncmp(arg, "-validate_hash=", 15) == 0)
  127. {
  128. validate_hash = arg + 15;
  129. }
  130. else if (strcmp(arg, "-h") == 0)
  131. {
  132. // Print usage
  133. cerr << "Usage:" << endl
  134. << "-s=<scene>: Select scene (Ragdoll, ConvexVsMesh)" << endl
  135. << "-i=<num physics steps>: Number of physics steps to simulate (default 500)" << endl
  136. << "-q=<quality>: Test only with specified quality (Discrete, LinearCast)" << endl
  137. << "-t=<num threads>: Test only with N threads (default is to iterate over 1 .. num hardware threads)" << endl
  138. << "-p: Write out profiles" << endl
  139. << "-r: Record debug renderer output for JoltViewer" << endl
  140. << "-f: Record per frame timings" << endl
  141. << "-no_sleep: Disable sleeping" << endl
  142. << "-rs: Record state" << endl
  143. << "-vs: Validate state" << endl
  144. << "-validate_hash=<hash>: Validate hash (return 0 if successful, 1 if failed)" << endl;
  145. return 0;
  146. }
  147. }
  148. // Install callbacks
  149. Trace = TraceImpl;
  150. // Create a factory
  151. Factory::sInstance = new Factory();
  152. // Register all Jolt physics types
  153. RegisterTypes();
  154. // Create temp allocator
  155. TempAllocatorImpl temp_allocator(10 * 1024 * 1024);
  156. // Load the scene
  157. if (scene == nullptr)
  158. scene = unique_ptr<PerformanceTestScene>(new RagdollScene);
  159. if (!scene->Load())
  160. return 1;
  161. // Output scene we're running
  162. cout << "Running scene: " << scene->GetName() << endl;
  163. // Create mapping table from object layer to broadphase layer
  164. BPLayerInterfaceImpl broad_phase_layer_interface;
  165. // Start profiling this program
  166. JPH_PROFILE_START("Main");
  167. // Trace header
  168. cout << "Motion Quality, Thread Count, Steps / Second, Hash" << endl;
  169. // Iterate motion qualities
  170. for (uint mq = 0; mq < 2; ++mq)
  171. {
  172. // Skip quality if another was specified
  173. if (specified_quality != -1 && mq != (uint)specified_quality)
  174. continue;
  175. // Determine motion quality
  176. EMotionQuality motion_quality = mq == 0? EMotionQuality::Discrete : EMotionQuality::LinearCast;
  177. String motion_quality_str = mq == 0? "Discrete" : "LinearCast";
  178. // Determine which thread counts to test
  179. Array<uint> thread_permutations;
  180. if (specified_threads > 0)
  181. thread_permutations.push_back((uint)specified_threads - 1);
  182. else
  183. for (uint num_threads = 0; num_threads < thread::hardware_concurrency(); ++num_threads)
  184. thread_permutations.push_back(num_threads);
  185. // Test thread permutations
  186. for (uint num_threads : thread_permutations)
  187. {
  188. // Create job system with desired number of threads
  189. JobSystemThreadPool job_system(cMaxPhysicsJobs, cMaxPhysicsBarriers, num_threads);
  190. // Create physics system
  191. PhysicsSystem physics_system;
  192. physics_system.Init(10240, 0, 65536, 10240, broad_phase_layer_interface, BroadPhaseCanCollide, ObjectCanCollide);
  193. // Start test scene
  194. scene->StartTest(physics_system, motion_quality);
  195. // Disable sleeping if requested
  196. if (disable_sleep)
  197. {
  198. const BodyLockInterface &bli = physics_system.GetBodyLockInterfaceNoLock();
  199. BodyIDVector body_ids;
  200. physics_system.GetBodies(body_ids);
  201. for (BodyID id : body_ids)
  202. {
  203. BodyLockWrite lock(bli, id);
  204. if (lock.Succeeded())
  205. {
  206. Body &body = lock.GetBody();
  207. if (!body.IsStatic())
  208. body.SetAllowSleeping(false);
  209. }
  210. }
  211. }
  212. // Optimize the broadphase to prevent an expensive first frame
  213. physics_system.OptimizeBroadPhase();
  214. // A tag used to identify the test
  215. String tag = ToLower(motion_quality_str) + "_th" + ConvertToString(num_threads + 1);
  216. #ifdef JPH_DEBUG_RENDERER
  217. // Open renderer output
  218. ofstream renderer_file;
  219. if (enable_debug_renderer)
  220. renderer_file.open(("performance_test_" + tag + ".jor").c_str(), ofstream::out | ofstream::binary | ofstream::trunc);
  221. StreamOutWrapper renderer_stream(renderer_file);
  222. DebugRendererRecorder renderer(renderer_stream);
  223. #endif // JPH_DEBUG_RENDERER
  224. // Open per frame timing output
  225. ofstream per_frame_file;
  226. if (enable_per_frame_recording)
  227. {
  228. per_frame_file.open(("per_frame_" + tag + ".csv").c_str(), ofstream::out | ofstream::trunc);
  229. per_frame_file << "Frame, Time (ms)" << endl;
  230. }
  231. ofstream record_state_file;
  232. ifstream validate_state_file;
  233. if (record_state)
  234. record_state_file.open(("state_" + ToLower(motion_quality_str) + ".bin").c_str(), ofstream::out | ofstream::binary | ofstream::trunc);
  235. else if (validate_state)
  236. validate_state_file.open(("state_" + ToLower(motion_quality_str) + ".bin").c_str(), ifstream::in | ifstream::binary);
  237. chrono::nanoseconds total_duration(0);
  238. // Step the world for a fixed amount of iterations
  239. for (uint iterations = 0; iterations < max_iterations; ++iterations)
  240. {
  241. JPH_PROFILE_NEXTFRAME();
  242. // Start measuring
  243. chrono::high_resolution_clock::time_point clock_start = chrono::high_resolution_clock::now();
  244. // Do a physics step
  245. physics_system.Update(cDeltaTime, 1, 1, &temp_allocator, &job_system);
  246. // Stop measuring
  247. chrono::high_resolution_clock::time_point clock_end = chrono::high_resolution_clock::now();
  248. chrono::nanoseconds duration = chrono::duration_cast<chrono::nanoseconds>(clock_end - clock_start);
  249. total_duration += duration;
  250. #ifdef JPH_DEBUG_RENDERER
  251. if (enable_debug_renderer)
  252. {
  253. // Draw the state of the world
  254. BodyManager::DrawSettings settings;
  255. physics_system.DrawBodies(settings, &renderer);
  256. // Mark end of frame
  257. renderer.EndFrame();
  258. }
  259. #endif // JPH_DEBUG_RENDERER
  260. // Record time taken this iteration
  261. if (enable_per_frame_recording)
  262. per_frame_file << iterations << ", " << (1.0e-6 * duration.count()) << endl;
  263. // Dump profile information every 100 iterations
  264. if (enable_profiler && iterations % 100 == 0)
  265. {
  266. JPH_PROFILE_DUMP(tag + "_it" + ConvertToString(iterations));
  267. }
  268. if (record_state)
  269. {
  270. // Record state
  271. StateRecorderImpl recorder;
  272. physics_system.SaveState(recorder);
  273. // Write to file
  274. string data = recorder.GetData();
  275. size_t size = data.size();
  276. record_state_file.write((char *)&size, sizeof(size));
  277. record_state_file.write(data.data(), size);
  278. }
  279. else if (validate_state)
  280. {
  281. // Read state
  282. size_t size = 0;
  283. validate_state_file.read((char *)&size, sizeof(size));
  284. string data;
  285. data.resize(size);
  286. validate_state_file.read(data.data(), size);
  287. // Copy to validator
  288. StateRecorderImpl validator;
  289. validator.WriteBytes(data.data(), size);
  290. // Validate state
  291. validator.SetValidating(true);
  292. physics_system.RestoreState(validator);
  293. }
  294. }
  295. // Calculate hash of all positions and rotations of the bodies
  296. uint64 hash = HashBytes(nullptr, 0); // Ensure we start with the proper seed
  297. BodyInterface &bi = physics_system.GetBodyInterfaceNoLock();
  298. BodyIDVector body_ids;
  299. physics_system.GetBodies(body_ids);
  300. for (BodyID id : body_ids)
  301. {
  302. Vec3 pos = bi.GetPosition(id);
  303. hash = HashBytes(&pos, 3 * sizeof(float), hash);
  304. Quat rot = bi.GetRotation(id);
  305. hash = HashBytes(&rot, sizeof(Quat), hash);
  306. }
  307. // Convert hash to string
  308. stringstream hash_stream;
  309. hash_stream << "0x" << hex << hash << dec;
  310. string hash_str = hash_stream.str();
  311. // Stop test scene
  312. scene->StopTest(physics_system);
  313. // Trace stat line
  314. cout << motion_quality_str << ", " << num_threads + 1 << ", " << double(max_iterations) / (1.0e-9 * total_duration.count()) << ", " << hash_str << endl;
  315. // Check hash code
  316. if (validate_hash != nullptr && hash_str != validate_hash)
  317. {
  318. cout << "Fail hash validation. Was: " << hash_str << ", expected: " << validate_hash << endl;
  319. return 1;
  320. }
  321. }
  322. }
  323. #ifdef JPH_TRACK_NARROWPHASE_STATS
  324. NarrowPhaseStat::sReportStats();
  325. #endif // JPH_TRACK_NARROWPHASE_STATS
  326. // Destroy the factory
  327. delete Factory::sInstance;
  328. Factory::sInstance = nullptr;
  329. // End profiling this program
  330. JPH_PROFILE_END();
  331. return 0;
  332. }