Engine.cpp 31 KB

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