App.cpp 20 KB

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