Engine.cpp 36 KB

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