App.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. // Copyright (C) 2009-present, 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/Util/CVarSet.h>
  7. #include <AnKi/GpuMemory/UnifiedGeometryBuffer.h>
  8. #include <AnKi/Util/Logger.h>
  9. #include <AnKi/Util/File.h>
  10. #include <AnKi/Util/Filesystem.h>
  11. #include <AnKi/Util/System.h>
  12. #include <AnKi/Util/Tracer.h>
  13. #include <AnKi/Util/HighRezTimer.h>
  14. #include <AnKi/Core/CoreTracer.h>
  15. #include <AnKi/GpuMemory/RebarTransientMemoryPool.h>
  16. #include <AnKi/GpuMemory/GpuVisibleTransientMemoryPool.h>
  17. #include <AnKi/GpuMemory/GpuReadbackMemoryPool.h>
  18. #include <AnKi/Core/StatsSet.h>
  19. #include <AnKi/Window/NativeWindow.h>
  20. #include <AnKi/Core/MaliHwCounters.h>
  21. #include <AnKi/Window/Input.h>
  22. #include <AnKi/Scene/SceneGraph.h>
  23. #include <AnKi/Resource/ResourceManager.h>
  24. #include <AnKi/Physics/PhysicsWorld.h>
  25. #include <AnKi/Renderer/Renderer.h>
  26. #include <AnKi/Script/ScriptManager.h>
  27. #include <AnKi/Resource/ResourceFilesystem.h>
  28. #include <AnKi/Resource/AsyncLoader.h>
  29. #include <AnKi/Ui/UiManager.h>
  30. #include <AnKi/Ui/Canvas.h>
  31. #include <AnKi/Scene/DeveloperConsoleUiNode.h>
  32. #include <csignal>
  33. #if ANKI_OS_ANDROID
  34. # include <android_native_app_glue.h>
  35. #endif
  36. namespace anki {
  37. #if ANKI_OS_ANDROID
  38. /// The one and only android hack
  39. android_app* g_androidApp = nullptr;
  40. #endif
  41. StatCounter g_cpuAllocatedMemStatVar(StatCategory::kCpuMem, "Total", StatFlag::kBytes);
  42. StatCounter g_cpuAllocationCountStatVar(StatCategory::kCpuMem, "Allocations/frame", StatFlag::kBytes | StatFlag::kZeroEveryFrame);
  43. StatCounter g_cpuFreesCountStatVar(StatCategory::kCpuMem, "Frees/frame", StatFlag::kBytes | StatFlag::kZeroEveryFrame);
  44. #if ANKI_PLATFORM_MOBILE
  45. inline StatCounter g_maliGpuActiveStatVar(StatCategory::kGpuMisc, "Mali active cycles", StatFlag::kMainThreadUpdates);
  46. inline StatCounter g_maliGpuReadBandwidthStatVar(StatCategory::kGpuMisc, "Mali read bandwidth", StatFlag::kMainThreadUpdates);
  47. inline StatCounter g_maliGpuWriteBandwidthStatVar(StatCategory::kGpuMisc, "Mali write bandwidth", StatFlag::kMainThreadUpdates);
  48. #endif
  49. void* App::statsAllocCallback(void* userData, void* ptr, PtrSize size, [[maybe_unused]] PtrSize alignment)
  50. {
  51. ANKI_ASSERT(userData);
  52. constexpr PtrSize kMaxAlignment = 64;
  53. struct alignas(kMaxAlignment) Header
  54. {
  55. PtrSize m_allocatedSize;
  56. Array<U8, kMaxAlignment - sizeof(PtrSize)> _m_padding;
  57. };
  58. static_assert(sizeof(Header) == kMaxAlignment, "See file");
  59. static_assert(alignof(Header) == kMaxAlignment, "See file");
  60. void* out = nullptr;
  61. if(ptr == nullptr)
  62. {
  63. // Need to allocate
  64. ANKI_ASSERT(size > 0);
  65. ANKI_ASSERT(alignment > 0 && alignment <= kMaxAlignment);
  66. const PtrSize newAlignment = kMaxAlignment;
  67. const PtrSize newSize = sizeof(Header) + size;
  68. // Allocate
  69. App* self = static_cast<App*>(userData);
  70. Header* allocation = static_cast<Header*>(self->m_originalAllocCallback(self->m_originalAllocUserData, nullptr, newSize, newAlignment));
  71. allocation->m_allocatedSize = size;
  72. ++allocation;
  73. out = static_cast<void*>(allocation);
  74. // Update stats
  75. g_cpuAllocatedMemStatVar.increment(size);
  76. g_cpuAllocationCountStatVar.increment(1);
  77. }
  78. else
  79. {
  80. // Need to free
  81. App* self = static_cast<App*>(userData);
  82. Header* allocation = static_cast<Header*>(ptr);
  83. --allocation;
  84. ANKI_ASSERT(allocation->m_allocatedSize > 0);
  85. // Update stats
  86. g_cpuAllocatedMemStatVar.decrement(allocation->m_allocatedSize);
  87. g_cpuFreesCountStatVar.increment(1);
  88. // Free
  89. self->m_originalAllocCallback(self->m_originalAllocUserData, allocation, 0, 0);
  90. }
  91. return out;
  92. }
  93. App::App(AllocAlignedCallback allocCb, void* allocCbUserData)
  94. {
  95. m_originalAllocCallback = allocCb;
  96. m_originalAllocUserData = allocCbUserData;
  97. }
  98. App::~App()
  99. {
  100. ANKI_CORE_LOGI("Destroying application");
  101. cleanup();
  102. }
  103. void App::cleanup()
  104. {
  105. SceneGraph::freeSingleton();
  106. ScriptManager::freeSingleton();
  107. Renderer::freeSingleton();
  108. UiManager::freeSingleton();
  109. GpuSceneMicroPatcher::freeSingleton();
  110. ResourceManager::freeSingleton();
  111. PhysicsWorld::freeSingleton();
  112. RebarTransientMemoryPool::freeSingleton();
  113. GpuVisibleTransientMemoryPool::freeSingleton();
  114. UnifiedGeometryBuffer::freeSingleton();
  115. GpuSceneBuffer::freeSingleton();
  116. GpuReadbackMemoryPool::freeSingleton();
  117. CoreThreadJobManager::freeSingleton();
  118. MaliHwCounters::freeSingleton();
  119. GrManager::freeSingleton();
  120. Input::freeSingleton();
  121. NativeWindow::freeSingleton();
  122. #if ANKI_TRACING_ENABLED
  123. CoreTracer::freeSingleton();
  124. #endif
  125. GlobalFrameIndex::freeSingleton();
  126. m_settingsDir.destroy();
  127. m_cacheDir.destroy();
  128. CoreMemoryPool::freeSingleton();
  129. DefaultMemoryPool::freeSingleton();
  130. }
  131. Error App::init()
  132. {
  133. const Error err = initInternal();
  134. if(err)
  135. {
  136. ANKI_CORE_LOGE("App initialization failed. Shutting down");
  137. cleanup();
  138. }
  139. return err;
  140. }
  141. Error App::initInternal()
  142. {
  143. StatsSet::getSingleton().initFromMainThread();
  144. Logger::getSingleton().enableVerbosity(g_verboseLogCVar);
  145. AllocAlignedCallback allocCb = m_originalAllocCallback;
  146. void* allocCbUserData = m_originalAllocUserData;
  147. initMemoryCallbacks(allocCb, allocCbUserData);
  148. DefaultMemoryPool::allocateSingleton(allocCb, allocCbUserData);
  149. CoreMemoryPool::allocateSingleton(allocCb, allocCbUserData);
  150. ANKI_CHECK(initDirs());
  151. // Print a message
  152. const char* buildType =
  153. #if ANKI_OPTIMIZE
  154. "optimized, "
  155. #else
  156. "NOT optimized, "
  157. #endif
  158. #if ANKI_DEBUG_SYMBOLS
  159. "dbg symbols, "
  160. #else
  161. "NO dbg symbols, "
  162. #endif
  163. #if ANKI_EXTRA_CHECKS
  164. "extra checks, "
  165. #else
  166. "NO extra checks, "
  167. #endif
  168. #if ANKI_TRACING_ENABLED
  169. "built with tracing";
  170. #else
  171. "NOT built with tracing";
  172. #endif
  173. ANKI_CORE_LOGI("Initializing application");
  174. ANKI_CORE_LOGI("\tBuild type %s", buildType);
  175. ANKI_CORE_LOGI("\tBuild time %s %s", __DATE__, __TIME__);
  176. ANKI_CORE_LOGI("\tCompiler %s", ANKI_COMPILER_STR);
  177. ANKI_CORE_LOGI("\tCommit %s", ANKI_REVISION);
  178. // Check SIMD support
  179. #if ANKI_SIMD_SSE && ANKI_COMPILER_GCC_COMPATIBLE
  180. if(!__builtin_cpu_supports("sse4.2"))
  181. {
  182. ANKI_CORE_LOGF("AnKi is built with sse4.2 support but your CPU doesn't support it. Try bulding without SSE support");
  183. }
  184. #endif
  185. ANKI_CORE_LOGI("Number of job threads: %u", U32(g_jobThreadCountCVar));
  186. if(g_benchmarkModeCVar && g_vsyncCVar)
  187. {
  188. ANKI_CORE_LOGW("Vsync is enabled and benchmark mode as well. Will turn vsync off");
  189. g_vsyncCVar = false;
  190. }
  191. GlobalFrameIndex::allocateSingleton();
  192. //
  193. // Core tracer
  194. //
  195. #if ANKI_TRACING_ENABLED
  196. ANKI_CHECK(CoreTracer::allocateSingleton().init(m_settingsDir));
  197. #endif
  198. //
  199. // Window
  200. //
  201. NativeWindowInitInfo nwinit;
  202. nwinit.m_width = g_windowWidthCVar;
  203. nwinit.m_height = g_windowHeightCVar;
  204. nwinit.m_depthBits = 0;
  205. nwinit.m_stencilBits = 0;
  206. nwinit.m_fullscreenDesktopRez = g_windowFullscreenCVar > 0;
  207. nwinit.m_exclusiveFullscreen = g_windowFullscreenCVar == 2;
  208. nwinit.m_targetFps = g_targetFpsCVar;
  209. NativeWindow::allocateSingleton();
  210. ANKI_CHECK(NativeWindow::getSingleton().init(nwinit));
  211. //
  212. // Input
  213. //
  214. Input::allocateSingleton();
  215. ANKI_CHECK(Input::getSingleton().init());
  216. //
  217. // ThreadPool
  218. //
  219. const Bool pinThreads = !ANKI_OS_ANDROID;
  220. CoreThreadJobManager::allocateSingleton(U32(g_jobThreadCountCVar), pinThreads);
  221. //
  222. // Graphics API
  223. //
  224. GrManagerInitInfo grInit;
  225. grInit.m_allocCallback = allocCb;
  226. grInit.m_allocCallbackUserData = allocCbUserData;
  227. grInit.m_cacheDirectory = m_cacheDir.toCString();
  228. ANKI_CHECK(GrManager::allocateSingleton().init(grInit));
  229. //
  230. // Mali HW counters
  231. //
  232. #if ANKI_PLATFORM_MOBILE
  233. if(ANKI_STATS_ENABLED && GrManager::getSingleton().getDeviceCapabilities().m_gpuVendor == GpuVendor::kArm && g_maliHwCountersCVar)
  234. {
  235. MaliHwCounters::allocateSingleton();
  236. }
  237. #endif
  238. //
  239. // GPU mem
  240. //
  241. UnifiedGeometryBuffer::allocateSingleton().init();
  242. GpuSceneBuffer::allocateSingleton().init();
  243. RebarTransientMemoryPool::allocateSingleton().init();
  244. GpuVisibleTransientMemoryPool::allocateSingleton();
  245. GpuReadbackMemoryPool::allocateSingleton();
  246. //
  247. // Physics
  248. //
  249. PhysicsWorld::allocateSingleton();
  250. ANKI_CHECK(PhysicsWorld::getSingleton().init(allocCb, allocCbUserData));
  251. //
  252. // Resources
  253. //
  254. #if !ANKI_OS_ANDROID
  255. // Add the location of the executable where the shaders are supposed to be
  256. String executableFname;
  257. ANKI_CHECK(getApplicationPath(executableFname));
  258. ANKI_CORE_LOGI("Executable path is: %s", executableFname.cstr());
  259. String extraPaths;
  260. getParentFilepath(executableFname, extraPaths);
  261. extraPaths += "|ankiprogbin"; // Shaders
  262. extraPaths += ":" ANKI_SOURCE_DIRECTORY "|EngineAssets,!AndroidProject"; // EngineAssets
  263. extraPaths += ":";
  264. extraPaths += g_dataPathsCVar;
  265. g_dataPathsCVar = extraPaths;
  266. #endif
  267. ANKI_CHECK(ResourceManager::allocateSingleton().init(allocCb, allocCbUserData));
  268. //
  269. // UI
  270. //
  271. ANKI_CHECK(UiManager::allocateSingleton().init(allocCb, allocCbUserData));
  272. //
  273. // GPU scene
  274. //
  275. ANKI_CHECK(GpuSceneMicroPatcher::allocateSingleton().init());
  276. //
  277. // Renderer
  278. //
  279. RendererInitInfo renderInit;
  280. renderInit.m_swapchainSize = UVec2(NativeWindow::getSingleton().getWidth(), NativeWindow::getSingleton().getHeight());
  281. renderInit.m_allocCallback = allocCb;
  282. renderInit.m_allocCallbackUserData = allocCbUserData;
  283. ANKI_CHECK(Renderer::allocateSingleton().init(renderInit));
  284. //
  285. // Script
  286. //
  287. ScriptManager::allocateSingleton(allocCb, allocCbUserData);
  288. //
  289. // Scene
  290. //
  291. ANKI_CHECK(SceneGraph::allocateSingleton().init(allocCb, allocCbUserData));
  292. ANKI_CORE_LOGI("Application initialized");
  293. return Error::kNone;
  294. }
  295. Error App::initDirs()
  296. {
  297. // Settings path
  298. #if !ANKI_OS_ANDROID
  299. String home;
  300. ANKI_CHECK(getHomeDirectory(home));
  301. m_settingsDir.sprintf("%s/.anki", &home[0]);
  302. #else
  303. m_settingsDir.sprintf("%s/.anki", g_androidApp->activity->internalDataPath);
  304. #endif
  305. if(!directoryExists(m_settingsDir.toCString()))
  306. {
  307. ANKI_CORE_LOGI("Creating settings dir \"%s\"", &m_settingsDir[0]);
  308. ANKI_CHECK(createDirectory(m_settingsDir.toCString()));
  309. }
  310. else
  311. {
  312. ANKI_CORE_LOGI("Using settings dir \"%s\"", &m_settingsDir[0]);
  313. }
  314. // Cache
  315. m_cacheDir.sprintf("%s/cache", &m_settingsDir[0]);
  316. const Bool cacheDirExists = directoryExists(m_cacheDir.toCString());
  317. if(g_clearCachesCVar && cacheDirExists)
  318. {
  319. ANKI_CORE_LOGI("Will delete the cache dir and start fresh: %s", m_cacheDir.cstr());
  320. ANKI_CHECK(removeDirectory(m_cacheDir.toCString()));
  321. ANKI_CHECK(createDirectory(m_cacheDir.toCString()));
  322. }
  323. else if(!cacheDirExists)
  324. {
  325. ANKI_CORE_LOGI("Will create cache dir: %s", m_cacheDir.cstr());
  326. ANKI_CHECK(createDirectory(m_cacheDir.toCString()));
  327. }
  328. return Error::kNone;
  329. }
  330. Error App::mainLoop()
  331. {
  332. ANKI_CORE_LOGI("Entering main loop");
  333. Bool quit = false;
  334. Second prevUpdateTime = HighRezTimer::getCurrentTime();
  335. Second crntTime = prevUpdateTime;
  336. // Benchmark mode stuff:
  337. const Bool benchmarkMode = g_benchmarkModeCVar;
  338. Second aggregatedCpuTime = 0.0;
  339. Second aggregatedGpuTime = 0.0;
  340. constexpr U32 kBenchmarkFramesToGatherBeforeFlush = 60;
  341. U32 benchmarkFramesGathered = 0;
  342. File benchmarkCsvFile;
  343. CoreString benchmarkCsvFileFilename;
  344. if(benchmarkMode)
  345. {
  346. benchmarkCsvFileFilename.sprintf("%s/Benchmark.csv", m_settingsDir.cstr());
  347. ANKI_CHECK(benchmarkCsvFile.open(benchmarkCsvFileFilename, FileOpenFlag::kWrite));
  348. ANKI_CHECK(benchmarkCsvFile.writeText("CPU, GPU\n"));
  349. }
  350. while(!quit)
  351. {
  352. {
  353. ANKI_TRACE_SCOPED_EVENT(Frame);
  354. const Second startTime = HighRezTimer::getCurrentTime();
  355. prevUpdateTime = crntTime;
  356. crntTime = (!benchmarkMode) ? HighRezTimer::getCurrentTime() : (prevUpdateTime + 1.0_sec / 60.0_sec);
  357. // Update
  358. ANKI_CHECK(Input::getSingleton().handleEvents());
  359. // User update
  360. ANKI_CHECK(userMainLoop(quit, crntTime - prevUpdateTime));
  361. ANKI_CHECK(SceneGraph::getSingleton().update(prevUpdateTime, crntTime));
  362. // Render
  363. TexturePtr presentableTex = GrManager::getSingleton().acquireNextPresentableTexture();
  364. ANKI_CHECK(Renderer::getSingleton().render(presentableTex.get()));
  365. // If we get stats exclude the time of GR because it forces some GPU-CPU serialization. We don't want to count that
  366. Second grTime = 0.0;
  367. if(benchmarkMode || g_displayStatsCVar > 0) [[unlikely]]
  368. {
  369. grTime = HighRezTimer::getCurrentTime();
  370. }
  371. GrManager::getSingleton().swapBuffers();
  372. if(benchmarkMode || g_displayStatsCVar > 0) [[unlikely]]
  373. {
  374. grTime = HighRezTimer::getCurrentTime() - grTime;
  375. }
  376. RebarTransientMemoryPool::getSingleton().endFrame();
  377. UnifiedGeometryBuffer::getSingleton().endFrame();
  378. GpuSceneBuffer::getSingleton().endFrame();
  379. GpuVisibleTransientMemoryPool::getSingleton().endFrame();
  380. GpuReadbackMemoryPool::getSingleton().endFrame();
  381. // Sleep
  382. const Second endTime = HighRezTimer::getCurrentTime();
  383. const Second frameTime = endTime - startTime;
  384. g_cpuTotalTimeStatVar.set((frameTime - grTime) * 1000.0);
  385. if(!benchmarkMode) [[likely]]
  386. {
  387. const Second timerTick = 1.0_sec / Second(g_targetFpsCVar);
  388. if(frameTime < timerTick)
  389. {
  390. ANKI_TRACE_SCOPED_EVENT(TimerTickSleep);
  391. HighRezTimer::sleep(timerTick - frameTime);
  392. }
  393. }
  394. // Benchmark stats
  395. else
  396. {
  397. aggregatedCpuTime += frameTime - grTime;
  398. aggregatedGpuTime += 0; // TODO
  399. ++benchmarkFramesGathered;
  400. if(benchmarkFramesGathered >= kBenchmarkFramesToGatherBeforeFlush)
  401. {
  402. aggregatedCpuTime = aggregatedCpuTime / Second(kBenchmarkFramesToGatherBeforeFlush) * 1000.0;
  403. aggregatedGpuTime = aggregatedGpuTime / Second(kBenchmarkFramesToGatherBeforeFlush) * 1000.0;
  404. ANKI_CHECK(benchmarkCsvFile.writeTextf("%f,%f\n", aggregatedCpuTime, aggregatedGpuTime));
  405. benchmarkFramesGathered = 0;
  406. aggregatedCpuTime = 0.0;
  407. aggregatedGpuTime = 0.0;
  408. }
  409. }
  410. // Stats
  411. #if ANKI_PLATFORM_MOBILE
  412. if(MaliHwCounters::isAllocated())
  413. {
  414. MaliHwCountersOut out;
  415. MaliHwCounters::getSingleton().sample(out);
  416. g_maliGpuActiveStatVar.set(out.m_gpuActive);
  417. g_maliGpuReadBandwidthStatVar.set(out.m_readBandwidth);
  418. g_maliGpuWriteBandwidthStatVar.set(out.m_writeBandwidth);
  419. }
  420. #endif
  421. StatsSet::getSingleton().endFrame();
  422. ++GlobalFrameIndex::getSingleton().m_value;
  423. if(benchmarkMode) [[unlikely]]
  424. {
  425. if(GlobalFrameIndex::getSingleton().m_value >= g_benchmarkModeFrameCountCVar)
  426. {
  427. quit = true;
  428. }
  429. }
  430. }
  431. #if ANKI_TRACING_ENABLED
  432. static U64 frame = 1;
  433. CoreTracer::getSingleton().flushFrame(frame++);
  434. #endif
  435. }
  436. if(benchmarkMode) [[unlikely]]
  437. {
  438. ANKI_CORE_LOGI("Benchmark file saved in: %s", benchmarkCsvFileFilename.cstr());
  439. }
  440. return Error::kNone;
  441. }
  442. void App::initMemoryCallbacks(AllocAlignedCallback& allocCb, void*& allocCbUserData)
  443. {
  444. if(ANKI_STATS_ENABLED && g_displayStatsCVar > 1)
  445. {
  446. allocCb = statsAllocCallback;
  447. allocCbUserData = this;
  448. }
  449. else
  450. {
  451. // Leave the default
  452. }
  453. }
  454. Bool App::toggleDeveloperConsole()
  455. {
  456. SceneNode& node = SceneGraph::getSingleton().findSceneNode("_DevConsole");
  457. static_cast<DeveloperConsoleUiNode&>(node).toggleConsole();
  458. m_consoleEnabled = static_cast<DeveloperConsoleUiNode&>(node).isConsoleEnabled();
  459. return m_consoleEnabled;
  460. }
  461. } // end namespace anki