mainLoop.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  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
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell 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
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "app/mainLoop.h"
  23. #include "app/game.h"
  24. #include "platform/platformTimer.h"
  25. #include "platform/platformRedBook.h"
  26. #include "platform/platformVolume.h"
  27. #include "platform/platformMemory.h"
  28. #include "platform/platformTimer.h"
  29. #include "platform/platformNet.h"
  30. #include "platform/nativeDialogs/fileDialog.h"
  31. #include "platform/threads/thread.h"
  32. #include "core/module.h"
  33. #include "core/threadStatic.h"
  34. #include "core/iTickable.h"
  35. #include "core/stream/fileStream.h"
  36. #include "windowManager/platformWindowMgr.h"
  37. #include "core/util/journal/process.h"
  38. #include "util/fpsTracker.h"
  39. #include "console/debugOutputConsumer.h"
  40. #include "console/consoleTypes.h"
  41. #include "console/engineAPI.h"
  42. #include "gfx/bitmap/gBitmap.h"
  43. #include "gfx/gFont.h"
  44. #include "gfx/video/videoCapture.h"
  45. #include "gfx/gfxTextureManager.h"
  46. #include "sim/netStringTable.h"
  47. #include "sim/actionMap.h"
  48. #include "sim/netInterface.h"
  49. #include "util/sampler.h"
  50. #include "platform/threads/threadPool.h"
  51. // For the TickMs define... fix this for T2D...
  52. #include "T3D/gameBase/processList.h"
  53. #ifdef TORQUE_ENABLE_VFS
  54. #include "platform/platformVFS.h"
  55. #endif
  56. #ifndef _MODULE_MANAGER_H
  57. #include "module/moduleManager.h"
  58. #endif
  59. #ifndef _ASSET_MANAGER_H_
  60. #include "assets/assetManager.h"
  61. #endif
  62. DITTS( F32, gTimeScale, 1.0 );
  63. DITTS( U32, gTimeAdvance, 0 );
  64. DITTS( U32, gFrameSkip, 0 );
  65. extern S32 sgBackgroundProcessSleepTime;
  66. extern S32 sgTimeManagerProcessInterval;
  67. extern FPSTracker gFPS;
  68. TimeManager* tm = NULL;
  69. static bool gRequiresRestart = false;
  70. #ifdef TORQUE_DEBUG
  71. /// Temporary timer used to time startup times.
  72. static PlatformTimer* gStartupTimer;
  73. #endif
  74. #if defined( TORQUE_MINIDUMP ) && defined( TORQUE_RELEASE )
  75. StringTableEntry gMiniDumpDir;
  76. StringTableEntry gMiniDumpExec;
  77. StringTableEntry gMiniDumpParams;
  78. StringTableEntry gMiniDumpExecDir;
  79. #endif
  80. namespace engineAPI
  81. {
  82. // This is the magic switch for deciding which interop the engine
  83. // should use. It will go away when we drop the console system
  84. // entirely but for now it is necessary for several behaviors that
  85. // differ between the interops to decide what to do.
  86. bool gUseConsoleInterop = true;
  87. bool gIsInitialized = false;
  88. }
  89. // The following are some tricks to make the memory leak checker run after global
  90. // dtors have executed by placing some code in the termination segments.
  91. #if defined( TORQUE_DEBUG ) && !defined( TORQUE_DISABLE_MEMORY_MANAGER )
  92. #ifdef TORQUE_COMPILER_VISUALC
  93. # pragma data_seg( ".CRT$XTU" )
  94. static void* sCheckMemBeforeTermination = &Memory::ensureAllFreed;
  95. # pragma data_seg()
  96. #elif defined( TORQUE_COMPILER_GCC )
  97. __attribute__ ( ( destructor ) ) static void _ensureAllFreed()
  98. {
  99. Memory::ensureAllFreed();
  100. }
  101. #endif
  102. #endif
  103. // Process a time event and update all sub-processes
  104. void processTimeEvent(S32 elapsedTime)
  105. {
  106. PROFILE_START(ProcessTimeEvent);
  107. // If recording a video and not playinb back a journal, override the elapsedTime
  108. if (VIDCAP->isRecording() && !Journal::IsPlaying())
  109. elapsedTime = VIDCAP->getMsPerFrame();
  110. // cap the elapsed time to one second
  111. // if it's more than that we're probably in a bad catch-up situation
  112. if(elapsedTime > 1024)
  113. elapsedTime = 1024;
  114. U32 timeDelta;
  115. if(ATTS(gTimeAdvance))
  116. timeDelta = ATTS(gTimeAdvance);
  117. else
  118. timeDelta = (U32) (elapsedTime * ATTS(gTimeScale));
  119. Platform::advanceTime(elapsedTime);
  120. // Don't build up more time than a single tick... this makes the sim
  121. // frame rate dependent but is a useful hack for singleplayer.
  122. if ( ATTS(gFrameSkip) )
  123. if ( timeDelta > TickMs )
  124. timeDelta = TickMs;
  125. bool tickPass;
  126. PROFILE_START(ServerProcess);
  127. tickPass = serverProcess(timeDelta);
  128. PROFILE_END();
  129. PROFILE_START(ServerNetProcess);
  130. // only send packets if a tick happened
  131. if(tickPass)
  132. GNet->processServer();
  133. // Used to indicate if server was just ticked.
  134. Con::setBoolVariable( "$pref::hasServerTicked", tickPass );
  135. PROFILE_END();
  136. PROFILE_START(SimAdvanceTime);
  137. Sim::advanceTime(timeDelta);
  138. PROFILE_END();
  139. PROFILE_START(ClientProcess);
  140. tickPass = clientProcess(timeDelta);
  141. // Used to indicate if client was just ticked.
  142. Con::setBoolVariable( "$pref::hasClientTicked", tickPass );
  143. PROFILE_END_NAMED(ClientProcess);
  144. PROFILE_START(ClientNetProcess);
  145. if(tickPass)
  146. GNet->processClient();
  147. PROFILE_END();
  148. GNet->checkTimeouts();
  149. gFPS.update();
  150. // Give the texture manager a chance to cleanup any
  151. // textures that haven't been referenced for a bit.
  152. if( GFX )
  153. TEXMGR->cleanupCache( 5 );
  154. PROFILE_END();
  155. // Update the console time
  156. Con::setFloatVariable("Sim::Time",F32(Platform::getVirtualMilliseconds()) / 1000);
  157. }
  158. void StandardMainLoop::init()
  159. {
  160. #ifdef TORQUE_DEBUG
  161. gStartupTimer = PlatformTimer::create();
  162. #endif
  163. #ifdef TORQUE_DEBUG_GUARD
  164. Memory::flagCurrentAllocs( Memory::FLAG_Global );
  165. #endif
  166. Platform::setMathControlStateKnown();
  167. // Asserts should be created FIRST
  168. PlatformAssert::create();
  169. ManagedSingleton< ThreadManager >::createSingleton();
  170. FrameAllocator::init(TORQUE_FRAME_SIZE); // See comments in torqueConfig.h
  171. // Yell if we can't initialize the network.
  172. if(!Net::init())
  173. {
  174. AssertISV(false, "StandardMainLoop::initCore - could not initialize networking!");
  175. }
  176. _StringTable::create();
  177. // Set up the resource manager and get some basic file types in it.
  178. Con::init();
  179. Platform::initConsole();
  180. NetStringTable::create();
  181. // Use debug output logging on the Xbox and OSX builds
  182. #if defined( _XBOX ) || defined( TORQUE_OS_MAC )
  183. DebugOutputConsumer::init();
  184. #endif
  185. // init Filesystem first, so we can actually log errors for all components that follow
  186. Platform::FS::InstallFileSystems(); // install all drives for now until we have everything using the volume stuff
  187. Platform::FS::MountDefaults();
  188. // Set our working directory.
  189. Torque::FS::SetCwd( "game:/" );
  190. // Set our working directory.
  191. Platform::setCurrentDirectory( Platform::getMainDotCsDir() );
  192. Processor::init();
  193. Math::init();
  194. Platform::init(); // platform specific initialization
  195. RedBook::init();
  196. Platform::initConsole();
  197. ThreadPool::GlobalThreadPool::createSingleton();
  198. // Initialize modules.
  199. EngineModuleManager::initializeSystem();
  200. // Initialise ITickable.
  201. #ifdef TORQUE_TGB_ONLY
  202. ITickable::init( 4 );
  203. #endif
  204. #ifdef TORQUE_ENABLE_VFS
  205. // [tom, 10/28/2006] Load the VFS here so that it stays loaded
  206. Zip::ZipArchive *vfs = openEmbeddedVFSArchive();
  207. gResourceManager->addVFSRoot(vfs);
  208. #endif
  209. Con::addVariable("timeScale", TypeF32, &ATTS(gTimeScale), "Animation time scale.\n"
  210. "@ingroup platform");
  211. Con::addVariable("timeAdvance", TypeS32, &ATTS(gTimeAdvance), "The speed at which system processing time advances.\n"
  212. "@ingroup platform");
  213. Con::addVariable("frameSkip", TypeS32, &ATTS(gFrameSkip), "Sets the number of frames to skip while rendering the scene.\n"
  214. "@ingroup platform");
  215. Con::setVariable( "defaultGame", StringTable->insert("scripts") );
  216. Con::addVariable( "_forceAllMainThread", TypeBool, &ThreadPool::getForceAllMainThread(), "Force all work items to execute on main thread. turns this into a single-threaded system. Primarily useful to find whether malfunctions are caused by parallel execution or not.\n"
  217. "@ingroup platform" );
  218. #if defined( TORQUE_MINIDUMP ) && defined( TORQUE_RELEASE )
  219. Con::addVariable("MiniDump::Dir", TypeString, &gMiniDumpDir);
  220. Con::addVariable("MiniDump::Exec", TypeString, &gMiniDumpExec);
  221. Con::addVariable("MiniDump::Params", TypeString, &gMiniDumpParams);
  222. Con::addVariable("MiniDump::ExecDir", TypeString, &gMiniDumpExecDir);
  223. #endif
  224. // Register the module manager.
  225. ModuleDatabase.registerObject("ModuleDatabase");
  226. // Register the asset database.
  227. AssetDatabase.registerObject("AssetDatabase");
  228. // Register the asset database as a module listener.
  229. ModuleDatabase.addListener(&AssetDatabase);
  230. ActionMap* globalMap = new ActionMap;
  231. globalMap->registerObject("GlobalActionMap");
  232. Sim::getActiveActionMapSet()->pushObject(globalMap);
  233. // Do this before we init the process so that process notifiees can get the time manager
  234. tm = new TimeManager;
  235. tm->timeEvent.notify(&::processTimeEvent);
  236. // Start up the Input Event Manager
  237. INPUTMGR->start();
  238. Sampler::init();
  239. // Hook in for UDP notification
  240. Net::smPacketReceive.notify(GNet, &NetInterface::processPacketReceiveEvent);
  241. #ifdef TORQUE_DEBUG_GUARD
  242. Memory::flagCurrentAllocs( Memory::FLAG_Static );
  243. #endif
  244. }
  245. void StandardMainLoop::shutdown()
  246. {
  247. // Stop the Input Event Manager
  248. INPUTMGR->stop();
  249. delete tm;
  250. preShutdown();
  251. // Unregister the module database.
  252. ModuleDatabase.unregisterObject();
  253. // Unregister the asset database.
  254. AssetDatabase.unregisterObject();
  255. // Shut down modules.
  256. EngineModuleManager::shutdownSystem();
  257. ThreadPool::GlobalThreadPool::deleteSingleton();
  258. #ifdef TORQUE_ENABLE_VFS
  259. closeEmbeddedVFSArchive();
  260. #endif
  261. RedBook::destroy();
  262. Platform::shutdown();
  263. #if defined( _XBOX ) || defined( TORQUE_OS_MAC )
  264. DebugOutputConsumer::destroy();
  265. #endif
  266. NetStringTable::destroy();
  267. Con::shutdown();
  268. _StringTable::destroy();
  269. FrameAllocator::destroy();
  270. Net::shutdown();
  271. Sampler::destroy();
  272. ManagedSingleton< ThreadManager >::deleteSingleton();
  273. // asserts should be destroyed LAST
  274. PlatformAssert::destroy();
  275. #if defined( TORQUE_DEBUG ) && !defined( TORQUE_DISABLE_MEMORY_MANAGER )
  276. Memory::validate();
  277. #endif
  278. }
  279. void StandardMainLoop::preShutdown()
  280. {
  281. #ifdef TORQUE_TOOLS
  282. // Tools are given a chance to do pre-quit processing
  283. // - This is because for tools we like to do things such
  284. // as prompting to save changes before shutting down
  285. // and onExit is packaged which means we can't be sure
  286. // where in the shutdown namespace chain we are when using
  287. // onExit since some components of the tools may already be
  288. // destroyed that may be vital to saving changes to avoid
  289. // loss of work [1/5/2007 justind]
  290. if( Con::isFunction("onPreExit") )
  291. Con::executef( "onPreExit");
  292. #endif
  293. //exec the script onExit() function
  294. if ( Con::isFunction( "onExit" ) )
  295. Con::executef("onExit");
  296. }
  297. bool StandardMainLoop::handleCommandLine( S32 argc, const char **argv )
  298. {
  299. // Allow the window manager to process command line inputs; this is
  300. // done to let web plugin functionality happen in a fairly transparent way.
  301. PlatformWindowManager::get()->processCmdLineArgs(argc, argv);
  302. Process::handleCommandLine( argc, argv );
  303. // Set up the command line args for the console scripts...
  304. Con::setIntVariable("Game::argc", argc);
  305. U32 i;
  306. for (i = 0; i < argc; i++)
  307. Con::setVariable(avar("Game::argv%d", i), argv[i]);
  308. #ifdef TORQUE_PLAYER
  309. if(argc > 2 && dStricmp(argv[1], "-project") == 0)
  310. {
  311. char playerPath[1024];
  312. Platform::makeFullPathName(argv[2], playerPath, sizeof(playerPath));
  313. Platform::setCurrentDirectory(playerPath);
  314. argv += 2;
  315. argc -= 2;
  316. // Re-locate the game:/ asset mount.
  317. Torque::FS::Unmount( "game" );
  318. Torque::FS::Mount( "game", Platform::FS::createNativeFS( playerPath ) );
  319. }
  320. #endif
  321. // Executes an entry script file. This is "main.cs"
  322. // by default, but any file name (with no whitespace
  323. // in it) may be run if it is specified as the first
  324. // command-line parameter. The script used, default
  325. // or otherwise, is not compiled and is loaded here
  326. // directly because the resource system restricts
  327. // access to the "root" directory.
  328. #ifdef TORQUE_ENABLE_VFS
  329. Zip::ZipArchive *vfs = openEmbeddedVFSArchive();
  330. bool useVFS = vfs != NULL;
  331. #endif
  332. Stream *mainCsStream = NULL;
  333. // The working filestream.
  334. FileStream str;
  335. const char *defaultScriptName = "main.cs";
  336. bool useDefaultScript = true;
  337. // Check if any command-line parameters were passed (the first is just the app name).
  338. if (argc > 1)
  339. {
  340. // If so, check if the first parameter is a file to open.
  341. if ( (dStrcmp(argv[1], "") != 0 ) && (str.open(argv[1], Torque::FS::File::Read)) )
  342. {
  343. // If it opens, we assume it is the script to run.
  344. useDefaultScript = false;
  345. #ifdef TORQUE_ENABLE_VFS
  346. useVFS = false;
  347. #endif
  348. mainCsStream = &str;
  349. }
  350. }
  351. if (useDefaultScript)
  352. {
  353. bool success = false;
  354. #ifdef TORQUE_ENABLE_VFS
  355. if(useVFS)
  356. success = (mainCsStream = vfs->openFile(defaultScriptName, Zip::ZipArchive::Read)) != NULL;
  357. else
  358. #endif
  359. success = str.open(defaultScriptName, Torque::FS::File::Read);
  360. #if defined( TORQUE_DEBUG ) && defined (TORQUE_TOOLS) && !defined(TORQUE_DEDICATED) && !defined( _XBOX )
  361. if (!success)
  362. {
  363. OpenFileDialog ofd;
  364. FileDialogData &fdd = ofd.getData();
  365. fdd.mFilters = StringTable->insert("Main Entry Script (main.cs)|main.cs|");
  366. fdd.mTitle = StringTable->insert("Locate Game Entry Script");
  367. // Get the user's selection
  368. if( !ofd.Execute() )
  369. return false;
  370. // Process and update CWD so we can run the selected main.cs
  371. S32 pathLen = dStrlen( fdd.mFile );
  372. FrameTemp<char> szPathCopy( pathLen + 1);
  373. dStrcpy( szPathCopy, fdd.mFile );
  374. //forwardslash( szPathCopy );
  375. const char *path = dStrrchr(szPathCopy, '/');
  376. if(path)
  377. {
  378. U32 len = path - (const char*)szPathCopy;
  379. szPathCopy[len+1] = 0;
  380. Platform::setCurrentDirectory(szPathCopy);
  381. // Re-locate the game:/ asset mount.
  382. Torque::FS::Unmount( "game" );
  383. Torque::FS::Mount( "game", Platform::FS::createNativeFS( ( const char* ) szPathCopy ) );
  384. success = str.open(fdd.mFile, Torque::FS::File::Read);
  385. if(success)
  386. defaultScriptName = fdd.mFile;
  387. }
  388. }
  389. #endif
  390. if( !success )
  391. {
  392. char msg[1024];
  393. dSprintf(msg, sizeof(msg), "Failed to open \"%s\".", defaultScriptName);
  394. Platform::AlertOK("Error", msg);
  395. #ifdef TORQUE_ENABLE_VFS
  396. closeEmbeddedVFSArchive();
  397. #endif
  398. return false;
  399. }
  400. #ifdef TORQUE_ENABLE_VFS
  401. if(! useVFS)
  402. #endif
  403. mainCsStream = &str;
  404. }
  405. // This should rarely happen, but lets deal with
  406. // it gracefully if it does.
  407. if ( mainCsStream == NULL )
  408. return false;
  409. U32 size = mainCsStream->getStreamSize();
  410. char *script = new char[size + 1];
  411. mainCsStream->read(size, script);
  412. #ifdef TORQUE_ENABLE_VFS
  413. if(useVFS)
  414. vfs->closeFile(mainCsStream);
  415. else
  416. #endif
  417. str.close();
  418. script[size] = 0;
  419. char buffer[1024], *ptr;
  420. Platform::makeFullPathName(useDefaultScript ? defaultScriptName : argv[1], buffer, sizeof(buffer), Platform::getCurrentDirectory());
  421. ptr = dStrrchr(buffer, '/');
  422. if(ptr != NULL)
  423. *ptr = 0;
  424. Platform::setMainDotCsDir(buffer);
  425. Platform::setCurrentDirectory(buffer);
  426. Con::evaluate(script, false, useDefaultScript ? defaultScriptName : argv[1]);
  427. delete[] script;
  428. #ifdef TORQUE_ENABLE_VFS
  429. closeEmbeddedVFSArchive();
  430. #endif
  431. return true;
  432. }
  433. bool StandardMainLoop::doMainLoop()
  434. {
  435. #ifdef TORQUE_DEBUG
  436. if( gStartupTimer )
  437. {
  438. Con::printf( "Started up in %.2f seconds...",
  439. F32( gStartupTimer->getElapsedMs() ) / 1000.f );
  440. SAFE_DELETE( gStartupTimer );
  441. }
  442. #endif
  443. bool keepRunning = true;
  444. // while(keepRunning)
  445. {
  446. tm->setBackgroundThreshold(mClamp(sgBackgroundProcessSleepTime, 1, 200));
  447. tm->setForegroundThreshold(mClamp(sgTimeManagerProcessInterval, 1, 200));
  448. // update foreground/background status
  449. if(WindowManager->getFirstWindow())
  450. {
  451. static bool lastFocus = false;
  452. bool newFocus = ( WindowManager->getFocusedWindow() != NULL );
  453. if(lastFocus != newFocus)
  454. {
  455. #ifndef TORQUE_SHIPPING
  456. Con::printf("Window focus status changed: focus: %d", newFocus);
  457. if (!newFocus)
  458. Con::printf(" Using background sleep time: %u", Platform::getBackgroundSleepTime());
  459. #endif
  460. #ifdef TORQUE_OS_MAC
  461. if (newFocus)
  462. WindowManager->getFirstWindow()->show();
  463. #endif
  464. lastFocus = newFocus;
  465. }
  466. #ifndef TORQUE_OS_MAC
  467. // under the web plugin do not sleep the process when the child window loses focus as this will cripple the browser perfomance
  468. if (!Platform::getWebDeployment())
  469. tm->setBackground(!newFocus);
  470. else
  471. tm->setBackground(false);
  472. #else
  473. tm->setBackground(false);
  474. #endif
  475. }
  476. else
  477. {
  478. tm->setBackground(false);
  479. }
  480. PROFILE_START(MainLoop);
  481. Sampler::beginFrame();
  482. if(!Process::processEvents())
  483. keepRunning = false;
  484. ThreadPool::processMainThreadWorkItems();
  485. Sampler::endFrame();
  486. PROFILE_END_NAMED(MainLoop);
  487. }
  488. return keepRunning;
  489. }
  490. S32 StandardMainLoop::getReturnStatus()
  491. {
  492. return Process::getReturnStatus();
  493. }
  494. void StandardMainLoop::setRestart(bool restart )
  495. {
  496. gRequiresRestart = restart;
  497. }
  498. bool StandardMainLoop::requiresRestart()
  499. {
  500. return gRequiresRestart;
  501. }