Engine.cpp 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  1. //
  2. // Copyright (c) 2008-2017 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/EventProfiler.h"
  27. #include "../Core/ProcessUtils.h"
  28. #include "../Core/WorkQueue.h"
  29. #include "../Engine/Engine.h"
  30. #include "../Engine/EngineDefs.h"
  31. #include "../Graphics/Graphics.h"
  32. #include "../Graphics/Renderer.h"
  33. #include "../Input/Input.h"
  34. #include "../IO/FileSystem.h"
  35. #include "../IO/Log.h"
  36. #include "../IO/PackageFile.h"
  37. #ifdef ATOMIC_IK
  38. #include "../IK/IK.h"
  39. #endif
  40. // ATOMIC BEGIN
  41. #include "../Resource/XMLFile.h"
  42. // ATOMIC END
  43. #ifdef ATOMIC_NAVIGATION
  44. #include "../Navigation/NavigationMesh.h"
  45. #endif
  46. #ifdef ATOMIC_NETWORK
  47. #include "../Network/Network.h"
  48. #endif
  49. // ATOMIC BEGIN
  50. #ifdef ATOMIC_WEB
  51. #include "../Web/Web.h"
  52. #endif
  53. // ATOMIC END
  54. #ifdef ATOMIC_DATABASE
  55. #include "../Database/Database.h"
  56. #endif
  57. #ifdef ATOMIC_PHYSICS
  58. #include "../Physics/PhysicsWorld.h"
  59. #endif
  60. #include "../Resource/ResourceCache.h"
  61. #include "../Resource/Localization.h"
  62. #include "../Scene/Scene.h"
  63. #include "../Scene/SceneEvents.h"
  64. #include "../UI/UI.h"
  65. #ifdef ATOMIC_ATOMIC2D
  66. #include "../Atomic2D/Atomic2D.h"
  67. #endif
  68. #if defined(__EMSCRIPTEN__) && defined(ATOMIC_TESTING)
  69. #include <emscripten/emscripten.h>
  70. #endif
  71. #include "../DebugNew.h"
  72. // ATOMIC BEGIN
  73. static const float ENGINE_FPS_UPDATE_INTERVAL = 0.5f;
  74. // ATOMIC END
  75. #if defined(_MSC_VER) && defined(_DEBUG)
  76. // From dbgint.h
  77. #define nNoMansLandSize 4
  78. typedef struct _CrtMemBlockHeader
  79. {
  80. struct _CrtMemBlockHeader* pBlockHeaderNext;
  81. struct _CrtMemBlockHeader* pBlockHeaderPrev;
  82. char* szFileName;
  83. int nLine;
  84. size_t nDataSize;
  85. int nBlockUse;
  86. long lRequest;
  87. unsigned char gap[nNoMansLandSize];
  88. } _CrtMemBlockHeader;
  89. #endif
  90. namespace Atomic
  91. {
  92. extern const char* logLevelPrefixes[];
  93. Engine::Engine(Context* context) :
  94. Object(context),
  95. timeStep_(0.0f),
  96. timeStepSmoothing_(2),
  97. minFps_(10),
  98. #if defined(IOS) || defined(__ANDROID__) || defined(__arm__) || defined(__aarch64__)
  99. maxFps_(60),
  100. maxInactiveFps_(10),
  101. pauseMinimized_(true),
  102. #else
  103. maxFps_(200),
  104. maxInactiveFps_(60),
  105. pauseMinimized_(false),
  106. #endif
  107. #ifdef ATOMIC_TESTING
  108. timeOut_(0),
  109. #endif
  110. autoExit_(true),
  111. initialized_(false),
  112. exiting_(false),
  113. headless_(false),
  114. audioPaused_(false),
  115. // ATOMIC BEGIN
  116. paused_(false),
  117. runNextPausedFrame_(false),
  118. fpsTimeSinceUpdate_(ENGINE_FPS_UPDATE_INTERVAL),
  119. fpsFramesSinceUpdate_(0),
  120. fps_(0)
  121. // ATOMIC END
  122. {
  123. // Register self as a subsystem
  124. context_->RegisterSubsystem(this);
  125. // Create subsystems which do not depend on engine initialization or startup parameters
  126. context_->RegisterSubsystem(new Time(context_));
  127. context_->RegisterSubsystem(new WorkQueue(context_));
  128. #ifdef ATOMIC_PROFILING
  129. context_->RegisterSubsystem(new Profiler(context_));
  130. #endif
  131. context_->RegisterSubsystem(new FileSystem(context_));
  132. #ifdef ATOMIC_LOGGING
  133. context_->RegisterSubsystem(new Log(context_));
  134. #endif
  135. context_->RegisterSubsystem(new ResourceCache(context_));
  136. context_->RegisterSubsystem(new Localization(context_));
  137. #ifdef ATOMIC_NETWORK
  138. context_->RegisterSubsystem(new Network(context_));
  139. #endif
  140. // ATOMIC BEGIN
  141. #ifdef ATOMIC_WEB
  142. context_->RegisterSubsystem(new Web(context_));
  143. #endif
  144. // ATOMIC END
  145. #ifdef ATOMIC_DATABASE
  146. context_->RegisterSubsystem(new Database(context_));
  147. #endif
  148. context_->RegisterSubsystem(new Input(context_));
  149. context_->RegisterSubsystem(new Audio(context_));
  150. context_->RegisterSubsystem(new UI(context_));
  151. // Register object factories for libraries which are not automatically registered along with subsystem creation
  152. RegisterSceneLibrary(context_);
  153. #ifdef ATOMIC_IK
  154. RegisterIKLibrary(context_);
  155. #endif
  156. #ifdef ATOMIC_PHYSICS
  157. RegisterPhysicsLibrary(context_);
  158. #endif
  159. #ifdef ATOMIC_NAVIGATION
  160. RegisterNavigationLibrary(context_);
  161. #endif
  162. SubscribeToEvent(E_EXITREQUESTED, ATOMIC_HANDLER(Engine, HandleExitRequested));
  163. // ATOMIC BEGIN
  164. SubscribeToEvent(E_PAUSERESUMEREQUESTED, ATOMIC_HANDLER(Engine, HandlePauseResumeRequested));
  165. SubscribeToEvent(E_PAUSESTEPREQUESTED, ATOMIC_HANDLER(Engine, HandlePauseStepRequested));
  166. // ATOMIC END
  167. }
  168. Engine::~Engine()
  169. {
  170. }
  171. bool Engine::Initialize(const VariantMap& parameters)
  172. {
  173. if (initialized_)
  174. return true;
  175. ATOMIC_PROFILE(InitEngine);
  176. // Set headless mode
  177. headless_ = GetParameter(parameters, EP_HEADLESS, false).GetBool();
  178. // Register the rest of the subsystems
  179. if (!headless_)
  180. {
  181. context_->RegisterSubsystem(new Graphics(context_));
  182. context_->RegisterSubsystem(new Renderer(context_));
  183. }
  184. else
  185. {
  186. // Register graphics library objects explicitly in headless mode to allow them to work without using actual GPU resources
  187. RegisterGraphicsLibrary(context_);
  188. }
  189. #ifdef ATOMIC_ATOMIC2D
  190. // 2D graphics library is dependent on 3D graphics library
  191. RegisterAtomic2DLibrary(context_);
  192. #endif
  193. // Start logging
  194. Log* log = GetSubsystem<Log>();
  195. if (log)
  196. {
  197. if (HasParameter(parameters, EP_LOG_LEVEL))
  198. log->SetLevel(GetParameter(parameters, EP_LOG_LEVEL).GetInt());
  199. log->SetQuiet(GetParameter(parameters, EP_LOG_QUIET, false).GetBool());
  200. log->Open(GetParameter(parameters, EP_LOG_NAME, "Atomic.log").GetString());
  201. }
  202. // Set maximally accurate low res timer
  203. GetSubsystem<Time>()->SetTimerPeriod(1);
  204. // Configure max FPS
  205. if (GetParameter(parameters, EP_FRAME_LIMITER, true) == false)
  206. SetMaxFps(0);
  207. // Set amount of worker threads according to the available physical CPU cores. Using also hyperthreaded cores results in
  208. // unpredictable extra synchronization overhead. Also reserve one core for the main thread
  209. #ifdef ATOMIC_THREADING
  210. unsigned numThreads = GetParameter(parameters, EP_WORKER_THREADS, true).GetBool() ? GetNumPhysicalCPUs() - 1 : 0;
  211. if (numThreads)
  212. {
  213. GetSubsystem<WorkQueue>()->CreateThreads(numThreads);
  214. ATOMIC_LOGINFOF("Created %u worker thread%s", numThreads, numThreads > 1 ? "s" : "");
  215. }
  216. #endif
  217. // Add resource paths
  218. if (!InitializeResourceCache(parameters, false))
  219. return false;
  220. ResourceCache* cache = GetSubsystem<ResourceCache>();
  221. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  222. // Initialize graphics & audio output
  223. if (!headless_)
  224. {
  225. Graphics* graphics = GetSubsystem<Graphics>();
  226. Renderer* renderer = GetSubsystem<Renderer>();
  227. if (HasParameter(parameters, EP_EXTERNAL_WINDOW))
  228. graphics->SetExternalWindow(GetParameter(parameters, EP_EXTERNAL_WINDOW).GetVoidPtr());
  229. graphics->SetWindowTitle(GetParameter(parameters, EP_WINDOW_TITLE, "Atomic").GetString());
  230. graphics->SetWindowIcon(cache->GetResource<Image>(GetParameter(parameters, EP_WINDOW_ICON, String::EMPTY).GetString()));
  231. graphics->SetFlushGPU(GetParameter(parameters, EP_FLUSH_GPU, false).GetBool());
  232. graphics->SetOrientations(GetParameter(parameters, EP_ORIENTATIONS, "LandscapeLeft LandscapeRight").GetString());
  233. if (HasParameter(parameters, EP_WINDOW_POSITION_X) && HasParameter(parameters, EP_WINDOW_POSITION_Y))
  234. graphics->SetWindowPosition(GetParameter(parameters, EP_WINDOW_POSITION_X).GetInt(),
  235. GetParameter(parameters, EP_WINDOW_POSITION_Y).GetInt());
  236. #ifdef ATOMIC_OPENGL
  237. if (HasParameter(parameters, EP_FORCE_GL2))
  238. graphics->SetForceGL2(GetParameter(parameters, EP_FORCE_GL2).GetBool());
  239. #endif
  240. if (!graphics->SetMode(
  241. // ATOMIC BEGIN
  242. GetParameter(parameters, EP_WINDOW_MAXIMIZED, false).GetBool() ? 0 : GetParameter(parameters, EP_WINDOW_WIDTH, 0).GetInt(),
  243. GetParameter(parameters, EP_WINDOW_MAXIMIZED, false).GetBool() ? 0 : GetParameter(parameters, EP_WINDOW_HEIGHT, 0).GetInt(),
  244. // ATOMIC END
  245. GetParameter(parameters, EP_FULL_SCREEN, true).GetBool(),
  246. GetParameter(parameters, EP_BORDERLESS, false).GetBool(),
  247. GetParameter(parameters, EP_WINDOW_RESIZABLE, false).GetBool(),
  248. // ATOMIC BEGIN
  249. // default high dpi to false, until UI fully supports high dpi (including input)
  250. GetParameter(parameters, EP_HIGH_DPI, false).GetBool(),
  251. // ATOMIC END
  252. GetParameter(parameters, EP_VSYNC, false).GetBool(),
  253. GetParameter(parameters, EP_TRIPLE_BUFFER, false).GetBool(),
  254. GetParameter(parameters, EP_MULTI_SAMPLE, 1).GetInt(),
  255. GetParameter(parameters, EP_MONITOR, 0).GetInt(),
  256. GetParameter(parameters, EP_REFRESH_RATE, 0).GetInt()
  257. ))
  258. return false;
  259. graphics->SetShaderCacheDir(GetParameter(parameters, EP_SHADER_CACHE_DIR, fileSystem->GetAppPreferencesDir("atomic", "shadercache")).GetString());
  260. if (HasParameter(parameters, EP_DUMP_SHADERS))
  261. graphics->BeginDumpShaders(GetParameter(parameters, EP_DUMP_SHADERS, String::EMPTY).GetString());
  262. if (HasParameter(parameters, EP_RENDER_PATH))
  263. renderer->SetDefaultRenderPath(cache->GetResource<XMLFile>(GetParameter(parameters, EP_RENDER_PATH).GetString()));
  264. renderer->SetDrawShadows(GetParameter(parameters, EP_SHADOWS, true).GetBool());
  265. if (renderer->GetDrawShadows() && GetParameter(parameters, EP_LOW_QUALITY_SHADOWS, false).GetBool())
  266. renderer->SetShadowQuality(SHADOWQUALITY_SIMPLE_16BIT);
  267. renderer->SetMaterialQuality(GetParameter(parameters, EP_MATERIAL_QUALITY, QUALITY_HIGH).GetInt());
  268. renderer->SetTextureQuality(GetParameter(parameters, EP_TEXTURE_QUALITY, QUALITY_HIGH).GetInt());
  269. renderer->SetTextureFilterMode((TextureFilterMode)GetParameter(parameters, EP_TEXTURE_FILTER_MODE, FILTER_TRILINEAR).GetInt());
  270. renderer->SetTextureAnisotropy(GetParameter(parameters, EP_TEXTURE_ANISOTROPY, 4).GetInt());
  271. if (GetParameter(parameters, EP_SOUND, true).GetBool())
  272. {
  273. GetSubsystem<Audio>()->SetMode(
  274. GetParameter(parameters, EP_SOUND_BUFFER, 100).GetInt(),
  275. GetParameter(parameters, EP_SOUND_MIX_RATE, 44100).GetInt(),
  276. GetParameter(parameters, EP_SOUND_STEREO, true).GetBool(),
  277. GetParameter(parameters, EP_SOUND_INTERPOLATION, true).GetBool()
  278. );
  279. }
  280. }
  281. // Init FPU state of main thread
  282. InitFPU();
  283. // Initialize input
  284. if (HasParameter(parameters, EP_TOUCH_EMULATION))
  285. GetSubsystem<Input>()->SetTouchEmulation(GetParameter(parameters, EP_TOUCH_EMULATION).GetBool());
  286. // Initialize network
  287. #ifdef ATOMIC_NETWORK
  288. if (HasParameter(parameters, EP_PACKAGE_CACHE_DIR))
  289. GetSubsystem<Network>()->SetPackageCacheDir(GetParameter(parameters, EP_PACKAGE_CACHE_DIR).GetString());
  290. #endif
  291. #ifdef ATOMIC_TESTING
  292. if (HasParameter(parameters, EP_TIME_OUT))
  293. timeOut_ = GetParameter(parameters, EP_TIME_OUT, 0).GetInt() * 1000000LL;
  294. #endif
  295. #ifdef ATOMIC_PROFILING
  296. if (GetParameter(parameters, EP_EVENT_PROFILER, true).GetBool())
  297. {
  298. context_->RegisterSubsystem(new EventProfiler(context_));
  299. EventProfiler::SetActive(true);
  300. }
  301. #endif
  302. frameTimer_.Reset();
  303. ATOMIC_LOGINFO("Initialized engine");
  304. initialized_ = true;
  305. return true;
  306. }
  307. bool Engine::InitializeResourceCache(const VariantMap& parameters, bool removeOld /*= true*/)
  308. {
  309. ResourceCache* cache = GetSubsystem<ResourceCache>();
  310. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  311. // Remove all resource paths and packages
  312. if (removeOld)
  313. {
  314. Vector<String> resourceDirs = cache->GetResourceDirs();
  315. Vector<SharedPtr<PackageFile> > packageFiles = cache->GetPackageFiles();
  316. for (unsigned i = 0; i < resourceDirs.Size(); ++i)
  317. cache->RemoveResourceDir(resourceDirs[i]);
  318. for (unsigned i = 0; i < packageFiles.Size(); ++i)
  319. cache->RemovePackageFile(packageFiles[i]);
  320. }
  321. // Add resource paths
  322. Vector<String> resourcePrefixPaths = GetParameter(parameters, EP_RESOURCE_PREFIX_PATHS, String::EMPTY).GetString().Split(';', true);
  323. for (unsigned i = 0; i < resourcePrefixPaths.Size(); ++i)
  324. resourcePrefixPaths[i] = AddTrailingSlash(
  325. IsAbsolutePath(resourcePrefixPaths[i]) ? resourcePrefixPaths[i] : fileSystem->GetProgramDir() + resourcePrefixPaths[i]);
  326. Vector<String> resourcePaths = GetParameter(parameters, EP_RESOURCE_PATHS, "Data;CoreData").GetString().Split(';');
  327. Vector<String> resourcePackages = GetParameter(parameters, EP_RESOURCE_PACKAGES).GetString().Split(';');
  328. Vector<String> autoLoadPaths = GetParameter(parameters, EP_AUTOLOAD_PATHS, "Autoload").GetString().Split(';');
  329. for (unsigned i = 0; i < resourcePaths.Size(); ++i)
  330. {
  331. // If path is not absolute, prefer to add it as a package if possible
  332. if (!IsAbsolutePath(resourcePaths[i]))
  333. {
  334. unsigned j = 0;
  335. for (; j < resourcePrefixPaths.Size(); ++j)
  336. {
  337. // ATOMIC BEGIN
  338. String packageName = resourcePrefixPaths[j] + resourcePaths[i] + PAK_EXTENSION;
  339. // ATOMIC END
  340. if (fileSystem->FileExists(packageName))
  341. {
  342. if (cache->AddPackageFile(packageName))
  343. break;
  344. else
  345. return false; // The root cause of the error should have already been logged
  346. }
  347. String pathName = resourcePrefixPaths[j] + resourcePaths[i];
  348. if (fileSystem->DirExists(pathName))
  349. {
  350. if (cache->AddResourceDir(pathName))
  351. break;
  352. else
  353. return false;
  354. }
  355. }
  356. // ATOMIC: Only fail when CoreData can't be opened and not headless
  357. if (j == resourcePrefixPaths.Size() && !headless_)
  358. {
  359. ATOMIC_LOGERRORF(
  360. "Failed to add resource path '%s', check the documentation on how to set the 'resource prefix path'",
  361. resourcePaths[i].CString());
  362. return false;
  363. }
  364. }
  365. else
  366. {
  367. String pathName = resourcePaths[i];
  368. if (fileSystem->DirExists(pathName))
  369. if (!cache->AddResourceDir(pathName))
  370. return false;
  371. }
  372. }
  373. // Then add specified packages
  374. for (unsigned i = 0; i < resourcePackages.Size(); ++i)
  375. {
  376. unsigned j = 0;
  377. for (; j < resourcePrefixPaths.Size(); ++j)
  378. {
  379. String packageName = resourcePrefixPaths[j] + resourcePackages[i];
  380. if (fileSystem->FileExists(packageName))
  381. {
  382. if (cache->AddPackageFile(packageName))
  383. break;
  384. else
  385. return false;
  386. }
  387. }
  388. // ATOMIC: Only fail when CoreData can't be opened and not headless
  389. if (j == resourcePrefixPaths.Size() && !headless_)
  390. {
  391. ATOMIC_LOGERRORF(
  392. "Failed to add resource package '%s', check the documentation on how to set the 'resource prefix path'",
  393. resourcePackages[i].CString());
  394. return false;
  395. }
  396. }
  397. // Add auto load folders. Prioritize these (if exist) before the default folders
  398. for (unsigned i = 0; i < autoLoadPaths.Size(); ++i)
  399. {
  400. bool autoLoadPathExist = false;
  401. for (unsigned j = 0; j < resourcePrefixPaths.Size(); ++j)
  402. {
  403. String autoLoadPath(autoLoadPaths[i]);
  404. if (!IsAbsolutePath(autoLoadPath))
  405. autoLoadPath = resourcePrefixPaths[j] + autoLoadPath;
  406. if (fileSystem->DirExists(autoLoadPath))
  407. {
  408. autoLoadPathExist = true;
  409. // Add all the subdirs (non-recursive) as resource directory
  410. Vector<String> subdirs;
  411. fileSystem->ScanDir(subdirs, autoLoadPath, "*", SCAN_DIRS, false);
  412. for (unsigned y = 0; y < subdirs.Size(); ++y)
  413. {
  414. String dir = subdirs[y];
  415. if (dir.StartsWith("."))
  416. continue;
  417. String autoResourceDir = autoLoadPath + "/" + dir;
  418. if (!cache->AddResourceDir(autoResourceDir, 0))
  419. return false;
  420. }
  421. // Add all the found package files (non-recursive)
  422. Vector<String> paks;
  423. // ATOMIC BEGIN
  424. fileSystem->ScanDir(paks, autoLoadPath, ToString("*.%s", PAK_EXTENSION), SCAN_FILES, false);
  425. // ATOMIC END
  426. for (unsigned y = 0; y < paks.Size(); ++y)
  427. {
  428. String pak = paks[y];
  429. if (pak.StartsWith("."))
  430. continue;
  431. String autoPackageName = autoLoadPath + "/" + pak;
  432. if (!cache->AddPackageFile(autoPackageName, 0))
  433. return false;
  434. }
  435. }
  436. }
  437. // The following debug message is confusing when user is not aware of the autoload feature
  438. // Especially because the autoload feature is enabled by default without user intervention
  439. // The following extra conditional check below is to suppress unnecessary debug log entry under such default situation
  440. // The cleaner approach is to not enable the autoload by default, i.e. do not use 'Autoload' as default value for 'AutoloadPaths' engine parameter
  441. // However, doing so will break the existing applications that rely on this
  442. if (!autoLoadPathExist && (autoLoadPaths.Size() > 1 || autoLoadPaths[0] != "Autoload"))
  443. ATOMIC_LOGDEBUGF(
  444. "Skipped autoload path '%s' as it does not exist, check the documentation on how to set the 'resource prefix path'",
  445. autoLoadPaths[i].CString());
  446. }
  447. return true;
  448. }
  449. void Engine::RunFrame()
  450. {
  451. assert(initialized_);
  452. // If not headless, and the graphics subsystem no longer has a window open, assume we should exit
  453. if (!headless_ && !GetSubsystem<Graphics>()->IsInitialized())
  454. exiting_ = true;
  455. if (exiting_)
  456. return;
  457. // Note: there is a minimal performance cost to looking up subsystems (uses a hashmap); if they would be looked up several
  458. // times per frame it would be better to cache the pointers
  459. Time* time = GetSubsystem<Time>();
  460. Input* input = GetSubsystem<Input>();
  461. Audio* audio = GetSubsystem<Audio>();
  462. #ifdef ATOMIC_PROFILING
  463. if (EventProfiler::IsActive())
  464. {
  465. EventProfiler* eventProfiler = GetSubsystem<EventProfiler>();
  466. if (eventProfiler)
  467. eventProfiler->BeginFrame();
  468. }
  469. #endif
  470. time->BeginFrame(timeStep_);
  471. // ATOMIC BEGIN
  472. // check for exit again that comes in thru an event handler
  473. if ( exiting_ ) // needed to prevent scripts running the
  474. return; // current frame update with null objects
  475. // If paused, or pause when minimized -mode is in use, stop updates and audio as necessary
  476. if ((paused_ && !runNextPausedFrame_) ||
  477. (pauseMinimized_ && input->IsMinimized()))
  478. {
  479. if (audio->IsPlaying())
  480. {
  481. audio->Stop();
  482. audioPaused_ = true;
  483. }
  484. }
  485. else
  486. {
  487. // Only unpause when it was paused by the engine
  488. if (audioPaused_)
  489. {
  490. audio->Play();
  491. audioPaused_ = false;
  492. }
  493. // Only run one frame when stepping
  494. runNextPausedFrame_ = false;
  495. Update();
  496. }
  497. fpsTimeSinceUpdate_ += timeStep_;
  498. ++fpsFramesSinceUpdate_;
  499. if (fpsTimeSinceUpdate_ > ENGINE_FPS_UPDATE_INTERVAL)
  500. {
  501. fps_ = (int)(fpsFramesSinceUpdate_ / fpsTimeSinceUpdate_);
  502. fpsFramesSinceUpdate_ = 0;
  503. fpsTimeSinceUpdate_ = 0;
  504. }
  505. // ATOMIC END
  506. Render();
  507. ApplyFrameLimit();
  508. time->EndFrame();
  509. }
  510. Console* Engine::CreateConsole()
  511. {
  512. // ATOMIC BEGIN
  513. return 0;
  514. // ATOMIC END
  515. }
  516. DebugHud* Engine::CreateDebugHud()
  517. {
  518. // ATOMIC BEGIN
  519. return 0;
  520. // ATOMIC END
  521. }
  522. void Engine::SetTimeStepSmoothing(int frames)
  523. {
  524. timeStepSmoothing_ = (unsigned)Clamp(frames, 1, 20);
  525. }
  526. void Engine::SetMinFps(int fps)
  527. {
  528. minFps_ = (unsigned)Max(fps, 0);
  529. }
  530. void Engine::SetMaxFps(int fps)
  531. {
  532. maxFps_ = (unsigned)Max(fps, 0);
  533. }
  534. void Engine::SetMaxInactiveFps(int fps)
  535. {
  536. maxInactiveFps_ = (unsigned)Max(fps, 0);
  537. }
  538. void Engine::SetPauseMinimized(bool enable)
  539. {
  540. pauseMinimized_ = enable;
  541. }
  542. void Engine::SetAutoExit(bool enable)
  543. {
  544. // On mobile platforms exit is mandatory if requested by the platform itself and should not be attempted to be disabled
  545. #if defined(__ANDROID__) || defined(IOS)
  546. enable = true;
  547. #endif
  548. autoExit_ = enable;
  549. }
  550. void Engine::SetNextTimeStep(float seconds)
  551. {
  552. timeStep_ = Max(seconds, 0.0f);
  553. }
  554. void Engine::Exit()
  555. {
  556. #if defined(IOS)
  557. // On iOS it's not legal for the application to exit on its own, instead it will be minimized with the home key
  558. #else
  559. DoExit();
  560. #endif
  561. }
  562. void Engine::DumpProfiler()
  563. {
  564. #ifdef ATOMIC_LOGGING
  565. if (!Thread::IsMainThread())
  566. return;
  567. Profiler* profiler = GetSubsystem<Profiler>();
  568. if (profiler)
  569. ATOMIC_LOGRAW(profiler->PrintData(true, true) + "\n");
  570. #endif
  571. }
  572. void Engine::DumpResources(bool dumpFileName)
  573. {
  574. #ifdef ATOMIC_LOGGING
  575. if (!Thread::IsMainThread())
  576. return;
  577. ResourceCache* cache = GetSubsystem<ResourceCache>();
  578. const HashMap<StringHash, ResourceGroup>& resourceGroups = cache->GetAllResources();
  579. if (dumpFileName)
  580. {
  581. ATOMIC_LOGRAW("Used resources:\n");
  582. for (HashMap<StringHash, ResourceGroup>::ConstIterator i = resourceGroups.Begin(); i != resourceGroups.End(); ++i)
  583. {
  584. const HashMap<StringHash, SharedPtr<Resource> >& resources = i->second_.resources_;
  585. if (dumpFileName)
  586. {
  587. for (HashMap<StringHash, SharedPtr<Resource> >::ConstIterator j = resources.Begin(); j != resources.End(); ++j)
  588. ATOMIC_LOGRAW(j->second_->GetName() + "\n");
  589. }
  590. }
  591. }
  592. else
  593. ATOMIC_LOGRAW(cache->PrintMemoryUsage() + "\n");
  594. #endif
  595. }
  596. void Engine::DumpMemory()
  597. {
  598. #ifdef ATOMIC_LOGGING
  599. #if defined(_MSC_VER) && defined(_DEBUG)
  600. _CrtMemState state;
  601. _CrtMemCheckpoint(&state);
  602. _CrtMemBlockHeader* block = state.pBlockHeader;
  603. unsigned total = 0;
  604. unsigned blocks = 0;
  605. for (;;)
  606. {
  607. if (block && block->pBlockHeaderNext)
  608. block = block->pBlockHeaderNext;
  609. else
  610. break;
  611. }
  612. while (block)
  613. {
  614. if (block->nBlockUse > 0)
  615. {
  616. if (block->szFileName)
  617. ATOMIC_LOGRAW("Block " + String((int)block->lRequest) + ": " + String(block->nDataSize) + " bytes, file " + String(block->szFileName) + " line " + String(block->nLine) + "\n");
  618. else
  619. ATOMIC_LOGRAW("Block " + String((int)block->lRequest) + ": " + String(block->nDataSize) + " bytes\n");
  620. total += block->nDataSize;
  621. ++blocks;
  622. }
  623. block = block->pBlockHeaderPrev;
  624. }
  625. ATOMIC_LOGRAW("Total allocated memory " + String(total) + " bytes in " + String(blocks) + " blocks\n\n");
  626. #else
  627. ATOMIC_LOGRAW("DumpMemory() supported on MSVC debug mode only\n\n");
  628. #endif
  629. #endif
  630. }
  631. void Engine::Update()
  632. {
  633. ATOMIC_PROFILE(Update);
  634. // Logic update event
  635. using namespace Update;
  636. VariantMap& eventData = GetEventDataMap();
  637. eventData[P_TIMESTEP] = timeStep_;
  638. SendEvent(E_UPDATE, eventData);
  639. // Logic post-update event
  640. SendEvent(E_POSTUPDATE, eventData);
  641. // Rendering update event
  642. SendEvent(E_RENDERUPDATE, eventData);
  643. // Post-render update event
  644. SendEvent(E_POSTRENDERUPDATE, eventData);
  645. }
  646. void Engine::Render()
  647. {
  648. if (headless_)
  649. return;
  650. ATOMIC_PROFILE(Render);
  651. // If device is lost, BeginFrame will fail and we skip rendering
  652. Graphics* graphics = GetSubsystem<Graphics>();
  653. if (!graphics->BeginFrame())
  654. return;
  655. GetSubsystem<Renderer>()->Render();
  656. GetSubsystem<UI>()->Render();
  657. graphics->EndFrame();
  658. }
  659. void Engine::ApplyFrameLimit()
  660. {
  661. if (!initialized_)
  662. return;
  663. unsigned maxFps = maxFps_;
  664. Input* input = GetSubsystem<Input>();
  665. if (input && !input->HasFocus())
  666. maxFps = Min(maxInactiveFps_, maxFps);
  667. long long elapsed = 0;
  668. #ifndef __EMSCRIPTEN__
  669. // Perform waiting loop if maximum FPS set
  670. #ifndef IOS
  671. if (maxFps)
  672. #else
  673. // If on iOS and target framerate is 60 or above, just let the animation callback handle frame timing
  674. // instead of waiting ourselves
  675. if (maxFps < 60)
  676. #endif
  677. {
  678. ATOMIC_PROFILE(ApplyFrameLimit);
  679. long long targetMax = 1000000LL / maxFps;
  680. for (;;)
  681. {
  682. elapsed = frameTimer_.GetUSec(false);
  683. if (elapsed >= targetMax)
  684. break;
  685. // Sleep if 1 ms or more off the frame limiting goal
  686. if (targetMax - elapsed >= 1000LL)
  687. {
  688. unsigned sleepTime = (unsigned)((targetMax - elapsed) / 1000LL);
  689. Time::Sleep(sleepTime);
  690. }
  691. }
  692. }
  693. #endif
  694. elapsed = frameTimer_.GetUSec(true);
  695. #ifdef ATOMIC_TESTING
  696. if (timeOut_ > 0)
  697. {
  698. timeOut_ -= elapsed;
  699. if (timeOut_ <= 0)
  700. Exit();
  701. }
  702. #endif
  703. // If FPS lower than minimum, clamp elapsed time
  704. if (minFps_)
  705. {
  706. long long targetMin = 1000000LL / minFps_;
  707. if (elapsed > targetMin)
  708. elapsed = targetMin;
  709. }
  710. // Perform timestep smoothing
  711. timeStep_ = 0.0f;
  712. lastTimeSteps_.Push(elapsed / 1000000.0f);
  713. if (lastTimeSteps_.Size() > timeStepSmoothing_)
  714. {
  715. // If the smoothing configuration was changed, ensure correct amount of samples
  716. lastTimeSteps_.Erase(0, lastTimeSteps_.Size() - timeStepSmoothing_);
  717. for (unsigned i = 0; i < lastTimeSteps_.Size(); ++i)
  718. timeStep_ += lastTimeSteps_[i];
  719. timeStep_ /= lastTimeSteps_.Size();
  720. }
  721. else
  722. timeStep_ = lastTimeSteps_.Back();
  723. }
  724. VariantMap Engine::ParseParameters(const Vector<String>& arguments)
  725. {
  726. VariantMap ret;
  727. // Pre-initialize the parameters with environment variable values when they are set
  728. if (const char* paths = getenv("ATOMIC_PREFIX_PATH"))
  729. ret[EP_RESOURCE_PREFIX_PATHS] = paths;
  730. for (unsigned i = 0; i < arguments.Size(); ++i)
  731. {
  732. if (arguments[i].Length() > 1 && arguments[i][0] == '-')
  733. {
  734. String argument = arguments[i].Substring(1).ToLower();
  735. String value = i + 1 < arguments.Size() ? arguments[i + 1] : String::EMPTY;
  736. if (argument == "headless")
  737. ret[EP_HEADLESS] = true;
  738. else if (argument == "nolimit")
  739. ret[EP_FRAME_LIMITER] = false;
  740. else if (argument == "flushgpu")
  741. ret[EP_FLUSH_GPU] = true;
  742. else if (argument == "gl2")
  743. ret[EP_FORCE_GL2] = true;
  744. else if (argument == "landscape")
  745. ret[EP_ORIENTATIONS] = "LandscapeLeft LandscapeRight " + ret[EP_ORIENTATIONS].GetString();
  746. else if (argument == "portrait")
  747. ret[EP_ORIENTATIONS] = "Portrait PortraitUpsideDown " + ret[EP_ORIENTATIONS].GetString();
  748. else if (argument == "nosound")
  749. ret[EP_SOUND] = false;
  750. else if (argument == "noip")
  751. ret[EP_SOUND_INTERPOLATION] = false;
  752. else if (argument == "mono")
  753. ret[EP_SOUND_STEREO] = false;
  754. else if (argument == "prepass")
  755. ret[EP_RENDER_PATH] = "RenderPaths/Prepass.xml";
  756. else if (argument == "deferred")
  757. ret[EP_RENDER_PATH] = "RenderPaths/Deferred.xml";
  758. else if (argument == "renderpath" && !value.Empty())
  759. {
  760. ret[EP_RENDER_PATH] = value;
  761. ++i;
  762. }
  763. else if (argument == "noshadows")
  764. ret[EP_SHADOWS] = false;
  765. else if (argument == "lqshadows")
  766. ret[EP_LOW_QUALITY_SHADOWS] = true;
  767. else if (argument == "nothreads")
  768. ret[EP_WORKER_THREADS] = false;
  769. else if (argument == "v")
  770. ret[EP_VSYNC] = true;
  771. else if (argument == "t")
  772. ret[EP_TRIPLE_BUFFER] = true;
  773. else if (argument == "w")
  774. ret[EP_FULL_SCREEN] = false;
  775. else if (argument == "borderless")
  776. ret[EP_BORDERLESS] = true;
  777. else if (argument == "s")
  778. ret[EP_WINDOW_RESIZABLE] = true;
  779. else if (argument == "hd")
  780. ret[EP_HIGH_DPI] = true;
  781. else if (argument == "q")
  782. ret[EP_LOG_QUIET] = true;
  783. else if (argument == "log" && !value.Empty())
  784. {
  785. unsigned logLevel = GetStringListIndex(value.CString(), logLevelPrefixes, M_MAX_UNSIGNED);
  786. if (logLevel != M_MAX_UNSIGNED)
  787. {
  788. ret[EP_LOG_LEVEL] = logLevel;
  789. ++i;
  790. }
  791. }
  792. else if (argument == "x" && !value.Empty())
  793. {
  794. ret[EP_WINDOW_WIDTH] = ToInt(value);
  795. ++i;
  796. }
  797. else if (argument == "y" && !value.Empty())
  798. {
  799. ret[EP_WINDOW_HEIGHT] = ToInt(value);
  800. ++i;
  801. }
  802. else if (argument == "monitor" && !value.Empty()) {
  803. ret[EP_MONITOR] = ToInt(value);
  804. ++i;
  805. }
  806. else if (argument == "hz" && !value.Empty()) {
  807. ret[EP_REFRESH_RATE] = ToInt(value);
  808. ++i;
  809. }
  810. else if (argument == "m" && !value.Empty())
  811. {
  812. ret[EP_MULTI_SAMPLE] = ToInt(value);
  813. ++i;
  814. }
  815. else if (argument == "b" && !value.Empty())
  816. {
  817. ret[EP_SOUND_BUFFER] = ToInt(value);
  818. ++i;
  819. }
  820. else if (argument == "r" && !value.Empty())
  821. {
  822. ret[EP_SOUND_MIX_RATE] = ToInt(value);
  823. ++i;
  824. }
  825. else if (argument == "pp" && !value.Empty())
  826. {
  827. ret[EP_RESOURCE_PREFIX_PATHS] = value;
  828. ++i;
  829. }
  830. else if (argument == "p" && !value.Empty())
  831. {
  832. ret[EP_RESOURCE_PATHS] = value;
  833. ++i;
  834. }
  835. else if (argument == "pf" && !value.Empty())
  836. {
  837. ret[EP_RESOURCE_PACKAGES] = value;
  838. ++i;
  839. }
  840. else if (argument == "ap" && !value.Empty())
  841. {
  842. ret[EP_AUTOLOAD_PATHS] = value;
  843. ++i;
  844. }
  845. else if (argument == "ds" && !value.Empty())
  846. {
  847. ret[EP_DUMP_SHADERS] = value;
  848. ++i;
  849. }
  850. else if (argument == "mq" && !value.Empty())
  851. {
  852. ret[EP_MATERIAL_QUALITY] = ToInt(value);
  853. ++i;
  854. }
  855. else if (argument == "tq" && !value.Empty())
  856. {
  857. ret[EP_TEXTURE_QUALITY] = ToInt(value);
  858. ++i;
  859. }
  860. else if (argument == "tf" && !value.Empty())
  861. {
  862. ret[EP_TEXTURE_FILTER_MODE] = ToInt(value);
  863. ++i;
  864. }
  865. else if (argument == "af" && !value.Empty())
  866. {
  867. ret[EP_TEXTURE_FILTER_MODE] = FILTER_ANISOTROPIC;
  868. ret[EP_TEXTURE_ANISOTROPY] = ToInt(value);
  869. ++i;
  870. }
  871. else if (argument == "touch")
  872. ret[EP_TOUCH_EMULATION] = true;
  873. // ATOMIC BEGIN
  874. else if (argument == "logname" && !value.Empty())
  875. {
  876. ret[EP_LOG_NAME] = value;
  877. ++i;
  878. }
  879. else if (argument == "-autometrics") // --autometrics
  880. {
  881. ret[EP_AUTO_METRICS] = true;
  882. }
  883. // ATOMIC END
  884. #ifdef ATOMIC_TESTING
  885. else if (argument == "timeout" && !value.Empty())
  886. {
  887. ret[EP_TIME_OUT] = ToInt(value);
  888. ++i;
  889. }
  890. #endif
  891. }
  892. }
  893. return ret;
  894. }
  895. bool Engine::HasParameter(const VariantMap& parameters, const String& parameter)
  896. {
  897. StringHash nameHash(parameter);
  898. return parameters.Find(nameHash) != parameters.End();
  899. }
  900. const Variant& Engine::GetParameter(const VariantMap& parameters, const String& parameter, const Variant& defaultValue)
  901. {
  902. StringHash nameHash(parameter);
  903. VariantMap::ConstIterator i = parameters.Find(nameHash);
  904. return i != parameters.End() ? i->second_ : defaultValue;
  905. }
  906. void Engine::HandleExitRequested(StringHash eventType, VariantMap& eventData)
  907. {
  908. if (autoExit_)
  909. {
  910. // Do not call Exit() here, as it contains mobile platform -specific tests to not exit.
  911. // If we do receive an exit request from the system on those platforms, we must comply
  912. DoExit();
  913. }
  914. }
  915. void Engine::DoExit()
  916. {
  917. Graphics* graphics = GetSubsystem<Graphics>();
  918. if (graphics)
  919. graphics->Close();
  920. exiting_ = true;
  921. #if defined(__EMSCRIPTEN__) && defined(ATOMIC_TESTING)
  922. emscripten_force_exit(EXIT_SUCCESS); // Some how this is required to signal emrun to stop
  923. #endif
  924. }
  925. // ATOMIC BEGIN
  926. void Engine::SetPaused(bool paused)
  927. {
  928. paused_ = paused;
  929. using namespace UpdatesPaused;
  930. // Updates paused event
  931. VariantMap& eventData = GetEventDataMap();
  932. eventData[P_PAUSED] = paused_;
  933. SendEvent(E_UPDATESPAUSEDRESUMED, eventData);
  934. }
  935. void Engine::SetRunNextPausedFrame(bool run)
  936. {
  937. runNextPausedFrame_ = run;
  938. }
  939. void Engine::HandlePauseResumeRequested(StringHash eventType, VariantMap& eventData)
  940. {
  941. SetPaused(!IsPaused());
  942. }
  943. void Engine::HandlePauseStepRequested(StringHash eventType, VariantMap& eventData)
  944. {
  945. if (IsPaused())
  946. {
  947. SetRunNextPausedFrame(true);
  948. }
  949. }
  950. bool Engine::GetDebugBuild() const
  951. {
  952. #ifdef ATOMIC_DEBUG
  953. return true;
  954. #else
  955. return false;
  956. #endif
  957. }
  958. // ATOMIC END
  959. }