Engine.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  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(RPI)
  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 defaultPrefixPath(AddTrailingSlash(getenv("URHO3D_PREFIX_PATH")));
  178. if (defaultPrefixPath.Empty())
  179. defaultPrefixPath = fileSystem->GetProgramDir();
  180. String resourcePrefixPath = GetParameter(parameters, "ResourcePrefixPath", defaultPrefixPath).GetString();
  181. Vector<String> resourcePaths = GetParameter(parameters, "ResourcePaths", "Data;CoreData").GetString().Split(';');
  182. Vector<String> resourcePackages = GetParameter(parameters, "ResourcePackages").GetString().Split(';');
  183. Vector<String> autoLoadPaths = GetParameter(parameters, "AutoloadPaths", "Autoload").GetString().Split(';');
  184. for (unsigned i = 0; i < resourcePaths.Size(); ++i)
  185. {
  186. bool success = false;
  187. // If path is not absolute, prefer to add it as a package if possible
  188. if (!IsAbsolutePath(resourcePaths[i]))
  189. {
  190. String packageName = resourcePrefixPath + resourcePaths[i] + ".pak";
  191. if (fileSystem->FileExists(packageName))
  192. success = cache->AddPackageFile(packageName);
  193. if (!success)
  194. {
  195. String pathName = resourcePrefixPath + resourcePaths[i];
  196. if (fileSystem->DirExists(pathName))
  197. success = cache->AddResourceDir(pathName);
  198. }
  199. }
  200. else
  201. {
  202. String pathName = resourcePaths[i];
  203. if (fileSystem->DirExists(pathName))
  204. success = cache->AddResourceDir(pathName);
  205. }
  206. if (!success)
  207. {
  208. LOGERRORF("Failed to add resource path %s", resourcePaths[i].CString());
  209. return false;
  210. }
  211. }
  212. // Then add specified packages
  213. for (unsigned i = 0; i < resourcePackages.Size(); ++i)
  214. {
  215. String packageName = resourcePrefixPath + resourcePackages[i];
  216. if (fileSystem->FileExists(packageName))
  217. {
  218. if (!cache->AddPackageFile(packageName))
  219. {
  220. LOGERRORF("Failed to add resource package %s", resourcePackages[i].CString());
  221. return false;
  222. }
  223. }
  224. else
  225. LOGDEBUGF("Skip specified resource package %s as it does not exist", resourcePackages[i].CString());
  226. }
  227. // Add auto load folders. Prioritize these (if exist) before the default folders
  228. for (unsigned i = 0; i < autoLoadPaths.Size(); ++i)
  229. {
  230. String autoLoadPath(autoLoadPaths[i]);
  231. if (!IsAbsolutePath(autoLoadPath))
  232. autoLoadPath = resourcePrefixPath + autoLoadPath;
  233. if (fileSystem->DirExists(autoLoadPath))
  234. {
  235. // Add all the subdirs (non-recursive) as resource directory
  236. Vector<String> subdirs;
  237. fileSystem->ScanDir(subdirs, autoLoadPath, "*", SCAN_DIRS, false);
  238. for (unsigned y = 0; y < subdirs.Size(); ++y)
  239. {
  240. String dir = subdirs[y];
  241. if (dir.StartsWith("."))
  242. continue;
  243. String autoResourceDir = autoLoadPath + "/" + dir;
  244. if (!cache->AddResourceDir(autoResourceDir, 0))
  245. {
  246. LOGERRORF("Failed to add resource directory %s in autoload path %s", dir.CString(), autoLoadPaths[i].CString());
  247. return false;
  248. }
  249. }
  250. // Add all the found package files (non-recursive)
  251. Vector<String> paks;
  252. fileSystem->ScanDir(paks, autoLoadPath, "*.pak", SCAN_FILES, false);
  253. for (unsigned y = 0; y < paks.Size(); ++y)
  254. {
  255. String pak = paks[y];
  256. if (pak.StartsWith("."))
  257. continue;
  258. String autoPackageName = autoLoadPath + "/" + pak;
  259. if (!cache->AddPackageFile(autoPackageName, 0))
  260. {
  261. LOGERRORF("Failed to add package file %s in autoload path %s", pak.CString(), autoLoadPaths[i].CString());
  262. return false;
  263. }
  264. }
  265. }
  266. else
  267. LOGDEBUGF("Skipped autoload path %s as it does not exist", autoLoadPaths[i].CString());
  268. }
  269. // Initialize graphics & audio output
  270. if (!headless_)
  271. {
  272. Graphics* graphics = GetSubsystem<Graphics>();
  273. Renderer* renderer = GetSubsystem<Renderer>();
  274. if (HasParameter(parameters, "ExternalWindow"))
  275. graphics->SetExternalWindow(GetParameter(parameters, "ExternalWindow").GetVoidPtr());
  276. graphics->SetForceSM2(GetParameter(parameters, "ForceSM2", false).GetBool());
  277. graphics->SetWindowTitle(GetParameter(parameters, "WindowTitle", "Urho3D").GetString());
  278. graphics->SetWindowIcon(cache->GetResource<Image>(GetParameter(parameters, "WindowIcon", String::EMPTY).GetString()));
  279. graphics->SetFlushGPU(GetParameter(parameters, "FlushGPU", false).GetBool());
  280. graphics->SetOrientations(GetParameter(parameters, "Orientations", "LandscapeLeft LandscapeRight").GetString());
  281. if (HasParameter(parameters, "WindowPositionX") && HasParameter(parameters, "WindowPositionY"))
  282. graphics->SetWindowPosition(GetParameter(parameters, "WindowPositionX").GetInt(), GetParameter(parameters, "WindowPositionY").GetInt());
  283. if (!graphics->SetMode(
  284. GetParameter(parameters, "WindowWidth", 0).GetInt(),
  285. GetParameter(parameters, "WindowHeight", 0).GetInt(),
  286. GetParameter(parameters, "FullScreen", true).GetBool(),
  287. GetParameter(parameters, "Borderless", false).GetBool(),
  288. GetParameter(parameters, "WindowResizable", false).GetBool(),
  289. GetParameter(parameters, "VSync", false).GetBool(),
  290. GetParameter(parameters, "TripleBuffer", false).GetBool(),
  291. GetParameter(parameters, "MultiSample", 1).GetInt()
  292. ))
  293. return false;
  294. if (HasParameter(parameters, "DumpShaders"))
  295. graphics->BeginDumpShaders(GetParameter(parameters, "DumpShaders", String::EMPTY).GetString());
  296. if (HasParameter(parameters, "RenderPath"))
  297. renderer->SetDefaultRenderPath(cache->GetResource<XMLFile>(GetParameter(parameters, "RenderPath").GetString()));
  298. renderer->SetDrawShadows(GetParameter(parameters, "Shadows", true).GetBool());
  299. if (renderer->GetDrawShadows() && GetParameter(parameters, "LowQualityShadows", false).GetBool())
  300. renderer->SetShadowQuality(SHADOWQUALITY_LOW_16BIT);
  301. renderer->SetMaterialQuality(GetParameter(parameters, "MaterialQuality", QUALITY_HIGH).GetInt());
  302. renderer->SetTextureQuality(GetParameter(parameters, "TextureQuality", QUALITY_HIGH).GetInt());
  303. renderer->SetTextureFilterMode((TextureFilterMode)GetParameter(parameters, "TextureFilterMode", FILTER_TRILINEAR).GetInt());
  304. renderer->SetTextureAnisotropy(GetParameter(parameters, "TextureAnisotropy", 4).GetInt());
  305. if (GetParameter(parameters, "Sound", true).GetBool())
  306. {
  307. GetSubsystem<Audio>()->SetMode(
  308. GetParameter(parameters, "SoundBuffer", 100).GetInt(),
  309. GetParameter(parameters, "SoundMixRate", 44100).GetInt(),
  310. GetParameter(parameters, "SoundStereo", true).GetBool(),
  311. GetParameter(parameters, "SoundInterpolation", true).GetBool()
  312. );
  313. }
  314. }
  315. // Init FPU state of main thread
  316. InitFPU();
  317. // Initialize input
  318. if (HasParameter(parameters, "TouchEmulation"))
  319. GetSubsystem<Input>()->SetTouchEmulation(GetParameter(parameters, "TouchEmulation").GetBool());
  320. #ifdef URHO3D_TESTING
  321. if (HasParameter(parameters, "TimeOut"))
  322. timeOut_ = GetParameter(parameters, "TimeOut", 0).GetInt() * 1000000LL;
  323. #endif
  324. // In debug mode, check now that all factory created objects can be created without crashing
  325. #ifdef _DEBUG
  326. const HashMap<StringHash, SharedPtr<ObjectFactory> >& factories = context_->GetObjectFactories();
  327. for (HashMap<StringHash, SharedPtr<ObjectFactory> >::ConstIterator i = factories.Begin(); i != factories.End(); ++i)
  328. SharedPtr<Object> object = i->second_->CreateObject();
  329. #endif
  330. frameTimer_.Reset();
  331. LOGINFO("Initialized engine");
  332. initialized_ = true;
  333. return true;
  334. }
  335. void Engine::RunFrame()
  336. {
  337. assert(initialized_);
  338. // If not headless, and the graphics subsystem no longer has a window open, assume we should exit
  339. if (!headless_ && !GetSubsystem<Graphics>()->IsInitialized())
  340. exiting_ = true;
  341. if (exiting_)
  342. return;
  343. // Note: there is a minimal performance cost to looking up subsystems (uses a hashmap); if they would be looked up several
  344. // times per frame it would be better to cache the pointers
  345. Time* time = GetSubsystem<Time>();
  346. Input* input = GetSubsystem<Input>();
  347. Audio* audio = GetSubsystem<Audio>();
  348. time->BeginFrame(timeStep_);
  349. // If pause when minimized -mode is in use, stop updates and audio as necessary
  350. if (pauseMinimized_ && input->IsMinimized())
  351. {
  352. if (audio->IsPlaying())
  353. {
  354. audio->Stop();
  355. audioPaused_ = true;
  356. }
  357. }
  358. else
  359. {
  360. // Only unpause when it was paused by the engine
  361. if (audioPaused_)
  362. {
  363. audio->Play();
  364. audioPaused_ = false;
  365. }
  366. Update();
  367. }
  368. Render();
  369. ApplyFrameLimit();
  370. time->EndFrame();
  371. }
  372. Console* Engine::CreateConsole()
  373. {
  374. if (headless_ || !initialized_)
  375. return 0;
  376. // Return existing console if possible
  377. Console* console = GetSubsystem<Console>();
  378. if (!console)
  379. {
  380. console = new Console(context_);
  381. context_->RegisterSubsystem(console);
  382. }
  383. return console;
  384. }
  385. DebugHud* Engine::CreateDebugHud()
  386. {
  387. if (headless_ || !initialized_)
  388. return 0;
  389. // Return existing debug HUD if possible
  390. DebugHud* debugHud = GetSubsystem<DebugHud>();
  391. if (!debugHud)
  392. {
  393. debugHud = new DebugHud(context_);
  394. context_->RegisterSubsystem(debugHud);
  395. }
  396. return debugHud;
  397. }
  398. void Engine::SetTimeStepSmoothing(int frames)
  399. {
  400. timeStepSmoothing_ = Clamp(frames, 1, 20);
  401. }
  402. void Engine::SetMinFps(int fps)
  403. {
  404. minFps_ = Max(fps, 0);
  405. }
  406. void Engine::SetMaxFps(int fps)
  407. {
  408. maxFps_ = Max(fps, 0);
  409. }
  410. void Engine::SetMaxInactiveFps(int fps)
  411. {
  412. maxInactiveFps_ = Max(fps, 0);
  413. }
  414. void Engine::SetPauseMinimized(bool enable)
  415. {
  416. pauseMinimized_ = enable;
  417. }
  418. void Engine::SetAutoExit(bool enable)
  419. {
  420. // On mobile platforms exit is mandatory if requested by the platform itself and should not be attempted to be disabled
  421. #if defined(ANDROID) || defined(IOS)
  422. enable = true;
  423. #endif
  424. autoExit_ = enable;
  425. }
  426. void Engine::SetNextTimeStep(float seconds)
  427. {
  428. timeStep_ = Max(seconds, 0.0f);
  429. }
  430. void Engine::Exit()
  431. {
  432. #if defined(IOS)
  433. // On iOS it's not legal for the application to exit on its own, instead it will be minimized with the home key
  434. #else
  435. DoExit();
  436. #endif
  437. }
  438. void Engine::DumpProfiler()
  439. {
  440. Profiler* profiler = GetSubsystem<Profiler>();
  441. if (profiler)
  442. LOGRAW(profiler->GetData(true, true) + "\n");
  443. }
  444. void Engine::DumpResources(bool dumpFileName)
  445. {
  446. #ifdef URHO3D_LOGGING
  447. ResourceCache* cache = GetSubsystem<ResourceCache>();
  448. const HashMap<StringHash, ResourceGroup>& resourceGroups = cache->GetAllResources();
  449. LOGRAW("\n");
  450. if (dumpFileName)
  451. {
  452. LOGRAW("Used resources:\n");
  453. }
  454. for (HashMap<StringHash, ResourceGroup>::ConstIterator i = resourceGroups.Begin();
  455. i != resourceGroups.End(); ++i)
  456. {
  457. const HashMap<StringHash, SharedPtr<Resource> >& resources = i->second_.resources_;
  458. if (dumpFileName)
  459. {
  460. for (HashMap<StringHash, SharedPtr<Resource> >::ConstIterator j = resources.Begin();
  461. j != resources.End(); ++j)
  462. {
  463. LOGRAW(j->second_->GetName() + "\n");
  464. }
  465. }
  466. else
  467. {
  468. unsigned num = resources.Size();
  469. unsigned memoryUse = i->second_.memoryUse_;
  470. if (num)
  471. {
  472. LOGRAW("Resource type " + resources.Begin()->second_->GetTypeName() +
  473. ": count " + String(num) + " memory use " + String(memoryUse) + "\n");
  474. }
  475. }
  476. }
  477. if (!dumpFileName)
  478. {
  479. LOGRAW("Total memory use of all resources " + String(cache->GetTotalMemoryUse()) + "\n\n");
  480. }
  481. #endif
  482. }
  483. void Engine::DumpMemory()
  484. {
  485. #ifdef URHO3D_LOGGING
  486. #if defined(_MSC_VER) && defined(_DEBUG)
  487. _CrtMemState state;
  488. _CrtMemCheckpoint(&state);
  489. _CrtMemBlockHeader* block = state.pBlockHeader;
  490. unsigned total = 0;
  491. unsigned blocks = 0;
  492. for (;;)
  493. {
  494. if (block && block->pBlockHeaderNext)
  495. block = block->pBlockHeaderNext;
  496. else
  497. break;
  498. }
  499. while (block)
  500. {
  501. if (block->nBlockUse > 0)
  502. {
  503. if (block->szFileName)
  504. LOGRAW("Block " + String((int)block->lRequest) + ": " + String(block->nDataSize) + " bytes, file " + String(block->szFileName) + " line " + String(block->nLine) + "\n");
  505. else
  506. LOGRAW("Block " + String((int)block->lRequest) + ": " + String(block->nDataSize) + " bytes\n");
  507. total += block->nDataSize;
  508. ++blocks;
  509. }
  510. block = block->pBlockHeaderPrev;
  511. }
  512. LOGRAW("Total allocated memory " + String(total) + " bytes in " + String(blocks) + " blocks\n\n");
  513. #else
  514. LOGRAW("DumpMemory() supported on MSVC debug mode only\n\n");
  515. #endif
  516. #endif
  517. }
  518. void Engine::Update()
  519. {
  520. PROFILE(Update);
  521. // Logic update event
  522. using namespace Update;
  523. VariantMap& eventData = GetEventDataMap();
  524. eventData[P_TIMESTEP] = timeStep_;
  525. SendEvent(E_UPDATE, eventData);
  526. // Logic post-update event
  527. SendEvent(E_POSTUPDATE, eventData);
  528. // Rendering update event
  529. SendEvent(E_RENDERUPDATE, eventData);
  530. // Post-render update event
  531. SendEvent(E_POSTRENDERUPDATE, eventData);
  532. }
  533. void Engine::Render()
  534. {
  535. if (headless_)
  536. return;
  537. PROFILE(Render);
  538. // If device is lost, BeginFrame will fail and we skip rendering
  539. Graphics* graphics = GetSubsystem<Graphics>();
  540. if (!graphics->BeginFrame())
  541. return;
  542. GetSubsystem<Renderer>()->Render();
  543. GetSubsystem<UI>()->Render();
  544. graphics->EndFrame();
  545. }
  546. void Engine::ApplyFrameLimit()
  547. {
  548. if (!initialized_)
  549. return;
  550. int maxFps = maxFps_;
  551. Input* input = GetSubsystem<Input>();
  552. if (input && !input->HasFocus())
  553. maxFps = Min(maxInactiveFps_, maxFps);
  554. long long elapsed = 0;
  555. // Perform waiting loop if maximum FPS set
  556. if (maxFps)
  557. {
  558. PROFILE(ApplyFrameLimit);
  559. long long targetMax = 1000000LL / maxFps;
  560. for (;;)
  561. {
  562. elapsed = frameTimer_.GetUSec(false);
  563. if (elapsed >= targetMax)
  564. break;
  565. // Sleep if 1 ms or more off the frame limiting goal
  566. if (targetMax - elapsed >= 1000LL)
  567. {
  568. unsigned sleepTime = (unsigned)((targetMax - elapsed) / 1000LL);
  569. Time::Sleep(sleepTime);
  570. }
  571. }
  572. }
  573. elapsed = frameTimer_.GetUSec(true);
  574. #ifdef URHO3D_TESTING
  575. if (timeOut_ > 0)
  576. {
  577. timeOut_ -= elapsed;
  578. if (timeOut_ <= 0)
  579. Exit();
  580. }
  581. #endif
  582. // If FPS lower than minimum, clamp elapsed time
  583. if (minFps_)
  584. {
  585. long long targetMin = 1000000LL / minFps_;
  586. if (elapsed > targetMin)
  587. elapsed = targetMin;
  588. }
  589. // Perform timestep smoothing
  590. timeStep_ = 0.0f;
  591. lastTimeSteps_.Push(elapsed / 1000000.0f);
  592. if (lastTimeSteps_.Size() > timeStepSmoothing_)
  593. {
  594. // If the smoothing configuration was changed, ensure correct amount of samples
  595. lastTimeSteps_.Erase(0, lastTimeSteps_.Size() - timeStepSmoothing_);
  596. for (unsigned i = 0; i < lastTimeSteps_.Size(); ++i)
  597. timeStep_ += lastTimeSteps_[i];
  598. timeStep_ /= lastTimeSteps_.Size();
  599. }
  600. else
  601. timeStep_ = lastTimeSteps_.Back();
  602. }
  603. VariantMap Engine::ParseParameters(const Vector<String>& arguments)
  604. {
  605. VariantMap ret;
  606. for (unsigned i = 0; i < arguments.Size(); ++i)
  607. {
  608. if (arguments[i].Length() > 1 && arguments[i][0] == '-')
  609. {
  610. String argument = arguments[i].Substring(1).ToLower();
  611. String value = i + 1 < arguments.Size() ? arguments[i + 1] : String::EMPTY;
  612. if (argument == "headless")
  613. ret["Headless"] = true;
  614. else if (argument == "nolimit")
  615. ret["FrameLimiter"] = false;
  616. else if (argument == "flushgpu")
  617. ret["FlushGPU"] = true;
  618. else if (argument == "landscape")
  619. ret["Orientations"] = "LandscapeLeft LandscapeRight " + ret["Orientations"].GetString();
  620. else if (argument == "portrait")
  621. ret["Orientations"] = "Portrait PortraitUpsideDown " + ret["Orientations"].GetString();
  622. else if (argument == "nosound")
  623. ret["Sound"] = false;
  624. else if (argument == "noip")
  625. ret["SoundInterpolation"] = false;
  626. else if (argument == "mono")
  627. ret["SoundStereo"] = false;
  628. else if (argument == "prepass")
  629. ret["RenderPath"] = "RenderPaths/Prepass.xml";
  630. else if (argument == "deferred")
  631. ret["RenderPath"] = "RenderPaths/Deferred.xml";
  632. else if (argument == "noshadows")
  633. ret["Shadows"] = false;
  634. else if (argument == "lqshadows")
  635. ret["LowQualityShadows"] = true;
  636. else if (argument == "nothreads")
  637. ret["WorkerThreads"] = false;
  638. else if (argument == "sm2")
  639. ret["ForceSM2"] = true;
  640. else if (argument == "v")
  641. ret["VSync"] = true;
  642. else if (argument == "t")
  643. ret["TripleBuffer"] = true;
  644. else if (argument == "w")
  645. ret["FullScreen"] = false;
  646. else if (argument == "s")
  647. ret["WindowResizable"] = true;
  648. else if (argument == "borderless")
  649. ret["Borderless"] = true;
  650. else if (argument == "q")
  651. ret["LogQuiet"] = true;
  652. else if (argument == "log" && !value.Empty())
  653. {
  654. int logLevel = GetStringListIndex(value.CString(), logLevelPrefixes, -1);
  655. if (logLevel != -1)
  656. {
  657. ret["LogLevel"] = logLevel;
  658. ++i;
  659. }
  660. }
  661. else if (argument == "x" && !value.Empty())
  662. {
  663. ret["WindowWidth"] = ToInt(value);
  664. ++i;
  665. }
  666. else if (argument == "y" && !value.Empty())
  667. {
  668. ret["WindowHeight"] = ToInt(value);
  669. ++i;
  670. }
  671. else if (argument == "m" && !value.Empty())
  672. {
  673. ret["MultiSample"] = ToInt(value);
  674. ++i;
  675. }
  676. else if (argument == "b" && !value.Empty())
  677. {
  678. ret["SoundBuffer"] = ToInt(value);
  679. ++i;
  680. }
  681. else if (argument == "r" && !value.Empty())
  682. {
  683. ret["SoundMixRate"] = ToInt(value);
  684. ++i;
  685. }
  686. else if (argument == "pp" && !value.Empty())
  687. {
  688. ret["ResourcePrefixPath"] = value;
  689. ++i;
  690. }
  691. else if (argument == "p" && !value.Empty())
  692. {
  693. ret["ResourcePaths"] = value;
  694. ++i;
  695. }
  696. else if (argument == "pf" && !value.Empty())
  697. {
  698. ret["ResourcePackages"] = value;
  699. ++i;
  700. }
  701. else if (argument == "ap" && !value.Empty())
  702. {
  703. ret["AutoloadPaths"] = value;
  704. ++i;
  705. }
  706. else if (argument == "ds" && !value.Empty())
  707. {
  708. ret["DumpShaders"] = value;
  709. ++i;
  710. }
  711. else if (argument == "mq" && !value.Empty())
  712. {
  713. ret["MaterialQuality"] = ToInt(value);
  714. ++i;
  715. }
  716. else if (argument == "tq" && !value.Empty())
  717. {
  718. ret["TextureQuality"] = ToInt(value);
  719. ++i;
  720. }
  721. else if (argument == "tf" && !value.Empty())
  722. {
  723. ret["TextureFilterMode"] = ToInt(value);
  724. ++i;
  725. }
  726. else if (argument == "af" && !value.Empty())
  727. {
  728. ret["TextureFilterMode"] = FILTER_ANISOTROPIC;
  729. ret["TextureAnisotropy"] = ToInt(value);
  730. ++i;
  731. }
  732. else if (argument == "touch")
  733. ret["TouchEmulation"] = true;
  734. #ifdef URHO3D_TESTING
  735. else if (argument == "timeout" && !value.Empty())
  736. {
  737. ret["TimeOut"] = ToInt(value);
  738. ++i;
  739. }
  740. #endif
  741. }
  742. }
  743. return ret;
  744. }
  745. bool Engine::HasParameter(const VariantMap& parameters, const String& parameter)
  746. {
  747. StringHash nameHash(parameter);
  748. return parameters.Find(nameHash) != parameters.End();
  749. }
  750. const Variant& Engine::GetParameter(const VariantMap& parameters, const String& parameter, const Variant& defaultValue)
  751. {
  752. StringHash nameHash(parameter);
  753. VariantMap::ConstIterator i = parameters.Find(nameHash);
  754. return i != parameters.End() ? i->second_ : defaultValue;
  755. }
  756. void Engine::HandleExitRequested(StringHash eventType, VariantMap& eventData)
  757. {
  758. if (autoExit_)
  759. {
  760. // Do not call Exit() here, as it contains mobile platform -specific tests to not exit.
  761. // If we do receive an exit request from the system on those platforms, we must comply
  762. DoExit();
  763. }
  764. }
  765. void Engine::DoExit()
  766. {
  767. Graphics* graphics = GetSubsystem<Graphics>();
  768. if (graphics)
  769. graphics->Close();
  770. exiting_ = true;
  771. }
  772. }