Engine.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  1. //
  2. // Copyright (c) 2008-2017 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Audio/Audio.h"
  24. #include "../Core/Context.h"
  25. #include "../Core/CoreEvents.h"
  26. #include "../Core/EventProfiler.h"
  27. #include "../Core/ProcessUtils.h"
  28. #include "../Core/WorkQueue.h"
  29. #include "../Engine/Console.h"
  30. #include "../Engine/DebugHud.h"
  31. #include "../Engine/Engine.h"
  32. #include "../Engine/EngineDefs.h"
  33. #include "../Graphics/Graphics.h"
  34. #include "../Graphics/Renderer.h"
  35. #include "../Input/Input.h"
  36. #include "../IO/FileSystem.h"
  37. #include "../IO/Log.h"
  38. #include "../IO/PackageFile.h"
  39. #ifdef URHO3D_NAVIGATION
  40. #include "../Navigation/NavigationMesh.h"
  41. #endif
  42. #ifdef URHO3D_NETWORK
  43. #include "../Network/Network.h"
  44. #endif
  45. #ifdef URHO3D_DATABASE
  46. #include "../Database/Database.h"
  47. #endif
  48. #ifdef URHO3D_PHYSICS
  49. #include "../Physics/PhysicsWorld.h"
  50. #endif
  51. #include "../Resource/ResourceCache.h"
  52. #include "../Resource/Localization.h"
  53. #include "../Scene/Scene.h"
  54. #include "../Scene/SceneEvents.h"
  55. #include "../UI/UI.h"
  56. #ifdef URHO3D_URHO2D
  57. #include "../Urho2D/Urho2D.h"
  58. #endif
  59. #if defined(__EMSCRIPTEN__) && defined(URHO3D_TESTING)
  60. #include <emscripten/emscripten.h>
  61. #endif
  62. #include "../DebugNew.h"
  63. #if defined(_MSC_VER) && defined(_DEBUG)
  64. // From dbgint.h
  65. #define nNoMansLandSize 4
  66. typedef struct _CrtMemBlockHeader
  67. {
  68. struct _CrtMemBlockHeader* pBlockHeaderNext;
  69. struct _CrtMemBlockHeader* pBlockHeaderPrev;
  70. char* szFileName;
  71. int nLine;
  72. size_t nDataSize;
  73. int nBlockUse;
  74. long lRequest;
  75. unsigned char gap[nNoMansLandSize];
  76. } _CrtMemBlockHeader;
  77. #endif
  78. namespace Urho3D
  79. {
  80. extern const char* logLevelPrefixes[];
  81. Engine::Engine(Context* context) :
  82. Object(context),
  83. timeStep_(0.0f),
  84. timeStepSmoothing_(2),
  85. minFps_(10),
  86. #if defined(IOS) || defined(__ANDROID__) || defined(__arm__) || defined(__aarch64__)
  87. maxFps_(60),
  88. maxInactiveFps_(10),
  89. pauseMinimized_(true),
  90. #else
  91. maxFps_(200),
  92. maxInactiveFps_(60),
  93. pauseMinimized_(false),
  94. #endif
  95. #ifdef URHO3D_TESTING
  96. timeOut_(0),
  97. #endif
  98. autoExit_(true),
  99. initialized_(false),
  100. exiting_(false),
  101. headless_(false),
  102. audioPaused_(false)
  103. {
  104. // Register self as a subsystem
  105. context_->RegisterSubsystem(this);
  106. // Create subsystems which do not depend on engine initialization or startup parameters
  107. context_->RegisterSubsystem(new Time(context_));
  108. context_->RegisterSubsystem(new WorkQueue(context_));
  109. #ifdef URHO3D_PROFILING
  110. context_->RegisterSubsystem(new Profiler(context_));
  111. #endif
  112. context_->RegisterSubsystem(new FileSystem(context_));
  113. #ifdef URHO3D_LOGGING
  114. context_->RegisterSubsystem(new Log(context_));
  115. #endif
  116. context_->RegisterSubsystem(new ResourceCache(context_));
  117. context_->RegisterSubsystem(new Localization(context_));
  118. #ifdef URHO3D_NETWORK
  119. context_->RegisterSubsystem(new Network(context_));
  120. #endif
  121. #ifdef URHO3D_DATABASE
  122. context_->RegisterSubsystem(new Database(context_));
  123. #endif
  124. context_->RegisterSubsystem(new Input(context_));
  125. context_->RegisterSubsystem(new Audio(context_));
  126. context_->RegisterSubsystem(new UI(context_));
  127. // Register object factories for libraries which are not automatically registered along with subsystem creation
  128. RegisterSceneLibrary(context_);
  129. #ifdef URHO3D_PHYSICS
  130. RegisterPhysicsLibrary(context_);
  131. #endif
  132. #ifdef URHO3D_NAVIGATION
  133. RegisterNavigationLibrary(context_);
  134. #endif
  135. SubscribeToEvent(E_EXITREQUESTED, URHO3D_HANDLER(Engine, HandleExitRequested));
  136. }
  137. Engine::~Engine()
  138. {
  139. }
  140. bool Engine::Initialize(const VariantMap& parameters)
  141. {
  142. if (initialized_)
  143. return true;
  144. URHO3D_PROFILE(InitEngine);
  145. // Set headless mode
  146. headless_ = GetParameter(parameters, EP_HEADLESS, false).GetBool();
  147. // Register the rest of the subsystems
  148. if (!headless_)
  149. {
  150. context_->RegisterSubsystem(new Graphics(context_));
  151. context_->RegisterSubsystem(new Renderer(context_));
  152. }
  153. else
  154. {
  155. // Register graphics library objects explicitly in headless mode to allow them to work without using actual GPU resources
  156. RegisterGraphicsLibrary(context_);
  157. }
  158. #ifdef URHO3D_URHO2D
  159. // 2D graphics library is dependent on 3D graphics library
  160. RegisterUrho2DLibrary(context_);
  161. #endif
  162. // Start logging
  163. Log* log = GetSubsystem<Log>();
  164. if (log)
  165. {
  166. if (HasParameter(parameters, EP_LOG_LEVEL))
  167. log->SetLevel(GetParameter(parameters, EP_LOG_LEVEL).GetInt());
  168. log->SetQuiet(GetParameter(parameters, EP_LOG_QUIET, false).GetBool());
  169. log->Open(GetParameter(parameters, EP_LOG_NAME, "Urho3D.log").GetString());
  170. }
  171. // Set maximally accurate low res timer
  172. GetSubsystem<Time>()->SetTimerPeriod(1);
  173. // Configure max FPS
  174. if (GetParameter(parameters, EP_FRAME_LIMITER, true) == false)
  175. SetMaxFps(0);
  176. // Set amount of worker threads according to the available physical CPU cores. Using also hyperthreaded cores results in
  177. // unpredictable extra synchronization overhead. Also reserve one core for the main thread
  178. #ifdef URHO3D_THREADING
  179. unsigned numThreads = GetParameter(parameters, EP_WORKER_THREADS, true).GetBool() ? GetNumPhysicalCPUs() - 1 : 0;
  180. if (numThreads)
  181. {
  182. GetSubsystem<WorkQueue>()->CreateThreads(numThreads);
  183. URHO3D_LOGINFOF("Created %u worker thread%s", numThreads, numThreads > 1 ? "s" : "");
  184. }
  185. #endif
  186. // Add resource paths
  187. if (!InitializeResourceCache(parameters, false))
  188. return false;
  189. ResourceCache* cache = GetSubsystem<ResourceCache>();
  190. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  191. // Initialize graphics & audio output
  192. if (!headless_)
  193. {
  194. Graphics* graphics = GetSubsystem<Graphics>();
  195. Renderer* renderer = GetSubsystem<Renderer>();
  196. if (HasParameter(parameters, EP_EXTERNAL_WINDOW))
  197. graphics->SetExternalWindow(GetParameter(parameters, EP_EXTERNAL_WINDOW).GetVoidPtr());
  198. graphics->SetWindowTitle(GetParameter(parameters, EP_WINDOW_TITLE, "Urho3D").GetString());
  199. graphics->SetWindowIcon(cache->GetResource<Image>(GetParameter(parameters, EP_WINDOW_ICON, String::EMPTY).GetString()));
  200. graphics->SetFlushGPU(GetParameter(parameters, EP_FLUSH_GPU, false).GetBool());
  201. graphics->SetOrientations(GetParameter(parameters, EP_ORIENTATIONS, "LandscapeLeft LandscapeRight").GetString());
  202. if (HasParameter(parameters, EP_WINDOW_POSITION_X) && HasParameter(parameters, EP_WINDOW_POSITION_Y))
  203. graphics->SetWindowPosition(GetParameter(parameters, EP_WINDOW_POSITION_X).GetInt(),
  204. GetParameter(parameters, EP_WINDOW_POSITION_Y).GetInt());
  205. #ifdef URHO3D_OPENGL
  206. if (HasParameter(parameters, EP_FORCE_GL2))
  207. graphics->SetForceGL2(GetParameter(parameters, EP_FORCE_GL2).GetBool());
  208. #endif
  209. if (!graphics->SetMode(
  210. GetParameter(parameters, EP_WINDOW_WIDTH, 0).GetInt(),
  211. GetParameter(parameters, EP_WINDOW_HEIGHT, 0).GetInt(),
  212. GetParameter(parameters, EP_FULL_SCREEN, true).GetBool(),
  213. GetParameter(parameters, EP_BORDERLESS, false).GetBool(),
  214. GetParameter(parameters, EP_WINDOW_RESIZABLE, false).GetBool(),
  215. GetParameter(parameters, EP_HIGH_DPI, true).GetBool(),
  216. GetParameter(parameters, EP_VSYNC, false).GetBool(),
  217. GetParameter(parameters, EP_TRIPLE_BUFFER, false).GetBool(),
  218. GetParameter(parameters, EP_MULTI_SAMPLE, 1).GetInt(),
  219. GetParameter(parameters, EP_MONITOR, 0).GetInt(),
  220. GetParameter(parameters, EP_REFRESH_RATE, 0).GetInt()
  221. ))
  222. return false;
  223. graphics->SetShaderCacheDir(GetParameter(parameters, EP_SHADER_CACHE_DIR, fileSystem->GetAppPreferencesDir("urho3d", "shadercache")).GetString());
  224. if (HasParameter(parameters, EP_DUMP_SHADERS))
  225. graphics->BeginDumpShaders(GetParameter(parameters, EP_DUMP_SHADERS, String::EMPTY).GetString());
  226. if (HasParameter(parameters, EP_RENDER_PATH))
  227. renderer->SetDefaultRenderPath(cache->GetResource<XMLFile>(GetParameter(parameters, EP_RENDER_PATH).GetString()));
  228. renderer->SetDrawShadows(GetParameter(parameters, EP_SHADOWS, true).GetBool());
  229. if (renderer->GetDrawShadows() && GetParameter(parameters, EP_LOW_QUALITY_SHADOWS, false).GetBool())
  230. renderer->SetShadowQuality(SHADOWQUALITY_SIMPLE_16BIT);
  231. renderer->SetMaterialQuality(GetParameter(parameters, EP_MATERIAL_QUALITY, QUALITY_HIGH).GetInt());
  232. renderer->SetTextureQuality(GetParameter(parameters, EP_TEXTURE_QUALITY, QUALITY_HIGH).GetInt());
  233. renderer->SetTextureFilterMode((TextureFilterMode)GetParameter(parameters, EP_TEXTURE_FILTER_MODE, FILTER_TRILINEAR).GetInt());
  234. renderer->SetTextureAnisotropy(GetParameter(parameters, EP_TEXTURE_ANISOTROPY, 4).GetInt());
  235. if (GetParameter(parameters, EP_SOUND, true).GetBool())
  236. {
  237. GetSubsystem<Audio>()->SetMode(
  238. GetParameter(parameters, EP_SOUND_BUFFER, 100).GetInt(),
  239. GetParameter(parameters, EP_SOUND_MIX_RATE, 44100).GetInt(),
  240. GetParameter(parameters, EP_SOUND_STEREO, true).GetBool(),
  241. GetParameter(parameters, EP_SOUND_INTERPOLATION, true).GetBool()
  242. );
  243. }
  244. }
  245. // Init FPU state of main thread
  246. InitFPU();
  247. // Initialize input
  248. if (HasParameter(parameters, EP_TOUCH_EMULATION))
  249. GetSubsystem<Input>()->SetTouchEmulation(GetParameter(parameters, EP_TOUCH_EMULATION).GetBool());
  250. // Initialize network
  251. #ifdef URHO3D_NETWORK
  252. if (HasParameter(parameters, EP_PACKAGE_CACHE_DIR))
  253. GetSubsystem<Network>()->SetPackageCacheDir(GetParameter(parameters, EP_PACKAGE_CACHE_DIR).GetString());
  254. #endif
  255. #ifdef URHO3D_TESTING
  256. if (HasParameter(parameters, EP_TIME_OUT))
  257. timeOut_ = GetParameter(parameters, EP_TIME_OUT, 0).GetInt() * 1000000LL;
  258. #endif
  259. #ifdef URHO3D_PROFILING
  260. if (GetParameter(parameters, EP_EVENT_PROFILER, true).GetBool())
  261. {
  262. context_->RegisterSubsystem(new EventProfiler(context_));
  263. EventProfiler::SetActive(true);
  264. }
  265. #endif
  266. frameTimer_.Reset();
  267. URHO3D_LOGINFO("Initialized engine");
  268. initialized_ = true;
  269. return true;
  270. }
  271. bool Engine::InitializeResourceCache(const VariantMap& parameters, bool removeOld /*= true*/)
  272. {
  273. ResourceCache* cache = GetSubsystem<ResourceCache>();
  274. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  275. // Remove all resource paths and packages
  276. if (removeOld)
  277. {
  278. Vector<String> resourceDirs = cache->GetResourceDirs();
  279. Vector<SharedPtr<PackageFile> > packageFiles = cache->GetPackageFiles();
  280. for (unsigned i = 0; i < resourceDirs.Size(); ++i)
  281. cache->RemoveResourceDir(resourceDirs[i]);
  282. for (unsigned i = 0; i < packageFiles.Size(); ++i)
  283. cache->RemovePackageFile(packageFiles[i]);
  284. }
  285. // Add resource paths
  286. Vector<String> resourcePrefixPaths = GetParameter(parameters, EP_RESOURCE_PREFIX_PATHS, String::EMPTY).GetString().Split(';', true);
  287. for (unsigned i = 0; i < resourcePrefixPaths.Size(); ++i)
  288. resourcePrefixPaths[i] = AddTrailingSlash(
  289. IsAbsolutePath(resourcePrefixPaths[i]) ? resourcePrefixPaths[i] : fileSystem->GetProgramDir() + resourcePrefixPaths[i]);
  290. Vector<String> resourcePaths = GetParameter(parameters, EP_RESOURCE_PATHS, "Data;CoreData").GetString().Split(';');
  291. Vector<String> resourcePackages = GetParameter(parameters, EP_RESOURCE_PACKAGES).GetString().Split(';');
  292. Vector<String> autoLoadPaths = GetParameter(parameters, EP_AUTOLOAD_PATHS, "Autoload").GetString().Split(';');
  293. for (unsigned i = 0; i < resourcePaths.Size(); ++i)
  294. {
  295. // If path is not absolute, prefer to add it as a package if possible
  296. if (!IsAbsolutePath(resourcePaths[i]))
  297. {
  298. unsigned j = 0;
  299. for (; j < resourcePrefixPaths.Size(); ++j)
  300. {
  301. String packageName = resourcePrefixPaths[j] + resourcePaths[i] + ".pak";
  302. if (fileSystem->FileExists(packageName))
  303. {
  304. if (cache->AddPackageFile(packageName))
  305. break;
  306. else
  307. return false; // The root cause of the error should have already been logged
  308. }
  309. String pathName = resourcePrefixPaths[j] + resourcePaths[i];
  310. if (fileSystem->DirExists(pathName))
  311. {
  312. if (cache->AddResourceDir(pathName))
  313. break;
  314. else
  315. return false;
  316. }
  317. }
  318. if (j == resourcePrefixPaths.Size())
  319. {
  320. URHO3D_LOGERRORF(
  321. "Failed to add resource path '%s', check the documentation on how to set the 'resource prefix path'",
  322. resourcePaths[i].CString());
  323. return false;
  324. }
  325. }
  326. else
  327. {
  328. String pathName = resourcePaths[i];
  329. if (fileSystem->DirExists(pathName))
  330. if (!cache->AddResourceDir(pathName))
  331. return false;
  332. }
  333. }
  334. // Then add specified packages
  335. for (unsigned i = 0; i < resourcePackages.Size(); ++i)
  336. {
  337. unsigned j = 0;
  338. for (; j < resourcePrefixPaths.Size(); ++j)
  339. {
  340. String packageName = resourcePrefixPaths[j] + resourcePackages[i];
  341. if (fileSystem->FileExists(packageName))
  342. {
  343. if (cache->AddPackageFile(packageName))
  344. break;
  345. else
  346. return false;
  347. }
  348. }
  349. if (j == resourcePrefixPaths.Size())
  350. {
  351. URHO3D_LOGERRORF(
  352. "Failed to add resource package '%s', check the documentation on how to set the 'resource prefix path'",
  353. resourcePackages[i].CString());
  354. return false;
  355. }
  356. }
  357. // Add auto load folders. Prioritize these (if exist) before the default folders
  358. for (unsigned i = 0; i < autoLoadPaths.Size(); ++i)
  359. {
  360. bool autoLoadPathExist = false;
  361. for (unsigned j = 0; j < resourcePrefixPaths.Size(); ++j)
  362. {
  363. String autoLoadPath(autoLoadPaths[i]);
  364. if (!IsAbsolutePath(autoLoadPath))
  365. autoLoadPath = resourcePrefixPaths[j] + autoLoadPath;
  366. if (fileSystem->DirExists(autoLoadPath))
  367. {
  368. autoLoadPathExist = true;
  369. // Add all the subdirs (non-recursive) as resource directory
  370. Vector<String> subdirs;
  371. fileSystem->ScanDir(subdirs, autoLoadPath, "*", SCAN_DIRS, false);
  372. for (unsigned y = 0; y < subdirs.Size(); ++y)
  373. {
  374. String dir = subdirs[y];
  375. if (dir.StartsWith("."))
  376. continue;
  377. String autoResourceDir = autoLoadPath + "/" + dir;
  378. if (!cache->AddResourceDir(autoResourceDir, 0))
  379. return false;
  380. }
  381. // Add all the found package files (non-recursive)
  382. Vector<String> paks;
  383. fileSystem->ScanDir(paks, autoLoadPath, "*.pak", SCAN_FILES, false);
  384. for (unsigned y = 0; y < paks.Size(); ++y)
  385. {
  386. String pak = paks[y];
  387. if (pak.StartsWith("."))
  388. continue;
  389. String autoPackageName = autoLoadPath + "/" + pak;
  390. if (!cache->AddPackageFile(autoPackageName, 0))
  391. return false;
  392. }
  393. }
  394. }
  395. // The following debug message is confusing when user is not aware of the autoload feature
  396. // Especially because the autoload feature is enabled by default without user intervention
  397. // The following extra conditional check below is to suppress unnecessary debug log entry under such default situation
  398. // The cleaner approach is to not enable the autoload by default, i.e. do not use 'Autoload' as default value for 'AutoloadPaths' engine parameter
  399. // However, doing so will break the existing applications that rely on this
  400. if (!autoLoadPathExist && (autoLoadPaths.Size() > 1 || autoLoadPaths[0] != "Autoload"))
  401. URHO3D_LOGDEBUGF(
  402. "Skipped autoload path '%s' as it does not exist, check the documentation on how to set the 'resource prefix path'",
  403. autoLoadPaths[i].CString());
  404. }
  405. return true;
  406. }
  407. void Engine::RunFrame()
  408. {
  409. assert(initialized_);
  410. // If not headless, and the graphics subsystem no longer has a window open, assume we should exit
  411. if (!headless_ && !GetSubsystem<Graphics>()->IsInitialized())
  412. exiting_ = true;
  413. if (exiting_)
  414. return;
  415. // Note: there is a minimal performance cost to looking up subsystems (uses a hashmap); if they would be looked up several
  416. // times per frame it would be better to cache the pointers
  417. Time* time = GetSubsystem<Time>();
  418. Input* input = GetSubsystem<Input>();
  419. Audio* audio = GetSubsystem<Audio>();
  420. #ifdef URHO3D_PROFILING
  421. if (EventProfiler::IsActive())
  422. {
  423. EventProfiler* eventProfiler = GetSubsystem<EventProfiler>();
  424. if (eventProfiler)
  425. eventProfiler->BeginFrame();
  426. }
  427. #endif
  428. time->BeginFrame(timeStep_);
  429. // If pause when minimized -mode is in use, stop updates and audio as necessary
  430. if (pauseMinimized_ && input->IsMinimized())
  431. {
  432. if (audio->IsPlaying())
  433. {
  434. audio->Stop();
  435. audioPaused_ = true;
  436. }
  437. }
  438. else
  439. {
  440. // Only unpause when it was paused by the engine
  441. if (audioPaused_)
  442. {
  443. audio->Play();
  444. audioPaused_ = false;
  445. }
  446. Update();
  447. }
  448. Render();
  449. ApplyFrameLimit();
  450. time->EndFrame();
  451. }
  452. Console* Engine::CreateConsole()
  453. {
  454. if (headless_ || !initialized_)
  455. return 0;
  456. // Return existing console if possible
  457. Console* console = GetSubsystem<Console>();
  458. if (!console)
  459. {
  460. console = new Console(context_);
  461. context_->RegisterSubsystem(console);
  462. }
  463. return console;
  464. }
  465. DebugHud* Engine::CreateDebugHud()
  466. {
  467. if (headless_ || !initialized_)
  468. return 0;
  469. // Return existing debug HUD if possible
  470. DebugHud* debugHud = GetSubsystem<DebugHud>();
  471. if (!debugHud)
  472. {
  473. debugHud = new DebugHud(context_);
  474. context_->RegisterSubsystem(debugHud);
  475. }
  476. return debugHud;
  477. }
  478. void Engine::SetTimeStepSmoothing(int frames)
  479. {
  480. timeStepSmoothing_ = (unsigned)Clamp(frames, 1, 20);
  481. }
  482. void Engine::SetMinFps(int fps)
  483. {
  484. minFps_ = (unsigned)Max(fps, 0);
  485. }
  486. void Engine::SetMaxFps(int fps)
  487. {
  488. maxFps_ = (unsigned)Max(fps, 0);
  489. }
  490. void Engine::SetMaxInactiveFps(int fps)
  491. {
  492. maxInactiveFps_ = (unsigned)Max(fps, 0);
  493. }
  494. void Engine::SetPauseMinimized(bool enable)
  495. {
  496. pauseMinimized_ = enable;
  497. }
  498. void Engine::SetAutoExit(bool enable)
  499. {
  500. // On mobile platforms exit is mandatory if requested by the platform itself and should not be attempted to be disabled
  501. #if defined(__ANDROID__) || defined(IOS)
  502. enable = true;
  503. #endif
  504. autoExit_ = enable;
  505. }
  506. void Engine::SetNextTimeStep(float seconds)
  507. {
  508. timeStep_ = Max(seconds, 0.0f);
  509. }
  510. void Engine::Exit()
  511. {
  512. #if defined(IOS)
  513. // On iOS it's not legal for the application to exit on its own, instead it will be minimized with the home key
  514. #else
  515. DoExit();
  516. #endif
  517. }
  518. void Engine::DumpProfiler()
  519. {
  520. #ifdef URHO3D_LOGGING
  521. if (!Thread::IsMainThread())
  522. return;
  523. Profiler* profiler = GetSubsystem<Profiler>();
  524. if (profiler)
  525. URHO3D_LOGRAW(profiler->PrintData(true, true) + "\n");
  526. #endif
  527. }
  528. void Engine::DumpResources(bool dumpFileName)
  529. {
  530. #ifdef URHO3D_LOGGING
  531. if (!Thread::IsMainThread())
  532. return;
  533. ResourceCache* cache = GetSubsystem<ResourceCache>();
  534. const HashMap<StringHash, ResourceGroup>& resourceGroups = cache->GetAllResources();
  535. if (dumpFileName)
  536. {
  537. URHO3D_LOGRAW("Used resources:\n");
  538. for (HashMap<StringHash, ResourceGroup>::ConstIterator i = resourceGroups.Begin(); i != resourceGroups.End(); ++i)
  539. {
  540. const HashMap<StringHash, SharedPtr<Resource> >& resources = i->second_.resources_;
  541. if (dumpFileName)
  542. {
  543. for (HashMap<StringHash, SharedPtr<Resource> >::ConstIterator j = resources.Begin(); j != resources.End(); ++j)
  544. URHO3D_LOGRAW(j->second_->GetName() + "\n");
  545. }
  546. }
  547. }
  548. else
  549. URHO3D_LOGRAW(cache->PrintMemoryUsage() + "\n");
  550. #endif
  551. }
  552. void Engine::DumpMemory()
  553. {
  554. #ifdef URHO3D_LOGGING
  555. #if defined(_MSC_VER) && defined(_DEBUG)
  556. _CrtMemState state;
  557. _CrtMemCheckpoint(&state);
  558. _CrtMemBlockHeader* block = state.pBlockHeader;
  559. unsigned total = 0;
  560. unsigned blocks = 0;
  561. for (;;)
  562. {
  563. if (block && block->pBlockHeaderNext)
  564. block = block->pBlockHeaderNext;
  565. else
  566. break;
  567. }
  568. while (block)
  569. {
  570. if (block->nBlockUse > 0)
  571. {
  572. if (block->szFileName)
  573. URHO3D_LOGRAW("Block " + String((int)block->lRequest) + ": " + String(block->nDataSize) + " bytes, file " + String(block->szFileName) + " line " + String(block->nLine) + "\n");
  574. else
  575. URHO3D_LOGRAW("Block " + String((int)block->lRequest) + ": " + String(block->nDataSize) + " bytes\n");
  576. total += block->nDataSize;
  577. ++blocks;
  578. }
  579. block = block->pBlockHeaderPrev;
  580. }
  581. URHO3D_LOGRAW("Total allocated memory " + String(total) + " bytes in " + String(blocks) + " blocks\n\n");
  582. #else
  583. URHO3D_LOGRAW("DumpMemory() supported on MSVC debug mode only\n\n");
  584. #endif
  585. #endif
  586. }
  587. void Engine::Update()
  588. {
  589. URHO3D_PROFILE(Update);
  590. // Logic update event
  591. using namespace Update;
  592. VariantMap& eventData = GetEventDataMap();
  593. eventData[P_TIMESTEP] = timeStep_;
  594. SendEvent(E_UPDATE, eventData);
  595. // Logic post-update event
  596. SendEvent(E_POSTUPDATE, eventData);
  597. // Rendering update event
  598. SendEvent(E_RENDERUPDATE, eventData);
  599. // Post-render update event
  600. SendEvent(E_POSTRENDERUPDATE, eventData);
  601. }
  602. void Engine::Render()
  603. {
  604. if (headless_)
  605. return;
  606. URHO3D_PROFILE(Render);
  607. // If device is lost, BeginFrame will fail and we skip rendering
  608. Graphics* graphics = GetSubsystem<Graphics>();
  609. if (!graphics->BeginFrame())
  610. return;
  611. GetSubsystem<Renderer>()->Render();
  612. GetSubsystem<UI>()->Render();
  613. graphics->EndFrame();
  614. }
  615. void Engine::ApplyFrameLimit()
  616. {
  617. if (!initialized_)
  618. return;
  619. unsigned maxFps = maxFps_;
  620. Input* input = GetSubsystem<Input>();
  621. if (input && !input->HasFocus())
  622. maxFps = Min(maxInactiveFps_, maxFps);
  623. long long elapsed = 0;
  624. #ifndef __EMSCRIPTEN__
  625. // Perform waiting loop if maximum FPS set
  626. #ifndef IOS
  627. if (maxFps)
  628. #else
  629. // If on iOS and target framerate is 60 or above, just let the animation callback handle frame timing
  630. // instead of waiting ourselves
  631. if (maxFps < 60)
  632. #endif
  633. {
  634. URHO3D_PROFILE(ApplyFrameLimit);
  635. long long targetMax = 1000000LL / maxFps;
  636. for (;;)
  637. {
  638. elapsed = frameTimer_.GetUSec(false);
  639. if (elapsed >= targetMax)
  640. break;
  641. // Sleep if 1 ms or more off the frame limiting goal
  642. if (targetMax - elapsed >= 1000LL)
  643. {
  644. unsigned sleepTime = (unsigned)((targetMax - elapsed) / 1000LL);
  645. Time::Sleep(sleepTime);
  646. }
  647. }
  648. }
  649. #endif
  650. elapsed = frameTimer_.GetUSec(true);
  651. #ifdef URHO3D_TESTING
  652. if (timeOut_ > 0)
  653. {
  654. timeOut_ -= elapsed;
  655. if (timeOut_ <= 0)
  656. Exit();
  657. }
  658. #endif
  659. // If FPS lower than minimum, clamp elapsed time
  660. if (minFps_)
  661. {
  662. long long targetMin = 1000000LL / minFps_;
  663. if (elapsed > targetMin)
  664. elapsed = targetMin;
  665. }
  666. // Perform timestep smoothing
  667. timeStep_ = 0.0f;
  668. lastTimeSteps_.Push(elapsed / 1000000.0f);
  669. if (lastTimeSteps_.Size() > timeStepSmoothing_)
  670. {
  671. // If the smoothing configuration was changed, ensure correct amount of samples
  672. lastTimeSteps_.Erase(0, lastTimeSteps_.Size() - timeStepSmoothing_);
  673. for (unsigned i = 0; i < lastTimeSteps_.Size(); ++i)
  674. timeStep_ += lastTimeSteps_[i];
  675. timeStep_ /= lastTimeSteps_.Size();
  676. }
  677. else
  678. timeStep_ = lastTimeSteps_.Back();
  679. }
  680. VariantMap Engine::ParseParameters(const Vector<String>& arguments)
  681. {
  682. VariantMap ret;
  683. // Pre-initialize the parameters with environment variable values when they are set
  684. if (const char* paths = getenv("URHO3D_PREFIX_PATH"))
  685. ret[EP_RESOURCE_PREFIX_PATHS] = paths;
  686. for (unsigned i = 0; i < arguments.Size(); ++i)
  687. {
  688. if (arguments[i].Length() > 1 && arguments[i][0] == '-')
  689. {
  690. String argument = arguments[i].Substring(1).ToLower();
  691. String value = i + 1 < arguments.Size() ? arguments[i + 1] : String::EMPTY;
  692. if (argument == "headless")
  693. ret[EP_HEADLESS] = true;
  694. else if (argument == "nolimit")
  695. ret[EP_FRAME_LIMITER] = false;
  696. else if (argument == "flushgpu")
  697. ret[EP_FLUSH_GPU] = true;
  698. else if (argument == "gl2")
  699. ret[EP_FORCE_GL2] = true;
  700. else if (argument == "landscape")
  701. ret[EP_ORIENTATIONS] = "LandscapeLeft LandscapeRight " + ret[EP_ORIENTATIONS].GetString();
  702. else if (argument == "portrait")
  703. ret[EP_ORIENTATIONS] = "Portrait PortraitUpsideDown " + ret[EP_ORIENTATIONS].GetString();
  704. else if (argument == "nosound")
  705. ret[EP_SOUND] = false;
  706. else if (argument == "noip")
  707. ret[EP_SOUND_INTERPOLATION] = false;
  708. else if (argument == "mono")
  709. ret[EP_SOUND_STEREO] = false;
  710. else if (argument == "prepass")
  711. ret[EP_RENDER_PATH] = "RenderPaths/Prepass.xml";
  712. else if (argument == "deferred")
  713. ret[EP_RENDER_PATH] = "RenderPaths/Deferred.xml";
  714. else if (argument == "renderpath" && !value.Empty())
  715. {
  716. ret[EP_RENDER_PATH] = value;
  717. ++i;
  718. }
  719. else if (argument == "noshadows")
  720. ret[EP_SHADOWS] = false;
  721. else if (argument == "lqshadows")
  722. ret[EP_LOW_QUALITY_SHADOWS] = true;
  723. else if (argument == "nothreads")
  724. ret[EP_WORKER_THREADS] = false;
  725. else if (argument == "v")
  726. ret[EP_VSYNC] = true;
  727. else if (argument == "t")
  728. ret[EP_TRIPLE_BUFFER] = true;
  729. else if (argument == "w")
  730. ret[EP_FULL_SCREEN] = false;
  731. else if (argument == "borderless")
  732. ret[EP_BORDERLESS] = true;
  733. else if (argument == "s")
  734. ret[EP_WINDOW_RESIZABLE] = true;
  735. else if (argument == "q")
  736. ret[EP_LOG_QUIET] = true;
  737. else if (argument == "log" && !value.Empty())
  738. {
  739. unsigned logLevel = GetStringListIndex(value.CString(), logLevelPrefixes, M_MAX_UNSIGNED);
  740. if (logLevel != M_MAX_UNSIGNED)
  741. {
  742. ret[EP_LOG_LEVEL] = logLevel;
  743. ++i;
  744. }
  745. }
  746. else if (argument == "x" && !value.Empty())
  747. {
  748. ret[EP_WINDOW_WIDTH] = ToInt(value);
  749. ++i;
  750. }
  751. else if (argument == "y" && !value.Empty())
  752. {
  753. ret[EP_WINDOW_HEIGHT] = ToInt(value);
  754. ++i;
  755. }
  756. else if (argument == "monitor" && !value.Empty()) {
  757. ret[EP_MONITOR] = ToInt(value);
  758. ++i;
  759. }
  760. else if (argument == "hz" && !value.Empty()) {
  761. ret[EP_REFRESH_RATE] = ToInt(value);
  762. ++i;
  763. }
  764. else if (argument == "m" && !value.Empty())
  765. {
  766. ret[EP_MULTI_SAMPLE] = ToInt(value);
  767. ++i;
  768. }
  769. else if (argument == "b" && !value.Empty())
  770. {
  771. ret[EP_SOUND_BUFFER] = ToInt(value);
  772. ++i;
  773. }
  774. else if (argument == "r" && !value.Empty())
  775. {
  776. ret[EP_SOUND_MIX_RATE] = ToInt(value);
  777. ++i;
  778. }
  779. else if (argument == "pp" && !value.Empty())
  780. {
  781. ret[EP_RESOURCE_PREFIX_PATHS] = value;
  782. ++i;
  783. }
  784. else if (argument == "p" && !value.Empty())
  785. {
  786. ret[EP_RESOURCE_PATHS] = value;
  787. ++i;
  788. }
  789. else if (argument == "pf" && !value.Empty())
  790. {
  791. ret[EP_RESOURCE_PACKAGES] = value;
  792. ++i;
  793. }
  794. else if (argument == "ap" && !value.Empty())
  795. {
  796. ret[EP_AUTOLOAD_PATHS] = value;
  797. ++i;
  798. }
  799. else if (argument == "ds" && !value.Empty())
  800. {
  801. ret[EP_DUMP_SHADERS] = value;
  802. ++i;
  803. }
  804. else if (argument == "mq" && !value.Empty())
  805. {
  806. ret[EP_MATERIAL_QUALITY] = ToInt(value);
  807. ++i;
  808. }
  809. else if (argument == "tq" && !value.Empty())
  810. {
  811. ret[EP_TEXTURE_QUALITY] = ToInt(value);
  812. ++i;
  813. }
  814. else if (argument == "tf" && !value.Empty())
  815. {
  816. ret[EP_TEXTURE_FILTER_MODE] = ToInt(value);
  817. ++i;
  818. }
  819. else if (argument == "af" && !value.Empty())
  820. {
  821. ret[EP_TEXTURE_FILTER_MODE] = FILTER_ANISOTROPIC;
  822. ret[EP_TEXTURE_ANISOTROPY] = ToInt(value);
  823. ++i;
  824. }
  825. else if (argument == "touch")
  826. ret[EP_TOUCH_EMULATION] = true;
  827. #ifdef URHO3D_TESTING
  828. else if (argument == "timeout" && !value.Empty())
  829. {
  830. ret[EP_TIME_OUT] = ToInt(value);
  831. ++i;
  832. }
  833. #endif
  834. }
  835. }
  836. return ret;
  837. }
  838. bool Engine::HasParameter(const VariantMap& parameters, const String& parameter)
  839. {
  840. StringHash nameHash(parameter);
  841. return parameters.Find(nameHash) != parameters.End();
  842. }
  843. const Variant& Engine::GetParameter(const VariantMap& parameters, const String& parameter, const Variant& defaultValue)
  844. {
  845. StringHash nameHash(parameter);
  846. VariantMap::ConstIterator i = parameters.Find(nameHash);
  847. return i != parameters.End() ? i->second_ : defaultValue;
  848. }
  849. void Engine::HandleExitRequested(StringHash eventType, VariantMap& eventData)
  850. {
  851. if (autoExit_)
  852. {
  853. // Do not call Exit() here, as it contains mobile platform -specific tests to not exit.
  854. // If we do receive an exit request from the system on those platforms, we must comply
  855. DoExit();
  856. }
  857. }
  858. void Engine::DoExit()
  859. {
  860. Graphics* graphics = GetSubsystem<Graphics>();
  861. if (graphics)
  862. graphics->Close();
  863. exiting_ = true;
  864. #if defined(__EMSCRIPTEN__) && defined(URHO3D_TESTING)
  865. emscripten_force_exit(EXIT_SUCCESS); // Some how this is required to signal emrun to stop
  866. #endif
  867. }
  868. }