Engine.cpp 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091
  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. GetParameter(parameters, EP_HIGH_DPI, true).GetBool(),
  249. GetParameter(parameters, EP_VSYNC, false).GetBool(),
  250. GetParameter(parameters, EP_TRIPLE_BUFFER, false).GetBool(),
  251. GetParameter(parameters, EP_MULTI_SAMPLE, 1).GetInt(),
  252. GetParameter(parameters, EP_MONITOR, 0).GetInt(),
  253. GetParameter(parameters, EP_REFRESH_RATE, 0).GetInt()
  254. ))
  255. return false;
  256. graphics->SetShaderCacheDir(GetParameter(parameters, EP_SHADER_CACHE_DIR, fileSystem->GetAppPreferencesDir("atomic", "shadercache")).GetString());
  257. if (HasParameter(parameters, EP_DUMP_SHADERS))
  258. graphics->BeginDumpShaders(GetParameter(parameters, EP_DUMP_SHADERS, String::EMPTY).GetString());
  259. if (HasParameter(parameters, EP_RENDER_PATH))
  260. renderer->SetDefaultRenderPath(cache->GetResource<XMLFile>(GetParameter(parameters, EP_RENDER_PATH).GetString()));
  261. renderer->SetDrawShadows(GetParameter(parameters, EP_SHADOWS, true).GetBool());
  262. if (renderer->GetDrawShadows() && GetParameter(parameters, EP_LOW_QUALITY_SHADOWS, false).GetBool())
  263. renderer->SetShadowQuality(SHADOWQUALITY_SIMPLE_16BIT);
  264. renderer->SetMaterialQuality(GetParameter(parameters, EP_MATERIAL_QUALITY, QUALITY_HIGH).GetInt());
  265. renderer->SetTextureQuality(GetParameter(parameters, EP_TEXTURE_QUALITY, QUALITY_HIGH).GetInt());
  266. renderer->SetTextureFilterMode((TextureFilterMode)GetParameter(parameters, EP_TEXTURE_FILTER_MODE, FILTER_TRILINEAR).GetInt());
  267. renderer->SetTextureAnisotropy(GetParameter(parameters, EP_TEXTURE_ANISOTROPY, 4).GetInt());
  268. if (GetParameter(parameters, EP_SOUND, true).GetBool())
  269. {
  270. GetSubsystem<Audio>()->SetMode(
  271. GetParameter(parameters, EP_SOUND_BUFFER, 100).GetInt(),
  272. GetParameter(parameters, EP_SOUND_MIX_RATE, 44100).GetInt(),
  273. GetParameter(parameters, EP_SOUND_STEREO, true).GetBool(),
  274. GetParameter(parameters, EP_SOUND_INTERPOLATION, true).GetBool()
  275. );
  276. }
  277. }
  278. // Init FPU state of main thread
  279. InitFPU();
  280. // Initialize input
  281. if (HasParameter(parameters, EP_TOUCH_EMULATION))
  282. GetSubsystem<Input>()->SetTouchEmulation(GetParameter(parameters, EP_TOUCH_EMULATION).GetBool());
  283. // Initialize network
  284. #ifdef ATOMIC_NETWORK
  285. if (HasParameter(parameters, EP_PACKAGE_CACHE_DIR))
  286. GetSubsystem<Network>()->SetPackageCacheDir(GetParameter(parameters, EP_PACKAGE_CACHE_DIR).GetString());
  287. #endif
  288. #ifdef ATOMIC_TESTING
  289. if (HasParameter(parameters, EP_TIME_OUT))
  290. timeOut_ = GetParameter(parameters, EP_TIME_OUT, 0).GetInt() * 1000000LL;
  291. #endif
  292. #ifdef ATOMIC_PROFILING
  293. if (GetParameter(parameters, EP_EVENT_PROFILER, true).GetBool())
  294. {
  295. context_->RegisterSubsystem(new EventProfiler(context_));
  296. EventProfiler::SetActive(true);
  297. }
  298. #endif
  299. frameTimer_.Reset();
  300. ATOMIC_LOGINFO("Initialized engine");
  301. initialized_ = true;
  302. return true;
  303. }
  304. bool Engine::InitializeResourceCache(const VariantMap& parameters, bool removeOld /*= true*/)
  305. {
  306. ResourceCache* cache = GetSubsystem<ResourceCache>();
  307. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  308. // Remove all resource paths and packages
  309. if (removeOld)
  310. {
  311. Vector<String> resourceDirs = cache->GetResourceDirs();
  312. Vector<SharedPtr<PackageFile> > packageFiles = cache->GetPackageFiles();
  313. for (unsigned i = 0; i < resourceDirs.Size(); ++i)
  314. cache->RemoveResourceDir(resourceDirs[i]);
  315. for (unsigned i = 0; i < packageFiles.Size(); ++i)
  316. cache->RemovePackageFile(packageFiles[i]);
  317. }
  318. // Add resource paths
  319. Vector<String> resourcePrefixPaths = GetParameter(parameters, EP_RESOURCE_PREFIX_PATHS, String::EMPTY).GetString().Split(';', true);
  320. for (unsigned i = 0; i < resourcePrefixPaths.Size(); ++i)
  321. resourcePrefixPaths[i] = AddTrailingSlash(
  322. IsAbsolutePath(resourcePrefixPaths[i]) ? resourcePrefixPaths[i] : fileSystem->GetProgramDir() + resourcePrefixPaths[i]);
  323. Vector<String> resourcePaths = GetParameter(parameters, EP_RESOURCE_PATHS, "Data;CoreData").GetString().Split(';');
  324. Vector<String> resourcePackages = GetParameter(parameters, EP_RESOURCE_PACKAGES).GetString().Split(';');
  325. Vector<String> autoLoadPaths = GetParameter(parameters, EP_AUTOLOAD_PATHS, "Autoload").GetString().Split(';');
  326. for (unsigned i = 0; i < resourcePaths.Size(); ++i)
  327. {
  328. // If path is not absolute, prefer to add it as a package if possible
  329. if (!IsAbsolutePath(resourcePaths[i]))
  330. {
  331. unsigned j = 0;
  332. for (; j < resourcePrefixPaths.Size(); ++j)
  333. {
  334. // ATOMIC BEGIN
  335. String packageName = resourcePrefixPaths[j] + resourcePaths[i] + PAK_EXTENSION;
  336. // ATOMIC END
  337. if (fileSystem->FileExists(packageName))
  338. {
  339. if (cache->AddPackageFile(packageName))
  340. break;
  341. else
  342. return false; // The root cause of the error should have already been logged
  343. }
  344. String pathName = resourcePrefixPaths[j] + resourcePaths[i];
  345. if (fileSystem->DirExists(pathName))
  346. {
  347. if (cache->AddResourceDir(pathName))
  348. break;
  349. else
  350. return false;
  351. }
  352. }
  353. // ATOMIC: Only fail when CoreData can't be opened and not headless
  354. if (j == resourcePrefixPaths.Size() && !headless_)
  355. {
  356. ATOMIC_LOGERRORF(
  357. "Failed to add resource path '%s', check the documentation on how to set the 'resource prefix path'",
  358. resourcePaths[i].CString());
  359. return false;
  360. }
  361. }
  362. else
  363. {
  364. String pathName = resourcePaths[i];
  365. if (fileSystem->DirExists(pathName))
  366. if (!cache->AddResourceDir(pathName))
  367. return false;
  368. }
  369. }
  370. // Then add specified packages
  371. for (unsigned i = 0; i < resourcePackages.Size(); ++i)
  372. {
  373. unsigned j = 0;
  374. for (; j < resourcePrefixPaths.Size(); ++j)
  375. {
  376. String packageName = resourcePrefixPaths[j] + resourcePackages[i];
  377. if (fileSystem->FileExists(packageName))
  378. {
  379. if (cache->AddPackageFile(packageName))
  380. break;
  381. else
  382. return false;
  383. }
  384. }
  385. // ATOMIC: Only fail when CoreData can't be opened and not headless
  386. if (j == resourcePrefixPaths.Size() && !headless_)
  387. {
  388. ATOMIC_LOGERRORF(
  389. "Failed to add resource package '%s', check the documentation on how to set the 'resource prefix path'",
  390. resourcePackages[i].CString());
  391. return false;
  392. }
  393. }
  394. // Add auto load folders. Prioritize these (if exist) before the default folders
  395. for (unsigned i = 0; i < autoLoadPaths.Size(); ++i)
  396. {
  397. bool autoLoadPathExist = false;
  398. for (unsigned j = 0; j < resourcePrefixPaths.Size(); ++j)
  399. {
  400. String autoLoadPath(autoLoadPaths[i]);
  401. if (!IsAbsolutePath(autoLoadPath))
  402. autoLoadPath = resourcePrefixPaths[j] + autoLoadPath;
  403. if (fileSystem->DirExists(autoLoadPath))
  404. {
  405. autoLoadPathExist = true;
  406. // Add all the subdirs (non-recursive) as resource directory
  407. Vector<String> subdirs;
  408. fileSystem->ScanDir(subdirs, autoLoadPath, "*", SCAN_DIRS, false);
  409. for (unsigned y = 0; y < subdirs.Size(); ++y)
  410. {
  411. String dir = subdirs[y];
  412. if (dir.StartsWith("."))
  413. continue;
  414. String autoResourceDir = autoLoadPath + "/" + dir;
  415. if (!cache->AddResourceDir(autoResourceDir, 0))
  416. return false;
  417. }
  418. // Add all the found package files (non-recursive)
  419. Vector<String> paks;
  420. // ATOMIC BEGIN
  421. fileSystem->ScanDir(paks, autoLoadPath, ToString("*.%s", PAK_EXTENSION), SCAN_FILES, false);
  422. // ATOMIC END
  423. for (unsigned y = 0; y < paks.Size(); ++y)
  424. {
  425. String pak = paks[y];
  426. if (pak.StartsWith("."))
  427. continue;
  428. String autoPackageName = autoLoadPath + "/" + pak;
  429. if (!cache->AddPackageFile(autoPackageName, 0))
  430. return false;
  431. }
  432. }
  433. }
  434. // The following debug message is confusing when user is not aware of the autoload feature
  435. // Especially because the autoload feature is enabled by default without user intervention
  436. // The following extra conditional check below is to suppress unnecessary debug log entry under such default situation
  437. // The cleaner approach is to not enable the autoload by default, i.e. do not use 'Autoload' as default value for 'AutoloadPaths' engine parameter
  438. // However, doing so will break the existing applications that rely on this
  439. if (!autoLoadPathExist && (autoLoadPaths.Size() > 1 || autoLoadPaths[0] != "Autoload"))
  440. ATOMIC_LOGDEBUGF(
  441. "Skipped autoload path '%s' as it does not exist, check the documentation on how to set the 'resource prefix path'",
  442. autoLoadPaths[i].CString());
  443. }
  444. return true;
  445. }
  446. void Engine::RunFrame()
  447. {
  448. assert(initialized_);
  449. // If not headless, and the graphics subsystem no longer has a window open, assume we should exit
  450. if (!headless_ && !GetSubsystem<Graphics>()->IsInitialized())
  451. exiting_ = true;
  452. if (exiting_)
  453. return;
  454. // Note: there is a minimal performance cost to looking up subsystems (uses a hashmap); if they would be looked up several
  455. // times per frame it would be better to cache the pointers
  456. Time* time = GetSubsystem<Time>();
  457. Input* input = GetSubsystem<Input>();
  458. Audio* audio = GetSubsystem<Audio>();
  459. #ifdef ATOMIC_PROFILING
  460. if (EventProfiler::IsActive())
  461. {
  462. EventProfiler* eventProfiler = GetSubsystem<EventProfiler>();
  463. if (eventProfiler)
  464. eventProfiler->BeginFrame();
  465. }
  466. #endif
  467. time->BeginFrame(timeStep_);
  468. // ATOMIC BEGIN
  469. // check for exit again that comes in thru an event handler
  470. if ( exiting_ ) // needed to prevent scripts running the
  471. return; // current frame update with null objects
  472. // If paused, or pause when minimized -mode is in use, stop updates and audio as necessary
  473. if ((paused_ && !runNextPausedFrame_) ||
  474. (pauseMinimized_ && input->IsMinimized()))
  475. {
  476. if (audio->IsPlaying())
  477. {
  478. audio->Stop();
  479. audioPaused_ = true;
  480. }
  481. }
  482. else
  483. {
  484. // Only unpause when it was paused by the engine
  485. if (audioPaused_)
  486. {
  487. audio->Play();
  488. audioPaused_ = false;
  489. }
  490. // Only run one frame when stepping
  491. runNextPausedFrame_ = false;
  492. Update();
  493. }
  494. fpsTimeSinceUpdate_ += timeStep_;
  495. ++fpsFramesSinceUpdate_;
  496. if (fpsTimeSinceUpdate_ > ENGINE_FPS_UPDATE_INTERVAL)
  497. {
  498. fps_ = (int)(fpsFramesSinceUpdate_ / fpsTimeSinceUpdate_);
  499. fpsFramesSinceUpdate_ = 0;
  500. fpsTimeSinceUpdate_ = 0;
  501. }
  502. // ATOMIC END
  503. Render();
  504. ApplyFrameLimit();
  505. time->EndFrame();
  506. }
  507. Console* Engine::CreateConsole()
  508. {
  509. // ATOMIC BEGIN
  510. return 0;
  511. // ATOMIC END
  512. }
  513. DebugHud* Engine::CreateDebugHud()
  514. {
  515. // ATOMIC BEGIN
  516. return 0;
  517. // ATOMIC END
  518. }
  519. void Engine::SetTimeStepSmoothing(int frames)
  520. {
  521. timeStepSmoothing_ = (unsigned)Clamp(frames, 1, 20);
  522. }
  523. void Engine::SetMinFps(int fps)
  524. {
  525. minFps_ = (unsigned)Max(fps, 0);
  526. }
  527. void Engine::SetMaxFps(int fps)
  528. {
  529. maxFps_ = (unsigned)Max(fps, 0);
  530. }
  531. void Engine::SetMaxInactiveFps(int fps)
  532. {
  533. maxInactiveFps_ = (unsigned)Max(fps, 0);
  534. }
  535. void Engine::SetPauseMinimized(bool enable)
  536. {
  537. pauseMinimized_ = enable;
  538. }
  539. void Engine::SetAutoExit(bool enable)
  540. {
  541. // On mobile platforms exit is mandatory if requested by the platform itself and should not be attempted to be disabled
  542. #if defined(__ANDROID__) || defined(IOS)
  543. enable = true;
  544. #endif
  545. autoExit_ = enable;
  546. }
  547. void Engine::SetNextTimeStep(float seconds)
  548. {
  549. timeStep_ = Max(seconds, 0.0f);
  550. }
  551. void Engine::Exit()
  552. {
  553. #if defined(IOS)
  554. // On iOS it's not legal for the application to exit on its own, instead it will be minimized with the home key
  555. #else
  556. DoExit();
  557. #endif
  558. }
  559. void Engine::DumpProfiler()
  560. {
  561. #ifdef ATOMIC_LOGGING
  562. if (!Thread::IsMainThread())
  563. return;
  564. Profiler* profiler = GetSubsystem<Profiler>();
  565. if (profiler)
  566. ATOMIC_LOGRAW(profiler->PrintData(true, true) + "\n");
  567. #endif
  568. }
  569. void Engine::DumpResources(bool dumpFileName)
  570. {
  571. #ifdef ATOMIC_LOGGING
  572. if (!Thread::IsMainThread())
  573. return;
  574. ResourceCache* cache = GetSubsystem<ResourceCache>();
  575. const HashMap<StringHash, ResourceGroup>& resourceGroups = cache->GetAllResources();
  576. if (dumpFileName)
  577. {
  578. ATOMIC_LOGRAW("Used resources:\n");
  579. for (HashMap<StringHash, ResourceGroup>::ConstIterator i = resourceGroups.Begin(); i != resourceGroups.End(); ++i)
  580. {
  581. const HashMap<StringHash, SharedPtr<Resource> >& resources = i->second_.resources_;
  582. if (dumpFileName)
  583. {
  584. for (HashMap<StringHash, SharedPtr<Resource> >::ConstIterator j = resources.Begin(); j != resources.End(); ++j)
  585. ATOMIC_LOGRAW(j->second_->GetName() + "\n");
  586. }
  587. }
  588. }
  589. else
  590. ATOMIC_LOGRAW(cache->PrintMemoryUsage() + "\n");
  591. #endif
  592. }
  593. void Engine::DumpMemory()
  594. {
  595. #ifdef ATOMIC_LOGGING
  596. #if defined(_MSC_VER) && defined(_DEBUG)
  597. _CrtMemState state;
  598. _CrtMemCheckpoint(&state);
  599. _CrtMemBlockHeader* block = state.pBlockHeader;
  600. unsigned total = 0;
  601. unsigned blocks = 0;
  602. for (;;)
  603. {
  604. if (block && block->pBlockHeaderNext)
  605. block = block->pBlockHeaderNext;
  606. else
  607. break;
  608. }
  609. while (block)
  610. {
  611. if (block->nBlockUse > 0)
  612. {
  613. if (block->szFileName)
  614. ATOMIC_LOGRAW("Block " + String((int)block->lRequest) + ": " + String(block->nDataSize) + " bytes, file " + String(block->szFileName) + " line " + String(block->nLine) + "\n");
  615. else
  616. ATOMIC_LOGRAW("Block " + String((int)block->lRequest) + ": " + String(block->nDataSize) + " bytes\n");
  617. total += block->nDataSize;
  618. ++blocks;
  619. }
  620. block = block->pBlockHeaderPrev;
  621. }
  622. ATOMIC_LOGRAW("Total allocated memory " + String(total) + " bytes in " + String(blocks) + " blocks\n\n");
  623. #else
  624. ATOMIC_LOGRAW("DumpMemory() supported on MSVC debug mode only\n\n");
  625. #endif
  626. #endif
  627. }
  628. void Engine::Update()
  629. {
  630. ATOMIC_PROFILE(Update);
  631. // Logic update event
  632. using namespace Update;
  633. VariantMap& eventData = GetEventDataMap();
  634. eventData[P_TIMESTEP] = timeStep_;
  635. SendEvent(E_UPDATE, eventData);
  636. // Logic post-update event
  637. SendEvent(E_POSTUPDATE, eventData);
  638. // Rendering update event
  639. SendEvent(E_RENDERUPDATE, eventData);
  640. // Post-render update event
  641. SendEvent(E_POSTRENDERUPDATE, eventData);
  642. }
  643. void Engine::Render()
  644. {
  645. if (headless_)
  646. return;
  647. ATOMIC_PROFILE(Render);
  648. // If device is lost, BeginFrame will fail and we skip rendering
  649. Graphics* graphics = GetSubsystem<Graphics>();
  650. if (!graphics->BeginFrame())
  651. return;
  652. GetSubsystem<Renderer>()->Render();
  653. GetSubsystem<UI>()->Render();
  654. graphics->EndFrame();
  655. }
  656. void Engine::ApplyFrameLimit()
  657. {
  658. if (!initialized_)
  659. return;
  660. unsigned maxFps = maxFps_;
  661. Input* input = GetSubsystem<Input>();
  662. if (input && !input->HasFocus())
  663. maxFps = Min(maxInactiveFps_, maxFps);
  664. long long elapsed = 0;
  665. #ifndef __EMSCRIPTEN__
  666. // Perform waiting loop if maximum FPS set
  667. #ifndef IOS
  668. if (maxFps)
  669. #else
  670. // If on iOS and target framerate is 60 or above, just let the animation callback handle frame timing
  671. // instead of waiting ourselves
  672. if (maxFps < 60)
  673. #endif
  674. {
  675. ATOMIC_PROFILE(ApplyFrameLimit);
  676. long long targetMax = 1000000LL / maxFps;
  677. for (;;)
  678. {
  679. elapsed = frameTimer_.GetUSec(false);
  680. if (elapsed >= targetMax)
  681. break;
  682. // Sleep if 1 ms or more off the frame limiting goal
  683. if (targetMax - elapsed >= 1000LL)
  684. {
  685. unsigned sleepTime = (unsigned)((targetMax - elapsed) / 1000LL);
  686. Time::Sleep(sleepTime);
  687. }
  688. }
  689. }
  690. #endif
  691. elapsed = frameTimer_.GetUSec(true);
  692. #ifdef ATOMIC_TESTING
  693. if (timeOut_ > 0)
  694. {
  695. timeOut_ -= elapsed;
  696. if (timeOut_ <= 0)
  697. Exit();
  698. }
  699. #endif
  700. // If FPS lower than minimum, clamp elapsed time
  701. if (minFps_)
  702. {
  703. long long targetMin = 1000000LL / minFps_;
  704. if (elapsed > targetMin)
  705. elapsed = targetMin;
  706. }
  707. // Perform timestep smoothing
  708. timeStep_ = 0.0f;
  709. lastTimeSteps_.Push(elapsed / 1000000.0f);
  710. if (lastTimeSteps_.Size() > timeStepSmoothing_)
  711. {
  712. // If the smoothing configuration was changed, ensure correct amount of samples
  713. lastTimeSteps_.Erase(0, lastTimeSteps_.Size() - timeStepSmoothing_);
  714. for (unsigned i = 0; i < lastTimeSteps_.Size(); ++i)
  715. timeStep_ += lastTimeSteps_[i];
  716. timeStep_ /= lastTimeSteps_.Size();
  717. }
  718. else
  719. timeStep_ = lastTimeSteps_.Back();
  720. }
  721. VariantMap Engine::ParseParameters(const Vector<String>& arguments)
  722. {
  723. VariantMap ret;
  724. // Pre-initialize the parameters with environment variable values when they are set
  725. if (const char* paths = getenv("ATOMIC_PREFIX_PATH"))
  726. ret[EP_RESOURCE_PREFIX_PATHS] = paths;
  727. for (unsigned i = 0; i < arguments.Size(); ++i)
  728. {
  729. if (arguments[i].Length() > 1 && arguments[i][0] == '-')
  730. {
  731. String argument = arguments[i].Substring(1).ToLower();
  732. String value = i + 1 < arguments.Size() ? arguments[i + 1] : String::EMPTY;
  733. if (argument == "headless")
  734. ret[EP_HEADLESS] = true;
  735. else if (argument == "nolimit")
  736. ret[EP_FRAME_LIMITER] = false;
  737. else if (argument == "flushgpu")
  738. ret[EP_FLUSH_GPU] = true;
  739. else if (argument == "gl2")
  740. ret[EP_FORCE_GL2] = true;
  741. else if (argument == "landscape")
  742. ret[EP_ORIENTATIONS] = "LandscapeLeft LandscapeRight " + ret[EP_ORIENTATIONS].GetString();
  743. else if (argument == "portrait")
  744. ret[EP_ORIENTATIONS] = "Portrait PortraitUpsideDown " + ret[EP_ORIENTATIONS].GetString();
  745. else if (argument == "nosound")
  746. ret[EP_SOUND] = false;
  747. else if (argument == "noip")
  748. ret[EP_SOUND_INTERPOLATION] = false;
  749. else if (argument == "mono")
  750. ret[EP_SOUND_STEREO] = false;
  751. else if (argument == "prepass")
  752. ret[EP_RENDER_PATH] = "RenderPaths/Prepass.xml";
  753. else if (argument == "deferred")
  754. ret[EP_RENDER_PATH] = "RenderPaths/Deferred.xml";
  755. else if (argument == "renderpath" && !value.Empty())
  756. {
  757. ret[EP_RENDER_PATH] = value;
  758. ++i;
  759. }
  760. else if (argument == "noshadows")
  761. ret[EP_SHADOWS] = false;
  762. else if (argument == "lqshadows")
  763. ret[EP_LOW_QUALITY_SHADOWS] = true;
  764. else if (argument == "nothreads")
  765. ret[EP_WORKER_THREADS] = false;
  766. else if (argument == "v")
  767. ret[EP_VSYNC] = true;
  768. else if (argument == "t")
  769. ret[EP_TRIPLE_BUFFER] = true;
  770. else if (argument == "w")
  771. ret[EP_FULL_SCREEN] = false;
  772. else if (argument == "borderless")
  773. ret[EP_BORDERLESS] = true;
  774. else if (argument == "s")
  775. ret[EP_WINDOW_RESIZABLE] = true;
  776. else if (argument == "hd")
  777. ret[EP_HIGH_DPI] = true;
  778. else if (argument == "q")
  779. ret[EP_LOG_QUIET] = true;
  780. else if (argument == "log" && !value.Empty())
  781. {
  782. unsigned logLevel = GetStringListIndex(value.CString(), logLevelPrefixes, M_MAX_UNSIGNED);
  783. if (logLevel != M_MAX_UNSIGNED)
  784. {
  785. ret[EP_LOG_LEVEL] = logLevel;
  786. ++i;
  787. }
  788. }
  789. else if (argument == "x" && !value.Empty())
  790. {
  791. ret[EP_WINDOW_WIDTH] = ToInt(value);
  792. ++i;
  793. }
  794. else if (argument == "y" && !value.Empty())
  795. {
  796. ret[EP_WINDOW_HEIGHT] = ToInt(value);
  797. ++i;
  798. }
  799. else if (argument == "monitor" && !value.Empty()) {
  800. ret[EP_MONITOR] = ToInt(value);
  801. ++i;
  802. }
  803. else if (argument == "hz" && !value.Empty()) {
  804. ret[EP_REFRESH_RATE] = ToInt(value);
  805. ++i;
  806. }
  807. else if (argument == "m" && !value.Empty())
  808. {
  809. ret[EP_MULTI_SAMPLE] = ToInt(value);
  810. ++i;
  811. }
  812. else if (argument == "b" && !value.Empty())
  813. {
  814. ret[EP_SOUND_BUFFER] = ToInt(value);
  815. ++i;
  816. }
  817. else if (argument == "r" && !value.Empty())
  818. {
  819. ret[EP_SOUND_MIX_RATE] = ToInt(value);
  820. ++i;
  821. }
  822. else if (argument == "pp" && !value.Empty())
  823. {
  824. ret[EP_RESOURCE_PREFIX_PATHS] = value;
  825. ++i;
  826. }
  827. else if (argument == "p" && !value.Empty())
  828. {
  829. ret[EP_RESOURCE_PATHS] = value;
  830. ++i;
  831. }
  832. else if (argument == "pf" && !value.Empty())
  833. {
  834. ret[EP_RESOURCE_PACKAGES] = value;
  835. ++i;
  836. }
  837. else if (argument == "ap" && !value.Empty())
  838. {
  839. ret[EP_AUTOLOAD_PATHS] = value;
  840. ++i;
  841. }
  842. else if (argument == "ds" && !value.Empty())
  843. {
  844. ret[EP_DUMP_SHADERS] = value;
  845. ++i;
  846. }
  847. else if (argument == "mq" && !value.Empty())
  848. {
  849. ret[EP_MATERIAL_QUALITY] = ToInt(value);
  850. ++i;
  851. }
  852. else if (argument == "tq" && !value.Empty())
  853. {
  854. ret[EP_TEXTURE_QUALITY] = ToInt(value);
  855. ++i;
  856. }
  857. else if (argument == "tf" && !value.Empty())
  858. {
  859. ret[EP_TEXTURE_FILTER_MODE] = ToInt(value);
  860. ++i;
  861. }
  862. else if (argument == "af" && !value.Empty())
  863. {
  864. ret[EP_TEXTURE_FILTER_MODE] = FILTER_ANISOTROPIC;
  865. ret[EP_TEXTURE_ANISOTROPY] = ToInt(value);
  866. ++i;
  867. }
  868. else if (argument == "touch")
  869. ret[EP_TOUCH_EMULATION] = true;
  870. // ATOMIC BEGIN
  871. else if (argument == "logname" && !value.Empty())
  872. {
  873. ret[EP_LOG_NAME] = value;
  874. ++i;
  875. }
  876. else if (argument == "-autometrics") // --autometrics
  877. {
  878. ret[EP_AUTO_METRICS] = true;
  879. }
  880. // ATOMIC END
  881. #ifdef ATOMIC_TESTING
  882. else if (argument == "timeout" && !value.Empty())
  883. {
  884. ret[EP_TIME_OUT] = ToInt(value);
  885. ++i;
  886. }
  887. #endif
  888. }
  889. }
  890. return ret;
  891. }
  892. bool Engine::HasParameter(const VariantMap& parameters, const String& parameter)
  893. {
  894. StringHash nameHash(parameter);
  895. return parameters.Find(nameHash) != parameters.End();
  896. }
  897. const Variant& Engine::GetParameter(const VariantMap& parameters, const String& parameter, const Variant& defaultValue)
  898. {
  899. StringHash nameHash(parameter);
  900. VariantMap::ConstIterator i = parameters.Find(nameHash);
  901. return i != parameters.End() ? i->second_ : defaultValue;
  902. }
  903. void Engine::HandleExitRequested(StringHash eventType, VariantMap& eventData)
  904. {
  905. if (autoExit_)
  906. {
  907. // Do not call Exit() here, as it contains mobile platform -specific tests to not exit.
  908. // If we do receive an exit request from the system on those platforms, we must comply
  909. DoExit();
  910. }
  911. }
  912. void Engine::DoExit()
  913. {
  914. Graphics* graphics = GetSubsystem<Graphics>();
  915. if (graphics)
  916. graphics->Close();
  917. exiting_ = true;
  918. #if defined(__EMSCRIPTEN__) && defined(ATOMIC_TESTING)
  919. emscripten_force_exit(EXIT_SUCCESS); // Some how this is required to signal emrun to stop
  920. #endif
  921. }
  922. // ATOMIC BEGIN
  923. void Engine::SetPaused(bool paused)
  924. {
  925. paused_ = paused;
  926. using namespace UpdatesPaused;
  927. // Updates paused event
  928. VariantMap& eventData = GetEventDataMap();
  929. eventData[P_PAUSED] = paused_;
  930. SendEvent(E_UPDATESPAUSEDRESUMED, eventData);
  931. }
  932. void Engine::SetRunNextPausedFrame(bool run)
  933. {
  934. runNextPausedFrame_ = run;
  935. }
  936. void Engine::HandlePauseResumeRequested(StringHash eventType, VariantMap& eventData)
  937. {
  938. SetPaused(!IsPaused());
  939. }
  940. void Engine::HandlePauseStepRequested(StringHash eventType, VariantMap& eventData)
  941. {
  942. if (IsPaused())
  943. {
  944. SetRunNextPausedFrame(true);
  945. }
  946. }
  947. bool Engine::GetDebugBuild() const
  948. {
  949. #ifdef ATOMIC_DEBUG
  950. return true;
  951. #else
  952. return false;
  953. #endif
  954. }
  955. // ATOMIC END
  956. }