Engine.cpp 33 KB

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