App.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  1. // Copyright (C) 2009-2023, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include <AnKi/Core/App.h>
  6. #include <AnKi/Core/ConfigSet.h>
  7. #include <AnKi/Util/Logger.h>
  8. #include <AnKi/Util/File.h>
  9. #include <AnKi/Util/Filesystem.h>
  10. #include <AnKi/Util/System.h>
  11. #include <AnKi/Util/ThreadHive.h>
  12. #include <AnKi/Util/Tracer.h>
  13. #include <AnKi/Util/HighRezTimer.h>
  14. #include <AnKi/Core/CoreTracer.h>
  15. #include <AnKi/Core/DeveloperConsole.h>
  16. #include <AnKi/Core/StatsUi.h>
  17. #include <AnKi/Core/NativeWindow.h>
  18. #include <AnKi/Core/MaliHwCounters.h>
  19. #include <AnKi/Input/Input.h>
  20. #include <AnKi/Scene/SceneGraph.h>
  21. #include <AnKi/Renderer/RenderQueue.h>
  22. #include <AnKi/Resource/ResourceManager.h>
  23. #include <AnKi/Physics/PhysicsWorld.h>
  24. #include <AnKi/Renderer/MainRenderer.h>
  25. #include <AnKi/Script/ScriptManager.h>
  26. #include <AnKi/Resource/ResourceFilesystem.h>
  27. #include <AnKi/Resource/AsyncLoader.h>
  28. #include <AnKi/Core/GpuMemoryPools.h>
  29. #include <AnKi/Ui/UiManager.h>
  30. #include <AnKi/Ui/Canvas.h>
  31. #include <csignal>
  32. #if ANKI_OS_ANDROID
  33. # include <android_native_app_glue.h>
  34. #endif
  35. namespace anki {
  36. #if ANKI_OS_ANDROID
  37. /// The one and only android hack
  38. android_app* g_androidApp = nullptr;
  39. #endif
  40. void* App::MemStats::allocCallback(void* userData, void* ptr, PtrSize size, [[maybe_unused]] PtrSize alignment)
  41. {
  42. ANKI_ASSERT(userData);
  43. constexpr PtrSize kMaxAlignment = 64;
  44. struct alignas(kMaxAlignment) Header
  45. {
  46. PtrSize m_allocatedSize;
  47. Array<U8, kMaxAlignment - sizeof(PtrSize)> _m_padding;
  48. };
  49. static_assert(sizeof(Header) == kMaxAlignment, "See file");
  50. static_assert(alignof(Header) == kMaxAlignment, "See file");
  51. void* out = nullptr;
  52. if(ptr == nullptr)
  53. {
  54. // Need to allocate
  55. ANKI_ASSERT(size > 0);
  56. ANKI_ASSERT(alignment > 0 && alignment <= kMaxAlignment);
  57. const PtrSize newAlignment = kMaxAlignment;
  58. const PtrSize newSize = sizeof(Header) + size;
  59. // Allocate
  60. MemStats* self = static_cast<MemStats*>(userData);
  61. Header* allocation = static_cast<Header*>(
  62. self->m_originalAllocCallback(self->m_originalUserData, nullptr, newSize, newAlignment));
  63. allocation->m_allocatedSize = size;
  64. ++allocation;
  65. out = static_cast<void*>(allocation);
  66. // Update stats
  67. self->m_allocatedMem.fetchAdd(size);
  68. self->m_allocCount.fetchAdd(1);
  69. }
  70. else
  71. {
  72. // Need to free
  73. MemStats* self = static_cast<MemStats*>(userData);
  74. Header* allocation = static_cast<Header*>(ptr);
  75. --allocation;
  76. ANKI_ASSERT(allocation->m_allocatedSize > 0);
  77. // Update stats
  78. self->m_freeCount.fetchAdd(1);
  79. self->m_allocatedMem.fetchSub(allocation->m_allocatedSize);
  80. // Free
  81. self->m_originalAllocCallback(self->m_originalUserData, allocation, 0, 0);
  82. }
  83. return out;
  84. }
  85. App::App()
  86. {
  87. }
  88. App::~App()
  89. {
  90. ANKI_CORE_LOGI("Destroying application");
  91. cleanup();
  92. }
  93. void App::cleanup()
  94. {
  95. m_statsUi.reset(nullptr);
  96. m_console.reset(nullptr);
  97. deleteInstance(m_mainPool, m_scene);
  98. m_scene = nullptr;
  99. deleteInstance(m_mainPool, m_script);
  100. m_script = nullptr;
  101. deleteInstance(m_mainPool, m_renderer);
  102. m_renderer = nullptr;
  103. deleteInstance(m_mainPool, m_ui);
  104. m_ui = nullptr;
  105. deleteInstance(m_mainPool, m_gpuSceneMicroPatcher);
  106. m_gpuSceneMicroPatcher = nullptr;
  107. deleteInstance(m_mainPool, m_resources);
  108. m_resources = nullptr;
  109. deleteInstance(m_mainPool, m_resourceFs);
  110. m_resourceFs = nullptr;
  111. deleteInstance(m_mainPool, m_physics);
  112. m_physics = nullptr;
  113. deleteInstance(m_mainPool, m_rebarPool);
  114. m_rebarPool = nullptr;
  115. deleteInstance(m_mainPool, m_unifiedGometryMemPool);
  116. m_unifiedGometryMemPool = nullptr;
  117. deleteInstance(m_mainPool, m_gpuSceneMemPool);
  118. m_gpuSceneMemPool = nullptr;
  119. deleteInstance(m_mainPool, m_threadHive);
  120. m_threadHive = nullptr;
  121. deleteInstance(m_mainPool, m_maliHwCounters);
  122. m_maliHwCounters = nullptr;
  123. GrManager::deleteInstance(m_gr);
  124. m_gr = nullptr;
  125. Input::deleteInstance(m_input);
  126. m_input = nullptr;
  127. NativeWindow::deleteInstance(m_window);
  128. m_window = nullptr;
  129. #if ANKI_ENABLE_TRACE
  130. deleteInstance(m_mainPool, m_coreTracer);
  131. m_coreTracer = nullptr;
  132. #endif
  133. m_settingsDir.destroy(m_mainPool);
  134. m_cacheDir.destroy(m_mainPool);
  135. }
  136. Error App::init(ConfigSet* config, AllocAlignedCallback allocCb, void* allocCbUserData)
  137. {
  138. ANKI_ASSERT(config);
  139. m_config = config;
  140. const Error err = initInternal(allocCb, allocCbUserData);
  141. if(err)
  142. {
  143. ANKI_CORE_LOGE("App initialization failed. Shutting down");
  144. cleanup();
  145. }
  146. return err;
  147. }
  148. Error App::initInternal(AllocAlignedCallback allocCb, void* allocCbUserData)
  149. {
  150. Logger::getSingleton().enableVerbosity(m_config->getCoreVerboseLog());
  151. setSignalHandlers();
  152. initMemoryCallbacks(allocCb, allocCbUserData);
  153. m_mainPool.init(allocCb, allocCbUserData, "Core");
  154. ANKI_CHECK(initDirs());
  155. // Print a message
  156. const char* buildType =
  157. #if ANKI_OPTIMIZE
  158. "optimized, "
  159. #else
  160. "NOT optimized, "
  161. #endif
  162. #if ANKI_DEBUG_SYMBOLS
  163. "dbg symbols, "
  164. #else
  165. "NO dbg symbols, "
  166. #endif
  167. #if ANKI_EXTRA_CHECKS
  168. "extra checks, "
  169. #else
  170. "NO extra checks, "
  171. #endif
  172. #if ANKI_ENABLE_TRACE
  173. "built with tracing";
  174. #else
  175. "NOT built with tracing";
  176. #endif
  177. ANKI_CORE_LOGI("Initializing application ("
  178. "version %u.%u, "
  179. "%s, "
  180. "compiler %s, "
  181. "build date %s, "
  182. "commit %s)",
  183. ANKI_VERSION_MAJOR, ANKI_VERSION_MINOR, buildType, ANKI_COMPILER_STR, __DATE__, ANKI_REVISION);
  184. // Check SIMD support
  185. #if ANKI_SIMD_SSE && ANKI_COMPILER_GCC_COMPATIBLE
  186. if(!__builtin_cpu_supports("sse4.2"))
  187. {
  188. ANKI_CORE_LOGF(
  189. "AnKi is built with sse4.2 support but your CPU doesn't support it. Try bulding without SSE support");
  190. }
  191. #endif
  192. ANKI_CORE_LOGI("Number of job threads: %u", m_config->getCoreJobThreadCount());
  193. if(m_config->getCoreBenchmarkMode() && m_config->getGrVsync())
  194. {
  195. ANKI_CORE_LOGW("Vsync is enabled and benchmark mode as well. Will turn vsync off");
  196. m_config->setGrVsync(false);
  197. }
  198. //
  199. // Core tracer
  200. //
  201. #if ANKI_ENABLE_TRACE
  202. m_coreTracer = newInstance<CoreTracer>(m_mainPool);
  203. ANKI_CHECK(m_coreTracer->init(&m_mainPool, m_settingsDir));
  204. #endif
  205. //
  206. // Window
  207. //
  208. NativeWindowInitInfo nwinit;
  209. nwinit.m_allocCallback = m_mainPool.getAllocationCallback();
  210. nwinit.m_allocCallbackUserData = m_mainPool.getAllocationCallbackUserData();
  211. nwinit.m_width = m_config->getWidth();
  212. nwinit.m_height = m_config->getHeight();
  213. nwinit.m_depthBits = 0;
  214. nwinit.m_stencilBits = 0;
  215. nwinit.m_fullscreenDesktopRez = m_config->getWindowFullscreen() > 0;
  216. nwinit.m_exclusiveFullscreen = m_config->getWindowFullscreen() == 2;
  217. nwinit.m_targetFps = m_config->getCoreTargetFps();
  218. ANKI_CHECK(NativeWindow::newInstance(nwinit, m_window));
  219. //
  220. // Input
  221. //
  222. ANKI_CHECK(Input::newInstance(m_mainPool.getAllocationCallback(), m_mainPool.getAllocationCallbackUserData(),
  223. m_window, m_input));
  224. //
  225. // ThreadPool
  226. //
  227. const Bool pinThreads = !ANKI_OS_ANDROID;
  228. m_threadHive = newInstance<ThreadHive>(m_mainPool, m_config->getCoreJobThreadCount(), &m_mainPool, pinThreads);
  229. //
  230. // Graphics API
  231. //
  232. GrManagerInitInfo grInit;
  233. grInit.m_allocCallback = m_mainPool.getAllocationCallback();
  234. grInit.m_allocCallbackUserData = m_mainPool.getAllocationCallbackUserData();
  235. grInit.m_cacheDirectory = m_cacheDir.toCString();
  236. grInit.m_config = m_config;
  237. grInit.m_window = m_window;
  238. ANKI_CHECK(GrManager::newInstance(grInit, m_gr));
  239. //
  240. // Mali HW counters
  241. //
  242. if(m_gr->getDeviceCapabilities().m_gpuVendor == GpuVendor::kArm && m_config->getCoreMaliHwCounters())
  243. {
  244. m_maliHwCounters = newInstance<MaliHwCounters>(m_mainPool, &m_mainPool);
  245. }
  246. //
  247. // GPU mem
  248. //
  249. m_unifiedGometryMemPool = newInstance<UnifiedGeometryMemoryPool>(m_mainPool);
  250. m_unifiedGometryMemPool->init(&m_mainPool, m_gr, *m_config);
  251. m_gpuSceneMemPool = newInstance<GpuSceneMemoryPool>(m_mainPool);
  252. m_gpuSceneMemPool->init(&m_mainPool, m_gr, *m_config);
  253. m_rebarPool = newInstance<RebarStagingGpuMemoryPool>(m_mainPool);
  254. ANKI_CHECK(m_rebarPool->init(m_gr, *m_config));
  255. //
  256. // Physics
  257. //
  258. m_physics = newInstance<PhysicsWorld>(m_mainPool);
  259. ANKI_CHECK(m_physics->init(m_mainPool.getAllocationCallback(), m_mainPool.getAllocationCallbackUserData()));
  260. //
  261. // Resource FS
  262. //
  263. #if !ANKI_OS_ANDROID
  264. // Add the location of the executable where the shaders are supposed to be
  265. StringRaii executableFname(&m_mainPool);
  266. ANKI_CHECK(getApplicationPath(executableFname));
  267. ANKI_CORE_LOGI("Executable path is: %s", executableFname.cstr());
  268. StringRaii shadersPath(&m_mainPool);
  269. getParentFilepath(executableFname, shadersPath);
  270. shadersPath.append(":");
  271. shadersPath.append(m_config->getRsrcDataPaths());
  272. m_config->setRsrcDataPaths(shadersPath);
  273. #endif
  274. m_resourceFs = newInstance<ResourceFilesystem>(m_mainPool);
  275. ANKI_CHECK(
  276. m_resourceFs->init(*m_config, m_mainPool.getAllocationCallback(), m_mainPool.getAllocationCallbackUserData()));
  277. //
  278. // Resources
  279. //
  280. ResourceManagerInitInfo rinit;
  281. rinit.m_grManager = m_gr;
  282. rinit.m_physicsWorld = m_physics;
  283. rinit.m_resourceFilesystem = m_resourceFs;
  284. rinit.m_unifiedGometryMemoryPool = m_unifiedGometryMemPool;
  285. rinit.m_config = m_config;
  286. rinit.m_allocCallback = m_mainPool.getAllocationCallback();
  287. rinit.m_allocCallbackData = m_mainPool.getAllocationCallbackUserData();
  288. m_resources = newInstance<ResourceManager>(m_mainPool);
  289. ANKI_CHECK(m_resources->init(rinit));
  290. //
  291. // UI
  292. //
  293. UiManagerInitInfo uiInitInfo;
  294. uiInitInfo.m_allocCallback = m_mainPool.getAllocationCallback();
  295. uiInitInfo.m_allocCallbackUserData = m_mainPool.getAllocationCallbackUserData();
  296. uiInitInfo.m_grManager = m_gr;
  297. uiInitInfo.m_input = m_input;
  298. uiInitInfo.m_resourceFilesystem = m_resourceFs;
  299. uiInitInfo.m_resourceManager = m_resources;
  300. uiInitInfo.m_rebarPool = m_rebarPool;
  301. m_ui = newInstance<UiManager>(m_mainPool);
  302. ANKI_CHECK(m_ui->init(uiInitInfo));
  303. //
  304. // GPU scene
  305. //
  306. m_gpuSceneMicroPatcher = newInstance<GpuSceneMicroPatcher>(m_mainPool);
  307. ANKI_CHECK(m_gpuSceneMicroPatcher->init(m_resources));
  308. //
  309. // Renderer
  310. //
  311. MainRendererInitInfo renderInit;
  312. renderInit.m_swapchainSize = UVec2(m_window->getWidth(), m_window->getHeight());
  313. renderInit.m_allocCallback = m_mainPool.getAllocationCallback();
  314. renderInit.m_allocCallbackUserData = m_mainPool.getAllocationCallbackUserData();
  315. renderInit.m_threadHive = m_threadHive;
  316. renderInit.m_resourceManager = m_resources;
  317. renderInit.m_grManager = m_gr;
  318. renderInit.m_rebarStagingPool = m_rebarPool;
  319. renderInit.m_uiManager = m_ui;
  320. renderInit.m_config = m_config;
  321. renderInit.m_globTimestamp = &m_globalTimestamp;
  322. renderInit.m_gpuScenePool = m_gpuSceneMemPool;
  323. renderInit.m_gpuSceneMicroPatcher = m_gpuSceneMicroPatcher;
  324. renderInit.m_unifiedGometryMemoryPool = m_unifiedGometryMemPool;
  325. renderInit.m_physicsWorld = m_physics;
  326. m_renderer = newInstance<MainRenderer>(m_mainPool);
  327. ANKI_CHECK(m_renderer->init(renderInit));
  328. //
  329. // Script
  330. //
  331. m_script = newInstance<ScriptManager>(m_mainPool);
  332. ANKI_CHECK(m_script->init(m_mainPool.getAllocationCallback(), m_mainPool.getAllocationCallbackUserData()));
  333. //
  334. // Scene
  335. //
  336. m_scene = newInstance<SceneGraph>(m_mainPool);
  337. SceneGraphInitInfo sceneInit;
  338. sceneInit.m_allocCallback = m_mainPool.getAllocationCallback();
  339. sceneInit.m_allocCallbackData = m_mainPool.getAllocationCallbackUserData();
  340. sceneInit.m_config = m_config;
  341. sceneInit.m_globalTimestamp = &m_globalTimestamp;
  342. sceneInit.m_gpuSceneMemoryPool = m_gpuSceneMemPool;
  343. sceneInit.m_gpuSceneMicroPatcher = m_gpuSceneMicroPatcher;
  344. sceneInit.m_input = m_input;
  345. sceneInit.m_resourceManager = m_resources;
  346. sceneInit.m_scriptManager = m_script;
  347. sceneInit.m_threadHive = m_threadHive;
  348. sceneInit.m_uiManager = m_ui;
  349. sceneInit.m_unifiedGeometryMemPool = m_unifiedGometryMemPool;
  350. sceneInit.m_grManager = m_gr;
  351. sceneInit.m_physicsWorld = m_physics;
  352. ANKI_CHECK(m_scene->init(sceneInit));
  353. // Inform the script engine about some subsystems
  354. m_script->setRenderer(m_renderer);
  355. m_script->setSceneGraph(m_scene);
  356. //
  357. // Misc
  358. //
  359. ANKI_CHECK(m_ui->newInstance<StatsUi>(m_statsUi));
  360. ANKI_CHECK(m_ui->newInstance<DeveloperConsole>(m_console, m_script));
  361. ANKI_CORE_LOGI("Application initialized");
  362. return Error::kNone;
  363. }
  364. Error App::initDirs()
  365. {
  366. // Settings path
  367. #if !ANKI_OS_ANDROID
  368. StringRaii home(&m_mainPool);
  369. ANKI_CHECK(getHomeDirectory(home));
  370. m_settingsDir.sprintf(m_mainPool, "%s/.anki", &home[0]);
  371. #else
  372. m_settingsDir.sprintf(m_mainPool, "%s/.anki", g_androidApp->activity->internalDataPath);
  373. #endif
  374. if(!directoryExists(m_settingsDir.toCString()))
  375. {
  376. ANKI_CORE_LOGI("Creating settings dir \"%s\"", &m_settingsDir[0]);
  377. ANKI_CHECK(createDirectory(m_settingsDir.toCString()));
  378. }
  379. else
  380. {
  381. ANKI_CORE_LOGI("Using settings dir \"%s\"", &m_settingsDir[0]);
  382. }
  383. // Cache
  384. m_cacheDir.sprintf(m_mainPool, "%s/cache", &m_settingsDir[0]);
  385. const Bool cacheDirExists = directoryExists(m_cacheDir.toCString());
  386. if(m_config->getCoreClearCaches() && cacheDirExists)
  387. {
  388. ANKI_CORE_LOGI("Will delete the cache dir and start fresh: %s", &m_cacheDir[0]);
  389. ANKI_CHECK(removeDirectory(m_cacheDir.toCString(), m_mainPool));
  390. ANKI_CHECK(createDirectory(m_cacheDir.toCString()));
  391. }
  392. else if(!cacheDirExists)
  393. {
  394. ANKI_CORE_LOGI("Will create cache dir: %s", &m_cacheDir[0]);
  395. ANKI_CHECK(createDirectory(m_cacheDir.toCString()));
  396. }
  397. return Error::kNone;
  398. }
  399. Error App::mainLoop()
  400. {
  401. ANKI_CORE_LOGI("Entering main loop");
  402. Bool quit = false;
  403. Second prevUpdateTime = HighRezTimer::getCurrentTime();
  404. Second crntTime = prevUpdateTime;
  405. // Benchmark mode stuff:
  406. const Bool benchmarkMode = m_config->getCoreBenchmarkMode();
  407. Second aggregatedCpuTime = 0.0;
  408. Second aggregatedGpuTime = 0.0;
  409. constexpr U32 kBenchmarkFramesToGatherBeforeFlush = 60;
  410. U32 benchmarkFramesGathered = 0;
  411. File benchmarkCsvFile;
  412. StringRaii benchmarkCsvFileFilename(&m_mainPool);
  413. if(benchmarkMode)
  414. {
  415. benchmarkCsvFileFilename.sprintf("%s/Benchmark.csv", m_settingsDir.cstr());
  416. ANKI_CHECK(benchmarkCsvFile.open(benchmarkCsvFileFilename, FileOpenFlag::kWrite));
  417. ANKI_CHECK(benchmarkCsvFile.writeText("CPU, GPU\n"));
  418. }
  419. while(!quit)
  420. {
  421. {
  422. ANKI_TRACE_SCOPED_EVENT(Frame);
  423. const Second startTime = HighRezTimer::getCurrentTime();
  424. prevUpdateTime = crntTime;
  425. crntTime = (!benchmarkMode) ? HighRezTimer::getCurrentTime() : (prevUpdateTime + 1.0_sec / 60.0_sec);
  426. // Update
  427. ANKI_CHECK(m_input->handleEvents());
  428. // User update
  429. ANKI_CHECK(userMainLoop(quit, crntTime - prevUpdateTime));
  430. ANKI_CHECK(m_scene->update(prevUpdateTime, crntTime));
  431. RenderQueue rqueue;
  432. m_scene->doVisibilityTests(rqueue);
  433. // Inject stats UI
  434. DynamicArrayRaii<UiQueueElement> newUiElementArr(&m_mainPool);
  435. injectUiElements(newUiElementArr, rqueue);
  436. // Render
  437. TexturePtr presentableTex = m_gr->acquireNextPresentableTexture();
  438. m_renderer->setStatsEnabled(m_config->getCoreDisplayStats() > 0 || benchmarkMode
  439. #if ANKI_ENABLE_TRACE
  440. || Tracer::getSingleton().getEnabled()
  441. #endif
  442. );
  443. ANKI_CHECK(m_renderer->render(rqueue, presentableTex));
  444. // Pause and sync async loader. That will force all tasks before the pause to finish in this frame.
  445. m_resources->getAsyncLoader().pause();
  446. // If we get stats exclude the time of GR because it forces some GPU-CPU serialization. We don't want to
  447. // count that
  448. Second grTime = 0.0;
  449. if(benchmarkMode || m_config->getCoreDisplayStats() > 0) [[unlikely]]
  450. {
  451. grTime = HighRezTimer::getCurrentTime();
  452. }
  453. m_gr->swapBuffers();
  454. if(benchmarkMode || m_config->getCoreDisplayStats() > 0) [[unlikely]]
  455. {
  456. grTime = HighRezTimer::getCurrentTime() - grTime;
  457. }
  458. const PtrSize rebarMemUsed = m_rebarPool->endFrame();
  459. m_unifiedGometryMemPool->endFrame();
  460. m_gpuSceneMemPool->endFrame();
  461. // Update the trace info with some async loader stats
  462. U64 asyncTaskCount = m_resources->getAsyncLoader().getCompletedTaskCount();
  463. ANKI_TRACE_INC_COUNTER(RsrcAsyncTasks, asyncTaskCount - m_resourceCompletedAsyncTaskCount);
  464. m_resourceCompletedAsyncTaskCount = asyncTaskCount;
  465. // Now resume the loader
  466. m_resources->getAsyncLoader().resume();
  467. // Sleep
  468. const Second endTime = HighRezTimer::getCurrentTime();
  469. const Second frameTime = endTime - startTime;
  470. if(!benchmarkMode) [[likely]]
  471. {
  472. const Second timerTick = 1.0_sec / Second(m_config->getCoreTargetFps());
  473. if(frameTime < timerTick)
  474. {
  475. ANKI_TRACE_SCOPED_EVENT(TimerTickSleep);
  476. HighRezTimer::sleep(timerTick - frameTime);
  477. }
  478. }
  479. // Benchmark stats
  480. else
  481. {
  482. aggregatedCpuTime += frameTime - grTime;
  483. aggregatedGpuTime += m_renderer->getStats().m_renderingGpuTime;
  484. ++benchmarkFramesGathered;
  485. if(benchmarkFramesGathered >= kBenchmarkFramesToGatherBeforeFlush)
  486. {
  487. aggregatedCpuTime = aggregatedCpuTime / Second(kBenchmarkFramesToGatherBeforeFlush) * 1000.0;
  488. aggregatedGpuTime = aggregatedGpuTime / Second(kBenchmarkFramesToGatherBeforeFlush) * 1000.0;
  489. ANKI_CHECK(benchmarkCsvFile.writeTextf("%f,%f\n", aggregatedCpuTime, aggregatedGpuTime));
  490. benchmarkFramesGathered = 0;
  491. aggregatedCpuTime = 0.0;
  492. aggregatedGpuTime = 0.0;
  493. }
  494. }
  495. // Stats
  496. if(m_config->getCoreDisplayStats() > 0)
  497. {
  498. StatsUiInput in;
  499. in.m_cpuFrameTime = frameTime - grTime;
  500. in.m_rendererTime = m_renderer->getStats().m_renderingCpuTime;
  501. in.m_sceneUpdateTime = m_scene->getStats().m_updateTime;
  502. in.m_visibilityTestsTime = m_scene->getStats().m_visibilityTestsTime;
  503. in.m_physicsTime = m_scene->getStats().m_physicsUpdate;
  504. in.m_gpuFrameTime = m_renderer->getStats().m_renderingGpuTime;
  505. if(m_maliHwCounters)
  506. {
  507. MaliHwCountersOut out;
  508. m_maliHwCounters->sample(out);
  509. in.m_gpuActiveCycles = out.m_gpuActive;
  510. in.m_gpuReadBandwidth = out.m_readBandwidth;
  511. in.m_gpuWriteBandwidth = out.m_writeBandwidth;
  512. }
  513. in.m_cpuAllocatedMemory = m_memStats.m_allocatedMem.load();
  514. in.m_cpuAllocationCount = m_memStats.m_allocCount.load();
  515. in.m_cpuFreeCount = m_memStats.m_freeCount.load();
  516. const GrManagerStats grStats = m_gr->getStats();
  517. m_unifiedGometryMemPool->getStats(in.m_unifiedGometryExternalFragmentation,
  518. in.m_unifiedGeometryAllocated, in.m_unifiedGeometryTotal);
  519. m_gpuSceneMemPool->getStats(in.m_gpuSceneExternalFragmentation, in.m_gpuSceneAllocated,
  520. in.m_gpuSceneTotal);
  521. in.m_gpuDeviceMemoryAllocated = grStats.m_deviceMemoryAllocated;
  522. in.m_gpuDeviceMemoryInUse = grStats.m_deviceMemoryInUse;
  523. in.m_reBar = rebarMemUsed;
  524. in.m_drawableCount = rqueue.countAllRenderables();
  525. in.m_vkCommandBufferCount = grStats.m_commandBufferCount;
  526. StatsUi& statsUi = *static_cast<StatsUi*>(m_statsUi.get());
  527. const StatsUiDetail detail =
  528. (m_config->getCoreDisplayStats() == 1) ? StatsUiDetail::kFpsOnly : StatsUiDetail::kDetailed;
  529. statsUi.setStats(in, detail);
  530. }
  531. #if ANKI_ENABLE_TRACE
  532. if(m_renderer->getStats().m_renderingGpuTime >= 0.0)
  533. {
  534. ANKI_TRACE_CUSTOM_EVENT(Gpu, m_renderer->getStats().m_renderingGpuSubmitTimestamp,
  535. m_renderer->getStats().m_renderingGpuTime);
  536. }
  537. #endif
  538. ++m_globalTimestamp;
  539. if(benchmarkMode) [[unlikely]]
  540. {
  541. if(m_globalTimestamp >= m_config->getCoreBenchmarkModeFrameCount())
  542. {
  543. quit = true;
  544. }
  545. }
  546. }
  547. #if ANKI_ENABLE_TRACE
  548. static U64 frame = 1;
  549. m_coreTracer->flushFrame(frame++);
  550. #endif
  551. }
  552. if(benchmarkMode) [[unlikely]]
  553. {
  554. ANKI_CORE_LOGI("Benchmark file saved in: %s", benchmarkCsvFileFilename.cstr());
  555. }
  556. return Error::kNone;
  557. }
  558. void App::injectUiElements(DynamicArrayRaii<UiQueueElement>& newUiElementArr, RenderQueue& rqueue)
  559. {
  560. const U32 originalCount = rqueue.m_uis.getSize();
  561. if(m_config->getCoreDisplayStats() > 0 || m_consoleEnabled)
  562. {
  563. const U32 extraElements = (m_config->getCoreDisplayStats() > 0) + (m_consoleEnabled != 0);
  564. newUiElementArr.create(originalCount + extraElements);
  565. if(originalCount > 0)
  566. {
  567. memcpy(&newUiElementArr[0], &rqueue.m_uis[0], rqueue.m_uis.getSizeInBytes());
  568. }
  569. rqueue.m_uis = WeakArray<UiQueueElement>(newUiElementArr);
  570. }
  571. U32 count = originalCount;
  572. if(m_config->getCoreDisplayStats() > 0)
  573. {
  574. newUiElementArr[count].m_userData = m_statsUi.get();
  575. newUiElementArr[count].m_drawCallback = [](CanvasPtr& canvas, void* userData) -> void {
  576. static_cast<StatsUi*>(userData)->build(canvas);
  577. };
  578. ++count;
  579. }
  580. if(m_consoleEnabled)
  581. {
  582. newUiElementArr[count].m_userData = m_console.get();
  583. newUiElementArr[count].m_drawCallback = [](CanvasPtr& canvas, void* userData) -> void {
  584. static_cast<DeveloperConsole*>(userData)->build(canvas);
  585. };
  586. ++count;
  587. }
  588. }
  589. void App::initMemoryCallbacks(AllocAlignedCallback& allocCb, void*& allocCbUserData)
  590. {
  591. if(m_config->getCoreDisplayStats() > 1)
  592. {
  593. m_memStats.m_originalAllocCallback = allocCb;
  594. m_memStats.m_originalUserData = allocCbUserData;
  595. allocCb = MemStats::allocCallback;
  596. allocCbUserData = &m_memStats;
  597. }
  598. else
  599. {
  600. // Leave the default
  601. }
  602. }
  603. void App::setSignalHandlers()
  604. {
  605. auto handler = [](int signum) -> void {
  606. const char* name = nullptr;
  607. switch(signum)
  608. {
  609. case SIGABRT:
  610. name = "SIGABRT";
  611. break;
  612. case SIGSEGV:
  613. name = "SIGSEGV";
  614. break;
  615. #if ANKI_POSIX
  616. case SIGBUS:
  617. name = "SIGBUS";
  618. break;
  619. #endif
  620. case SIGILL:
  621. name = "SIGILL";
  622. break;
  623. case SIGFPE:
  624. name = "SIGFPE";
  625. break;
  626. }
  627. if(name)
  628. printf("Caught signal %d (%s)\n", signum, name);
  629. else
  630. printf("Caught signal %d\n", signum);
  631. U32 count = 0;
  632. printf("Backtrace:\n");
  633. HeapMemoryPool pool(allocAligned, nullptr);
  634. backtrace(pool, [&count](CString symbol) {
  635. printf("%.2u: %s\n", count++, symbol.cstr());
  636. });
  637. ANKI_DEBUG_BREAK();
  638. };
  639. signal(SIGSEGV, handler);
  640. signal(SIGILL, handler);
  641. signal(SIGFPE, handler);
  642. #if ANKI_POSIX
  643. signal(SIGBUS, handler);
  644. #endif
  645. // Ignore for now: signal(SIGABRT, handler);
  646. }
  647. } // end namespace anki