Engine.cpp 32 KB

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