App.cpp 14 KB

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