Engine.cpp 30 KB

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