App.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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. ANKI_CORE_LOGI("Application finished shutting down");
  131. }
  132. Error App::init()
  133. {
  134. const Error err = initInternal();
  135. if(err)
  136. {
  137. ANKI_CORE_LOGE("App initialization failed. Shutting down");
  138. cleanup();
  139. }
  140. return err;
  141. }
  142. Error App::initInternal()
  143. {
  144. StatsSet::getSingleton().initFromMainThread();
  145. Logger::getSingleton().enableVerbosity(g_verboseLogCVar);
  146. AllocAlignedCallback allocCb = m_originalAllocCallback;
  147. void* allocCbUserData = m_originalAllocUserData;
  148. initMemoryCallbacks(allocCb, allocCbUserData);
  149. DefaultMemoryPool::allocateSingleton(allocCb, allocCbUserData);
  150. CoreMemoryPool::allocateSingleton(allocCb, allocCbUserData);
  151. ANKI_CHECK(initDirs());
  152. ANKI_CORE_LOGI("Initializing application. Build config: %s", kAnKiBuildConfigString);
  153. // Check SIMD support
  154. #if ANKI_SIMD_SSE && ANKI_COMPILER_GCC_COMPATIBLE
  155. if(!__builtin_cpu_supports("sse4.2"))
  156. {
  157. ANKI_CORE_LOGF("AnKi is built with sse4.2 support but your CPU doesn't support it. Try bulding without SSE support");
  158. }
  159. #endif
  160. ANKI_CORE_LOGI("Number of job threads: %u", U32(g_jobThreadCountCVar));
  161. if(g_benchmarkModeCVar && g_vsyncCVar)
  162. {
  163. ANKI_CORE_LOGW("Vsync is enabled and benchmark mode as well. Will turn vsync off");
  164. g_vsyncCVar = false;
  165. }
  166. GlobalFrameIndex::allocateSingleton();
  167. //
  168. // Core tracer
  169. //
  170. #if ANKI_TRACING_ENABLED
  171. ANKI_CHECK(CoreTracer::allocateSingleton().init(m_settingsDir));
  172. #endif
  173. //
  174. // Window
  175. //
  176. NativeWindowInitInfo nwinit;
  177. nwinit.m_width = g_windowWidthCVar;
  178. nwinit.m_height = g_windowHeightCVar;
  179. nwinit.m_depthBits = 0;
  180. nwinit.m_stencilBits = 0;
  181. nwinit.m_fullscreenDesktopRez = g_windowFullscreenCVar > 0;
  182. nwinit.m_exclusiveFullscreen = g_windowFullscreenCVar == 2;
  183. nwinit.m_targetFps = g_targetFpsCVar;
  184. NativeWindow::allocateSingleton();
  185. ANKI_CHECK(NativeWindow::getSingleton().init(nwinit));
  186. //
  187. // Input
  188. //
  189. Input::allocateSingleton();
  190. ANKI_CHECK(Input::getSingleton().init());
  191. //
  192. // ThreadPool
  193. //
  194. const Bool pinThreads = !ANKI_OS_ANDROID;
  195. CoreThreadJobManager::allocateSingleton(U32(g_jobThreadCountCVar), pinThreads);
  196. //
  197. // Graphics API
  198. //
  199. GrManagerInitInfo grInit;
  200. grInit.m_allocCallback = allocCb;
  201. grInit.m_allocCallbackUserData = allocCbUserData;
  202. grInit.m_cacheDirectory = m_cacheDir.toCString();
  203. ANKI_CHECK(GrManager::allocateSingleton().init(grInit));
  204. //
  205. // Mali HW counters
  206. //
  207. #if ANKI_PLATFORM_MOBILE
  208. if(ANKI_STATS_ENABLED && GrManager::getSingleton().getDeviceCapabilities().m_gpuVendor == GpuVendor::kArm && g_maliHwCountersCVar)
  209. {
  210. MaliHwCounters::allocateSingleton();
  211. }
  212. #endif
  213. //
  214. // GPU mem
  215. //
  216. UnifiedGeometryBuffer::allocateSingleton().init();
  217. GpuSceneBuffer::allocateSingleton().init();
  218. RebarTransientMemoryPool::allocateSingleton().init();
  219. GpuVisibleTransientMemoryPool::allocateSingleton();
  220. GpuReadbackMemoryPool::allocateSingleton();
  221. //
  222. // Physics
  223. //
  224. PhysicsWorld::allocateSingleton();
  225. ANKI_CHECK(PhysicsWorld::getSingleton().init(allocCb, allocCbUserData));
  226. //
  227. // Resources
  228. //
  229. #if !ANKI_OS_ANDROID
  230. // Add the location of the executable where the shaders are supposed to be
  231. String executableFname;
  232. ANKI_CHECK(getApplicationPath(executableFname));
  233. ANKI_CORE_LOGI("Executable path is: %s", executableFname.cstr());
  234. String extraPaths;
  235. getParentFilepath(executableFname, extraPaths);
  236. extraPaths += "|ankiprogbin"; // Shaders
  237. extraPaths += ":" ANKI_SOURCE_DIRECTORY "|EngineAssets,!AndroidProject"; // EngineAssets
  238. extraPaths += ":";
  239. extraPaths += g_dataPathsCVar;
  240. g_dataPathsCVar = extraPaths;
  241. #endif
  242. ANKI_CHECK(ResourceManager::allocateSingleton().init(allocCb, allocCbUserData));
  243. //
  244. // UI
  245. //
  246. ANKI_CHECK(UiManager::allocateSingleton().init(allocCb, allocCbUserData));
  247. //
  248. // GPU scene
  249. //
  250. ANKI_CHECK(GpuSceneMicroPatcher::allocateSingleton().init());
  251. //
  252. // Renderer
  253. //
  254. RendererInitInfo renderInit;
  255. renderInit.m_swapchainSize = UVec2(NativeWindow::getSingleton().getWidth(), NativeWindow::getSingleton().getHeight());
  256. renderInit.m_allocCallback = allocCb;
  257. renderInit.m_allocCallbackUserData = allocCbUserData;
  258. ANKI_CHECK(Renderer::allocateSingleton().init(renderInit));
  259. //
  260. // Script
  261. //
  262. ScriptManager::allocateSingleton(allocCb, allocCbUserData);
  263. //
  264. // Scene
  265. //
  266. ANKI_CHECK(SceneGraph::allocateSingleton().init(allocCb, allocCbUserData));
  267. ANKI_CORE_LOGI("Application initialized");
  268. return Error::kNone;
  269. }
  270. Error App::initDirs()
  271. {
  272. // Settings path
  273. #if !ANKI_OS_ANDROID
  274. String home;
  275. ANKI_CHECK(getHomeDirectory(home));
  276. m_settingsDir.sprintf("%s/.anki", &home[0]);
  277. #else
  278. m_settingsDir.sprintf("%s/.anki", g_androidApp->activity->internalDataPath);
  279. #endif
  280. if(!directoryExists(m_settingsDir.toCString()))
  281. {
  282. ANKI_CORE_LOGI("Creating settings dir \"%s\"", &m_settingsDir[0]);
  283. ANKI_CHECK(createDirectory(m_settingsDir.toCString()));
  284. }
  285. else
  286. {
  287. ANKI_CORE_LOGI("Using settings dir \"%s\"", &m_settingsDir[0]);
  288. }
  289. // Cache
  290. m_cacheDir.sprintf("%s/cache", &m_settingsDir[0]);
  291. const Bool cacheDirExists = directoryExists(m_cacheDir.toCString());
  292. if(g_clearCachesCVar && cacheDirExists)
  293. {
  294. ANKI_CORE_LOGI("Will delete the cache dir and start fresh: %s", m_cacheDir.cstr());
  295. ANKI_CHECK(removeDirectory(m_cacheDir.toCString()));
  296. ANKI_CHECK(createDirectory(m_cacheDir.toCString()));
  297. }
  298. else if(!cacheDirExists)
  299. {
  300. ANKI_CORE_LOGI("Will create cache dir: %s", m_cacheDir.cstr());
  301. ANKI_CHECK(createDirectory(m_cacheDir.toCString()));
  302. }
  303. return Error::kNone;
  304. }
  305. Error App::mainLoop()
  306. {
  307. ANKI_CORE_LOGI("Entering main loop");
  308. Bool quit = false;
  309. Second prevUpdateTime = HighRezTimer::getCurrentTime();
  310. Second crntTime = prevUpdateTime;
  311. // Benchmark mode stuff:
  312. const Bool benchmarkMode = g_benchmarkModeCVar;
  313. Second aggregatedCpuTime = 0.0;
  314. Second aggregatedGpuTime = 0.0;
  315. constexpr U32 kBenchmarkFramesToGatherBeforeFlush = 60;
  316. U32 benchmarkFramesGathered = 0;
  317. File benchmarkCsvFile;
  318. CoreString benchmarkCsvFileFilename;
  319. if(benchmarkMode)
  320. {
  321. benchmarkCsvFileFilename.sprintf("%s/Benchmark.csv", m_settingsDir.cstr());
  322. ANKI_CHECK(benchmarkCsvFile.open(benchmarkCsvFileFilename, FileOpenFlag::kWrite));
  323. ANKI_CHECK(benchmarkCsvFile.writeText("CPU, GPU\n"));
  324. }
  325. while(!quit)
  326. {
  327. {
  328. ANKI_TRACE_SCOPED_EVENT(Frame);
  329. const Second startTime = HighRezTimer::getCurrentTime();
  330. prevUpdateTime = crntTime;
  331. crntTime = (!benchmarkMode) ? HighRezTimer::getCurrentTime() : (prevUpdateTime + 1.0_sec / 60.0_sec);
  332. // Update
  333. ANKI_CHECK(Input::getSingleton().handleEvents());
  334. // User update
  335. ANKI_CHECK(userMainLoop(quit, crntTime - prevUpdateTime));
  336. SceneGraph::getSingleton().update(prevUpdateTime, crntTime);
  337. // Render
  338. TexturePtr presentableTex = GrManager::getSingleton().acquireNextPresentableTexture();
  339. ANKI_CHECK(Renderer::getSingleton().render(presentableTex.get()));
  340. // If we get stats exclude the time of GR because it forces some GPU-CPU serialization. We don't want to count that
  341. Second grTime = 0.0;
  342. if(benchmarkMode || g_displayStatsCVar > 0) [[unlikely]]
  343. {
  344. grTime = HighRezTimer::getCurrentTime();
  345. }
  346. GrManager::getSingleton().swapBuffers();
  347. if(benchmarkMode || g_displayStatsCVar > 0) [[unlikely]]
  348. {
  349. grTime = HighRezTimer::getCurrentTime() - grTime;
  350. }
  351. RebarTransientMemoryPool::getSingleton().endFrame();
  352. UnifiedGeometryBuffer::getSingleton().endFrame();
  353. GpuSceneBuffer::getSingleton().endFrame();
  354. GpuVisibleTransientMemoryPool::getSingleton().endFrame();
  355. GpuReadbackMemoryPool::getSingleton().endFrame();
  356. // Sleep
  357. const Second endTime = HighRezTimer::getCurrentTime();
  358. const Second frameTime = endTime - startTime;
  359. g_cpuTotalTimeStatVar.set((frameTime - grTime) * 1000.0);
  360. if(!benchmarkMode) [[likely]]
  361. {
  362. const Second timerTick = 1.0_sec / Second(g_targetFpsCVar);
  363. if(frameTime < timerTick)
  364. {
  365. ANKI_TRACE_SCOPED_EVENT(TimerTickSleep);
  366. HighRezTimer::sleep(timerTick - frameTime);
  367. }
  368. }
  369. // Benchmark stats
  370. else
  371. {
  372. aggregatedCpuTime += frameTime - grTime;
  373. aggregatedGpuTime += 0; // TODO
  374. ++benchmarkFramesGathered;
  375. if(benchmarkFramesGathered >= kBenchmarkFramesToGatherBeforeFlush)
  376. {
  377. aggregatedCpuTime = aggregatedCpuTime / Second(kBenchmarkFramesToGatherBeforeFlush) * 1000.0;
  378. aggregatedGpuTime = aggregatedGpuTime / Second(kBenchmarkFramesToGatherBeforeFlush) * 1000.0;
  379. ANKI_CHECK(benchmarkCsvFile.writeTextf("%f,%f\n", aggregatedCpuTime, aggregatedGpuTime));
  380. benchmarkFramesGathered = 0;
  381. aggregatedCpuTime = 0.0;
  382. aggregatedGpuTime = 0.0;
  383. }
  384. }
  385. // Stats
  386. #if ANKI_PLATFORM_MOBILE
  387. if(MaliHwCounters::isAllocated())
  388. {
  389. MaliHwCountersOut out;
  390. MaliHwCounters::getSingleton().sample(out);
  391. g_maliGpuActiveStatVar.set(out.m_gpuActive);
  392. g_maliGpuReadBandwidthStatVar.set(out.m_readBandwidth);
  393. g_maliGpuWriteBandwidthStatVar.set(out.m_writeBandwidth);
  394. }
  395. #endif
  396. StatsSet::getSingleton().endFrame();
  397. ++GlobalFrameIndex::getSingleton().m_value;
  398. if(benchmarkMode) [[unlikely]]
  399. {
  400. if(GlobalFrameIndex::getSingleton().m_value >= g_benchmarkModeFrameCountCVar)
  401. {
  402. quit = true;
  403. }
  404. }
  405. }
  406. #if ANKI_TRACING_ENABLED
  407. static U64 frame = 1;
  408. CoreTracer::getSingleton().flushFrame(frame++);
  409. #endif
  410. }
  411. if(benchmarkMode) [[unlikely]]
  412. {
  413. ANKI_CORE_LOGI("Benchmark file saved in: %s", benchmarkCsvFileFilename.cstr());
  414. }
  415. return Error::kNone;
  416. }
  417. void App::initMemoryCallbacks(AllocAlignedCallback& allocCb, void*& allocCbUserData)
  418. {
  419. if(ANKI_STATS_ENABLED && g_displayStatsCVar > 1)
  420. {
  421. allocCb = statsAllocCallback;
  422. allocCbUserData = this;
  423. }
  424. else
  425. {
  426. // Leave the default
  427. }
  428. }
  429. Bool App::toggleDeveloperConsole()
  430. {
  431. SceneNode& node = SceneGraph::getSingleton().findSceneNode("_DevConsole");
  432. static_cast<DeveloperConsoleUiNode&>(node).toggleConsole();
  433. m_consoleEnabled = static_cast<DeveloperConsoleUiNode&>(node).isConsoleEnabled();
  434. return m_consoleEnabled;
  435. }
  436. } // end namespace anki