Engine.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  1. //
  2. // Copyright (c) 2008-2013 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. #include "Navigation.h"
  35. #include "Network.h"
  36. #include "PackageFile.h"
  37. #include "PhysicsWorld.h"
  38. #include "ProcessUtils.h"
  39. #include "Profiler.h"
  40. #include "Renderer.h"
  41. #include "ResourceCache.h"
  42. #include "Scene.h"
  43. #include "SceneEvents.h"
  44. #include "StringUtils.h"
  45. #include "UI.h"
  46. #include "WorkQueue.h"
  47. #include "XMLFile.h"
  48. #include "DebugNew.h"
  49. #if defined(_MSC_VER) && defined(_DEBUG)
  50. // From dbgint.h
  51. #define nNoMansLandSize 4
  52. typedef struct _CrtMemBlockHeader
  53. {
  54. struct _CrtMemBlockHeader* pBlockHeaderNext;
  55. struct _CrtMemBlockHeader* pBlockHeaderPrev;
  56. char* szFileName;
  57. int nLine;
  58. size_t nDataSize;
  59. int nBlockUse;
  60. long lRequest;
  61. unsigned char gap[nNoMansLandSize];
  62. } _CrtMemBlockHeader;
  63. #endif
  64. #ifdef ANDROID
  65. extern "C"
  66. {
  67. void Android_JNI_FinishActivity();
  68. }
  69. #endif
  70. namespace Urho3D
  71. {
  72. extern const char* logLevelPrefixes[];
  73. Engine::Engine(Context* context) :
  74. Object(context),
  75. timeStep_(0.0f),
  76. timeStepSmoothing_(2),
  77. minFps_(10),
  78. #if defined(ANDROID) || defined(IOS) || defined(RASPI)
  79. maxFps_(60),
  80. maxInactiveFps_(10),
  81. pauseMinimized_(true),
  82. #else
  83. maxFps_(200),
  84. maxInactiveFps_(60),
  85. pauseMinimized_(false),
  86. #endif
  87. #ifdef ENABLE_TESTING
  88. timeOut_(0),
  89. #endif
  90. autoExit_(true),
  91. initialized_(false),
  92. #ifdef ANDROID
  93. exitRequested_(false),
  94. #endif
  95. exiting_(false),
  96. headless_(false),
  97. audioPaused_(false)
  98. {
  99. // Register self as a subsystem
  100. context_->RegisterSubsystem(this);
  101. // Create subsystems which do not depend on engine initialization or startup parameters
  102. context_->RegisterSubsystem(new Time(context_));
  103. context_->RegisterSubsystem(new WorkQueue(context_));
  104. #ifdef ENABLE_PROFILING
  105. context_->RegisterSubsystem(new Profiler(context_));
  106. #endif
  107. context_->RegisterSubsystem(new FileSystem(context_));
  108. #ifdef ENABLE_LOGGING
  109. context_->RegisterSubsystem(new Log(context_));
  110. #endif
  111. context_->RegisterSubsystem(new ResourceCache(context_));
  112. context_->RegisterSubsystem(new Network(context_));
  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. RegisterPhysicsLibrary(context_);
  119. RegisterNavigationLibrary(context_);
  120. SubscribeToEvent(E_EXITREQUESTED, HANDLER(Engine, HandleExitRequested));
  121. }
  122. Engine::~Engine()
  123. {
  124. }
  125. bool Engine::Initialize(const VariantMap& parameters)
  126. {
  127. if (initialized_)
  128. return true;
  129. PROFILE(InitEngine);
  130. // Set headless mode
  131. headless_ = GetParameter(parameters, "Headless", false).GetBool();
  132. // Register the rest of the subsystems
  133. if (!headless_)
  134. {
  135. context_->RegisterSubsystem(new Graphics(context_));
  136. context_->RegisterSubsystem(new Renderer(context_));
  137. }
  138. else
  139. {
  140. // Register graphics library objects explicitly in headless mode to allow them to work without using actual GPU resources
  141. RegisterGraphicsLibrary(context_);
  142. }
  143. // In debug mode, check now that all factory created objects can be created without crashing
  144. #ifdef _DEBUG
  145. const HashMap<ShortStringHash, SharedPtr<ObjectFactory> >& factories = context_->GetObjectFactories();
  146. for (HashMap<ShortStringHash, SharedPtr<ObjectFactory> >::ConstIterator i = factories.Begin(); i != factories.End(); ++i)
  147. SharedPtr<Object> object = i->second_->CreateObject();
  148. #endif
  149. // Start logging
  150. Log* log = GetSubsystem<Log>();
  151. if (log)
  152. {
  153. if (HasParameter(parameters, "LogLevel"))
  154. log->SetLevel(GetParameter(parameters, "LogLevel").GetInt());
  155. log->SetQuiet(GetParameter(parameters, "LogQuiet", false).GetBool());
  156. log->Open(GetParameter(parameters, "LogName", "Urho3D.log").GetString());
  157. }
  158. // Set maximally accurate low res timer
  159. GetSubsystem<Time>()->SetTimerPeriod(1);
  160. // Configure max FPS
  161. if (GetParameter(parameters, "FrameLimiter", true) == false)
  162. SetMaxFps(0);
  163. // Set amount of worker threads according to the available physical CPU cores. Using also hyperthreaded cores results in
  164. // unpredictable extra synchronization overhead. Also reserve one core for the main thread
  165. unsigned numThreads = GetParameter(parameters, "WorkerThreads", true).GetBool() ? GetNumPhysicalCPUs() - 1 : 0;
  166. if (numThreads)
  167. {
  168. GetSubsystem<WorkQueue>()->CreateThreads(numThreads);
  169. LOGINFO(ToString("Created %u worker thread%s", numThreads, numThreads > 1 ? "s" : ""));
  170. }
  171. // Add resource paths
  172. ResourceCache* cache = GetSubsystem<ResourceCache>();
  173. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  174. String exePath = fileSystem->GetProgramDir();
  175. Vector<String> resourcePaths = GetParameter(parameters, "ResourcePaths", "CoreData;Data").GetString().Split(';');
  176. Vector<String> resourcePackages = GetParameter(parameters, "ResourcePackages").GetString().Split(';');
  177. for (unsigned i = 0; i < resourcePaths.Size(); ++i)
  178. {
  179. bool success = false;
  180. // If path is not absolute, prefer to add it as a package if possible
  181. if (!IsAbsolutePath(resourcePaths[i]))
  182. {
  183. String packageName = exePath + resourcePaths[i] + ".pak";
  184. if (fileSystem->FileExists(packageName))
  185. {
  186. SharedPtr<PackageFile> package(new PackageFile(context_));
  187. if (package->Open(packageName))
  188. {
  189. cache->AddPackageFile(package);
  190. success = true;
  191. }
  192. }
  193. if (!success)
  194. {
  195. String pathName = exePath + 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. LOGERROR("Failed to add resource path " + resourcePaths[i]);
  209. return false;
  210. }
  211. }
  212. // Then add specified packages
  213. for (unsigned i = 0; i < resourcePackages.Size(); ++i)
  214. {
  215. bool success = false;
  216. String packageName = exePath + resourcePackages[i];
  217. if (fileSystem->FileExists(packageName))
  218. {
  219. SharedPtr<PackageFile> package(new PackageFile(context_));
  220. if (package->Open(packageName))
  221. {
  222. cache->AddPackageFile(package);
  223. success = true;
  224. }
  225. }
  226. if (!success)
  227. {
  228. LOGERROR("Failed to add resource package " + resourcePackages[i]);
  229. return false;
  230. }
  231. }
  232. // Initialize graphics & audio output
  233. if (!headless_)
  234. {
  235. Graphics* graphics = GetSubsystem<Graphics>();
  236. Renderer* renderer = GetSubsystem<Renderer>();
  237. if (HasParameter(parameters, "ExternalWindow"))
  238. graphics->SetExternalWindow(GetParameter(parameters, "ExternalWindow").GetPtr());
  239. graphics->SetForceSM2(GetParameter(parameters, "ForceSM2", false).GetBool());
  240. graphics->SetWindowTitle(GetParameter(parameters, "WindowTitle", "Urho3D").GetString());
  241. graphics->SetWindowIcon(cache->GetResource<Image>(GetParameter(parameters, "WindowIcon", String::EMPTY).GetString()));
  242. if (!graphics->SetMode(
  243. GetParameter(parameters, "WindowWidth", 0).GetInt(),
  244. GetParameter(parameters, "WindowHeight", 0).GetInt(),
  245. GetParameter(parameters, "FullScreen", true).GetBool(),
  246. GetParameter(parameters, "Borderless", false).GetBool(),
  247. GetParameter(parameters, "WindowResizable", false).GetBool(),
  248. GetParameter(parameters, "VSync", false).GetBool(),
  249. GetParameter(parameters, "TripleBuffer", false).GetBool(),
  250. GetParameter(parameters, "MultiSample", 1).GetInt()
  251. ))
  252. return false;
  253. if (HasParameter(parameters, "RenderPath"))
  254. renderer->SetDefaultRenderPath(cache->GetResource<XMLFile>(GetParameter(parameters, "RenderPath").GetString()));
  255. renderer->SetDrawShadows(GetParameter(parameters, "Shadows", true).GetBool());
  256. if (renderer->GetDrawShadows() && GetParameter(parameters, "LowQualityShadows", false).GetBool())
  257. renderer->SetShadowQuality(SHADOWQUALITY_LOW_16BIT);
  258. if (GetParameter(parameters, "Sound", true).GetBool())
  259. {
  260. GetSubsystem<Audio>()->SetMode(
  261. GetParameter(parameters, "SoundBuffer", 100).GetInt(),
  262. GetParameter(parameters, "SoundMixRate", 44100).GetInt(),
  263. GetParameter(parameters, "SoundStereo", true).GetBool(),
  264. GetParameter(parameters, "SoundInterpolation", true).GetBool()
  265. );
  266. }
  267. }
  268. // Init FPU state of main thread
  269. InitFPU();
  270. #ifdef ENABLE_TESTING
  271. if (HasParameter(parameters, "TimeOut"))
  272. timeOut_ = GetParameter(parameters, "TimeOut", 0).GetInt() * 1000000LL;
  273. #endif
  274. frameTimer_.Reset();
  275. initialized_ = true;
  276. return true;
  277. }
  278. void Engine::RunFrame()
  279. {
  280. assert(initialized_);
  281. // If not headless, and the graphics subsystem no longer has a window open, assume we should exit
  282. if (!headless_ && !GetSubsystem<Graphics>()->IsInitialized())
  283. exiting_ = true;
  284. if (exiting_)
  285. return;
  286. // Note: there is a minimal performance cost to looking up subsystems (uses a hashmap); if they would be looked up several
  287. // times per frame it would be better to cache the pointers
  288. Time* time = GetSubsystem<Time>();
  289. Input* input = GetSubsystem<Input>();
  290. Audio* audio = GetSubsystem<Audio>();
  291. time->BeginFrame(timeStep_);
  292. // If pause when minimized -mode is in use, stop updates and audio as necessary
  293. if (pauseMinimized_ && input->IsMinimized())
  294. {
  295. if (audio->IsPlaying())
  296. {
  297. audio->Stop();
  298. audioPaused_ = true;
  299. }
  300. }
  301. else
  302. {
  303. // Only unpause when it was paused by the engine
  304. if (audioPaused_)
  305. {
  306. audio->Play();
  307. audioPaused_ = false;
  308. }
  309. Update();
  310. }
  311. Render();
  312. ApplyFrameLimit();
  313. time->EndFrame();
  314. }
  315. Console* Engine::CreateConsole()
  316. {
  317. if (headless_ || !initialized_)
  318. return 0;
  319. // Return existing console if possible
  320. Console* console = GetSubsystem<Console>();
  321. if (!console)
  322. {
  323. console = new Console(context_);
  324. context_->RegisterSubsystem(console);
  325. }
  326. return console;
  327. }
  328. DebugHud* Engine::CreateDebugHud()
  329. {
  330. if (headless_ || !initialized_)
  331. return 0;
  332. // Return existing debug HUD if possible
  333. DebugHud* debugHud = GetSubsystem<DebugHud>();
  334. if (!debugHud)
  335. {
  336. debugHud = new DebugHud(context_);
  337. context_->RegisterSubsystem(debugHud);
  338. }
  339. return debugHud;
  340. }
  341. void Engine::SetTimeStepSmoothing(int frames)
  342. {
  343. timeStepSmoothing_ = Clamp(frames, 1, 20);
  344. }
  345. void Engine::SetMinFps(int fps)
  346. {
  347. minFps_ = Max(fps, 0);
  348. }
  349. void Engine::SetMaxFps(int fps)
  350. {
  351. maxFps_ = Max(fps, 0);
  352. }
  353. void Engine::SetMaxInactiveFps(int fps)
  354. {
  355. maxInactiveFps_ = Max(fps, 0);
  356. }
  357. void Engine::SetPauseMinimized(bool enable)
  358. {
  359. pauseMinimized_ = enable;
  360. }
  361. void Engine::SetAutoExit(bool enable)
  362. {
  363. // On mobile platforms exit is mandatory if requested by the platform itself and should not be attempted to be disabled
  364. #if defined(ANDROID) || defined(IOS)
  365. enable = true;
  366. #endif
  367. autoExit_ = enable;
  368. }
  369. void Engine::Exit()
  370. {
  371. #if defined(IOS)
  372. // On iOS it's not legal for the application to exit on its own, instead it will be minimized with the home key
  373. #elif defined(ANDROID)
  374. // On Android we request the Java activity to finish itself
  375. if (!exitRequested_)
  376. {
  377. Android_JNI_FinishActivity();
  378. exitRequested_ = true;
  379. }
  380. #else
  381. DoExit();
  382. #endif
  383. }
  384. void Engine::DumpProfiler()
  385. {
  386. Profiler* profiler = GetSubsystem<Profiler>();
  387. if (profiler)
  388. LOGRAW(profiler->GetData(true, true) + "\n");
  389. }
  390. void Engine::DumpResources()
  391. {
  392. #ifdef ENABLE_LOGGING
  393. ResourceCache* cache = GetSubsystem<ResourceCache>();
  394. const HashMap<ShortStringHash, ResourceGroup>& resourceGroups = cache->GetAllResources();
  395. LOGRAW("\n");
  396. for (HashMap<ShortStringHash, ResourceGroup>::ConstIterator i = resourceGroups.Begin();
  397. i != resourceGroups.End(); ++i)
  398. {
  399. unsigned num = i->second_.resources_.Size();
  400. unsigned memoryUse = i->second_.memoryUse_;
  401. if (num)
  402. {
  403. LOGRAW("Resource type " + i->second_.resources_.Begin()->second_->GetTypeName() +
  404. ": count " + String(num) + " memory use " + String(memoryUse) + "\n");
  405. }
  406. }
  407. LOGRAW("Total memory use of all resources " + String(cache->GetTotalMemoryUse()) + "\n\n");
  408. #endif
  409. }
  410. void Engine::DumpMemory()
  411. {
  412. #ifdef ENABLE_LOGGING
  413. #if defined(_MSC_VER) && defined(_DEBUG)
  414. _CrtMemState state;
  415. _CrtMemCheckpoint(&state);
  416. _CrtMemBlockHeader* block = state.pBlockHeader;
  417. unsigned total = 0;
  418. unsigned blocks = 0;
  419. for (;;)
  420. {
  421. if (block && block->pBlockHeaderNext)
  422. block = block->pBlockHeaderNext;
  423. else
  424. break;
  425. }
  426. while (block)
  427. {
  428. if (block->nBlockUse > 0)
  429. {
  430. if (block->szFileName)
  431. LOGRAW("Block " + String((int)block->lRequest) + ": " + String(block->nDataSize) + " bytes, file " + String(block->szFileName) + " line " + String(block->nLine) + "\n");
  432. else
  433. LOGRAW("Block " + String((int)block->lRequest) + ": " + String(block->nDataSize) + " bytes\n");
  434. total += block->nDataSize;
  435. ++blocks;
  436. }
  437. block = block->pBlockHeaderPrev;
  438. }
  439. LOGRAW("Total allocated memory " + String(total) + " bytes in " + String(blocks) + " blocks\n\n");
  440. #else
  441. LOGRAW("DumpMemory() supported on MSVC debug mode only\n\n");
  442. #endif
  443. #endif
  444. }
  445. void Engine::Update()
  446. {
  447. PROFILE(Update);
  448. // Logic update event
  449. using namespace Update;
  450. VariantMap eventData;
  451. eventData[P_TIMESTEP] = timeStep_;
  452. SendEvent(E_UPDATE, eventData);
  453. // Logic post-update event
  454. SendEvent(E_POSTUPDATE, eventData);
  455. // Rendering update event
  456. SendEvent(E_RENDERUPDATE, eventData);
  457. // Post-render update event
  458. SendEvent(E_POSTRENDERUPDATE, eventData);
  459. }
  460. void Engine::Render()
  461. {
  462. if (headless_)
  463. return;
  464. PROFILE(Render);
  465. // If device is lost, BeginFrame will fail and we skip rendering
  466. Graphics* graphics = GetSubsystem<Graphics>();
  467. if (!graphics->BeginFrame())
  468. return;
  469. GetSubsystem<Renderer>()->Render();
  470. GetSubsystem<UI>()->Render();
  471. graphics->EndFrame();
  472. }
  473. void Engine::ApplyFrameLimit()
  474. {
  475. if (!initialized_)
  476. return;
  477. int maxFps = maxFps_;
  478. Input* input = GetSubsystem<Input>();
  479. if (input && !input->HasFocus())
  480. maxFps = Min(maxInactiveFps_, maxFps);
  481. long long elapsed = 0;
  482. // Perform waiting loop if maximum FPS set
  483. if (maxFps)
  484. {
  485. PROFILE(ApplyFrameLimit);
  486. long long targetMax = 1000000LL / maxFps;
  487. for (;;)
  488. {
  489. elapsed = frameTimer_.GetUSec(false);
  490. if (elapsed >= targetMax)
  491. break;
  492. // Sleep if 1 ms or more off the frame limiting goal
  493. if (targetMax - elapsed >= 1000LL)
  494. {
  495. unsigned sleepTime = (unsigned)((targetMax - elapsed) / 1000LL);
  496. Time::Sleep(sleepTime);
  497. }
  498. }
  499. }
  500. elapsed = frameTimer_.GetUSec(true);
  501. #ifdef ENABLE_TESTING
  502. if (timeOut_ != 0)
  503. {
  504. timeOut_ -= elapsed;
  505. if (timeOut_ < 0)
  506. Exit();
  507. }
  508. #endif
  509. // If FPS lower than minimum, clamp elapsed time
  510. if (minFps_)
  511. {
  512. long long targetMin = 1000000LL / minFps_;
  513. if (elapsed > targetMin)
  514. elapsed = targetMin;
  515. }
  516. // Perform timestep smoothing
  517. timeStep_ = 0.0f;
  518. lastTimeSteps_.Push(elapsed / 1000000.0f);
  519. if (lastTimeSteps_.Size() > timeStepSmoothing_)
  520. {
  521. // If the smoothing configuration was changed, ensure correct amount of samples
  522. lastTimeSteps_.Erase(0, lastTimeSteps_.Size() - timeStepSmoothing_);
  523. for (unsigned i = 0; i < lastTimeSteps_.Size(); ++i)
  524. timeStep_ += lastTimeSteps_[i];
  525. timeStep_ /= lastTimeSteps_.Size();
  526. }
  527. else
  528. timeStep_ = lastTimeSteps_.Back();
  529. }
  530. VariantMap Engine::ParseParameters(const Vector<String>& arguments)
  531. {
  532. VariantMap ret;
  533. for (unsigned i = 0; i < arguments.Size(); ++i)
  534. {
  535. if (arguments[i].Length() > 1 && arguments[i][0] == '-')
  536. {
  537. String argument = arguments[i].Substring(1).ToLower();
  538. String value = i + 1 < arguments.Size() ? arguments[i + 1] : String::EMPTY;
  539. if (argument == "headless")
  540. ret["Headless"] = true;
  541. else if (argument == "nolimit")
  542. ret["FrameLimiter"] = false;
  543. else if (argument == "nosound")
  544. ret["Sound"] = false;
  545. else if (argument == "noip")
  546. ret["SoundInterpolation"] = false;
  547. else if (argument == "mono")
  548. ret["SoundStereo"] = false;
  549. else if (argument == "prepass")
  550. ret["RenderPath"] = "RenderPaths/Prepass.xml";
  551. else if (argument == "deferred")
  552. ret["RenderPath"] = "RenderPaths/Deferred.xml";
  553. else if (argument == "noshadows")
  554. ret["Shadows"] = false;
  555. else if (argument == "lqshadows")
  556. ret["LowQualityShadows"] = true;
  557. else if (argument == "nothreads")
  558. ret["WorkerThreads"] = false;
  559. else if (argument == "sm2")
  560. ret["ForceSM2"] = true;
  561. else if (argument == "v")
  562. ret["VSync"] = true;
  563. else if (argument == "t")
  564. ret["TripleBuffer"] = true;
  565. else if (argument == "w")
  566. ret["FullScreen"] = false;
  567. else if (argument == "s")
  568. ret["WindowResizable"] = true;
  569. else if (argument == "borderless")
  570. ret["Borderless"] = true;
  571. else if (argument == "q")
  572. ret["LogQuiet"] = true;
  573. else if (argument == "log" && !value.Empty())
  574. {
  575. int logLevel = GetStringListIndex(value.CString(), logLevelPrefixes, -1);
  576. if (logLevel != -1)
  577. {
  578. ret["LogLevel"] = logLevel;
  579. ++i;
  580. }
  581. }
  582. else if (argument == "x" && !value.Empty())
  583. {
  584. ret["WindowWidth"] = ToInt(value);
  585. ++i;
  586. }
  587. else if (argument == "y" && !value.Empty())
  588. {
  589. ret["WindowHeight"] = ToInt(value);
  590. ++i;
  591. }
  592. else if (argument == "m" && !value.Empty())
  593. {
  594. ret["MultiSample"] = ToInt(value);
  595. ++i;
  596. }
  597. else if (argument == "b" && !value.Empty())
  598. {
  599. ret["SoundBuffer"] = ToInt(value);
  600. ++i;
  601. }
  602. else if (argument == "r" && !value.Empty())
  603. {
  604. ret["SoundMixRate"] = ToInt(value);
  605. ++i;
  606. }
  607. else if (argument == "p" && !value.Empty())
  608. {
  609. ret["ResourcePaths"] = value;
  610. ++i;
  611. }
  612. #ifdef ENABLE_TESTING
  613. else if (argument == "timeout" && !value.Empty())
  614. {
  615. ret["TimeOut"] = ToInt(value);
  616. ++i;
  617. }
  618. #endif
  619. }
  620. }
  621. return ret;
  622. }
  623. bool Engine::HasParameter(const VariantMap& parameters, const String& parameter)
  624. {
  625. ShortStringHash nameHash(parameter);
  626. return parameters.Find(nameHash) != parameters.End();
  627. }
  628. const Variant& Engine::GetParameter(const VariantMap& parameters, const String& parameter, const Variant& defaultValue)
  629. {
  630. ShortStringHash nameHash(parameter);
  631. VariantMap::ConstIterator i = parameters.Find(nameHash);
  632. return i != parameters.End() ? i->second_ : defaultValue;
  633. }
  634. void Engine::HandleExitRequested(StringHash eventType, VariantMap& eventData)
  635. {
  636. if (autoExit_)
  637. {
  638. // Do not call Exit() here, as it contains mobile platform -specific tests to not exit.
  639. // If we do receive an exit request from the system on those platforms, we must comply
  640. DoExit();
  641. }
  642. }
  643. void Engine::DoExit()
  644. {
  645. Graphics* graphics = GetSubsystem<Graphics>();
  646. if (graphics)
  647. graphics->Close();
  648. exiting_ = true;
  649. }
  650. }