App.cpp 20 KB

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