Engine.cpp 33 KB

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