Engine.cpp 38 KB

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