| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523 |
- // Copyright (C) 2009-present, Panagiotis Christopoulos Charitos and contributors.
- // All rights reserved.
- // Code licensed under the BSD License.
- // http://www.anki3d.org/LICENSE
- #include <AnKi/Core/App.h>
- #include <AnKi/Util/CVarSet.h>
- #include <AnKi/GpuMemory/UnifiedGeometryBuffer.h>
- #include <AnKi/Util/Logger.h>
- #include <AnKi/Util/File.h>
- #include <AnKi/Util/Filesystem.h>
- #include <AnKi/Util/System.h>
- #include <AnKi/Util/Tracer.h>
- #include <AnKi/Util/HighRezTimer.h>
- #include <AnKi/Core/CoreTracer.h>
- #include <AnKi/GpuMemory/RebarTransientMemoryPool.h>
- #include <AnKi/GpuMemory/GpuVisibleTransientMemoryPool.h>
- #include <AnKi/GpuMemory/GpuReadbackMemoryPool.h>
- #include <AnKi/Core/StatsSet.h>
- #include <AnKi/Window/NativeWindow.h>
- #include <AnKi/Core/MaliHwCounters.h>
- #include <AnKi/Window/Input.h>
- #include <AnKi/Scene/SceneGraph.h>
- #include <AnKi/Resource/ResourceManager.h>
- #include <AnKi/Physics/PhysicsWorld.h>
- #include <AnKi/Renderer/Renderer.h>
- #include <AnKi/Script/ScriptManager.h>
- #include <AnKi/Resource/ResourceFilesystem.h>
- #include <AnKi/Resource/AsyncLoader.h>
- #include <AnKi/Ui/UiManager.h>
- #include <AnKi/Ui/Canvas.h>
- #include <AnKi/Scene/DeveloperConsoleUiNode.h>
- #include <csignal>
- #if ANKI_OS_ANDROID
- # include <android_native_app_glue.h>
- #endif
- namespace anki {
- #if ANKI_OS_ANDROID
- /// The one and only android hack
- android_app* g_androidApp = nullptr;
- #endif
- StatCounter g_cpuAllocatedMemStatVar(StatCategory::kCpuMem, "Total", StatFlag::kBytes);
- StatCounter g_cpuAllocationCountStatVar(StatCategory::kCpuMem, "Allocations/frame", StatFlag::kBytes | StatFlag::kZeroEveryFrame);
- StatCounter g_cpuFreesCountStatVar(StatCategory::kCpuMem, "Frees/frame", StatFlag::kBytes | StatFlag::kZeroEveryFrame);
- #if ANKI_PLATFORM_MOBILE
- inline StatCounter g_maliGpuActiveStatVar(StatCategory::kGpuMisc, "Mali active cycles", StatFlag::kMainThreadUpdates);
- inline StatCounter g_maliGpuReadBandwidthStatVar(StatCategory::kGpuMisc, "Mali read bandwidth", StatFlag::kMainThreadUpdates);
- inline StatCounter g_maliGpuWriteBandwidthStatVar(StatCategory::kGpuMisc, "Mali write bandwidth", StatFlag::kMainThreadUpdates);
- #endif
- void* App::statsAllocCallback(void* userData, void* ptr, PtrSize size, [[maybe_unused]] PtrSize alignment)
- {
- ANKI_ASSERT(userData);
- constexpr PtrSize kMaxAlignment = 64;
- struct alignas(kMaxAlignment) Header
- {
- PtrSize m_allocatedSize;
- Array<U8, kMaxAlignment - sizeof(PtrSize)> _m_padding;
- };
- static_assert(sizeof(Header) == kMaxAlignment, "See file");
- static_assert(alignof(Header) == kMaxAlignment, "See file");
- void* out = nullptr;
- if(ptr == nullptr)
- {
- // Need to allocate
- ANKI_ASSERT(size > 0);
- ANKI_ASSERT(alignment > 0 && alignment <= kMaxAlignment);
- const PtrSize newAlignment = kMaxAlignment;
- const PtrSize newSize = sizeof(Header) + size;
- // Allocate
- App* self = static_cast<App*>(userData);
- Header* allocation = static_cast<Header*>(self->m_originalAllocCallback(self->m_originalAllocUserData, nullptr, newSize, newAlignment));
- allocation->m_allocatedSize = size;
- ++allocation;
- out = static_cast<void*>(allocation);
- // Update stats
- g_cpuAllocatedMemStatVar.increment(size);
- g_cpuAllocationCountStatVar.increment(1);
- }
- else
- {
- // Need to free
- App* self = static_cast<App*>(userData);
- Header* allocation = static_cast<Header*>(ptr);
- --allocation;
- ANKI_ASSERT(allocation->m_allocatedSize > 0);
- // Update stats
- g_cpuAllocatedMemStatVar.decrement(allocation->m_allocatedSize);
- g_cpuFreesCountStatVar.increment(1);
- // Free
- self->m_originalAllocCallback(self->m_originalAllocUserData, allocation, 0, 0);
- }
- return out;
- }
- App::App(AllocAlignedCallback allocCb, void* allocCbUserData)
- {
- m_originalAllocCallback = allocCb;
- m_originalAllocUserData = allocCbUserData;
- }
- App::~App()
- {
- ANKI_CORE_LOGI("Destroying application");
- cleanup();
- }
- void App::cleanup()
- {
- SceneGraph::freeSingleton();
- ScriptManager::freeSingleton();
- Renderer::freeSingleton();
- UiManager::freeSingleton();
- GpuSceneMicroPatcher::freeSingleton();
- ResourceManager::freeSingleton();
- PhysicsWorld::freeSingleton();
- RebarTransientMemoryPool::freeSingleton();
- GpuVisibleTransientMemoryPool::freeSingleton();
- UnifiedGeometryBuffer::freeSingleton();
- GpuSceneBuffer::freeSingleton();
- GpuReadbackMemoryPool::freeSingleton();
- CoreThreadJobManager::freeSingleton();
- MaliHwCounters::freeSingleton();
- GrManager::freeSingleton();
- Input::freeSingleton();
- NativeWindow::freeSingleton();
- #if ANKI_TRACING_ENABLED
- CoreTracer::freeSingleton();
- #endif
- GlobalFrameIndex::freeSingleton();
- m_settingsDir.destroy();
- m_cacheDir.destroy();
- CoreMemoryPool::freeSingleton();
- DefaultMemoryPool::freeSingleton();
- ANKI_CORE_LOGI("Application finished shutting down");
- }
- Error App::init()
- {
- const Error err = initInternal();
- if(err)
- {
- ANKI_CORE_LOGE("App initialization failed. Shutting down");
- cleanup();
- }
- return err;
- }
- Error App::initInternal()
- {
- StatsSet::getSingleton().initFromMainThread();
- Logger::getSingleton().enableVerbosity(g_verboseLogCVar);
- AllocAlignedCallback allocCb = m_originalAllocCallback;
- void* allocCbUserData = m_originalAllocUserData;
- initMemoryCallbacks(allocCb, allocCbUserData);
- DefaultMemoryPool::allocateSingleton(allocCb, allocCbUserData);
- CoreMemoryPool::allocateSingleton(allocCb, allocCbUserData);
- ANKI_CHECK(initDirs());
- ANKI_CORE_LOGI("Initializing application. Build config: %s", kAnKiBuildConfigString);
- // Check SIMD support
- #if ANKI_SIMD_SSE && ANKI_COMPILER_GCC_COMPATIBLE
- if(!__builtin_cpu_supports("sse4.2"))
- {
- ANKI_CORE_LOGF("AnKi is built with sse4.2 support but your CPU doesn't support it. Try bulding without SSE support");
- }
- #endif
- ANKI_CORE_LOGI("Number of job threads: %u", U32(g_jobThreadCountCVar));
- if(g_benchmarkModeCVar && g_vsyncCVar)
- {
- ANKI_CORE_LOGW("Vsync is enabled and benchmark mode as well. Will turn vsync off");
- g_vsyncCVar = false;
- }
- GlobalFrameIndex::allocateSingleton();
- //
- // Core tracer
- //
- #if ANKI_TRACING_ENABLED
- ANKI_CHECK(CoreTracer::allocateSingleton().init(m_settingsDir));
- #endif
- //
- // Window
- //
- NativeWindowInitInfo nwinit;
- nwinit.m_width = g_windowWidthCVar;
- nwinit.m_height = g_windowHeightCVar;
- nwinit.m_depthBits = 0;
- nwinit.m_stencilBits = 0;
- nwinit.m_fullscreenDesktopRez = g_windowFullscreenCVar > 0;
- nwinit.m_exclusiveFullscreen = g_windowFullscreenCVar == 2;
- nwinit.m_targetFps = g_targetFpsCVar;
- NativeWindow::allocateSingleton();
- ANKI_CHECK(NativeWindow::getSingleton().init(nwinit));
- //
- // Input
- //
- Input::allocateSingleton();
- ANKI_CHECK(Input::getSingleton().init());
- //
- // ThreadPool
- //
- const Bool pinThreads = !ANKI_OS_ANDROID;
- CoreThreadJobManager::allocateSingleton(U32(g_jobThreadCountCVar), pinThreads);
- //
- // Graphics API
- //
- GrManagerInitInfo grInit;
- grInit.m_allocCallback = allocCb;
- grInit.m_allocCallbackUserData = allocCbUserData;
- grInit.m_cacheDirectory = m_cacheDir.toCString();
- ANKI_CHECK(GrManager::allocateSingleton().init(grInit));
- //
- // Mali HW counters
- //
- #if ANKI_PLATFORM_MOBILE
- if(ANKI_STATS_ENABLED && GrManager::getSingleton().getDeviceCapabilities().m_gpuVendor == GpuVendor::kArm && g_maliHwCountersCVar)
- {
- MaliHwCounters::allocateSingleton();
- }
- #endif
- //
- // GPU mem
- //
- UnifiedGeometryBuffer::allocateSingleton().init();
- GpuSceneBuffer::allocateSingleton().init();
- RebarTransientMemoryPool::allocateSingleton().init();
- GpuVisibleTransientMemoryPool::allocateSingleton();
- GpuReadbackMemoryPool::allocateSingleton();
- //
- // Physics
- //
- PhysicsWorld::allocateSingleton();
- ANKI_CHECK(PhysicsWorld::getSingleton().init(allocCb, allocCbUserData));
- //
- // Resources
- //
- #if !ANKI_OS_ANDROID
- // Add the location of the executable where the shaders are supposed to be
- String executableFname;
- ANKI_CHECK(getApplicationPath(executableFname));
- ANKI_CORE_LOGI("Executable path is: %s", executableFname.cstr());
- String extraPaths;
- getParentFilepath(executableFname, extraPaths);
- extraPaths += "|ankiprogbin"; // Shaders
- extraPaths += ":" ANKI_SOURCE_DIRECTORY "|EngineAssets,!AndroidProject"; // EngineAssets
- extraPaths += ":";
- extraPaths += g_dataPathsCVar;
- g_dataPathsCVar = extraPaths;
- #endif
- ANKI_CHECK(ResourceManager::allocateSingleton().init(allocCb, allocCbUserData));
- //
- // UI
- //
- ANKI_CHECK(UiManager::allocateSingleton().init(allocCb, allocCbUserData));
- //
- // GPU scene
- //
- ANKI_CHECK(GpuSceneMicroPatcher::allocateSingleton().init());
- //
- // Renderer
- //
- RendererInitInfo renderInit;
- renderInit.m_swapchainSize = UVec2(NativeWindow::getSingleton().getWidth(), NativeWindow::getSingleton().getHeight());
- renderInit.m_allocCallback = allocCb;
- renderInit.m_allocCallbackUserData = allocCbUserData;
- ANKI_CHECK(Renderer::allocateSingleton().init(renderInit));
- //
- // Script
- //
- ScriptManager::allocateSingleton(allocCb, allocCbUserData);
- //
- // Scene
- //
- ANKI_CHECK(SceneGraph::allocateSingleton().init(allocCb, allocCbUserData));
- ANKI_CORE_LOGI("Application initialized");
- return Error::kNone;
- }
- Error App::initDirs()
- {
- // Settings path
- #if !ANKI_OS_ANDROID
- String home;
- ANKI_CHECK(getHomeDirectory(home));
- m_settingsDir.sprintf("%s/.anki", &home[0]);
- #else
- m_settingsDir.sprintf("%s/.anki", g_androidApp->activity->internalDataPath);
- #endif
- if(!directoryExists(m_settingsDir.toCString()))
- {
- ANKI_CORE_LOGI("Creating settings dir \"%s\"", &m_settingsDir[0]);
- ANKI_CHECK(createDirectory(m_settingsDir.toCString()));
- }
- else
- {
- ANKI_CORE_LOGI("Using settings dir \"%s\"", &m_settingsDir[0]);
- }
- // Cache
- m_cacheDir.sprintf("%s/cache", &m_settingsDir[0]);
- const Bool cacheDirExists = directoryExists(m_cacheDir.toCString());
- if(g_clearCachesCVar && cacheDirExists)
- {
- ANKI_CORE_LOGI("Will delete the cache dir and start fresh: %s", m_cacheDir.cstr());
- ANKI_CHECK(removeDirectory(m_cacheDir.toCString()));
- ANKI_CHECK(createDirectory(m_cacheDir.toCString()));
- }
- else if(!cacheDirExists)
- {
- ANKI_CORE_LOGI("Will create cache dir: %s", m_cacheDir.cstr());
- ANKI_CHECK(createDirectory(m_cacheDir.toCString()));
- }
- return Error::kNone;
- }
- Error App::mainLoop()
- {
- ANKI_CORE_LOGI("Entering main loop");
- Bool quit = false;
- Second prevUpdateTime = HighRezTimer::getCurrentTime();
- Second crntTime = prevUpdateTime;
- // Benchmark mode stuff:
- const Bool benchmarkMode = g_benchmarkModeCVar;
- Second aggregatedCpuTime = 0.0;
- Second aggregatedGpuTime = 0.0;
- constexpr U32 kBenchmarkFramesToGatherBeforeFlush = 60;
- U32 benchmarkFramesGathered = 0;
- File benchmarkCsvFile;
- CoreString benchmarkCsvFileFilename;
- if(benchmarkMode)
- {
- benchmarkCsvFileFilename.sprintf("%s/Benchmark.csv", m_settingsDir.cstr());
- ANKI_CHECK(benchmarkCsvFile.open(benchmarkCsvFileFilename, FileOpenFlag::kWrite));
- ANKI_CHECK(benchmarkCsvFile.writeText("CPU, GPU\n"));
- }
- while(!quit)
- {
- {
- ANKI_TRACE_SCOPED_EVENT(Frame);
- const Second startTime = HighRezTimer::getCurrentTime();
- prevUpdateTime = crntTime;
- crntTime = (!benchmarkMode) ? HighRezTimer::getCurrentTime() : (prevUpdateTime + 1.0_sec / 60.0_sec);
- // Update
- ANKI_CHECK(Input::getSingleton().handleEvents());
- // User update
- ANKI_CHECK(userMainLoop(quit, crntTime - prevUpdateTime));
- SceneGraph::getSingleton().update(prevUpdateTime, crntTime);
- // Render
- TexturePtr presentableTex = GrManager::getSingleton().acquireNextPresentableTexture();
- ANKI_CHECK(Renderer::getSingleton().render(presentableTex.get()));
- // If we get stats exclude the time of GR because it forces some GPU-CPU serialization. We don't want to count that
- Second grTime = 0.0;
- if(benchmarkMode || g_displayStatsCVar > 0) [[unlikely]]
- {
- grTime = HighRezTimer::getCurrentTime();
- }
- GrManager::getSingleton().swapBuffers();
- if(benchmarkMode || g_displayStatsCVar > 0) [[unlikely]]
- {
- grTime = HighRezTimer::getCurrentTime() - grTime;
- }
- RebarTransientMemoryPool::getSingleton().endFrame();
- UnifiedGeometryBuffer::getSingleton().endFrame();
- GpuSceneBuffer::getSingleton().endFrame();
- GpuVisibleTransientMemoryPool::getSingleton().endFrame();
- GpuReadbackMemoryPool::getSingleton().endFrame();
- // Sleep
- const Second endTime = HighRezTimer::getCurrentTime();
- const Second frameTime = endTime - startTime;
- g_cpuTotalTimeStatVar.set((frameTime - grTime) * 1000.0);
- if(!benchmarkMode) [[likely]]
- {
- const Second timerTick = 1.0_sec / Second(g_targetFpsCVar);
- if(frameTime < timerTick)
- {
- ANKI_TRACE_SCOPED_EVENT(TimerTickSleep);
- HighRezTimer::sleep(timerTick - frameTime);
- }
- }
- // Benchmark stats
- else
- {
- aggregatedCpuTime += frameTime - grTime;
- aggregatedGpuTime += 0; // TODO
- ++benchmarkFramesGathered;
- if(benchmarkFramesGathered >= kBenchmarkFramesToGatherBeforeFlush)
- {
- aggregatedCpuTime = aggregatedCpuTime / Second(kBenchmarkFramesToGatherBeforeFlush) * 1000.0;
- aggregatedGpuTime = aggregatedGpuTime / Second(kBenchmarkFramesToGatherBeforeFlush) * 1000.0;
- ANKI_CHECK(benchmarkCsvFile.writeTextf("%f,%f\n", aggregatedCpuTime, aggregatedGpuTime));
- benchmarkFramesGathered = 0;
- aggregatedCpuTime = 0.0;
- aggregatedGpuTime = 0.0;
- }
- }
- // Stats
- #if ANKI_PLATFORM_MOBILE
- if(MaliHwCounters::isAllocated())
- {
- MaliHwCountersOut out;
- MaliHwCounters::getSingleton().sample(out);
- g_maliGpuActiveStatVar.set(out.m_gpuActive);
- g_maliGpuReadBandwidthStatVar.set(out.m_readBandwidth);
- g_maliGpuWriteBandwidthStatVar.set(out.m_writeBandwidth);
- }
- #endif
- StatsSet::getSingleton().endFrame();
- ++GlobalFrameIndex::getSingleton().m_value;
- if(benchmarkMode) [[unlikely]]
- {
- if(GlobalFrameIndex::getSingleton().m_value >= g_benchmarkModeFrameCountCVar)
- {
- quit = true;
- }
- }
- }
- #if ANKI_TRACING_ENABLED
- static U64 frame = 1;
- CoreTracer::getSingleton().flushFrame(frame++);
- #endif
- }
- if(benchmarkMode) [[unlikely]]
- {
- ANKI_CORE_LOGI("Benchmark file saved in: %s", benchmarkCsvFileFilename.cstr());
- }
- return Error::kNone;
- }
- void App::initMemoryCallbacks(AllocAlignedCallback& allocCb, void*& allocCbUserData)
- {
- if(ANKI_STATS_ENABLED && g_displayStatsCVar > 1)
- {
- allocCb = statsAllocCallback;
- allocCbUserData = this;
- }
- else
- {
- // Leave the default
- }
- }
- Bool App::toggleDeveloperConsole()
- {
- SceneNode& node = SceneGraph::getSingleton().findSceneNode("_DevConsole");
- static_cast<DeveloperConsoleUiNode&>(node).toggleConsole();
- m_consoleEnabled = static_cast<DeveloperConsoleUiNode&>(node).isConsoleEnabled();
- return m_consoleEnabled;
- }
- } // end namespace anki
|