Engine.cpp 34 KB

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