PerformanceTest.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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. // If no scene was specified use the default scene
  203. if (scene == nullptr)
  204. scene = create_ragdoll_scene();
  205. // Output scene we're running
  206. Trace("Running scene: %s", scene->GetName());
  207. // Load the scene
  208. if (!scene->Load())
  209. return 1;
  210. // Create mapping table from object layer to broadphase layer
  211. BPLayerInterfaceImpl broad_phase_layer_interface;
  212. // Create class that filters object vs broadphase layers
  213. ObjectVsBroadPhaseLayerFilterImpl object_vs_broadphase_layer_filter;
  214. // Create class that filters object vs object layers
  215. ObjectLayerPairFilterImpl object_vs_object_layer_filter;
  216. // Start profiling this program
  217. JPH_PROFILE_START("Main");
  218. // Trace header
  219. Trace("Motion Quality, Thread Count, Steps / Second, Hash");
  220. // Repeat test
  221. for (int r = 0; r < repeat; ++r)
  222. {
  223. // Iterate motion qualities
  224. for (uint mq = 0; mq < 2; ++mq)
  225. {
  226. // Skip quality if another was specified
  227. if (specified_quality != -1 && mq != (uint)specified_quality)
  228. continue;
  229. // Determine motion quality
  230. EMotionQuality motion_quality = mq == 0? EMotionQuality::Discrete : EMotionQuality::LinearCast;
  231. String motion_quality_str = mq == 0? "Discrete" : "LinearCast";
  232. // Determine which thread counts to test
  233. Array<uint> thread_permutations;
  234. if (specified_threads > 0)
  235. thread_permutations.push_back((uint)specified_threads - 1);
  236. else
  237. for (uint num_threads = 0; num_threads < thread::hardware_concurrency(); ++num_threads)
  238. thread_permutations.push_back(num_threads);
  239. // Test thread permutations
  240. for (uint num_threads : thread_permutations)
  241. {
  242. // Create job system with desired number of threads
  243. JobSystemThreadPool job_system(cMaxPhysicsJobs, cMaxPhysicsBarriers, num_threads);
  244. // Create physics system
  245. PhysicsSystem physics_system;
  246. physics_system.Init(10240, 0, 65536, 20480, broad_phase_layer_interface, object_vs_broadphase_layer_filter, object_vs_object_layer_filter);
  247. // Start test scene
  248. scene->StartTest(physics_system, motion_quality);
  249. // Disable sleeping if requested
  250. if (disable_sleep)
  251. {
  252. const BodyLockInterface &bli = physics_system.GetBodyLockInterfaceNoLock();
  253. BodyIDVector body_ids;
  254. physics_system.GetBodies(body_ids);
  255. for (BodyID id : body_ids)
  256. {
  257. BodyLockWrite lock(bli, id);
  258. if (lock.Succeeded())
  259. {
  260. Body &body = lock.GetBody();
  261. if (!body.IsStatic())
  262. body.SetAllowSleeping(false);
  263. }
  264. }
  265. }
  266. // Optimize the broadphase to prevent an expensive first frame
  267. physics_system.OptimizeBroadPhase();
  268. // A tag used to identify the test
  269. String tag = ToLower(motion_quality_str) + "_th" + ConvertToString(num_threads + 1);
  270. #ifdef JPH_DEBUG_RENDERER
  271. // Open renderer output
  272. ofstream renderer_file;
  273. if (enable_debug_renderer)
  274. renderer_file.open(("performance_test_" + tag + ".jor").c_str(), ofstream::out | ofstream::binary | ofstream::trunc);
  275. StreamOutWrapper renderer_stream(renderer_file);
  276. DebugRendererRecorder renderer(renderer_stream);
  277. #endif // JPH_DEBUG_RENDERER
  278. // Open per frame timing output
  279. ofstream per_frame_file;
  280. if (enable_per_frame_recording)
  281. {
  282. per_frame_file.open(("per_frame_" + tag + ".csv").c_str(), ofstream::out | ofstream::trunc);
  283. per_frame_file << "Frame, Time (ms)" << endl;
  284. }
  285. ofstream record_state_file;
  286. ifstream validate_state_file;
  287. if (record_state)
  288. record_state_file.open(("state_" + ToLower(motion_quality_str) + ".bin").c_str(), ofstream::out | ofstream::binary | ofstream::trunc);
  289. else if (validate_state)
  290. validate_state_file.open(("state_" + ToLower(motion_quality_str) + ".bin").c_str(), ifstream::in | ifstream::binary);
  291. chrono::nanoseconds total_duration(0);
  292. // Step the world for a fixed amount of iterations
  293. for (uint iterations = 0; iterations < max_iterations; ++iterations)
  294. {
  295. JPH_PROFILE_NEXTFRAME();
  296. JPH_DET_LOG("Iteration: " << iterations);
  297. // Start measuring
  298. chrono::high_resolution_clock::time_point clock_start = chrono::high_resolution_clock::now();
  299. // Do a physics step
  300. physics_system.Update(cDeltaTime, 1, &temp_allocator, &job_system);
  301. // Stop measuring
  302. chrono::high_resolution_clock::time_point clock_end = chrono::high_resolution_clock::now();
  303. chrono::nanoseconds duration = chrono::duration_cast<chrono::nanoseconds>(clock_end - clock_start);
  304. total_duration += duration;
  305. #ifdef JPH_DEBUG_RENDERER
  306. if (enable_debug_renderer)
  307. {
  308. // Draw the state of the world
  309. BodyManager::DrawSettings settings;
  310. physics_system.DrawBodies(settings, &renderer);
  311. // Mark end of frame
  312. renderer.EndFrame();
  313. }
  314. #endif // JPH_DEBUG_RENDERER
  315. // Record time taken this iteration
  316. if (enable_per_frame_recording)
  317. per_frame_file << iterations << ", " << (1.0e-6 * duration.count()) << endl;
  318. // Dump profile information every 100 iterations
  319. if (enable_profiler && iterations % 100 == 0)
  320. {
  321. JPH_PROFILE_DUMP(tag + "_it" + ConvertToString(iterations));
  322. }
  323. if (record_state)
  324. {
  325. // Record state
  326. StateRecorderImpl recorder;
  327. physics_system.SaveState(recorder);
  328. // Write to file
  329. string data = recorder.GetData();
  330. uint32 size = uint32(data.size());
  331. record_state_file.write((char *)&size, sizeof(size));
  332. record_state_file.write(data.data(), size);
  333. }
  334. else if (validate_state)
  335. {
  336. // Read state
  337. uint32 size = 0;
  338. validate_state_file.read((char *)&size, sizeof(size));
  339. string data;
  340. data.resize(size);
  341. validate_state_file.read(data.data(), size);
  342. // Copy to validator
  343. StateRecorderImpl validator;
  344. validator.WriteBytes(data.data(), size);
  345. // Validate state
  346. validator.SetValidating(true);
  347. physics_system.RestoreState(validator);
  348. }
  349. #ifdef JPH_ENABLE_DETERMINISM_LOG
  350. const BodyLockInterface &bli = physics_system.GetBodyLockInterfaceNoLock();
  351. BodyIDVector body_ids;
  352. physics_system.GetBodies(body_ids);
  353. for (BodyID id : body_ids)
  354. {
  355. BodyLockRead lock(bli, id);
  356. const Body &body = lock.GetBody();
  357. if (!body.IsStatic())
  358. JPH_DET_LOG(id << ": p: " << body.GetPosition() << " r: " << body.GetRotation() << " v: " << body.GetLinearVelocity() << " w: " << body.GetAngularVelocity());
  359. }
  360. #endif // JPH_ENABLE_DETERMINISM_LOG
  361. }
  362. // Calculate hash of all positions and rotations of the bodies
  363. uint64 hash = HashBytes(nullptr, 0); // Ensure we start with the proper seed
  364. BodyInterface &bi = physics_system.GetBodyInterfaceNoLock();
  365. BodyIDVector body_ids;
  366. physics_system.GetBodies(body_ids);
  367. for (BodyID id : body_ids)
  368. {
  369. RVec3 pos = bi.GetPosition(id);
  370. hash = HashBytes(&pos, 3 * sizeof(Real), hash);
  371. Quat rot = bi.GetRotation(id);
  372. hash = HashBytes(&rot, sizeof(Quat), hash);
  373. }
  374. // Convert hash to string
  375. stringstream hash_stream;
  376. hash_stream << "0x" << hex << hash << dec;
  377. string hash_str = hash_stream.str();
  378. // Stop test scene
  379. scene->StopTest(physics_system);
  380. // Trace stat line
  381. 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());
  382. // Check hash code
  383. if (validate_hash != nullptr && hash_str != validate_hash)
  384. {
  385. Trace("Fail hash validation. Was: %s, expected: %s", hash_str.c_str(), validate_hash);
  386. return 1;
  387. }
  388. }
  389. }
  390. }
  391. #ifdef JPH_TRACK_NARROWPHASE_STATS
  392. NarrowPhaseStat::sReportStats();
  393. #endif // JPH_TRACK_NARROWPHASE_STATS
  394. // Unregisters all types with the factory and cleans up the default material
  395. UnregisterTypes();
  396. // Destroy the factory
  397. delete Factory::sInstance;
  398. Factory::sInstance = nullptr;
  399. // End profiling this program
  400. JPH_PROFILE_END();
  401. return 0;
  402. }
  403. #ifdef JPH_PLATFORM_ANDROID
  404. // Main entry point for android
  405. void android_main(struct android_app *ioApp)
  406. {
  407. // Run the regular main function
  408. const char *args[] = { "Unused", "-s=ConvexVsMesh", "-t=max" };
  409. main(size(args), (char **)args);
  410. }
  411. #endif // JPH_PLATFORM_ANDROID