Engine.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Audio.h"
  25. #include "Console.h"
  26. #include "Context.h"
  27. #include "CoreEvents.h"
  28. #include "DebugHud.h"
  29. #include "Engine.h"
  30. #include "FileSystem.h"
  31. #include "Graphics.h"
  32. #include "Input.h"
  33. #include "Log.h"
  34. #include "Network.h"
  35. #include "PackageFile.h"
  36. #include "PhysicsWorld.h"
  37. #include "ProcessUtils.h"
  38. #include "Profiler.h"
  39. #include "Renderer.h"
  40. #include "ResourceCache.h"
  41. #include "Scene.h"
  42. #include "SceneEvents.h"
  43. #include "Script.h"
  44. #include "ScriptAPI.h"
  45. #include "StringUtils.h"
  46. #include "UI.h"
  47. #include <Windows.h>
  48. #include "DebugNew.h"
  49. OBJECTTYPESTATIC(Engine);
  50. Engine::Engine(Context* context) :
  51. Object(context),
  52. minFps_(10),
  53. maxFps_(200),
  54. maxInactiveFps_(50),
  55. timeStep_(0),
  56. initialized_(false),
  57. exiting_(false),
  58. headless_(false)
  59. {
  60. }
  61. Engine::~Engine()
  62. {
  63. }
  64. bool Engine::Initialize(const String& windowTitle, const String& logName, const Vector<String>& arguments)
  65. {
  66. if (initialized_)
  67. return true;
  68. RenderMode mode = RENDER_FORWARD;
  69. int width = 0;
  70. int height = 0;
  71. int multiSample = 0;
  72. bool fullscreen = true;
  73. bool vsync = false;
  74. bool forceSM2 = false;
  75. bool shadows = true;
  76. int mixRate = 44100;
  77. int buffer = 100;
  78. bool sound = true;
  79. bool stereo = true;
  80. bool sixteenBit = true;
  81. bool interpolate = true;
  82. for (unsigned i = 0; i < arguments.Size(); ++i)
  83. {
  84. if ((arguments[i][0] == '-') && (arguments[i].Length() >= 2))
  85. {
  86. String argument = arguments[i].Substring(1).ToLower();
  87. if (argument == "headless")
  88. headless_ = true;
  89. else if (argument == "prepass")
  90. mode = RENDER_PREPASS;
  91. else if (argument == "deferred")
  92. mode = RENDER_DEFERRED;
  93. else if (argument == "nolimit")
  94. SetMaxFps(0);
  95. else if (argument == "nosound")
  96. sound = false;
  97. else if (argument == "noip")
  98. interpolate = false;
  99. else if (argument == "mono")
  100. stereo = false;
  101. else if (argument == "8bit")
  102. sixteenBit = false;
  103. else if (argument == "noshadows")
  104. shadows = false;
  105. else if (argument == "sm2")
  106. forceSM2 = true;
  107. else
  108. {
  109. switch (tolower(argument[0]))
  110. {
  111. case 'x':
  112. if (arguments[i].Length() > 1)
  113. width = ToInt(argument.Substring(1));
  114. break;
  115. case 'y':
  116. if (arguments[i].Length() > 1)
  117. height = ToInt(argument.Substring(1));
  118. break;
  119. case 'm':
  120. if (arguments[i].Length() > 1)
  121. multiSample = ToInt(argument.Substring(1));
  122. break;
  123. case 'b':
  124. if (arguments[i].Length() > 1)
  125. buffer = ToInt(argument.Substring(1));
  126. break;
  127. case 'r':
  128. if (arguments[i].Length() > 1)
  129. mixRate = ToInt(argument.Substring(1));
  130. break;
  131. case 'v':
  132. vsync = true;
  133. break;
  134. case 'f':
  135. fullscreen = true;
  136. break;
  137. case 'w':
  138. fullscreen = false;
  139. break;
  140. }
  141. }
  142. }
  143. }
  144. // Register object factories and attributes first, then subsystems
  145. RegisterObjects();
  146. RegisterSubsystems();
  147. // Start logging
  148. Log* log = GetSubsystem<Log>();
  149. log->Open(logName);
  150. // Add default resource paths: CoreData package or directory, Data package or directory, system fonts directory
  151. ResourceCache* cache = GetSubsystem<ResourceCache>();
  152. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  153. String exePath = fileSystem->GetProgramDir();
  154. if (fileSystem->FileExists(exePath + "CoreData.pak"))
  155. {
  156. SharedPtr<PackageFile> package(new PackageFile(context_));
  157. package->Open(exePath + "CoreData.pak");
  158. cache->AddPackageFile(package);
  159. }
  160. else if (fileSystem->DirExists(exePath + "CoreData"))
  161. cache->AddResourcePath(exePath + "CoreData");
  162. if (fileSystem->FileExists(exePath + "Data.pak"))
  163. {
  164. SharedPtr<PackageFile> package(new PackageFile(context_));
  165. package->Open(exePath + "Data.pak");
  166. cache->AddPackageFile(package);
  167. }
  168. else if (fileSystem->DirExists(exePath + "Data"))
  169. cache->AddResourcePath(exePath + "Data");
  170. cache->AddResourcePath(fileSystem->GetSystemFontDir());
  171. // Initialize graphics & audio output
  172. if (!headless_)
  173. {
  174. Graphics* graphics = GetSubsystem<Graphics>();
  175. graphics->SetForceSM2(forceSM2);
  176. if (!graphics->SetMode(mode, width, height, fullscreen, vsync, multiSample))
  177. return false;
  178. graphics->SetWindowTitle(windowTitle);
  179. if (!shadows)
  180. GetSubsystem<Renderer>()->SetDrawShadows(false);
  181. if (sound)
  182. GetSubsystem<Audio>()->SetMode(buffer, mixRate, sixteenBit, stereo, interpolate);
  183. }
  184. initialized_ = true;
  185. return true;
  186. }
  187. bool Engine::InitializeScripting()
  188. {
  189. if (!initialized_)
  190. return false;
  191. // Check if scripting already initialized
  192. if (GetSubsystem<Script>())
  193. return true;
  194. RegisterScriptLibrary(context_);
  195. context_->RegisterSubsystem(new Script(context_));
  196. {
  197. PROFILE(RegisterScriptAPI);
  198. asIScriptEngine* engine = GetSubsystem<Script>()->GetScriptEngine();
  199. RegisterMathAPI(engine);
  200. RegisterCoreAPI(engine);
  201. RegisterIOAPI(engine);
  202. RegisterResourceAPI(engine);
  203. RegisterSceneAPI(engine);
  204. RegisterGraphicsAPI(engine);
  205. RegisterInputAPI(engine);
  206. RegisterAudioAPI(engine);
  207. RegisterUIAPI(engine);
  208. RegisterNetworkAPI(engine);
  209. RegisterPhysicsAPI(engine);
  210. RegisterScriptAPI(engine);
  211. RegisterEngineAPI(engine);
  212. }
  213. return true;
  214. }
  215. void Engine::RunFrame()
  216. {
  217. if ((!initialized_) || (exiting_))
  218. return;
  219. if (!headless_)
  220. {
  221. if (!GetSubsystem<Graphics>()->GetWindowHandle())
  222. {
  223. Exit();
  224. return;
  225. }
  226. }
  227. Time* time = GetSubsystem<Time>();
  228. time->BeginFrame(timeStep_);
  229. Render();
  230. // If scripting initialized, garbage collect before getting the next time step
  231. Script* script = GetSubsystem<Script>();
  232. if (script)
  233. script->GarbageCollect(false);
  234. GetNextTimeStep();
  235. time->EndFrame();
  236. }
  237. Console* Engine::CreateConsole()
  238. {
  239. if ((headless_) || (!initialized_))
  240. return 0;
  241. context_->RegisterSubsystem(new Console(context_));
  242. return GetSubsystem<Console>();
  243. }
  244. DebugHud* Engine::CreateDebugHud()
  245. {
  246. if ((headless_) || (!initialized_))
  247. return 0;
  248. context_->RegisterSubsystem(new DebugHud(context_));
  249. return GetSubsystem<DebugHud>();
  250. }
  251. void Engine::SetMinFps(int fps)
  252. {
  253. minFps_ = Max(fps, 0);
  254. }
  255. void Engine::SetMaxFps(int fps)
  256. {
  257. maxFps_ = Max(fps, 0);
  258. }
  259. void Engine::SetMaxInactiveFps(int fps)
  260. {
  261. maxInactiveFps_ = Max(fps, 0);
  262. }
  263. void Engine::Exit()
  264. {
  265. Graphics* graphics = GetSubsystem<Graphics>();
  266. if (graphics)
  267. graphics->Close();
  268. exiting_ = true;
  269. }
  270. void Engine::DumpProfilingData()
  271. {
  272. Profiler* profiler = GetSubsystem<Profiler>();
  273. if (profiler)
  274. {
  275. profiler->EndFrame();
  276. LOGRAW(profiler->GetData(true, false, true) + "\n");
  277. }
  278. }
  279. void Engine::DumpResources()
  280. {
  281. ResourceCache* cache = GetSubsystem<ResourceCache>();
  282. const Map<ShortStringHash, ResourceGroup>& resourceGroups = cache->GetAllResources();
  283. LOGRAW("\n");
  284. for (Map<ShortStringHash, ResourceGroup>::ConstIterator i = resourceGroups.Begin();
  285. i != resourceGroups.End(); ++i)
  286. {
  287. unsigned num = i->second_.resources_.Size();
  288. unsigned memoryUse = i->second_.memoryUse_;
  289. if (num)
  290. {
  291. LOGRAW("Resource type " + i->second_.resources_.Begin()->second_->GetTypeName() +
  292. ": count " + num + " memory use " + String(memoryUse) + "\n");
  293. }
  294. }
  295. LOGRAW("Total memory use of all resources " + String(cache->GetTotalMemoryUse()) + "\n\n");
  296. }
  297. void Engine::Render()
  298. {
  299. Graphics* graphics = GetSubsystem<Graphics>();
  300. // Do not render if device lost
  301. if ((graphics) && (graphics->BeginFrame()))
  302. {
  303. GetSubsystem<Renderer>()->Render();
  304. GetSubsystem<UI>()->Render();
  305. graphics->EndFrame();
  306. }
  307. }
  308. void Engine::GetNextTimeStep()
  309. {
  310. PROFILE(ApplyFrameLimiter);
  311. if (!initialized_)
  312. return;
  313. int maxFps = maxFps_;
  314. Input* input = GetSubsystem<Input>();
  315. if ((input) && (!input->IsActive()))
  316. maxFps = maxInactiveFps_;
  317. int timeAcc = 0;
  318. if (maxFps)
  319. {
  320. int targetMax = 1000 / maxFps;
  321. for (;;)
  322. {
  323. timeAcc += frameTimer_.GetMSec(true);
  324. if (timeAcc >= targetMax)
  325. break;
  326. unsigned wait = (targetMax - timeAcc);
  327. Sleep(wait / 2);
  328. }
  329. }
  330. else
  331. timeAcc = frameTimer_.GetMSec(true);
  332. // If FPS lower than minimum, clamp elapsed time
  333. if (minFps_)
  334. {
  335. int targetMin = 1000 / minFps_;
  336. if (timeAcc > targetMin)
  337. timeAcc = targetMin;
  338. }
  339. timeStep_ = timeAcc;
  340. }
  341. void Engine::RegisterObjects()
  342. {
  343. RegisterResourceLibrary(context_);
  344. RegisterSceneLibrary(context_);
  345. RegisterGraphicsLibrary(context_);
  346. RegisterAudioLibrary(context_);
  347. RegisterUILibrary(context_);
  348. RegisterPhysicsLibrary(context_);
  349. }
  350. void Engine::RegisterSubsystems()
  351. {
  352. // Register self as a subsystem
  353. context_->RegisterSubsystem(this);
  354. // Create and register the rest of the subsystems
  355. context_->RegisterSubsystem(new Time(context_));
  356. #ifdef ENABLE_PROFILING
  357. context_->RegisterSubsystem(new Profiler(context_));
  358. #endif
  359. context_->RegisterSubsystem(new Log(context_));
  360. context_->RegisterSubsystem(new FileSystem(context_));
  361. context_->RegisterSubsystem(new ResourceCache(context_));
  362. context_->RegisterSubsystem(new Network(context_));
  363. if (!headless_)
  364. {
  365. context_->RegisterSubsystem(new Graphics(context_));
  366. context_->RegisterSubsystem(new Renderer(context_));
  367. }
  368. context_->RegisterSubsystem(new Input(context_));
  369. context_->RegisterSubsystem(new UI(context_));
  370. context_->RegisterSubsystem(new Audio(context_));
  371. }