Engine.cpp 38 KB

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