Engine.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  1. //
  2. // Copyright (c) 2008-2014 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.h"
  24. #include "Console.h"
  25. #include "Context.h"
  26. #include "CoreEvents.h"
  27. #include "DebugHud.h"
  28. #include "Engine.h"
  29. #include "FileSystem.h"
  30. #include "Graphics.h"
  31. #include "Input.h"
  32. #include "InputEvents.h"
  33. #include "Log.h"
  34. #ifdef URHO3D_NAVIGATION
  35. #include "NavigationMesh.h"
  36. #endif
  37. #ifdef URHO3D_NETWORK
  38. #include "Network.h"
  39. #endif
  40. #include "PackageFile.h"
  41. #ifdef URHO3D_PHYSICS
  42. #include "PhysicsWorld.h"
  43. #endif
  44. #include "ProcessUtils.h"
  45. #include "Profiler.h"
  46. #include "Renderer.h"
  47. #include "ResourceCache.h"
  48. #include "Scene.h"
  49. #include "SceneEvents.h"
  50. #include "UI.h"
  51. #ifdef URHO3D_URHO2D
  52. #include "Urho2D.h"
  53. #endif
  54. #include "WorkQueue.h"
  55. #include "XMLFile.h"
  56. #include "DebugNew.h"
  57. #if defined(_MSC_VER) && defined(_DEBUG)
  58. // From dbgint.h
  59. #define nNoMansLandSize 4
  60. typedef struct _CrtMemBlockHeader
  61. {
  62. struct _CrtMemBlockHeader* pBlockHeaderNext;
  63. struct _CrtMemBlockHeader* pBlockHeaderPrev;
  64. char* szFileName;
  65. int nLine;
  66. size_t nDataSize;
  67. int nBlockUse;
  68. long lRequest;
  69. unsigned char gap[nNoMansLandSize];
  70. } _CrtMemBlockHeader;
  71. #endif
  72. namespace Urho3D
  73. {
  74. extern const char* logLevelPrefixes[];
  75. Engine::Engine(Context* context) :
  76. Object(context),
  77. timeStep_(0.0f),
  78. timeStepSmoothing_(2),
  79. minFps_(10),
  80. #if defined(ANDROID) || defined(IOS) || defined(RASPI)
  81. maxFps_(60),
  82. maxInactiveFps_(10),
  83. pauseMinimized_(true),
  84. #else
  85. maxFps_(200),
  86. maxInactiveFps_(60),
  87. pauseMinimized_(false),
  88. #endif
  89. #ifdef URHO3D_TESTING
  90. timeOut_(0),
  91. #endif
  92. autoExit_(true),
  93. initialized_(false),
  94. exiting_(false),
  95. headless_(false),
  96. audioPaused_(false)
  97. {
  98. // Register self as a subsystem
  99. context_->RegisterSubsystem(this);
  100. // Create subsystems which do not depend on engine initialization or startup parameters
  101. context_->RegisterSubsystem(new Time(context_));
  102. context_->RegisterSubsystem(new WorkQueue(context_));
  103. #ifdef URHO3D_PROFILING
  104. context_->RegisterSubsystem(new Profiler(context_));
  105. #endif
  106. context_->RegisterSubsystem(new FileSystem(context_));
  107. #ifdef URHO3D_LOGGING
  108. context_->RegisterSubsystem(new Log(context_));
  109. #endif
  110. context_->RegisterSubsystem(new ResourceCache(context_));
  111. #ifdef URHO3D_NETWORK
  112. context_->RegisterSubsystem(new Network(context_));
  113. #endif
  114. context_->RegisterSubsystem(new Input(context_));
  115. context_->RegisterSubsystem(new Audio(context_));
  116. context_->RegisterSubsystem(new UI(context_));
  117. // Register object factories for libraries which are not automatically registered along with subsystem creation
  118. RegisterSceneLibrary(context_);
  119. #ifdef URHO3D_PHYSICS
  120. RegisterPhysicsLibrary(context_);
  121. #endif
  122. #ifdef URHO3D_NAVIGATION
  123. RegisterNavigationLibrary(context_);
  124. #endif
  125. SubscribeToEvent(E_EXITREQUESTED, HANDLER(Engine, HandleExitRequested));
  126. }
  127. Engine::~Engine()
  128. {
  129. }
  130. bool Engine::Initialize(const VariantMap& parameters)
  131. {
  132. if (initialized_)
  133. return true;
  134. PROFILE(InitEngine);
  135. // Set headless mode
  136. headless_ = GetParameter(parameters, "Headless", false).GetBool();
  137. // Register the rest of the subsystems
  138. if (!headless_)
  139. {
  140. context_->RegisterSubsystem(new Graphics(context_));
  141. context_->RegisterSubsystem(new Renderer(context_));
  142. }
  143. else
  144. {
  145. // Register graphics library objects explicitly in headless mode to allow them to work without using actual GPU resources
  146. RegisterGraphicsLibrary(context_);
  147. }
  148. #ifdef URHO3D_URHO2D
  149. // 2D graphics library is dependent on 3D graphics library
  150. RegisterUrho2DLibrary(context_);
  151. #endif
  152. // Start logging
  153. Log* log = GetSubsystem<Log>();
  154. if (log)
  155. {
  156. if (HasParameter(parameters, "LogLevel"))
  157. log->SetLevel(GetParameter(parameters, "LogLevel").GetInt());
  158. log->SetQuiet(GetParameter(parameters, "LogQuiet", false).GetBool());
  159. log->Open(GetParameter(parameters, "LogName", "Urho3D.log").GetString());
  160. }
  161. // Set maximally accurate low res timer
  162. GetSubsystem<Time>()->SetTimerPeriod(1);
  163. // Configure max FPS
  164. if (GetParameter(parameters, "FrameLimiter", true) == false)
  165. SetMaxFps(0);
  166. // Set amount of worker threads according to the available physical CPU cores. Using also hyperthreaded cores results in
  167. // unpredictable extra synchronization overhead. Also reserve one core for the main thread
  168. unsigned numThreads = GetParameter(parameters, "WorkerThreads", true).GetBool() ? GetNumPhysicalCPUs() - 1 : 0;
  169. if (numThreads)
  170. {
  171. GetSubsystem<WorkQueue>()->CreateThreads(numThreads);
  172. LOGINFOF("Created %u worker thread%s", numThreads, numThreads > 1 ? "s" : "");
  173. }
  174. // Add resource paths
  175. ResourceCache* cache = GetSubsystem<ResourceCache>();
  176. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  177. String exePath = fileSystem->GetProgramDir();
  178. Vector<String> resourcePaths = GetParameter(parameters, "ResourcePaths", "Data;CoreData").GetString().Split(';');
  179. Vector<String> resourcePackages = GetParameter(parameters, "ResourcePackages").GetString().Split(';');
  180. Vector<String> autoloadFolders = GetParameter(parameters, "AutoloadPaths", "Extra").GetString().Split(';');
  181. for (unsigned i = 0; i < resourcePaths.Size(); ++i)
  182. {
  183. bool success = false;
  184. // If path is not absolute, prefer to add it as a package if possible
  185. if (!IsAbsolutePath(resourcePaths[i]))
  186. {
  187. String packageName = exePath + resourcePaths[i] + ".pak";
  188. if (fileSystem->FileExists(packageName))
  189. {
  190. SharedPtr<PackageFile> package(new PackageFile(context_));
  191. if (package->Open(packageName))
  192. {
  193. cache->AddPackageFile(package);
  194. success = true;
  195. }
  196. }
  197. if (!success)
  198. {
  199. String pathName = exePath + resourcePaths[i];
  200. if (fileSystem->DirExists(pathName))
  201. success = cache->AddResourceDir(pathName);
  202. }
  203. }
  204. else
  205. {
  206. String pathName = resourcePaths[i];
  207. if (fileSystem->DirExists(pathName))
  208. success = cache->AddResourceDir(pathName);
  209. }
  210. if (!success)
  211. {
  212. LOGERROR("Failed to add resource path " + resourcePaths[i]);
  213. return false;
  214. }
  215. }
  216. // Then add specified packages
  217. for (unsigned i = 0; i < resourcePackages.Size(); ++i)
  218. {
  219. bool success = false;
  220. String packageName = exePath + resourcePackages[i];
  221. if (fileSystem->FileExists(packageName))
  222. {
  223. SharedPtr<PackageFile> package(new PackageFile(context_));
  224. if (package->Open(packageName))
  225. {
  226. cache->AddPackageFile(package);
  227. success = true;
  228. }
  229. }
  230. if (!success)
  231. {
  232. LOGERROR("Failed to add resource package " + resourcePackages[i]);
  233. return false;
  234. }
  235. }
  236. // Add auto load folders. Prioritize these (if exist) before the default folders
  237. for (unsigned i = 0; i < autoloadFolders.Size(); ++i)
  238. {
  239. bool success = true;
  240. String autoloadFolder = autoloadFolders[i];
  241. String badResource;
  242. if (fileSystem->DirExists(autoloadFolder))
  243. {
  244. Vector<String> folders;
  245. fileSystem->ScanDir(folders, autoloadFolder, "*", SCAN_DIRS, false);
  246. for (unsigned y = 0; y < folders.Size(); ++y)
  247. {
  248. String folder = folders[y];
  249. if (folder.StartsWith("."))
  250. continue;
  251. String autoResourceDir = exePath + autoloadFolder + "/" + folder;
  252. success = cache->AddResourceDir(autoResourceDir, 0);
  253. if (!success)
  254. {
  255. badResource = folder;
  256. break;
  257. }
  258. }
  259. if (success)
  260. {
  261. Vector<String> paks;
  262. fileSystem->ScanDir(paks, autoloadFolder, "*.pak", SCAN_FILES, false);
  263. for (unsigned y = 0; y < paks.Size(); ++y)
  264. {
  265. String pak = paks[y];
  266. if (pak.StartsWith("."))
  267. continue;
  268. String autoResourcePak = exePath + autoloadFolder + "/" + pak;
  269. SharedPtr<PackageFile> package(new PackageFile(context_));
  270. if (package->Open(autoResourcePak))
  271. cache->AddPackageFile(package, 0);
  272. else
  273. {
  274. badResource = autoResourcePak;
  275. success = false;
  276. break;
  277. }
  278. }
  279. }
  280. }
  281. else
  282. LOGWARNING("Skipped autoload folder " + autoloadFolders[i] + " as it does not exist");
  283. if (!success)
  284. {
  285. LOGERROR("Failed to add resource " + badResource + " in autoload folder " + autoloadFolders[i]);
  286. return false;
  287. }
  288. }
  289. // Initialize graphics & audio output
  290. if (!headless_)
  291. {
  292. Graphics* graphics = GetSubsystem<Graphics>();
  293. Renderer* renderer = GetSubsystem<Renderer>();
  294. if (HasParameter(parameters, "ExternalWindow"))
  295. graphics->SetExternalWindow(GetParameter(parameters, "ExternalWindow").GetVoidPtr());
  296. graphics->SetForceSM2(GetParameter(parameters, "ForceSM2", false).GetBool());
  297. graphics->SetWindowTitle(GetParameter(parameters, "WindowTitle", "Urho3D").GetString());
  298. graphics->SetWindowIcon(cache->GetResource<Image>(GetParameter(parameters, "WindowIcon", String::EMPTY).GetString()));
  299. graphics->SetFlushGPU(GetParameter(parameters, "FlushGPU", false).GetBool());
  300. graphics->SetOrientations(GetParameter(parameters, "Orientations", "LandscapeLeft LandscapeRight").GetString());
  301. if (HasParameter(parameters, "WindowPositionX") && HasParameter(parameters, "WindowPositionY"))
  302. graphics->SetWindowPosition(GetParameter(parameters, "WindowPositionX").GetInt(), GetParameter(parameters, "WindowPositionY").GetInt());
  303. if (!graphics->SetMode(
  304. GetParameter(parameters, "WindowWidth", 0).GetInt(),
  305. GetParameter(parameters, "WindowHeight", 0).GetInt(),
  306. GetParameter(parameters, "FullScreen", true).GetBool(),
  307. GetParameter(parameters, "Borderless", false).GetBool(),
  308. GetParameter(parameters, "WindowResizable", false).GetBool(),
  309. GetParameter(parameters, "VSync", false).GetBool(),
  310. GetParameter(parameters, "TripleBuffer", false).GetBool(),
  311. GetParameter(parameters, "MultiSample", 1).GetInt()
  312. ))
  313. return false;
  314. if (HasParameter(parameters, "DumpShaders"))
  315. graphics->BeginDumpShaders(GetParameter(parameters, "DumpShaders", String::EMPTY).GetString());
  316. if (HasParameter(parameters, "RenderPath"))
  317. renderer->SetDefaultRenderPath(cache->GetResource<XMLFile>(GetParameter(parameters, "RenderPath").GetString()));
  318. renderer->SetDrawShadows(GetParameter(parameters, "Shadows", true).GetBool());
  319. if (renderer->GetDrawShadows() && GetParameter(parameters, "LowQualityShadows", false).GetBool())
  320. renderer->SetShadowQuality(SHADOWQUALITY_LOW_16BIT);
  321. renderer->SetMaterialQuality(GetParameter(parameters, "MaterialQuality", QUALITY_HIGH).GetInt());
  322. renderer->SetTextureQuality(GetParameter(parameters, "TextureQuality", QUALITY_HIGH).GetInt());
  323. renderer->SetTextureFilterMode((TextureFilterMode)GetParameter(parameters, "TextureFilterMode", FILTER_TRILINEAR).GetInt());
  324. renderer->SetTextureAnisotropy(GetParameter(parameters, "TextureAnisotropy", 4).GetInt());
  325. if (GetParameter(parameters, "Sound", true).GetBool())
  326. {
  327. GetSubsystem<Audio>()->SetMode(
  328. GetParameter(parameters, "SoundBuffer", 100).GetInt(),
  329. GetParameter(parameters, "SoundMixRate", 44100).GetInt(),
  330. GetParameter(parameters, "SoundStereo", true).GetBool(),
  331. GetParameter(parameters, "SoundInterpolation", true).GetBool()
  332. );
  333. }
  334. }
  335. // Init FPU state of main thread
  336. InitFPU();
  337. // Initialize input
  338. if (HasParameter(parameters, "TouchEmulation"))
  339. GetSubsystem<Input>()->SetTouchEmulation(GetParameter(parameters, "TouchEmulation").GetBool());
  340. #ifdef URHO3D_TESTING
  341. if (HasParameter(parameters, "TimeOut"))
  342. timeOut_ = GetParameter(parameters, "TimeOut", 0).GetInt() * 1000000LL;
  343. #endif
  344. // In debug mode, check now that all factory created objects can be created without crashing
  345. #ifdef _DEBUG
  346. const HashMap<StringHash, SharedPtr<ObjectFactory> >& factories = context_->GetObjectFactories();
  347. for (HashMap<StringHash, SharedPtr<ObjectFactory> >::ConstIterator i = factories.Begin(); i != factories.End(); ++i)
  348. SharedPtr<Object> object = i->second_->CreateObject();
  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_ = Clamp(frames, 1, 20);
  421. }
  422. void Engine::SetMinFps(int fps)
  423. {
  424. minFps_ = Max(fps, 0);
  425. }
  426. void Engine::SetMaxFps(int fps)
  427. {
  428. maxFps_ = Max(fps, 0);
  429. }
  430. void Engine::SetMaxInactiveFps(int fps)
  431. {
  432. maxInactiveFps_ = 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 == "landscape")
  639. ret["Orientations"] = "LandscapeLeft LandscapeRight " + ret["Orientations"].GetString();
  640. else if (argument == "portrait")
  641. ret["Orientations"] = "Portrait PortraitUpsideDown " + ret["Orientations"].GetString();
  642. else if (argument == "nosound")
  643. ret["Sound"] = false;
  644. else if (argument == "noip")
  645. ret["SoundInterpolation"] = false;
  646. else if (argument == "mono")
  647. ret["SoundStereo"] = false;
  648. else if (argument == "prepass")
  649. ret["RenderPath"] = "RenderPaths/Prepass.xml";
  650. else if (argument == "deferred")
  651. ret["RenderPath"] = "RenderPaths/Deferred.xml";
  652. else if (argument == "noshadows")
  653. ret["Shadows"] = false;
  654. else if (argument == "lqshadows")
  655. ret["LowQualityShadows"] = true;
  656. else if (argument == "nothreads")
  657. ret["WorkerThreads"] = false;
  658. else if (argument == "sm2")
  659. ret["ForceSM2"] = true;
  660. else if (argument == "v")
  661. ret["VSync"] = true;
  662. else if (argument == "t")
  663. ret["TripleBuffer"] = true;
  664. else if (argument == "w")
  665. ret["FullScreen"] = false;
  666. else if (argument == "s")
  667. ret["WindowResizable"] = true;
  668. else if (argument == "borderless")
  669. ret["Borderless"] = true;
  670. else if (argument == "q")
  671. ret["LogQuiet"] = true;
  672. else if (argument == "log" && !value.Empty())
  673. {
  674. int logLevel = GetStringListIndex(value.CString(), logLevelPrefixes, -1);
  675. if (logLevel != -1)
  676. {
  677. ret["LogLevel"] = logLevel;
  678. ++i;
  679. }
  680. }
  681. else if (argument == "x" && !value.Empty())
  682. {
  683. ret["WindowWidth"] = ToInt(value);
  684. ++i;
  685. }
  686. else if (argument == "y" && !value.Empty())
  687. {
  688. ret["WindowHeight"] = ToInt(value);
  689. ++i;
  690. }
  691. else if (argument == "m" && !value.Empty())
  692. {
  693. ret["MultiSample"] = ToInt(value);
  694. ++i;
  695. }
  696. else if (argument == "b" && !value.Empty())
  697. {
  698. ret["SoundBuffer"] = ToInt(value);
  699. ++i;
  700. }
  701. else if (argument == "r" && !value.Empty())
  702. {
  703. ret["SoundMixRate"] = ToInt(value);
  704. ++i;
  705. }
  706. else if (argument == "p" && !value.Empty())
  707. {
  708. ret["ResourcePaths"] = value;
  709. ++i;
  710. }
  711. else if (argument == "ap" && !value.Empty())
  712. {
  713. ret["AutoloadPaths"] = value;
  714. ++i;
  715. }
  716. else if (argument == "ds" && !value.Empty())
  717. {
  718. ret["DumpShaders"] = value;
  719. ++i;
  720. }
  721. else if (argument == "mq" && !value.Empty())
  722. {
  723. ret["MaterialQuality"] = ToInt(value);
  724. ++i;
  725. }
  726. else if (argument == "tq" && !value.Empty())
  727. {
  728. ret["TextureQuality"] = ToInt(value);
  729. ++i;
  730. }
  731. else if (argument == "tf" && !value.Empty())
  732. {
  733. ret["TextureFilterMode"] = ToInt(value);
  734. ++i;
  735. }
  736. else if (argument == "af" && !value.Empty())
  737. {
  738. ret["TextureFilterMode"] = FILTER_ANISOTROPIC;
  739. ret["TextureAnisotropy"] = ToInt(value);
  740. ++i;
  741. }
  742. else if (argument == "touch")
  743. ret["TouchEmulation"] = true;
  744. #ifdef URHO3D_TESTING
  745. else if (argument == "timeout" && !value.Empty())
  746. {
  747. ret["TimeOut"] = ToInt(value);
  748. ++i;
  749. }
  750. #endif
  751. }
  752. }
  753. return ret;
  754. }
  755. bool Engine::HasParameter(const VariantMap& parameters, const String& parameter)
  756. {
  757. StringHash nameHash(parameter);
  758. return parameters.Find(nameHash) != parameters.End();
  759. }
  760. const Variant& Engine::GetParameter(const VariantMap& parameters, const String& parameter, const Variant& defaultValue)
  761. {
  762. StringHash nameHash(parameter);
  763. VariantMap::ConstIterator i = parameters.Find(nameHash);
  764. return i != parameters.End() ? i->second_ : defaultValue;
  765. }
  766. void Engine::HandleExitRequested(StringHash eventType, VariantMap& eventData)
  767. {
  768. if (autoExit_)
  769. {
  770. // Do not call Exit() here, as it contains mobile platform -specific tests to not exit.
  771. // If we do receive an exit request from the system on those platforms, we must comply
  772. DoExit();
  773. }
  774. }
  775. void Engine::DoExit()
  776. {
  777. Graphics* graphics = GetSubsystem<Graphics>();
  778. if (graphics)
  779. graphics->Close();
  780. exiting_ = true;
  781. }
  782. }