BsCoreApplication.cpp 12 KB

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