mainLoop.cpp 18 KB

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