Engine.cpp 37 KB

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