Engine.cpp 30 KB

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