BsCoreApplication.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsCoreApplication.h"
  4. #include "RenderAPI/BsRenderAPI.h"
  5. #include "Managers/BsRenderAPIManager.h"
  6. #include "Platform/BsPlatform.h"
  7. #include "Managers/BsHardwareBufferManager.h"
  8. #include "RenderAPI/BsRenderWindow.h"
  9. #include "RenderAPI/BsViewport.h"
  10. #include "Math/BsVector2.h"
  11. #include "RenderAPI/BsGpuProgram.h"
  12. #include "CoreThread/BsCoreObjectManager.h"
  13. #include "Scene/BsGameObjectManager.h"
  14. #include "Utility/BsDynLib.h"
  15. #include "Utility/BsDynLibManager.h"
  16. #include "Scene/BsSceneManager.h"
  17. #include "Importer/BsImporter.h"
  18. #include "Resources/BsResources.h"
  19. #include "Mesh/BsMesh.h"
  20. #include "Scene/BsSceneObject.h"
  21. #include "Utility/BsTime.h"
  22. #include "Input/BsInput.h"
  23. #include "Renderer/BsRendererManager.h"
  24. #include "Managers/BsGpuProgramManager.h"
  25. #include "Managers/BsMeshManager.h"
  26. #include "Material/BsMaterialManager.h"
  27. #include "Text/BsFontManager.h"
  28. #include "Managers/BsRenderWindowManager.h"
  29. #include "Renderer/BsRenderer.h"
  30. #include "Utility/BsDeferredCallManager.h"
  31. #include "CoreThread/BsCoreThread.h"
  32. #include "Localization/BsStringTableManager.h"
  33. #include "Profiling/BsProfilingManager.h"
  34. #include "Profiling/BsProfilerCPU.h"
  35. #include "Profiling/BsProfilerGPU.h"
  36. #include "Managers/BsQueryManager.h"
  37. #include "Threading/BsThreadPool.h"
  38. #include "Threading/BsTaskScheduler.h"
  39. #include "Profiling/BsRenderStats.h"
  40. #include "Utility/BsMessageHandler.h"
  41. #include "Managers/BsResourceListenerManager.h"
  42. #include "Managers/BsRenderStateManager.h"
  43. #include "Material/BsShaderManager.h"
  44. #include "Physics/BsPhysicsManager.h"
  45. #include "Physics/BsPhysics.h"
  46. #include "Audio/BsAudioManager.h"
  47. #include "Audio/BsAudio.h"
  48. #include "Animation/BsAnimationManager.h"
  49. #include "Renderer/BsParamBlocks.h"
  50. namespace bs
  51. {
  52. CoreApplication::CoreApplication(START_UP_DESC desc)
  53. : mPrimaryWindow(nullptr), mStartUpDesc(desc), mFrameStep(16666), mLastFrameTime(0), mRendererPlugin(nullptr)
  54. , mIsFrameRenderingFinished(true), mSimThreadId(BS_THREAD_CURRENT_ID), mRunMainLoop(false)
  55. {
  56. // Ensure all errors are reported properly
  57. CrashHandler::startUp();
  58. }
  59. CoreApplication::~CoreApplication()
  60. {
  61. mPrimaryWindow->destroy();
  62. mPrimaryWindow = nullptr;
  63. Importer::shutDown();
  64. FontManager::shutDown();
  65. MaterialManager::shutDown();
  66. MeshManager::shutDown();
  67. ProfilerGPU::shutDown();
  68. SceneManager::shutDown();
  69. Input::shutDown();
  70. ct::ParamBlockManager::shutDown();
  71. StringTableManager::shutDown();
  72. Resources::shutDown();
  73. GameObjectManager::shutDown();
  74. ResourceListenerManager::shutDown();
  75. RenderStateManager::shutDown();
  76. // This must be done after all resources are released since it will unload the physics plugin, and some resources
  77. // might be instances of types from that plugin.
  78. AnimationManager::shutDown();
  79. PhysicsManager::shutDown();
  80. AudioManager::shutDown();
  81. RendererManager::shutDown();
  82. // All CoreObject related modules should be shut down now. They have likely queued CoreObjects for destruction, so
  83. // we need to wait for those objects to get destroyed before continuing.
  84. CoreObjectManager::instance().syncToCore();
  85. gCoreThread().update();
  86. gCoreThread().submitAll(true);
  87. unloadPlugin(mRendererPlugin);
  88. RenderAPIManager::shutDown();
  89. ct::GpuProgramManager::shutDown();
  90. GpuProgramManager::shutDown();
  91. CoreObjectManager::shutDown(); // Must shut down before DynLibManager to ensure all objects are destroyed before unloading their libraries
  92. DynLibManager::shutDown();
  93. Time::shutDown();
  94. DeferredCallManager::shutDown();
  95. CoreThread::shutDown();
  96. RenderStats::shutDown();
  97. TaskScheduler::shutDown();
  98. ThreadPool::shutDown();
  99. ProfilingManager::shutDown();
  100. ProfilerCPU::shutDown();
  101. MessageHandler::shutDown();
  102. ShaderManager::shutDown();
  103. MemStack::endThread();
  104. Platform::_shutDown();
  105. CrashHandler::shutDown();
  106. }
  107. void CoreApplication::onStartUp()
  108. {
  109. UINT32 numWorkerThreads = BS_THREAD_HARDWARE_CONCURRENCY - 1; // Number of cores while excluding current thread.
  110. Platform::_startUp();
  111. MemStack::beginThread();
  112. ShaderManager::startUp(getShaderIncludeHandler());
  113. MessageHandler::startUp();
  114. ProfilerCPU::startUp();
  115. ProfilingManager::startUp();
  116. ThreadPool::startUp<TThreadPool<ThreadBansheePolicy>>((numWorkerThreads));
  117. TaskScheduler::startUp();
  118. TaskScheduler::instance().removeWorker();
  119. RenderStats::startUp();
  120. CoreThread::startUp();
  121. StringTableManager::startUp();
  122. DeferredCallManager::startUp();
  123. Time::startUp();
  124. DynLibManager::startUp();
  125. CoreObjectManager::startUp();
  126. GameObjectManager::startUp();
  127. Resources::startUp();
  128. ResourceListenerManager::startUp();
  129. GpuProgramManager::startUp();
  130. RenderStateManager::startUp();
  131. ct::GpuProgramManager::startUp();
  132. RenderAPIManager::startUp();
  133. mPrimaryWindow = RenderAPIManager::instance().initialize(mStartUpDesc.renderAPI, mStartUpDesc.primaryWindowDesc);
  134. ct::ParamBlockManager::startUp();
  135. Input::startUp();
  136. RendererManager::startUp();
  137. loadPlugin(mStartUpDesc.renderer, &mRendererPlugin);
  138. SceneManager::startUp();
  139. RendererManager::instance().setActive(mStartUpDesc.renderer);
  140. startUpRenderer();
  141. ProfilerGPU::startUp();
  142. MeshManager::startUp();
  143. MaterialManager::startUp();
  144. FontManager::startUp();
  145. Importer::startUp();
  146. AudioManager::startUp(mStartUpDesc.audio);
  147. PhysicsManager::startUp(mStartUpDesc.physics, isEditor());
  148. AnimationManager::startUp();
  149. for (auto& importerName : mStartUpDesc.importers)
  150. loadPlugin(importerName);
  151. }
  152. void CoreApplication::runMainLoop()
  153. {
  154. mRunMainLoop = true;
  155. while(mRunMainLoop)
  156. {
  157. // Limit FPS if needed
  158. if (mFrameStep > 0)
  159. {
  160. UINT64 currentTime = gTime().getTimePrecise();
  161. UINT64 nextFrameTime = mLastFrameTime + mFrameStep;
  162. while (nextFrameTime > currentTime)
  163. {
  164. UINT32 waitTime = (UINT32)(nextFrameTime - currentTime);
  165. // If waiting for longer, sleep
  166. if (waitTime >= 2000)
  167. {
  168. Platform::sleep(waitTime / 1000);
  169. currentTime = gTime().getTimePrecise();
  170. }
  171. else
  172. {
  173. // Otherwise we just spin, sleep timer granularity is too low and we might end up wasting a
  174. // millisecond otherwise.
  175. // Note: For mobiles where power might be more important than input latency, consider using sleep.
  176. while(nextFrameTime > currentTime)
  177. currentTime = gTime().getTimePrecise();
  178. }
  179. }
  180. mLastFrameTime = currentTime;
  181. }
  182. gProfilerCPU().beginThread("Sim");
  183. Platform::_update();
  184. DeferredCallManager::instance()._update();
  185. gTime()._update();
  186. gInput()._update();
  187. // RenderWindowManager::update needs to happen after Input::update and before Input::_triggerCallbacks,
  188. // so that all input is properly captured in case there is a focus change, and so that
  189. // focus change is registered before input events are sent out (mouse press can result in code
  190. // checking if a window is in focus, so it has to be up to date)
  191. RenderWindowManager::instance()._update();
  192. gInput()._triggerCallbacks();
  193. gDebug()._triggerCallbacks();
  194. AnimationManager::instance().preUpdate();
  195. preUpdate();
  196. PROFILE_CALL(gSceneManager()._update(), "SceneManager");
  197. gAudio()._update();
  198. gPhysics().update();
  199. AnimationManager::instance().postUpdate();
  200. // Update plugins
  201. for (auto& pluginUpdateFunc : mPluginUpdateFunctions)
  202. pluginUpdateFunc.second();
  203. postUpdate();
  204. // Send out resource events in case any were loaded/destroyed/modified
  205. ResourceListenerManager::instance().update();
  206. // Trigger any renderer task callbacks (should be done before scene object update, or core sync, so objects have
  207. // a chance to respond to the callback).
  208. RendererManager::instance().getActive()->update();
  209. gSceneManager()._updateCoreObjectTransforms();
  210. PROFILE_CALL(RendererManager::instance().getActive()->renderAll(), "Render");
  211. // Core and sim thread run in lockstep. This will result in a larger input latency than if I was
  212. // running just a single thread. Latency becomes worse if the core thread takes longer than sim
  213. // thread, in which case sim thread needs to wait. Optimal solution would be to get an average
  214. // difference between sim/core thread and start the sim thread a bit later so they finish at nearly the same time.
  215. {
  216. Lock lock(mFrameRenderingFinishedMutex);
  217. while(!mIsFrameRenderingFinished)
  218. {
  219. TaskScheduler::instance().addWorker();
  220. mFrameRenderingFinishedCondition.wait(lock);
  221. TaskScheduler::instance().removeWorker();
  222. }
  223. mIsFrameRenderingFinished = false;
  224. }
  225. gCoreThread().queueCommand(std::bind(&CoreApplication::beginCoreProfiling, this), CTQF_InternalQueue);
  226. gCoreThread().queueCommand(&Platform::_coreUpdate, CTQF_InternalQueue);
  227. gCoreThread().update();
  228. gCoreThread().submitAll();
  229. gCoreThread().queueCommand(std::bind(&CoreApplication::frameRenderingFinishedCallback, this), CTQF_InternalQueue);
  230. gCoreThread().queueCommand(std::bind(&ct::RenderWindowManager::_update, ct::RenderWindowManager::instancePtr()), CTQF_InternalQueue);
  231. gCoreThread().queueCommand(std::bind(&ct::QueryManager::_update, ct::QueryManager::instancePtr()), CTQF_InternalQueue);
  232. gCoreThread().queueCommand(std::bind(&CoreApplication::endCoreProfiling, this), CTQF_InternalQueue);
  233. gProfilerCPU().endThread();
  234. gProfiler()._update();
  235. }
  236. // Wait until last core frame is finished before exiting
  237. {
  238. Lock lock(mFrameRenderingFinishedMutex);
  239. while (!mIsFrameRenderingFinished)
  240. {
  241. TaskScheduler::instance().addWorker();
  242. mFrameRenderingFinishedCondition.wait(lock);
  243. TaskScheduler::instance().removeWorker();
  244. }
  245. }
  246. }
  247. void CoreApplication::preUpdate()
  248. {
  249. // Do nothing
  250. }
  251. void CoreApplication::postUpdate()
  252. {
  253. // Do nothing
  254. }
  255. void CoreApplication::stopMainLoop()
  256. {
  257. mRunMainLoop = false; // No sync primitives needed, in that rare case of
  258. // a race condition we might run the loop one extra iteration which is acceptable
  259. }
  260. void CoreApplication::quitRequested()
  261. {
  262. stopMainLoop();
  263. }
  264. void CoreApplication::setFPSLimit(UINT32 limit)
  265. {
  266. mFrameStep = (UINT64)1000000 / limit;
  267. }
  268. void CoreApplication::frameRenderingFinishedCallback()
  269. {
  270. Lock lock(mFrameRenderingFinishedMutex);
  271. mIsFrameRenderingFinished = true;
  272. mFrameRenderingFinishedCondition.notify_one();
  273. }
  274. void CoreApplication::startUpRenderer()
  275. {
  276. RendererManager::instance().initialize();
  277. }
  278. void CoreApplication::beginCoreProfiling()
  279. {
  280. gProfilerCPU().beginThread("Core");
  281. }
  282. void CoreApplication::endCoreProfiling()
  283. {
  284. ProfilerGPU::instance()._update();
  285. gProfilerCPU().endThread();
  286. gProfiler()._updateCore();
  287. }
  288. void* CoreApplication::loadPlugin(const String& pluginName, DynLib** library, void* passThrough)
  289. {
  290. DynLib* loadedLibrary = gDynLibManager().load(pluginName);
  291. if(library != nullptr)
  292. *library = loadedLibrary;
  293. void* retVal = nullptr;
  294. if(loadedLibrary != nullptr)
  295. {
  296. if (passThrough == nullptr)
  297. {
  298. typedef void* (*LoadPluginFunc)();
  299. LoadPluginFunc loadPluginFunc = (LoadPluginFunc)loadedLibrary->getSymbol("loadPlugin");
  300. if (loadPluginFunc != nullptr)
  301. retVal = loadPluginFunc();
  302. }
  303. else
  304. {
  305. typedef void* (*LoadPluginFunc)(void*);
  306. LoadPluginFunc loadPluginFunc = (LoadPluginFunc)loadedLibrary->getSymbol("loadPlugin");
  307. if (loadPluginFunc != nullptr)
  308. retVal = loadPluginFunc(passThrough);
  309. }
  310. UpdatePluginFunc loadPluginFunc = (UpdatePluginFunc)loadedLibrary->getSymbol("updatePlugin");
  311. if (loadPluginFunc != nullptr)
  312. mPluginUpdateFunctions[loadedLibrary] = loadPluginFunc;
  313. }
  314. return retVal;
  315. }
  316. void CoreApplication::unloadPlugin(DynLib* library)
  317. {
  318. typedef void (*UnloadPluginFunc)();
  319. UnloadPluginFunc unloadPluginFunc = (UnloadPluginFunc)library->getSymbol("unloadPlugin");
  320. if(unloadPluginFunc != nullptr)
  321. unloadPluginFunc();
  322. mPluginUpdateFunctions.erase(library);
  323. gDynLibManager().unload(library);
  324. }
  325. SPtr<IShaderIncludeHandler> CoreApplication::getShaderIncludeHandler() const
  326. {
  327. return bs_shared_ptr_new<DefaultShaderIncludeHandler>();
  328. }
  329. CoreApplication& gCoreApplication()
  330. {
  331. return CoreApplication::instance();
  332. }
  333. }