Engine.cpp 30 KB

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