PerformanceTest.cpp 14 KB

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