Engine.cpp 36 KB

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