Engine.cpp 29 KB

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