Engine.cpp 33 KB

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