BsCoreApplication.cpp 12 KB

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