App.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  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/Window/NativeWindow.h>
  18. #include <AnKi/Core/MaliHwCounters.h>
  19. #include <AnKi/Window/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. // Config is special
  88. ConfigSet::allocateSingleton(allocAligned, nullptr);
  89. }
  90. App::~App()
  91. {
  92. ANKI_CORE_LOGI("Destroying application");
  93. cleanup();
  94. }
  95. void App::cleanup()
  96. {
  97. m_statsUi.reset(nullptr);
  98. m_console.reset(nullptr);
  99. deleteInstance(m_mainPool, m_scene);
  100. m_scene = nullptr;
  101. deleteInstance(m_mainPool, m_script);
  102. m_script = nullptr;
  103. deleteInstance(m_mainPool, m_renderer);
  104. m_renderer = nullptr;
  105. deleteInstance(m_mainPool, m_ui);
  106. m_ui = nullptr;
  107. deleteInstance(m_mainPool, m_gpuSceneMicroPatcher);
  108. m_gpuSceneMicroPatcher = nullptr;
  109. deleteInstance(m_mainPool, m_resources);
  110. m_resources = nullptr;
  111. deleteInstance(m_mainPool, m_resourceFs);
  112. m_resourceFs = nullptr;
  113. PhysicsWorld::freeSingleton();
  114. deleteInstance(m_mainPool, m_rebarPool);
  115. m_rebarPool = nullptr;
  116. deleteInstance(m_mainPool, m_unifiedGometryMemPool);
  117. m_unifiedGometryMemPool = nullptr;
  118. deleteInstance(m_mainPool, m_gpuSceneMemPool);
  119. m_gpuSceneMemPool = nullptr;
  120. deleteInstance(m_mainPool, m_threadHive);
  121. m_threadHive = nullptr;
  122. deleteInstance(m_mainPool, m_maliHwCounters);
  123. m_maliHwCounters = nullptr;
  124. GrManager::deleteInstance(m_gr);
  125. m_gr = nullptr;
  126. Input::freeSingleton();
  127. NativeWindow::freeSingleton();
  128. #if ANKI_ENABLE_TRACE
  129. deleteInstance(m_mainPool, m_coreTracer);
  130. m_coreTracer = nullptr;
  131. #endif
  132. ConfigSet::freeSingleton();
  133. m_settingsDir.destroy();
  134. m_cacheDir.destroy();
  135. CoreMemoryPool::freeSingleton();
  136. }
  137. Error App::init(AllocAlignedCallback allocCb, void* allocCbUserData)
  138. {
  139. const Error err = initInternal(allocCb, allocCbUserData);
  140. if(err)
  141. {
  142. ANKI_CORE_LOGE("App initialization failed. Shutting down");
  143. cleanup();
  144. }
  145. return err;
  146. }
  147. Error App::initInternal(AllocAlignedCallback allocCb, void* allocCbUserData)
  148. {
  149. Logger::getSingleton().enableVerbosity(ConfigSet::getSingleton().getCoreVerboseLog());
  150. setSignalHandlers();
  151. initMemoryCallbacks(allocCb, allocCbUserData);
  152. CoreMemoryPool::allocateSingleton(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", ConfigSet::getSingleton().getCoreJobThreadCount());
  193. if(ConfigSet::getSingleton().getCoreBenchmarkMode() && ConfigSet::getSingleton().getGrVsync())
  194. {
  195. ANKI_CORE_LOGW("Vsync is enabled and benchmark mode as well. Will turn vsync off");
  196. ConfigSet::getSingleton().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_width = ConfigSet::getSingleton().getWidth();
  210. nwinit.m_height = ConfigSet::getSingleton().getHeight();
  211. nwinit.m_depthBits = 0;
  212. nwinit.m_stencilBits = 0;
  213. nwinit.m_fullscreenDesktopRez = ConfigSet::getSingleton().getWindowFullscreen() > 0;
  214. nwinit.m_exclusiveFullscreen = ConfigSet::getSingleton().getWindowFullscreen() == 2;
  215. nwinit.m_targetFps = ConfigSet::getSingleton().getCoreTargetFps();
  216. NativeWindow::allocateSingleton();
  217. ANKI_CHECK(NativeWindow::getSingleton().init(nwinit));
  218. //
  219. // Input
  220. //
  221. Input::allocateSingleton();
  222. ANKI_CHECK(Input::getSingleton().init());
  223. //
  224. // ThreadPool
  225. //
  226. const Bool pinThreads = !ANKI_OS_ANDROID;
  227. m_threadHive =
  228. newInstance<ThreadHive>(m_mainPool, ConfigSet::getSingleton().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. ANKI_CHECK(GrManager::newInstance(grInit, m_gr));
  237. //
  238. // Mali HW counters
  239. //
  240. if(m_gr->getDeviceCapabilities().m_gpuVendor == GpuVendor::kArm
  241. && ConfigSet::getSingleton().getCoreMaliHwCounters())
  242. {
  243. m_maliHwCounters = newInstance<MaliHwCounters>(m_mainPool, &m_mainPool);
  244. }
  245. //
  246. // GPU mem
  247. //
  248. m_unifiedGometryMemPool = newInstance<UnifiedGeometryMemoryPool>(m_mainPool);
  249. m_unifiedGometryMemPool->init(&m_mainPool, m_gr);
  250. m_gpuSceneMemPool = newInstance<GpuSceneMemoryPool>(m_mainPool);
  251. m_gpuSceneMemPool->init(&m_mainPool, m_gr);
  252. m_rebarPool = newInstance<RebarStagingGpuMemoryPool>(m_mainPool);
  253. ANKI_CHECK(m_rebarPool->init(m_gr));
  254. //
  255. // Physics
  256. //
  257. PhysicsWorld::allocateSingleton();
  258. ANKI_CHECK(PhysicsWorld::getSingleton().init(m_mainPool.getAllocationCallback(),
  259. 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(ConfigSet::getSingleton().getRsrcDataPaths());
  272. ConfigSet::getSingleton().setRsrcDataPaths(shadersPath);
  273. #endif
  274. m_resourceFs = newInstance<ResourceFilesystem>(m_mainPool);
  275. ANKI_CHECK(m_resourceFs->init(m_mainPool.getAllocationCallback(), m_mainPool.getAllocationCallbackUserData()));
  276. //
  277. // Resources
  278. //
  279. ResourceManagerInitInfo rinit;
  280. rinit.m_grManager = m_gr;
  281. rinit.m_resourceFilesystem = m_resourceFs;
  282. rinit.m_unifiedGometryMemoryPool = m_unifiedGometryMemPool;
  283. rinit.m_allocCallback = m_mainPool.getAllocationCallback();
  284. rinit.m_allocCallbackData = m_mainPool.getAllocationCallbackUserData();
  285. m_resources = newInstance<ResourceManager>(m_mainPool);
  286. ANKI_CHECK(m_resources->init(rinit));
  287. //
  288. // UI
  289. //
  290. UiManagerInitInfo uiInitInfo;
  291. uiInitInfo.m_allocCallback = m_mainPool.getAllocationCallback();
  292. uiInitInfo.m_allocCallbackUserData = m_mainPool.getAllocationCallbackUserData();
  293. uiInitInfo.m_grManager = m_gr;
  294. uiInitInfo.m_resourceFilesystem = m_resourceFs;
  295. uiInitInfo.m_resourceManager = m_resources;
  296. uiInitInfo.m_rebarPool = m_rebarPool;
  297. m_ui = newInstance<UiManager>(m_mainPool);
  298. ANKI_CHECK(m_ui->init(uiInitInfo));
  299. //
  300. // GPU scene
  301. //
  302. m_gpuSceneMicroPatcher = newInstance<GpuSceneMicroPatcher>(m_mainPool);
  303. ANKI_CHECK(m_gpuSceneMicroPatcher->init(m_resources));
  304. //
  305. // Renderer
  306. //
  307. MainRendererInitInfo renderInit;
  308. renderInit.m_swapchainSize =
  309. UVec2(NativeWindow::getSingleton().getWidth(), NativeWindow::getSingleton().getHeight());
  310. renderInit.m_allocCallback = m_mainPool.getAllocationCallback();
  311. renderInit.m_allocCallbackUserData = m_mainPool.getAllocationCallbackUserData();
  312. renderInit.m_threadHive = m_threadHive;
  313. renderInit.m_resourceManager = m_resources;
  314. renderInit.m_grManager = m_gr;
  315. renderInit.m_rebarStagingPool = m_rebarPool;
  316. renderInit.m_uiManager = m_ui;
  317. renderInit.m_globTimestamp = &m_globalTimestamp;
  318. renderInit.m_gpuScenePool = m_gpuSceneMemPool;
  319. renderInit.m_gpuSceneMicroPatcher = m_gpuSceneMicroPatcher;
  320. renderInit.m_unifiedGometryMemoryPool = m_unifiedGometryMemPool;
  321. m_renderer = newInstance<MainRenderer>(m_mainPool);
  322. ANKI_CHECK(m_renderer->init(renderInit));
  323. //
  324. // Script
  325. //
  326. m_script = newInstance<ScriptManager>(m_mainPool);
  327. ANKI_CHECK(m_script->init(m_mainPool.getAllocationCallback(), m_mainPool.getAllocationCallbackUserData()));
  328. //
  329. // Scene
  330. //
  331. m_scene = newInstance<SceneGraph>(m_mainPool);
  332. SceneGraphInitInfo sceneInit;
  333. sceneInit.m_allocCallback = m_mainPool.getAllocationCallback();
  334. sceneInit.m_allocCallbackData = m_mainPool.getAllocationCallbackUserData();
  335. sceneInit.m_globalTimestamp = &m_globalTimestamp;
  336. sceneInit.m_gpuSceneMemoryPool = m_gpuSceneMemPool;
  337. sceneInit.m_gpuSceneMicroPatcher = m_gpuSceneMicroPatcher;
  338. sceneInit.m_resourceManager = m_resources;
  339. sceneInit.m_scriptManager = m_script;
  340. sceneInit.m_threadHive = m_threadHive;
  341. sceneInit.m_uiManager = m_ui;
  342. sceneInit.m_unifiedGeometryMemPool = m_unifiedGometryMemPool;
  343. sceneInit.m_grManager = m_gr;
  344. ANKI_CHECK(m_scene->init(sceneInit));
  345. // Inform the script engine about some subsystems
  346. m_script->setRenderer(m_renderer);
  347. m_script->setSceneGraph(m_scene);
  348. //
  349. // Misc
  350. //
  351. ANKI_CHECK(m_ui->newInstance<StatsUi>(m_statsUi));
  352. ANKI_CHECK(m_ui->newInstance<DeveloperConsole>(m_console, m_script));
  353. ANKI_CORE_LOGI("Application initialized");
  354. return Error::kNone;
  355. }
  356. Error App::initDirs()
  357. {
  358. // Settings path
  359. #if !ANKI_OS_ANDROID
  360. StringRaii home(&m_mainPool);
  361. ANKI_CHECK(getHomeDirectory(home));
  362. m_settingsDir.sprintf("%s/.anki", &home[0]);
  363. #else
  364. m_settingsDir.sprintf("%s/.anki", g_androidApp->activity->internalDataPath);
  365. #endif
  366. if(!directoryExists(m_settingsDir.toCString()))
  367. {
  368. ANKI_CORE_LOGI("Creating settings dir \"%s\"", &m_settingsDir[0]);
  369. ANKI_CHECK(createDirectory(m_settingsDir.toCString()));
  370. }
  371. else
  372. {
  373. ANKI_CORE_LOGI("Using settings dir \"%s\"", &m_settingsDir[0]);
  374. }
  375. // Cache
  376. m_cacheDir.sprintf("%s/cache", &m_settingsDir[0]);
  377. const Bool cacheDirExists = directoryExists(m_cacheDir.toCString());
  378. if(ConfigSet::getSingleton().getCoreClearCaches() && cacheDirExists)
  379. {
  380. ANKI_CORE_LOGI("Will delete the cache dir and start fresh: %s", m_cacheDir.cstr());
  381. ANKI_CHECK(removeDirectory(m_cacheDir.toCString(), m_mainPool));
  382. ANKI_CHECK(createDirectory(m_cacheDir.toCString()));
  383. }
  384. else if(!cacheDirExists)
  385. {
  386. ANKI_CORE_LOGI("Will create cache dir: %s", m_cacheDir.cstr());
  387. ANKI_CHECK(createDirectory(m_cacheDir.toCString()));
  388. }
  389. return Error::kNone;
  390. }
  391. Error App::mainLoop()
  392. {
  393. ANKI_CORE_LOGI("Entering main loop");
  394. Bool quit = false;
  395. Second prevUpdateTime = HighRezTimer::getCurrentTime();
  396. Second crntTime = prevUpdateTime;
  397. // Benchmark mode stuff:
  398. const Bool benchmarkMode = ConfigSet::getSingleton().getCoreBenchmarkMode();
  399. Second aggregatedCpuTime = 0.0;
  400. Second aggregatedGpuTime = 0.0;
  401. constexpr U32 kBenchmarkFramesToGatherBeforeFlush = 60;
  402. U32 benchmarkFramesGathered = 0;
  403. File benchmarkCsvFile;
  404. StringRaii benchmarkCsvFileFilename(&m_mainPool);
  405. if(benchmarkMode)
  406. {
  407. benchmarkCsvFileFilename.sprintf("%s/Benchmark.csv", m_settingsDir.cstr());
  408. ANKI_CHECK(benchmarkCsvFile.open(benchmarkCsvFileFilename, FileOpenFlag::kWrite));
  409. ANKI_CHECK(benchmarkCsvFile.writeText("CPU, GPU\n"));
  410. }
  411. while(!quit)
  412. {
  413. {
  414. ANKI_TRACE_SCOPED_EVENT(Frame);
  415. const Second startTime = HighRezTimer::getCurrentTime();
  416. prevUpdateTime = crntTime;
  417. crntTime = (!benchmarkMode) ? HighRezTimer::getCurrentTime() : (prevUpdateTime + 1.0_sec / 60.0_sec);
  418. // Update
  419. ANKI_CHECK(Input::getSingleton().handleEvents());
  420. // User update
  421. ANKI_CHECK(userMainLoop(quit, crntTime - prevUpdateTime));
  422. ANKI_CHECK(m_scene->update(prevUpdateTime, crntTime));
  423. RenderQueue rqueue;
  424. m_scene->doVisibilityTests(rqueue);
  425. // Inject stats UI
  426. DynamicArrayRaii<UiQueueElement> newUiElementArr(&m_mainPool);
  427. injectUiElements(newUiElementArr, rqueue);
  428. // Render
  429. TexturePtr presentableTex = m_gr->acquireNextPresentableTexture();
  430. m_renderer->setStatsEnabled(ConfigSet::getSingleton().getCoreDisplayStats() > 0 || benchmarkMode
  431. #if ANKI_ENABLE_TRACE
  432. || Tracer::getSingleton().getEnabled()
  433. #endif
  434. );
  435. ANKI_CHECK(m_renderer->render(rqueue, presentableTex));
  436. // Pause and sync async loader. That will force all tasks before the pause to finish in this frame.
  437. m_resources->getAsyncLoader().pause();
  438. // If we get stats exclude the time of GR because it forces some GPU-CPU serialization. We don't want to
  439. // count that
  440. Second grTime = 0.0;
  441. if(benchmarkMode || ConfigSet::getSingleton().getCoreDisplayStats() > 0) [[unlikely]]
  442. {
  443. grTime = HighRezTimer::getCurrentTime();
  444. }
  445. m_gr->swapBuffers();
  446. if(benchmarkMode || ConfigSet::getSingleton().getCoreDisplayStats() > 0) [[unlikely]]
  447. {
  448. grTime = HighRezTimer::getCurrentTime() - grTime;
  449. }
  450. const PtrSize rebarMemUsed = m_rebarPool->endFrame();
  451. m_unifiedGometryMemPool->endFrame();
  452. m_gpuSceneMemPool->endFrame();
  453. // Update the trace info with some async loader stats
  454. U64 asyncTaskCount = m_resources->getAsyncLoader().getCompletedTaskCount();
  455. ANKI_TRACE_INC_COUNTER(RsrcAsyncTasks, asyncTaskCount - m_resourceCompletedAsyncTaskCount);
  456. m_resourceCompletedAsyncTaskCount = asyncTaskCount;
  457. // Now resume the loader
  458. m_resources->getAsyncLoader().resume();
  459. // Sleep
  460. const Second endTime = HighRezTimer::getCurrentTime();
  461. const Second frameTime = endTime - startTime;
  462. if(!benchmarkMode) [[likely]]
  463. {
  464. const Second timerTick = 1.0_sec / Second(ConfigSet::getSingleton().getCoreTargetFps());
  465. if(frameTime < timerTick)
  466. {
  467. ANKI_TRACE_SCOPED_EVENT(TimerTickSleep);
  468. HighRezTimer::sleep(timerTick - frameTime);
  469. }
  470. }
  471. // Benchmark stats
  472. else
  473. {
  474. aggregatedCpuTime += frameTime - grTime;
  475. aggregatedGpuTime += m_renderer->getStats().m_renderingGpuTime;
  476. ++benchmarkFramesGathered;
  477. if(benchmarkFramesGathered >= kBenchmarkFramesToGatherBeforeFlush)
  478. {
  479. aggregatedCpuTime = aggregatedCpuTime / Second(kBenchmarkFramesToGatherBeforeFlush) * 1000.0;
  480. aggregatedGpuTime = aggregatedGpuTime / Second(kBenchmarkFramesToGatherBeforeFlush) * 1000.0;
  481. ANKI_CHECK(benchmarkCsvFile.writeTextf("%f,%f\n", aggregatedCpuTime, aggregatedGpuTime));
  482. benchmarkFramesGathered = 0;
  483. aggregatedCpuTime = 0.0;
  484. aggregatedGpuTime = 0.0;
  485. }
  486. }
  487. // Stats
  488. if(ConfigSet::getSingleton().getCoreDisplayStats() > 0)
  489. {
  490. StatsUiInput in;
  491. in.m_cpuFrameTime = frameTime - grTime;
  492. in.m_rendererTime = m_renderer->getStats().m_renderingCpuTime;
  493. in.m_sceneUpdateTime = m_scene->getStats().m_updateTime;
  494. in.m_visibilityTestsTime = m_scene->getStats().m_visibilityTestsTime;
  495. in.m_physicsTime = m_scene->getStats().m_physicsUpdate;
  496. in.m_gpuFrameTime = m_renderer->getStats().m_renderingGpuTime;
  497. if(m_maliHwCounters)
  498. {
  499. MaliHwCountersOut out;
  500. m_maliHwCounters->sample(out);
  501. in.m_gpuActiveCycles = out.m_gpuActive;
  502. in.m_gpuReadBandwidth = out.m_readBandwidth;
  503. in.m_gpuWriteBandwidth = out.m_writeBandwidth;
  504. }
  505. in.m_cpuAllocatedMemory = m_memStats.m_allocatedMem.load();
  506. in.m_cpuAllocationCount = m_memStats.m_allocCount.load();
  507. in.m_cpuFreeCount = m_memStats.m_freeCount.load();
  508. const GrManagerStats grStats = m_gr->getStats();
  509. m_unifiedGometryMemPool->getStats(in.m_unifiedGometryExternalFragmentation,
  510. in.m_unifiedGeometryAllocated, in.m_unifiedGeometryTotal);
  511. m_gpuSceneMemPool->getStats(in.m_gpuSceneExternalFragmentation, in.m_gpuSceneAllocated,
  512. in.m_gpuSceneTotal);
  513. in.m_gpuDeviceMemoryAllocated = grStats.m_deviceMemoryAllocated;
  514. in.m_gpuDeviceMemoryInUse = grStats.m_deviceMemoryInUse;
  515. in.m_reBar = rebarMemUsed;
  516. in.m_drawableCount = rqueue.countAllRenderables();
  517. in.m_vkCommandBufferCount = grStats.m_commandBufferCount;
  518. StatsUi& statsUi = *static_cast<StatsUi*>(m_statsUi.get());
  519. const StatsUiDetail detail = (ConfigSet::getSingleton().getCoreDisplayStats() == 1)
  520. ? StatsUiDetail::kFpsOnly
  521. : StatsUiDetail::kDetailed;
  522. statsUi.setStats(in, detail);
  523. }
  524. #if ANKI_ENABLE_TRACE
  525. if(m_renderer->getStats().m_renderingGpuTime >= 0.0)
  526. {
  527. ANKI_TRACE_CUSTOM_EVENT(Gpu, m_renderer->getStats().m_renderingGpuSubmitTimestamp,
  528. m_renderer->getStats().m_renderingGpuTime);
  529. }
  530. #endif
  531. ++m_globalTimestamp;
  532. if(benchmarkMode) [[unlikely]]
  533. {
  534. if(m_globalTimestamp >= ConfigSet::getSingleton().getCoreBenchmarkModeFrameCount())
  535. {
  536. quit = true;
  537. }
  538. }
  539. }
  540. #if ANKI_ENABLE_TRACE
  541. static U64 frame = 1;
  542. m_coreTracer->flushFrame(frame++);
  543. #endif
  544. }
  545. if(benchmarkMode) [[unlikely]]
  546. {
  547. ANKI_CORE_LOGI("Benchmark file saved in: %s", benchmarkCsvFileFilename.cstr());
  548. }
  549. return Error::kNone;
  550. }
  551. void App::injectUiElements(DynamicArrayRaii<UiQueueElement>& newUiElementArr, RenderQueue& rqueue)
  552. {
  553. const U32 originalCount = rqueue.m_uis.getSize();
  554. if(ConfigSet::getSingleton().getCoreDisplayStats() > 0 || m_consoleEnabled)
  555. {
  556. const U32 extraElements = (ConfigSet::getSingleton().getCoreDisplayStats() > 0) + (m_consoleEnabled != 0);
  557. newUiElementArr.create(originalCount + extraElements);
  558. if(originalCount > 0)
  559. {
  560. memcpy(&newUiElementArr[0], &rqueue.m_uis[0], rqueue.m_uis.getSizeInBytes());
  561. }
  562. rqueue.m_uis = WeakArray<UiQueueElement>(newUiElementArr);
  563. }
  564. U32 count = originalCount;
  565. if(ConfigSet::getSingleton().getCoreDisplayStats() > 0)
  566. {
  567. newUiElementArr[count].m_userData = m_statsUi.get();
  568. newUiElementArr[count].m_drawCallback = [](CanvasPtr& canvas, void* userData) -> void {
  569. static_cast<StatsUi*>(userData)->build(canvas);
  570. };
  571. ++count;
  572. }
  573. if(m_consoleEnabled)
  574. {
  575. newUiElementArr[count].m_userData = m_console.get();
  576. newUiElementArr[count].m_drawCallback = [](CanvasPtr& canvas, void* userData) -> void {
  577. static_cast<DeveloperConsole*>(userData)->build(canvas);
  578. };
  579. ++count;
  580. }
  581. }
  582. void App::initMemoryCallbacks(AllocAlignedCallback& allocCb, void*& allocCbUserData)
  583. {
  584. if(ConfigSet::getSingleton().getCoreDisplayStats() > 1)
  585. {
  586. m_memStats.m_originalAllocCallback = allocCb;
  587. m_memStats.m_originalUserData = allocCbUserData;
  588. allocCb = MemStats::allocCallback;
  589. allocCbUserData = &m_memStats;
  590. }
  591. else
  592. {
  593. // Leave the default
  594. }
  595. }
  596. void App::setSignalHandlers()
  597. {
  598. auto handler = [](int signum) -> void {
  599. const char* name = nullptr;
  600. switch(signum)
  601. {
  602. case SIGABRT:
  603. name = "SIGABRT";
  604. break;
  605. case SIGSEGV:
  606. name = "SIGSEGV";
  607. break;
  608. #if ANKI_POSIX
  609. case SIGBUS:
  610. name = "SIGBUS";
  611. break;
  612. #endif
  613. case SIGILL:
  614. name = "SIGILL";
  615. break;
  616. case SIGFPE:
  617. name = "SIGFPE";
  618. break;
  619. }
  620. if(name)
  621. printf("Caught signal %d (%s)\n", signum, name);
  622. else
  623. printf("Caught signal %d\n", signum);
  624. U32 count = 0;
  625. printf("Backtrace:\n");
  626. HeapMemoryPool pool(allocAligned, nullptr);
  627. backtrace(pool, [&count](CString symbol) {
  628. printf("%.2u: %s\n", count++, symbol.cstr());
  629. });
  630. ANKI_DEBUG_BREAK();
  631. };
  632. signal(SIGSEGV, handler);
  633. signal(SIGILL, handler);
  634. signal(SIGFPE, handler);
  635. #if ANKI_POSIX
  636. signal(SIGBUS, handler);
  637. #endif
  638. // Ignore for now: signal(SIGABRT, handler);
  639. }
  640. } // end namespace anki