BsCoreApplication.cpp 11 KB

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