Engine.cpp 30 KB

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