App.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  1. // Copyright (C) 2009-2021, 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/NativeWindow.h>
  17. #include <AnKi/Input/Input.h>
  18. #include <AnKi/Scene/SceneGraph.h>
  19. #include <AnKi/Renderer/RenderQueue.h>
  20. #include <AnKi/Resource/ResourceManager.h>
  21. #include <AnKi/Physics/PhysicsWorld.h>
  22. #include <AnKi/Renderer/MainRenderer.h>
  23. #include <AnKi/Script/ScriptManager.h>
  24. #include <AnKi/Resource/ResourceFilesystem.h>
  25. #include <AnKi/Resource/AsyncLoader.h>
  26. #include <AnKi/Core/StagingGpuMemoryManager.h>
  27. #include <AnKi/Ui/UiManager.h>
  28. #include <AnKi/Ui/Canvas.h>
  29. #include <csignal>
  30. #if ANKI_OS_ANDROID
  31. # include <android_native_app_glue.h>
  32. #endif
  33. namespace anki {
  34. #if ANKI_OS_ANDROID
  35. /// The one and only android hack
  36. android_app* g_androidApp = nullptr;
  37. #endif
  38. class App::StatsUi
  39. {
  40. public:
  41. template<typename T>
  42. class BufferedValue
  43. {
  44. public:
  45. void set(T x)
  46. {
  47. m_total += x;
  48. ++m_count;
  49. }
  50. F64 get(Bool flush)
  51. {
  52. if(flush)
  53. {
  54. m_avg = F64(m_total) / m_count;
  55. m_count = 0;
  56. m_total = 0.0;
  57. }
  58. return m_avg;
  59. }
  60. private:
  61. T m_total = T(0);
  62. F64 m_avg = 0.0;
  63. U32 m_count = 0;
  64. };
  65. GenericMemoryPoolAllocator<U8> m_alloc;
  66. BufferedValue<Second> m_frameTime;
  67. BufferedValue<Second> m_renderTime;
  68. BufferedValue<Second> m_sceneUpdateTime;
  69. BufferedValue<Second> m_visTestsTime;
  70. BufferedValue<Second> m_physicsTime;
  71. BufferedValue<Second> m_gpuTime;
  72. PtrSize m_allocatedCpuMem = 0;
  73. U64 m_allocCount = 0;
  74. U64 m_freeCount = 0;
  75. U64 m_vkCpuMem = 0;
  76. U64 m_vkGpuMem = 0;
  77. U32 m_vkCmdbCount = 0;
  78. PtrSize m_drawableCount = 0;
  79. static const U32 BUFFERED_FRAMES = 16;
  80. U32 m_bufferedFrames = 0;
  81. StatsUi(const GenericMemoryPoolAllocator<U8>& alloc)
  82. : m_alloc(alloc)
  83. {
  84. }
  85. void build(CanvasPtr canvas)
  86. {
  87. // Misc
  88. ++m_bufferedFrames;
  89. Bool flush = false;
  90. if(m_bufferedFrames == BUFFERED_FRAMES)
  91. {
  92. flush = true;
  93. m_bufferedFrames = 0;
  94. }
  95. // Start drawing the UI
  96. canvas->pushFont(canvas->getDefaultFont(), 16);
  97. const Vec4 oldWindowColor = ImGui::GetStyle().Colors[ImGuiCol_WindowBg];
  98. ImGui::GetStyle().Colors[ImGuiCol_WindowBg].w = 0.3f;
  99. if(ImGui::Begin("Stats", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_AlwaysAutoResize))
  100. {
  101. ImGui::SetWindowPos(Vec2(5.0f, 5.0f));
  102. ImGui::SetWindowSize(Vec2(230.0f, 450.0f));
  103. ImGui::Text("CPU Time:");
  104. labelTime(m_frameTime.get(flush), "Total frame");
  105. labelTime(m_renderTime.get(flush), "Renderer");
  106. labelTime(m_sceneUpdateTime.get(flush), "Scene update");
  107. labelTime(m_visTestsTime.get(flush), "Visibility");
  108. labelTime(m_physicsTime.get(flush), "Physics");
  109. ImGui::Text("----");
  110. ImGui::Text("GPU Time:");
  111. labelTime(m_gpuTime.get(flush), "Total frame");
  112. ImGui::Text("----");
  113. ImGui::Text("Memory:");
  114. labelBytes(m_allocatedCpuMem, "Total CPU");
  115. labelUint(m_allocCount, "Total allocations");
  116. labelUint(m_freeCount, "Total frees");
  117. labelBytes(m_vkCpuMem, "Vulkan CPU");
  118. labelBytes(m_vkGpuMem, "Vulkan GPU");
  119. ImGui::Text("----");
  120. ImGui::Text("Vulkan:");
  121. labelUint(m_vkCmdbCount, "Cmd buffers");
  122. ImGui::Text("----");
  123. ImGui::Text("Other:");
  124. labelUint(m_drawableCount, "Drawbles");
  125. }
  126. ImGui::End();
  127. ImGui::GetStyle().Colors[ImGuiCol_WindowBg] = oldWindowColor;
  128. canvas->popFont();
  129. }
  130. void labelTime(Second val, CString name)
  131. {
  132. ImGui::Text("%s: %fms", name.cstr(), val * 1000.0);
  133. }
  134. void labelBytes(PtrSize val, CString name)
  135. {
  136. PtrSize gb, mb, kb, b;
  137. gb = val / 1_GB;
  138. val -= gb * 1_GB;
  139. mb = val / 1_MB;
  140. val -= mb * 1_MB;
  141. kb = val / 1_KB;
  142. val -= kb * 1_KB;
  143. b = val;
  144. StringAuto timestamp(m_alloc);
  145. if(gb)
  146. {
  147. timestamp.sprintf("%s: %4u,%04u,%04u,%04u", name.cstr(), gb, mb, kb, b);
  148. }
  149. else if(mb)
  150. {
  151. timestamp.sprintf("%s: %4u,%04u,%04u", name.cstr(), mb, kb, b);
  152. }
  153. else if(kb)
  154. {
  155. timestamp.sprintf("%s: %4u,%04u", name.cstr(), kb, b);
  156. }
  157. else
  158. {
  159. timestamp.sprintf("%s: %4u", name.cstr(), b);
  160. }
  161. ImGui::TextUnformatted(timestamp.cstr());
  162. }
  163. void labelUint(U64 val, CString name)
  164. {
  165. ImGui::Text("%s: %lu", name.cstr(), val);
  166. }
  167. };
  168. void* App::MemStats::allocCallback(void* userData, void* ptr, PtrSize size, PtrSize alignment)
  169. {
  170. ANKI_ASSERT(userData);
  171. static const PtrSize MAX_ALIGNMENT = 64;
  172. struct alignas(MAX_ALIGNMENT) Header
  173. {
  174. PtrSize m_allocatedSize;
  175. Array<U8, MAX_ALIGNMENT - sizeof(PtrSize)> _m_padding;
  176. };
  177. static_assert(sizeof(Header) == MAX_ALIGNMENT, "See file");
  178. static_assert(alignof(Header) == MAX_ALIGNMENT, "See file");
  179. void* out = nullptr;
  180. if(ptr == nullptr)
  181. {
  182. // Need to allocate
  183. ANKI_ASSERT(size > 0);
  184. ANKI_ASSERT(alignment > 0 && alignment <= MAX_ALIGNMENT);
  185. const PtrSize newAlignment = MAX_ALIGNMENT;
  186. const PtrSize newSize = sizeof(Header) + size;
  187. // Allocate
  188. MemStats* self = static_cast<MemStats*>(userData);
  189. Header* allocation = static_cast<Header*>(
  190. self->m_originalAllocCallback(self->m_originalUserData, nullptr, newSize, newAlignment));
  191. allocation->m_allocatedSize = size;
  192. ++allocation;
  193. out = static_cast<void*>(allocation);
  194. // Update stats
  195. self->m_allocatedMem.fetchAdd(size);
  196. self->m_allocCount.fetchAdd(1);
  197. }
  198. else
  199. {
  200. // Need to free
  201. MemStats* self = static_cast<MemStats*>(userData);
  202. Header* allocation = static_cast<Header*>(ptr);
  203. --allocation;
  204. ANKI_ASSERT(allocation->m_allocatedSize > 0);
  205. // Update stats
  206. self->m_freeCount.fetchAdd(1);
  207. self->m_allocatedMem.fetchSub(allocation->m_allocatedSize);
  208. // Free
  209. self->m_originalAllocCallback(self->m_originalUserData, allocation, 0, 0);
  210. }
  211. return out;
  212. }
  213. App::App()
  214. {
  215. }
  216. App::~App()
  217. {
  218. cleanup();
  219. }
  220. void App::cleanup()
  221. {
  222. m_heapAlloc.deleteInstance(m_statsUi);
  223. m_console.reset(nullptr);
  224. m_heapAlloc.deleteInstance(m_scene);
  225. m_scene = nullptr;
  226. m_heapAlloc.deleteInstance(m_script);
  227. m_script = nullptr;
  228. m_heapAlloc.deleteInstance(m_renderer);
  229. m_renderer = nullptr;
  230. m_heapAlloc.deleteInstance(m_ui);
  231. m_ui = nullptr;
  232. m_heapAlloc.deleteInstance(m_resources);
  233. m_resources = nullptr;
  234. m_heapAlloc.deleteInstance(m_resourceFs);
  235. m_resourceFs = nullptr;
  236. m_heapAlloc.deleteInstance(m_physics);
  237. m_physics = nullptr;
  238. m_heapAlloc.deleteInstance(m_stagingMem);
  239. m_stagingMem = nullptr;
  240. m_heapAlloc.deleteInstance(m_threadHive);
  241. m_threadHive = nullptr;
  242. GrManager::deleteInstance(m_gr);
  243. m_gr = nullptr;
  244. Input::deleteInstance(m_input);
  245. m_input = nullptr;
  246. NativeWindow::deleteInstance(m_window);
  247. m_window = nullptr;
  248. #if ANKI_ENABLE_TRACE
  249. m_heapAlloc.deleteInstance(m_coreTracer);
  250. m_coreTracer = nullptr;
  251. #endif
  252. m_settingsDir.destroy(m_heapAlloc);
  253. m_cacheDir.destroy(m_heapAlloc);
  254. }
  255. Error App::init(const ConfigSet& config, AllocAlignedCallback allocCb, void* allocCbUserData)
  256. {
  257. const Error err = initInternal(config, allocCb, allocCbUserData);
  258. if(err)
  259. {
  260. ANKI_CORE_LOGE("App initialization failed. Shutting down");
  261. cleanup();
  262. }
  263. return err;
  264. }
  265. Error App::initInternal(const ConfigSet& config_, AllocAlignedCallback allocCb, void* allocCbUserData)
  266. {
  267. setSignalHandlers();
  268. Thread::setNameOfCurrentThread("anki_main");
  269. ConfigSet config = config_;
  270. m_displayStats = config.getNumberU32("core_displayStats");
  271. initMemoryCallbacks(allocCb, allocCbUserData);
  272. m_heapAlloc = HeapAllocator<U8>(m_allocCb, m_allocCbData);
  273. ANKI_CHECK(initDirs(config));
  274. // Print a message
  275. const char* buildType =
  276. #if ANKI_OPTIMIZE
  277. "optimized, "
  278. #else
  279. "NOT optimized, "
  280. #endif
  281. #if ANKI_DEBUG_SYMBOLS
  282. "dbg symbols, "
  283. #else
  284. "NO dbg symbols, "
  285. #endif
  286. #if ANKI_EXTRA_CHECKS
  287. "extra checks, "
  288. #else
  289. "NO extra checks, "
  290. #endif
  291. #if ANKI_ENABLE_TRACE
  292. "built with tracing";
  293. #else
  294. "NOT built with tracing";
  295. #endif
  296. ANKI_CORE_LOGI("Initializing application ("
  297. "version %u.%u, "
  298. "%s, "
  299. "compiler %s, "
  300. "build date %s, "
  301. "commit %s)",
  302. ANKI_VERSION_MAJOR, ANKI_VERSION_MINOR, buildType, ANKI_COMPILER_STR, __DATE__, ANKI_REVISION);
  303. m_timerTick = 1.0 / F32(config.getNumberU32("core_targetFps")); // in sec. 1.0 / period
  304. // Check SIMD support
  305. #if ANKI_SIMD_SSE && ANKI_COMPILER_GCC_COMPATIBLE
  306. if(!__builtin_cpu_supports("sse4.2"))
  307. {
  308. ANKI_CORE_LOGF(
  309. "AnKi is built with sse4.2 support but your CPU doesn't support it. Try bulding without SSE support");
  310. }
  311. #endif
  312. ANKI_CORE_LOGI("Number of main threads: %u", config.getNumberU32("core_mainThreadCount"));
  313. //
  314. // Core tracer
  315. //
  316. #if ANKI_ENABLE_TRACE
  317. m_coreTracer = m_heapAlloc.newInstance<CoreTracer>();
  318. ANKI_CHECK(m_coreTracer->init(m_heapAlloc, m_settingsDir));
  319. #endif
  320. //
  321. // Window
  322. //
  323. NativeWindowInitInfo nwinit;
  324. nwinit.m_allocCallback = m_allocCb;
  325. nwinit.m_allocCallbackUserData = m_allocCbData;
  326. nwinit.m_width = config.getNumberU32("width");
  327. nwinit.m_height = config.getNumberU32("height");
  328. nwinit.m_depthBits = 0;
  329. nwinit.m_stencilBits = 0;
  330. nwinit.m_fullscreenDesktopRez = config.getBool("window_fullscreen");
  331. ANKI_CHECK(NativeWindow::newInstance(nwinit, m_window));
  332. //
  333. // Input
  334. //
  335. ANKI_CHECK(Input::newInstance(m_allocCb, m_allocCbData, m_window, m_input));
  336. //
  337. // ThreadPool
  338. //
  339. m_threadHive = m_heapAlloc.newInstance<ThreadHive>(config.getNumberU32("core_mainThreadCount"), m_heapAlloc, true);
  340. //
  341. // Graphics API
  342. //
  343. GrManagerInitInfo grInit;
  344. grInit.m_allocCallback = m_allocCb;
  345. grInit.m_allocCallbackUserData = m_allocCbData;
  346. grInit.m_cacheDirectory = m_cacheDir.toCString();
  347. grInit.m_config = &config;
  348. grInit.m_window = m_window;
  349. ANKI_CHECK(GrManager::newInstance(grInit, m_gr));
  350. //
  351. // Staging mem
  352. //
  353. m_stagingMem = m_heapAlloc.newInstance<StagingGpuMemoryManager>();
  354. ANKI_CHECK(m_stagingMem->init(m_gr, config));
  355. //
  356. // Physics
  357. //
  358. m_physics = m_heapAlloc.newInstance<PhysicsWorld>();
  359. ANKI_CHECK(m_physics->init(m_allocCb, m_allocCbData));
  360. //
  361. // Resource FS
  362. //
  363. m_resourceFs = m_heapAlloc.newInstance<ResourceFilesystem>(m_heapAlloc);
  364. ANKI_CHECK(m_resourceFs->init(config, m_cacheDir.toCString()));
  365. //
  366. // Resources
  367. //
  368. ResourceManagerInitInfo rinit;
  369. rinit.m_gr = m_gr;
  370. rinit.m_physics = m_physics;
  371. rinit.m_resourceFs = m_resourceFs;
  372. rinit.m_config = &config;
  373. rinit.m_cacheDir = m_cacheDir.toCString();
  374. rinit.m_allocCallback = m_allocCb;
  375. rinit.m_allocCallbackData = m_allocCbData;
  376. m_resources = m_heapAlloc.newInstance<ResourceManager>();
  377. ANKI_CHECK(m_resources->init(rinit));
  378. //
  379. // UI
  380. //
  381. m_ui = m_heapAlloc.newInstance<UiManager>();
  382. ANKI_CHECK(m_ui->init(m_allocCb, m_allocCbData, m_resources, m_gr, m_stagingMem, m_input));
  383. //
  384. // Renderer
  385. //
  386. if(nwinit.m_fullscreenDesktopRez)
  387. {
  388. config.set("width", m_window->getWidth());
  389. config.set("height", m_window->getHeight());
  390. }
  391. m_renderer = m_heapAlloc.newInstance<MainRenderer>();
  392. ANKI_CHECK(m_renderer->init(m_threadHive, m_resources, m_gr, m_stagingMem, m_ui, m_allocCb, m_allocCbData, config,
  393. &m_globalTimestamp));
  394. //
  395. // Script
  396. //
  397. m_script = m_heapAlloc.newInstance<ScriptManager>();
  398. ANKI_CHECK(m_script->init(m_allocCb, m_allocCbData));
  399. //
  400. // Scene
  401. //
  402. m_scene = m_heapAlloc.newInstance<SceneGraph>();
  403. ANKI_CHECK(m_scene->init(m_allocCb, m_allocCbData, m_threadHive, m_resources, m_input, m_script, m_ui,
  404. &m_globalTimestamp, config));
  405. // Inform the script engine about some subsystems
  406. m_script->setRenderer(m_renderer);
  407. m_script->setSceneGraph(m_scene);
  408. //
  409. // Misc
  410. //
  411. m_statsUi = m_heapAlloc.newInstance<StatsUi>(m_heapAlloc);
  412. ANKI_CHECK(m_ui->newInstance<DeveloperConsole>(m_console, m_allocCb, m_allocCbData, m_script));
  413. ANKI_CORE_LOGI("Application initialized");
  414. return Error::NONE;
  415. }
  416. Error App::initDirs(const ConfigSet& cfg)
  417. {
  418. // Settings path
  419. #if !ANKI_OS_ANDROID
  420. StringAuto home(m_heapAlloc);
  421. ANKI_CHECK(getHomeDirectory(home));
  422. m_settingsDir.sprintf(m_heapAlloc, "%s/.anki", &home[0]);
  423. #else
  424. m_settingsDir.sprintf(m_heapAlloc, "%s/.anki", g_androidApp->activity->internalDataPath);
  425. #endif
  426. if(!directoryExists(m_settingsDir.toCString()))
  427. {
  428. ANKI_CORE_LOGI("Creating settings dir \"%s\"", &m_settingsDir[0]);
  429. ANKI_CHECK(createDirectory(m_settingsDir.toCString()));
  430. }
  431. else
  432. {
  433. ANKI_CORE_LOGI("Using settings dir \"%s\"", &m_settingsDir[0]);
  434. }
  435. // Cache
  436. m_cacheDir.sprintf(m_heapAlloc, "%s/cache", &m_settingsDir[0]);
  437. const Bool cacheDirExists = directoryExists(m_cacheDir.toCString());
  438. if(cfg.getBool("core_clearCaches") && cacheDirExists)
  439. {
  440. ANKI_CORE_LOGI("Will delete the cache dir and start fresh: %s", &m_cacheDir[0]);
  441. ANKI_CHECK(removeDirectory(m_cacheDir.toCString(), m_heapAlloc));
  442. ANKI_CHECK(createDirectory(m_cacheDir.toCString()));
  443. }
  444. else if(!cacheDirExists)
  445. {
  446. ANKI_CORE_LOGI("Will create cache dir: %s", &m_cacheDir[0]);
  447. ANKI_CHECK(createDirectory(m_cacheDir.toCString()));
  448. }
  449. return Error::NONE;
  450. }
  451. Error App::mainLoop()
  452. {
  453. ANKI_CORE_LOGI("Entering main loop");
  454. Bool quit = false;
  455. Second prevUpdateTime = HighRezTimer::getCurrentTime();
  456. Second crntTime = prevUpdateTime;
  457. while(!quit)
  458. {
  459. {
  460. ANKI_TRACE_SCOPED_EVENT(FRAME);
  461. const Second startTime = HighRezTimer::getCurrentTime();
  462. prevUpdateTime = crntTime;
  463. crntTime = HighRezTimer::getCurrentTime();
  464. // Update
  465. ANKI_CHECK(m_input->handleEvents());
  466. // User update
  467. ANKI_CHECK(userMainLoop(quit, crntTime - prevUpdateTime));
  468. ANKI_CHECK(m_scene->update(prevUpdateTime, crntTime));
  469. RenderQueue rqueue;
  470. m_scene->doVisibilityTests(rqueue);
  471. // Inject stats UI
  472. DynamicArrayAuto<UiQueueElement> newUiElementArr(m_heapAlloc);
  473. injectUiElements(newUiElementArr, rqueue);
  474. // Render
  475. TexturePtr presentableTex = m_gr->acquireNextPresentableTexture();
  476. m_renderer->setStatsEnabled(m_displayStats
  477. #if ANKI_ENABLE_TRACE
  478. || TracerSingleton::get().getEnabled()
  479. #endif
  480. );
  481. ANKI_CHECK(m_renderer->render(rqueue, presentableTex));
  482. // Pause and sync async loader. That will force all tasks before the pause to finish in this frame.
  483. m_resources->getAsyncLoader().pause();
  484. m_gr->swapBuffers();
  485. m_stagingMem->endFrame();
  486. // Update the trace info with some async loader stats
  487. U64 asyncTaskCount = m_resources->getAsyncLoader().getCompletedTaskCount();
  488. ANKI_TRACE_INC_COUNTER(RESOURCE_ASYNC_TASKS, asyncTaskCount - m_resourceCompletedAsyncTaskCount);
  489. m_resourceCompletedAsyncTaskCount = asyncTaskCount;
  490. // Now resume the loader
  491. m_resources->getAsyncLoader().resume();
  492. // Sleep
  493. const Second endTime = HighRezTimer::getCurrentTime();
  494. const Second frameTime = endTime - startTime;
  495. if(frameTime < m_timerTick)
  496. {
  497. ANKI_TRACE_SCOPED_EVENT(TIMER_TICK_SLEEP);
  498. HighRezTimer::sleep(m_timerTick - frameTime);
  499. }
  500. // Stats
  501. if(m_displayStats)
  502. {
  503. m_statsUi->m_frameTime.set(frameTime);
  504. m_statsUi->m_renderTime.set(m_renderer->getStats().m_renderingCpuTime);
  505. m_statsUi->m_sceneUpdateTime.set(m_scene->getStats().m_updateTime);
  506. m_statsUi->m_visTestsTime.set(m_scene->getStats().m_visibilityTestsTime);
  507. m_statsUi->m_physicsTime.set(m_scene->getStats().m_physicsUpdate);
  508. m_statsUi->m_gpuTime.set(m_renderer->getStats().m_renderingGpuTime);
  509. m_statsUi->m_allocatedCpuMem = m_memStats.m_allocatedMem.load();
  510. m_statsUi->m_allocCount = m_memStats.m_allocCount.load();
  511. m_statsUi->m_freeCount = m_memStats.m_freeCount.load();
  512. GrManagerStats grStats = m_gr->getStats();
  513. m_statsUi->m_vkCpuMem = grStats.m_cpuMemory;
  514. m_statsUi->m_vkGpuMem = grStats.m_gpuMemory;
  515. m_statsUi->m_vkCmdbCount = grStats.m_commandBufferCount;
  516. m_statsUi->m_drawableCount = rqueue.countAllRenderables();
  517. }
  518. #if ANKI_ENABLE_TRACE
  519. if(m_renderer->getStats().m_renderingGpuTime >= 0.0)
  520. {
  521. ANKI_TRACE_CUSTOM_EVENT(GPU_TIME, m_renderer->getStats().m_renderingGpuSubmitTimestamp,
  522. m_renderer->getStats().m_renderingGpuTime);
  523. }
  524. #endif
  525. ++m_globalTimestamp;
  526. }
  527. #if ANKI_ENABLE_TRACE
  528. static U64 frame = 1;
  529. m_coreTracer->flushFrame(frame++);
  530. #endif
  531. }
  532. return Error::NONE;
  533. }
  534. void App::injectUiElements(DynamicArrayAuto<UiQueueElement>& newUiElementArr, RenderQueue& rqueue)
  535. {
  536. const U32 originalCount = rqueue.m_uis.getSize();
  537. if(m_displayStats || m_consoleEnabled)
  538. {
  539. const U32 extraElements = (m_displayStats != 0) + (m_consoleEnabled != 0);
  540. newUiElementArr.create(originalCount + extraElements);
  541. if(originalCount > 0)
  542. {
  543. memcpy(&newUiElementArr[0], &rqueue.m_uis[0], rqueue.m_uis.getSizeInBytes());
  544. }
  545. rqueue.m_uis = WeakArray<UiQueueElement>(newUiElementArr);
  546. }
  547. U32 count = originalCount;
  548. if(m_displayStats)
  549. {
  550. newUiElementArr[count].m_userData = m_statsUi;
  551. newUiElementArr[count].m_drawCallback = [](CanvasPtr& canvas, void* userData) -> void {
  552. static_cast<StatsUi*>(userData)->build(canvas);
  553. };
  554. ++count;
  555. }
  556. if(m_consoleEnabled)
  557. {
  558. newUiElementArr[count].m_userData = m_console.get();
  559. newUiElementArr[count].m_drawCallback = [](CanvasPtr& canvas, void* userData) -> void {
  560. static_cast<DeveloperConsole*>(userData)->build(canvas);
  561. };
  562. ++count;
  563. }
  564. }
  565. void App::initMemoryCallbacks(AllocAlignedCallback allocCb, void* allocCbUserData)
  566. {
  567. if(m_displayStats)
  568. {
  569. m_memStats.m_originalAllocCallback = allocCb;
  570. m_memStats.m_originalUserData = allocCbUserData;
  571. m_allocCb = MemStats::allocCallback;
  572. m_allocCbData = &m_memStats;
  573. }
  574. else
  575. {
  576. m_allocCb = allocCb;
  577. m_allocCbData = allocCbUserData;
  578. }
  579. }
  580. void App::setSignalHandlers()
  581. {
  582. auto handler = [](int signum) -> void {
  583. const char* name = nullptr;
  584. switch(signum)
  585. {
  586. case SIGABRT:
  587. name = "SIGABRT";
  588. break;
  589. case SIGSEGV:
  590. name = "SIGSEGV";
  591. break;
  592. #if ANKI_POSIX
  593. case SIGBUS:
  594. name = "SIGBUS";
  595. break;
  596. #endif
  597. case SIGILL:
  598. name = "SIGILL";
  599. break;
  600. case SIGFPE:
  601. name = "SIGFPE";
  602. break;
  603. }
  604. if(name)
  605. printf("Caught signal %d (%s)\n", signum, name);
  606. else
  607. printf("Caught signal %d\n", signum);
  608. U32 count = 0;
  609. printf("Backtrace:\n");
  610. backtrace(HeapAllocator<U8>(allocAligned, nullptr), [&count](CString symbol) {
  611. printf("%.2u: %s\n", count++, symbol.cstr());
  612. });
  613. ANKI_DEBUG_BREAK();
  614. };
  615. signal(SIGSEGV, handler);
  616. signal(SIGILL, handler);
  617. signal(SIGFPE, handler);
  618. #if ANKI_POSIX
  619. signal(SIGBUS, handler);
  620. #endif
  621. // Ignore for now: signal(SIGABRT, handler);
  622. }
  623. } // end namespace anki