PerformanceTest.cpp 15 KB

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