openttd.cpp

Go to the documentation of this file.
00001 /* $Id$ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
00008  */
00009 
00012 #include "stdafx.h"
00013 
00014 #include "blitter/factory.hpp"
00015 #include "sound/sound_driver.hpp"
00016 #include "music/music_driver.hpp"
00017 #include "video/video_driver.hpp"
00018 
00019 #include "fontcache.h"
00020 #include "error.h"
00021 #include "gui.h"
00022 
00023 #include "base_media_base.h"
00024 #include "saveload/saveload.h"
00025 #include "company_func.h"
00026 #include "command_func.h"
00027 #include "news_func.h"
00028 #include "fios.h"
00029 #include "aircraft.h"
00030 #include "roadveh.h"
00031 #include "train.h"
00032 #include "ship.h"
00033 #include "console_func.h"
00034 #include "screenshot.h"
00035 #include "network/network.h"
00036 #include "network/network_func.h"
00037 #include "ai/ai.hpp"
00038 #include "ai/ai_config.hpp"
00039 #include "settings_func.h"
00040 #include "genworld.h"
00041 #include "progress.h"
00042 #include "strings_func.h"
00043 #include "date_func.h"
00044 #include "vehicle_func.h"
00045 #include "gamelog.h"
00046 #include "animated_tile_func.h"
00047 #include "roadstop_base.h"
00048 #include "elrail_func.h"
00049 #include "rev.h"
00050 #include "highscore.h"
00051 #include "station_base.h"
00052 #include "crashlog.h"
00053 #include "engine_func.h"
00054 #include "core/random_func.hpp"
00055 #include "rail_gui.h"
00056 #include "core/backup_type.hpp"
00057 #include "hotkeys.h"
00058 #include "newgrf.h"
00059 #include "misc/getoptdata.h"
00060 #include "game/game.hpp"
00061 #include "game/game_config.hpp"
00062 
00063 
00064 
00065 #include "linkgraph/linkgraph.h"
00066 
00067 #include <stdarg.h>
00068 
00069 
00070 void CallLandscapeTick();
00071 void IncreaseDate();
00072 void DoPaletteAnimations();
00073 void MusicLoop();
00074 void ResetMusic();
00075 void CallWindowTickEvent();
00076 bool HandleBootstrap();
00077 
00078 extern void SetDifficultyLevel(int mode, DifficultySettings *gm_opt);
00079 extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
00080 extern void ShowOSErrorBox(const char *buf, bool system);
00081 extern char *_config_file;
00082 
00088 void CDECL usererror(const char *s, ...)
00089 {
00090   va_list va;
00091   char buf[512];
00092 
00093   va_start(va, s);
00094   vsnprintf(buf, lengthof(buf), s, va);
00095   va_end(va);
00096 
00097   ShowOSErrorBox(buf, false);
00098   if (_video_driver != NULL) _video_driver->Stop();
00099 
00100   exit(1);
00101 }
00102 
00108 void CDECL error(const char *s, ...)
00109 {
00110   va_list va;
00111   char buf[512];
00112 
00113   va_start(va, s);
00114   vsnprintf(buf, lengthof(buf), s, va);
00115   va_end(va);
00116 
00117   ShowOSErrorBox(buf, true);
00118 
00119   /* Set the error message for the crash log and then invoke it. */
00120   CrashLog::SetErrorMessage(buf);
00121   abort();
00122 }
00123 
00128 void CDECL ShowInfoF(const char *str, ...)
00129 {
00130   va_list va;
00131   char buf[1024];
00132   va_start(va, str);
00133   vsnprintf(buf, lengthof(buf), str, va);
00134   va_end(va);
00135   ShowInfo(buf);
00136 }
00137 
00141 static void ShowHelp()
00142 {
00143   char buf[8192];
00144   char *p = buf;
00145 
00146   p += seprintf(p, lastof(buf), "OpenTTD %s\n", _openttd_revision);
00147   p = strecpy(p,
00148     "\n"
00149     "\n"
00150     "Command line options:\n"
00151     "  -v drv              = Set video driver (see below)\n"
00152     "  -s drv              = Set sound driver (see below) (param bufsize,hz)\n"
00153     "  -m drv              = Set music driver (see below)\n"
00154     "  -b drv              = Set the blitter to use (see below)\n"
00155     "  -r res              = Set resolution (for instance 800x600)\n"
00156     "  -h                  = Display this help text\n"
00157     "  -t year             = Set starting year\n"
00158     "  -d [[fac=]lvl[,...]]= Debug mode\n"
00159     "  -e                  = Start Editor\n"
00160     "  -g [savegame]       = Start new/save game immediately\n"
00161     "  -G seed             = Set random seed\n"
00162 #if defined(ENABLE_NETWORK)
00163     "  -n [ip:port#company]= Start networkgame\n"
00164     "  -p password         = Password to join server\n"
00165     "  -P password         = Password to join company\n"
00166     "  -D [ip][:port]      = Start dedicated server\n"
00167     "  -l ip[:port]        = Redirect DEBUG()\n"
00168 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
00169     "  -f                  = Fork into the background (dedicated only)\n"
00170 #endif
00171 #endif /* ENABLE_NETWORK */
00172     "  -I graphics_set     = Force the graphics set (see below)\n"
00173     "  -S sounds_set       = Force the sounds set (see below)\n"
00174     "  -M music_set        = Force the music set (see below)\n"
00175     "  -c config_file      = Use 'config_file' instead of 'openttd.cfg'\n"
00176     "  -x                  = Do not automatically save to config file on exit\n"
00177     "  -q savegame         = Write some information about the savegame and exit\n"
00178     "\n",
00179     lastof(buf)
00180   );
00181 
00182   /* List the graphics packs */
00183   p = BaseGraphics::GetSetsList(p, lastof(buf));
00184 
00185   /* List the sounds packs */
00186   p = BaseSounds::GetSetsList(p, lastof(buf));
00187 
00188   /* List the music packs */
00189   p = BaseMusic::GetSetsList(p, lastof(buf));
00190 
00191   /* List the drivers */
00192   p = VideoDriverFactoryBase::GetDriversInfo(p, lastof(buf));
00193 
00194   /* List the blitters */
00195   p = BlitterFactoryBase::GetBlittersInfo(p, lastof(buf));
00196 
00197   /* List the debug facilities. */
00198   p = DumpDebugFacilityNames(p, lastof(buf));
00199 
00200   /* We need to initialize the AI, so it finds the AIs */
00201   AI::Initialize();
00202   p = AI::GetConsoleList(p, lastof(buf), true);
00203   AI::Uninitialize(true);
00204 
00205   /* We need to initialize the GameScript, so it finds the GSs */
00206   Game::Initialize();
00207   p = Game::GetConsoleList(p, lastof(buf), true);
00208   Game::Uninitialize(true);
00209 
00210   /* ShowInfo put output to stderr, but version information should go
00211    * to stdout; this is the only exception */
00212 #if !defined(WIN32) && !defined(WIN64)
00213   printf("%s\n", buf);
00214 #else
00215   ShowInfo(buf);
00216 #endif
00217 }
00218 
00219 static void WriteSavegameInfo(const char *name)
00220 {
00221   extern uint16 _sl_version;
00222   uint32 last_ottd_rev = 0;
00223   byte ever_modified = 0;
00224   bool removed_newgrfs = false;
00225 
00226   GamelogInfo(_load_check_data.gamelog_action, _load_check_data.gamelog_actions, &last_ottd_rev, &ever_modified, &removed_newgrfs);
00227 
00228   char buf[8192];
00229   char *p = buf;
00230   p += seprintf(p, lastof(buf), "Name:         %s\n", name);
00231   p += seprintf(p, lastof(buf), "Savegame ver: %d\n", _sl_version);
00232   p += seprintf(p, lastof(buf), "NewGRF ver:   0x%08X\n", last_ottd_rev);
00233   p += seprintf(p, lastof(buf), "Modified:     %d\n", ever_modified);
00234 
00235   if (removed_newgrfs) {
00236     p += seprintf(p, lastof(buf), "NewGRFs have been removed\n");
00237   }
00238 
00239   p = strecpy(p, "NewGRFs:\n", lastof(buf));
00240   if (_load_check_data.HasNewGrfs()) {
00241     for (GRFConfig *c = _load_check_data.grfconfig; c != NULL; c = c->next) {
00242       char md5sum[33];
00243       md5sumToString(md5sum, lastof(md5sum), HasBit(c->flags, GCF_COMPATIBLE) ? c->original_md5sum : c->ident.md5sum);
00244       p += seprintf(p, lastof(buf), "%08X %s %s\n", c->ident.grfid, md5sum, c->filename);
00245     }
00246   }
00247 
00248   /* ShowInfo put output to stderr, but version information should go
00249    * to stdout; this is the only exception */
00250 #if !defined(WIN32) && !defined(WIN64)
00251   printf("%s\n", buf);
00252 #else
00253   ShowInfo(buf);
00254 #endif
00255 }
00256 
00257 
00264 static void ParseResolution(Dimension *res, const char *s)
00265 {
00266   const char *t = strchr(s, 'x');
00267   if (t == NULL) {
00268     ShowInfoF("Invalid resolution '%s'", s);
00269     return;
00270   }
00271 
00272   res->width  = max(strtoul(s, NULL, 0), 64UL);
00273   res->height = max(strtoul(t + 1, NULL, 0), 64UL);
00274 }
00275 
00276 
00281 static void ShutdownGame()
00282 {
00283   IConsoleFree();
00284 
00285   if (_network_available) NetworkShutDown(); // Shut down the network and close any open connections
00286 
00287   DriverFactoryBase::ShutdownDrivers();
00288 
00289   UnInitWindowSystem();
00290 
00291   /* stop the scripts */
00292   AI::Uninitialize(false);
00293   Game::Uninitialize(false);
00294 
00295   /* Uninitialize variables that are allocated dynamically */
00296   GamelogReset();
00297 
00298   /* Reinitialize the link graphs to forcibly stop the threads.
00299    * If a link graph thread is running while the link graph handlers are
00300    * deleted we get a crash.
00301    */
00302   InitializeLinkGraphs();
00303 
00304 #ifdef ENABLE_NETWORK
00305   free(_config_file);
00306 #endif
00307 
00308   PoolBase::Clean(PT_ALL);
00309 
00310   /* No NewGRFs were loaded when it was still bootstrapping. */
00311   if (_game_mode != GM_BOOTSTRAP) ResetNewGRFData();
00312 
00313   /* Close all and any open filehandles */
00314   FioCloseAll();
00315 
00316   UninitFreeType();
00317 }
00318 
00323 static void LoadIntroGame(bool load_newgrfs = true)
00324 {
00325   _game_mode = GM_MENU;
00326 
00327   if (load_newgrfs) ResetGRFConfig(false);
00328 
00329   /* Setup main window */
00330   ResetWindowSystem();
00331   SetupColoursAndInitialWindow();
00332 
00333   /* Load the default opening screen savegame */
00334   if (SaveOrLoad("opntitle.dat", SL_LOAD, BASESET_DIR) != SL_OK) {
00335     GenerateWorld(GWM_EMPTY, 64, 64); // if failed loading, make empty world.
00336     WaitTillGeneratedWorld();
00337     SetLocalCompany(COMPANY_SPECTATOR);
00338   } else {
00339     SetLocalCompany(COMPANY_FIRST);
00340   }
00341 
00342   _pause_mode = PM_UNPAUSED;
00343   _cursor.fix_at = false;
00344 
00345   if (load_newgrfs) CheckForMissingSprites();
00346   CheckForMissingGlyphs();
00347 
00348   /* Play main theme */
00349   if (_music_driver->IsSongPlaying()) ResetMusic();
00350 }
00351 
00352 void MakeNewgameSettingsLive()
00353 {
00354   for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
00355     if (_settings_game.ai_config[c] != NULL) {
00356       delete _settings_game.ai_config[c];
00357     }
00358   }
00359   if (_settings_game.game_config != NULL) {
00360     delete _settings_game.game_config;
00361   }
00362 
00363   /* Copy newgame settings to active settings.
00364    * Also initialise old settings needed for savegame conversion. */
00365   _settings_game = _settings_newgame;
00366   _old_vds = _settings_client.company.vehicle;
00367 
00368   for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
00369     _settings_game.ai_config[c] = NULL;
00370     if (_settings_newgame.ai_config[c] != NULL) {
00371       _settings_game.ai_config[c] = new AIConfig(_settings_newgame.ai_config[c]);
00372     }
00373   }
00374   _settings_game.game_config = NULL;
00375   if (_settings_newgame.game_config != NULL) {
00376     _settings_game.game_config = new GameConfig(_settings_newgame.game_config);
00377   }
00378 }
00379 
00380 void OpenBrowser(const char *url)
00381 {
00382   /* Make sure we only accept urls that are sure to open a browser. */
00383   if (strstr(url, "http://") != url && strstr(url, "https://") != url) return;
00384 
00385   extern void OSOpenBrowser(const char *url);
00386   OSOpenBrowser(url);
00387 }
00388 
00390 struct AfterNewGRFScan : NewGRFScanCallback {
00391   Year startyear;                    
00392   uint generation_seed;              
00393   char *dedicated_host;              
00394   uint16 dedicated_port;             
00395   char *network_conn;                
00396   const char *join_server_password;  
00397   const char *join_company_password; 
00398   bool *save_config_ptr;             
00399   bool save_config;                  
00400 
00406   AfterNewGRFScan(bool *save_config_ptr) :
00407       startyear(INVALID_YEAR), generation_seed(GENERATE_NEW_SEED),
00408       dedicated_host(NULL), dedicated_port(0), network_conn(NULL),
00409       join_server_password(NULL), join_company_password(NULL),
00410       save_config_ptr(save_config_ptr), save_config(true)
00411   {
00412   }
00413 
00414   virtual void OnNewGRFsScanned()
00415   {
00416     ResetGRFConfig(false);
00417 
00418     TarScanner::DoScan(TarScanner::SCENARIO);
00419 
00420     AI::Initialize();
00421     Game::Initialize();
00422 
00423     /* We want the new (correct) NewGRF count to survive the loading. */
00424     uint last_newgrf_count = _settings_client.gui.last_newgrf_count;
00425     LoadFromConfig();
00426     _settings_client.gui.last_newgrf_count = last_newgrf_count;
00427     /* Since the default for the palette might have changed due to
00428      * reading the configuration file, recalculate that now. */
00429     UpdateNewGRFConfigPalette();
00430 
00431     Game::Uninitialize(true);
00432     AI::Uninitialize(true);
00433     CheckConfig();
00434     LoadFromHighScore();
00435     LoadHotkeysFromConfig();
00436 
00437     /* We have loaded the config, so we may possibly save it. */
00438     *save_config_ptr = save_config;
00439 
00440     /* restore saved music volume */
00441     _music_driver->SetVolume(_settings_client.music.music_vol);
00442 
00443     if (startyear != INVALID_YEAR) _settings_newgame.game_creation.starting_year = startyear;
00444     if (generation_seed != GENERATE_NEW_SEED) _settings_newgame.game_creation.generation_seed = generation_seed;
00445 
00446 #if defined(ENABLE_NETWORK)
00447     if (dedicated_host != NULL) {
00448       _network_bind_list.Clear();
00449       *_network_bind_list.Append() = strdup(dedicated_host);
00450     }
00451     if (dedicated_port != 0) _settings_client.network.server_port = dedicated_port;
00452 #endif /* ENABLE_NETWORK */
00453 
00454     /* initialize the ingame console */
00455     IConsoleInit();
00456     InitializeGUI();
00457     IConsoleCmdExec("exec scripts/autoexec.scr 0");
00458 
00459     /* Make sure _settings is filled with _settings_newgame if we switch to a game directly */
00460     if (_switch_mode != SM_NONE) MakeNewgameSettingsLive();
00461 
00462 #ifdef ENABLE_NETWORK
00463     if (_network_available && network_conn != NULL) {
00464       const char *port = NULL;
00465       const char *company = NULL;
00466       uint16 rport = NETWORK_DEFAULT_PORT;
00467       CompanyID join_as = COMPANY_NEW_COMPANY;
00468 
00469       ParseConnectionString(&company, &port, network_conn);
00470 
00471       if (company != NULL) {
00472         join_as = (CompanyID)atoi(company);
00473 
00474         if (join_as != COMPANY_SPECTATOR) {
00475           join_as--;
00476           if (join_as >= MAX_COMPANIES) {
00477             delete this;
00478             return;
00479           }
00480         }
00481       }
00482       if (port != NULL) rport = atoi(port);
00483 
00484       LoadIntroGame();
00485       _switch_mode = SM_NONE;
00486       NetworkClientConnectGame(NetworkAddress(network_conn, rport), join_as, join_server_password, join_company_password);
00487     }
00488 #endif /* ENABLE_NETWORK */
00489 
00490     /* After the scan we're not used anymore. */
00491     delete this;
00492   }
00493 };
00494 
00495 #if defined(UNIX) && !defined(__MORPHOS__)
00496 extern void DedicatedFork();
00497 #endif
00498 
00500 static const OptionData _options[] = {
00501    GETOPT_SHORT_VALUE('I'),
00502    GETOPT_SHORT_VALUE('S'),
00503    GETOPT_SHORT_VALUE('M'),
00504    GETOPT_SHORT_VALUE('m'),
00505    GETOPT_SHORT_VALUE('s'),
00506    GETOPT_SHORT_VALUE('v'),
00507    GETOPT_SHORT_VALUE('b'),
00508 #if defined(ENABLE_NETWORK)
00509   GETOPT_SHORT_OPTVAL('D'),
00510   GETOPT_SHORT_OPTVAL('n'),
00511    GETOPT_SHORT_VALUE('l'),
00512    GETOPT_SHORT_VALUE('p'),
00513    GETOPT_SHORT_VALUE('P'),
00514 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
00515    GETOPT_SHORT_NOVAL('f'),
00516 #endif
00517 #endif /* ENABLE_NETWORK */
00518    GETOPT_SHORT_VALUE('r'),
00519    GETOPT_SHORT_VALUE('t'),
00520   GETOPT_SHORT_OPTVAL('d'),
00521    GETOPT_SHORT_NOVAL('e'),
00522   GETOPT_SHORT_OPTVAL('g'),
00523    GETOPT_SHORT_VALUE('G'),
00524    GETOPT_SHORT_VALUE('c'),
00525    GETOPT_SHORT_NOVAL('x'),
00526    GETOPT_SHORT_VALUE('q'),
00527    GETOPT_SHORT_NOVAL('h'),
00528   GETOPT_END()
00529 };
00530 
00531 
00532 int ttd_main(int argc, char *argv[])
00533 {
00534   char *musicdriver = NULL;
00535   char *sounddriver = NULL;
00536   char *videodriver = NULL;
00537   char *blitter = NULL;
00538   char *graphics_set = NULL;
00539   char *sounds_set = NULL;
00540   char *music_set = NULL;
00541   Dimension resolution = {0, 0};
00542   /* AfterNewGRFScan sets save_config to true after scanning completed. */
00543   bool save_config = false;
00544   AfterNewGRFScan *scanner = new AfterNewGRFScan(&save_config);
00545 #if defined(ENABLE_NETWORK)
00546   bool dedicated = false;
00547   char *debuglog_conn = NULL;
00548 
00549   extern bool _dedicated_forks;
00550   _dedicated_forks = false;
00551 #endif /* ENABLE_NETWORK */
00552 
00553   _game_mode = GM_MENU;
00554   _switch_mode = SM_MENU;
00555   _config_file = NULL;
00556 
00557   GetOptData mgo(argc - 1, argv + 1, _options);
00558 
00559   int i;
00560   while ((i = mgo.GetOpt()) != -1) {
00561     switch (i) {
00562     case 'I': free(graphics_set); graphics_set = strdup(mgo.opt); break;
00563     case 'S': free(sounds_set); sounds_set = strdup(mgo.opt); break;
00564     case 'M': free(music_set); music_set = strdup(mgo.opt); break;
00565     case 'm': free(musicdriver); musicdriver = strdup(mgo.opt); break;
00566     case 's': free(sounddriver); sounddriver = strdup(mgo.opt); break;
00567     case 'v': free(videodriver); videodriver = strdup(mgo.opt); break;
00568     case 'b': free(blitter); blitter = strdup(mgo.opt); break;
00569 #if defined(ENABLE_NETWORK)
00570     case 'D':
00571       free(musicdriver);
00572       free(sounddriver);
00573       free(videodriver);
00574       free(blitter);
00575       musicdriver = strdup("null");
00576       sounddriver = strdup("null");
00577       videodriver = strdup("dedicated");
00578       blitter = strdup("null");
00579       dedicated = true;
00580       SetDebugString("net=6");
00581       if (mgo.opt != NULL) {
00582         /* Use the existing method for parsing (openttd -n).
00583          * However, we do ignore the #company part. */
00584         const char *temp = NULL;
00585         const char *port = NULL;
00586         ParseConnectionString(&temp, &port, mgo.opt);
00587         if (!StrEmpty(mgo.opt)) scanner->dedicated_host = mgo.opt;
00588         if (port != NULL) scanner->dedicated_port = atoi(port);
00589       }
00590       break;
00591     case 'f': _dedicated_forks = true; break;
00592     case 'n':
00593       scanner->network_conn = mgo.opt; // optional IP parameter, NULL if unset
00594       break;
00595     case 'l':
00596       debuglog_conn = mgo.opt;
00597       break;
00598     case 'p':
00599       scanner->join_server_password = mgo.opt;
00600       break;
00601     case 'P':
00602       scanner->join_company_password = mgo.opt;
00603       break;
00604 #endif /* ENABLE_NETWORK */
00605     case 'r': ParseResolution(&resolution, mgo.opt); break;
00606     case 't': scanner->startyear = atoi(mgo.opt); break;
00607     case 'd': {
00608 #if defined(WIN32)
00609         CreateConsole();
00610 #endif
00611         if (mgo.opt != NULL) SetDebugString(mgo.opt);
00612         break;
00613       }
00614     case 'e': _switch_mode = (_switch_mode == SM_LOAD_GAME || _switch_mode == SM_LOAD_SCENARIO ? SM_LOAD_SCENARIO : SM_EDITOR); break;
00615     case 'g':
00616       if (mgo.opt != NULL) {
00617         strecpy(_file_to_saveload.name, mgo.opt, lastof(_file_to_saveload.name));
00618         _switch_mode = (_switch_mode == SM_EDITOR || _switch_mode == SM_LOAD_SCENARIO ? SM_LOAD_SCENARIO : SM_LOAD_GAME);
00619         _file_to_saveload.mode = SL_LOAD;
00620 
00621         /* if the file doesn't exist or it is not a valid savegame, let the saveload code show an error */
00622         const char *t = strrchr(_file_to_saveload.name, '.');
00623         if (t != NULL) {
00624           FiosType ft = FiosGetSavegameListCallback(SLD_LOAD_GAME, _file_to_saveload.name, t, NULL, NULL);
00625           if (ft != FIOS_TYPE_INVALID) SetFiosType(ft);
00626         }
00627 
00628         break;
00629       }
00630 
00631       _switch_mode = SM_NEWGAME;
00632       /* Give a random map if no seed has been given */
00633       if (scanner->generation_seed == GENERATE_NEW_SEED) {
00634         scanner->generation_seed = InteractiveRandom();
00635       }
00636       break;
00637     case 'q': {
00638       DeterminePaths(argv[0]);
00639       if (StrEmpty(mgo.opt)) return 1;
00640       char title[80];
00641       title[0] = '\0';
00642       FiosGetSavegameListCallback(SLD_LOAD_GAME, mgo.opt, strrchr(mgo.opt, '.'), title, lastof(title));
00643 
00644       _load_check_data.Clear();
00645       SaveOrLoadResult res = SaveOrLoad(mgo.opt, SL_LOAD_CHECK, SAVE_DIR, false);
00646       if (res != SL_OK || _load_check_data.HasErrors()) {
00647         fprintf(stderr, "Failed to open savegame\n");
00648         if (_load_check_data.HasErrors()) {
00649           char buf[256];
00650           SetDParamStr(0, _load_check_data.error_data);
00651           GetString(buf, _load_check_data.error, lastof(buf));
00652           fprintf(stderr, "%s\n", buf);
00653         }
00654         return 1;
00655       }
00656 
00657       WriteSavegameInfo(title);
00658 
00659       return 0;
00660     }
00661     case 'G': scanner->generation_seed = atoi(mgo.opt); break;
00662     case 'c': _config_file = strdup(mgo.opt); break;
00663     case 'x': scanner->save_config = false; break;
00664     case 'h':
00665       i = -2; // Force printing of help.
00666       break;
00667     }
00668     if (i == -2) break;
00669   }
00670 
00671   if (i == -2 || mgo.numleft > 0) {
00672     /* Either the user typed '-h', he made an error, or he added unrecognized command line arguments.
00673      * In all cases, print the help, and exit.
00674      *
00675      * The next two functions are needed to list the graphics sets. We can't do them earlier
00676      * because then we cannot show it on the debug console as that hasn't been configured yet. */
00677     DeterminePaths(argv[0]);
00678     TarScanner::DoScan(TarScanner::BASESET);
00679     BaseGraphics::FindSets();
00680     BaseSounds::FindSets();
00681     BaseMusic::FindSets();
00682     ShowHelp();
00683     delete scanner;
00684     return 0;
00685   }
00686 
00687 #if defined(WINCE) && defined(_DEBUG)
00688   /* Switch on debug lvl 4 for WinCE if Debug release, as you can't give params, and you most likely do want this information */
00689   SetDebugString("4");
00690 #endif
00691 
00692   DeterminePaths(argv[0]);
00693   TarScanner::DoScan(TarScanner::BASESET);
00694 
00695 #if defined(ENABLE_NETWORK)
00696   if (dedicated) DEBUG(net, 0, "Starting dedicated version %s", _openttd_revision);
00697   if (_dedicated_forks && !dedicated) _dedicated_forks = false;
00698 
00699 #if defined(UNIX) && !defined(__MORPHOS__)
00700   /* We must fork here, or we'll end up without some resources we need (like sockets) */
00701   if (_dedicated_forks) DedicatedFork();
00702 #endif
00703 #endif
00704 
00705   LoadFromConfig(true);
00706 
00707   if (resolution.width != 0) _cur_resolution = resolution;
00708 
00709   /*
00710    * The width and height must be at least 1 pixel and width times
00711    * height times bytes per pixel must still fit within a 32 bits
00712    * integer, even for 32 bpp video modes. This way all internal
00713    * drawing routines work correctly.
00714    */
00715   _cur_resolution.width  = ClampU(_cur_resolution.width,  1, UINT16_MAX / 2);
00716   _cur_resolution.height = ClampU(_cur_resolution.height, 1, UINT16_MAX / 2);
00717 
00718   /* Assume the cursor starts within the game as not all video drivers
00719    * get an event that the cursor is within the window when it is opened.
00720    * Saying the cursor is there makes no visible difference as it would
00721    * just be out of the bounds of the window. */
00722   _cursor.in_window = true;
00723 
00724   /* enumerate language files */
00725   InitializeLanguagePacks();
00726 
00727   /* Initialize the regular font for FreeType */
00728   InitFreeType(false);
00729 
00730   /* This must be done early, since functions use the SetWindowDirty* calls */
00731   InitWindowSystem();
00732 
00733   BaseGraphics::FindSets();
00734   if (graphics_set == NULL && BaseGraphics::ini_set != NULL) graphics_set = strdup(BaseGraphics::ini_set);
00735   if (!BaseGraphics::SetSet(graphics_set) && !StrEmpty(graphics_set)) {
00736     usererror("Failed to select requested graphics set '%s'", graphics_set);
00737   }
00738   free(graphics_set);
00739 
00740   /* Initialize game palette */
00741   GfxInitPalettes();
00742 
00743   DEBUG(misc, 1, "Loading blitter...");
00744   if (blitter == NULL && _ini_blitter != NULL) blitter = strdup(_ini_blitter);
00745   _blitter_autodetected = StrEmpty(blitter);
00746   /* If we have a 32 bpp base set, try to select the 32 bpp blitter first, but only if we autoprobe the blitter. */
00747   if (!_blitter_autodetected || BaseGraphics::GetUsedSet() == NULL || BaseGraphics::GetUsedSet()->blitter == BLT_8BPP || BlitterFactoryBase::SelectBlitter("32bpp-anim") == NULL) {
00748     if (BlitterFactoryBase::SelectBlitter(blitter) == NULL) {
00749       StrEmpty(blitter) ?
00750         usererror("Failed to autoprobe blitter") :
00751         usererror("Failed to select requested blitter '%s'; does it exist?", blitter);
00752     }
00753   }
00754   free(blitter);
00755 
00756   if (videodriver == NULL && _ini_videodriver != NULL) videodriver = strdup(_ini_videodriver);
00757   _video_driver = (VideoDriver*)VideoDriverFactoryBase::SelectDriver(videodriver, Driver::DT_VIDEO);
00758   if (_video_driver == NULL) {
00759     StrEmpty(videodriver) ?
00760       usererror("Failed to autoprobe video driver") :
00761       usererror("Failed to select requested video driver '%s'", videodriver);
00762   }
00763   free(videodriver);
00764 
00765   /* Initialize the zoom level of the screen to normal */
00766   _screen.zoom = ZOOM_LVL_NORMAL;
00767 
00768   NetworkStartUp(); // initialize network-core
00769 
00770 #if defined(ENABLE_NETWORK)
00771   if (debuglog_conn != NULL && _network_available) {
00772     const char *not_used = NULL;
00773     const char *port = NULL;
00774     uint16 rport;
00775 
00776     rport = NETWORK_DEFAULT_DEBUGLOG_PORT;
00777 
00778     ParseConnectionString(&not_used, &port, debuglog_conn);
00779     if (port != NULL) rport = atoi(port);
00780 
00781     NetworkStartDebugLog(NetworkAddress(debuglog_conn, rport));
00782   }
00783 #endif /* ENABLE_NETWORK */
00784 
00785   if (!HandleBootstrap()) goto exit;
00786 
00787   _video_driver->ClaimMousePointer();
00788 
00789   /* initialize screenshot formats */
00790   InitializeScreenshotFormats();
00791 
00792   BaseSounds::FindSets();
00793   if (sounds_set == NULL && BaseSounds::ini_set != NULL) sounds_set = strdup(BaseSounds::ini_set);
00794   if (!BaseSounds::SetSet(sounds_set)) {
00795     StrEmpty(sounds_set) ?
00796       usererror("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 4.1 of readme.txt.") :
00797       usererror("Failed to select requested sounds set '%s'", sounds_set);
00798   }
00799   free(sounds_set);
00800 
00801   BaseMusic::FindSets();
00802   if (music_set == NULL && BaseMusic::ini_set != NULL) music_set = strdup(BaseMusic::ini_set);
00803   if (!BaseMusic::SetSet(music_set)) {
00804     StrEmpty(music_set) ?
00805       usererror("Failed to find a music set. Please acquire a music set for OpenTTD. See section 4.1 of readme.txt.") :
00806       usererror("Failed to select requested music set '%s'", music_set);
00807   }
00808   free(music_set);
00809 
00810   if (sounddriver == NULL && _ini_sounddriver != NULL) sounddriver = strdup(_ini_sounddriver);
00811   _sound_driver = (SoundDriver*)SoundDriverFactoryBase::SelectDriver(sounddriver, Driver::DT_SOUND);
00812   if (_sound_driver == NULL) {
00813     StrEmpty(sounddriver) ?
00814       usererror("Failed to autoprobe sound driver") :
00815       usererror("Failed to select requested sound driver '%s'", sounddriver);
00816   }
00817   free(sounddriver);
00818 
00819   if (musicdriver == NULL && _ini_musicdriver != NULL) musicdriver = strdup(_ini_musicdriver);
00820   _music_driver = (MusicDriver*)MusicDriverFactoryBase::SelectDriver(musicdriver, Driver::DT_MUSIC);
00821   if (_music_driver == NULL) {
00822     StrEmpty(musicdriver) ?
00823       usererror("Failed to autoprobe music driver") :
00824       usererror("Failed to select requested music driver '%s'", musicdriver);
00825   }
00826   free(musicdriver);
00827 
00828   /* Take our initial lock on whatever we might want to do! */
00829   _modal_progress_paint_mutex->BeginCritical();
00830   _modal_progress_work_mutex->BeginCritical();
00831 
00832   GenerateWorld(GWM_EMPTY, 64, 64); // Make the viewport initialization happy
00833   WaitTillGeneratedWorld();
00834 
00835   LoadIntroGame(false);
00836 
00837   CheckForMissingGlyphs();
00838 
00839   ScanNewGRFFiles(scanner);
00840 
00841   _video_driver->MainLoop();
00842 
00843   WaitTillSaved();
00844 
00845   /* only save config if we have to */
00846   if (save_config) {
00847     SaveToConfig();
00848     SaveHotkeysToConfig();
00849     SaveToHighScore();
00850   }
00851 
00852 exit:
00853   /* Reset windowing system, stop drivers, free used memory, ... */
00854   ShutdownGame();
00855 
00856   free(BaseGraphics::ini_set);
00857   free(BaseSounds::ini_set);
00858   free(BaseMusic::ini_set);
00859   free(_ini_musicdriver);
00860   free(_ini_sounddriver);
00861   free(_ini_videodriver);
00862   free(_ini_blitter);
00863 
00864   return 0;
00865 }
00866 
00867 void HandleExitGameRequest()
00868 {
00869   if (_game_mode == GM_MENU || _game_mode == GM_BOOTSTRAP) { // do not ask to quit on the main screen
00870     _exit_game = true;
00871   } else if (_settings_client.gui.autosave_on_exit) {
00872     DoExitSave();
00873     _exit_game = true;
00874   } else {
00875     AskExitGame();
00876   }
00877 }
00878 
00879 static void MakeNewGameDone()
00880 {
00881   SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
00882 
00883   /* In a dedicated server, the server does not play */
00884   if (!_video_driver->HasGUI()) {
00885     SetLocalCompany(COMPANY_SPECTATOR);
00886     IConsoleCmdExec("exec scripts/game_start.scr 0");
00887     return;
00888   }
00889 
00890   /* Create a single company */
00891   DoStartupNewCompany(false);
00892 
00893   Company *c = Company::Get(COMPANY_FIRST);
00894   c->settings = _settings_client.company;
00895 
00896   IConsoleCmdExec("exec scripts/game_start.scr 0");
00897 
00898   SetLocalCompany(COMPANY_FIRST);
00899 
00900   InitializeRailGUI();
00901 
00902 #ifdef ENABLE_NETWORK
00903   /* We are the server, we start a new company (not dedicated),
00904    * so set the default password *if* needed. */
00905   if (_network_server && !StrEmpty(_settings_client.network.default_company_pass)) {
00906     NetworkChangeCompanyPassword(_local_company, _settings_client.network.default_company_pass);
00907   }
00908 #endif /* ENABLE_NETWORK */
00909 
00910   if (_settings_client.gui.pause_on_newgame) DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
00911 
00912   MarkWholeScreenDirty();
00913 }
00914 
00915 static void MakeNewGame(bool from_heightmap, bool reset_settings)
00916 {
00917   _game_mode = GM_NORMAL;
00918 
00919   ResetGRFConfig(true);
00920 
00921   GenerateWorldSetCallback(&MakeNewGameDone);
00922   GenerateWorld(from_heightmap ? GWM_HEIGHTMAP : GWM_NEWGAME, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y, reset_settings);
00923 }
00924 
00925 static void MakeNewEditorWorldDone()
00926 {
00927   SetLocalCompany(OWNER_NONE);
00928 }
00929 
00930 static void MakeNewEditorWorld()
00931 {
00932   _game_mode = GM_EDITOR;
00933 
00934   ResetGRFConfig(true);
00935 
00936   GenerateWorldSetCallback(&MakeNewEditorWorldDone);
00937   GenerateWorld(GWM_EMPTY, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
00938 }
00939 
00950 bool SafeLoad(const char *filename, int mode, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = NULL)
00951 {
00952   assert(mode == SL_LOAD || (lf == NULL && mode == SL_OLD_LOAD));
00953   GameMode ogm = _game_mode;
00954 
00955   _game_mode = newgm;
00956 
00957   switch (lf == NULL ? SaveOrLoad(filename, mode, subdir) : LoadWithFilter(lf)) {
00958     case SL_OK: return true;
00959 
00960     case SL_REINIT:
00961 #ifdef ENABLE_NETWORK
00962       if (_network_dedicated) {
00963         /*
00964          * We need to reinit a network map...
00965          * We can't simply load the intro game here as that game has many
00966          * special cases which make clients desync immediately. So we fall
00967          * back to just generating a new game with the current settings.
00968          */
00969         DEBUG(net, 0, "Loading game failed, so a new (random) game will be started!");
00970         MakeNewGame(false, true);
00971         return false;
00972       }
00973       if (_network_server) {
00974         /* We can't load the intro game as server, so disconnect first. */
00975         NetworkDisconnect();
00976       }
00977 #endif /* ENABLE_NETWORK */
00978 
00979       switch (ogm) {
00980         default:
00981         case GM_MENU:   LoadIntroGame();      break;
00982         case GM_EDITOR: MakeNewEditorWorld(); break;
00983       }
00984       return false;
00985 
00986     default:
00987       _game_mode = ogm;
00988       return false;
00989   }
00990 }
00991 
00992 void SwitchToMode(SwitchMode new_mode)
00993 {
00994 #ifdef ENABLE_NETWORK
00995   /* If we are saving something, the network stays in his current state */
00996   if (new_mode != SM_SAVE_GAME) {
00997     /* If the network is active, make it not-active */
00998     if (_networking) {
00999       if (_network_server && (new_mode == SM_LOAD_GAME || new_mode == SM_NEWGAME || new_mode == SM_RESTARTGAME)) {
01000         NetworkReboot();
01001       } else {
01002         NetworkDisconnect();
01003       }
01004     }
01005 
01006     /* If we are a server, we restart the server */
01007     if (_is_network_server) {
01008       /* But not if we are going to the menu */
01009       if (new_mode != SM_MENU) {
01010         /* check if we should reload the config */
01011         if (_settings_client.network.reload_cfg) {
01012           LoadFromConfig();
01013           MakeNewgameSettingsLive();
01014           ResetGRFConfig(false);
01015         }
01016         NetworkServerStart();
01017       } else {
01018         /* This client no longer wants to be a network-server */
01019         _is_network_server = false;
01020       }
01021     }
01022   }
01023 #endif /* ENABLE_NETWORK */
01024   /* Make sure all AI controllers are gone at quiting game */
01025   if (new_mode != SM_SAVE_GAME) AI::KillAll();
01026 
01027   switch (new_mode) {
01028     case SM_EDITOR: // Switch to scenario editor
01029       MakeNewEditorWorld();
01030       break;
01031 
01032     case SM_RESTARTGAME: // Restart --> 'Random game' with current settings
01033     case SM_NEWGAME: // New Game --> 'Random game'
01034 #ifdef ENABLE_NETWORK
01035       if (_network_server) {
01036         snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "Random Map");
01037       }
01038 #endif /* ENABLE_NETWORK */
01039       MakeNewGame(false, new_mode == SM_NEWGAME);
01040       break;
01041 
01042     case SM_LOAD_GAME: { // Load game, Play Scenario
01043       ResetGRFConfig(true);
01044       ResetWindowSystem();
01045 
01046       if (!SafeLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_NORMAL, NO_DIRECTORY)) {
01047         SetDParamStr(0, GetSaveLoadErrorString());
01048         ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
01049       } else {
01050         if (_saveload_mode == SLD_LOAD_SCENARIO) {
01051           StartupEngines();
01052         }
01053         /* Update the local company for a loaded game. It is either always
01054          * company #1 (eg 0) or in the case of a dedicated server a spectator */
01055         SetLocalCompany(_network_dedicated ? COMPANY_SPECTATOR : COMPANY_FIRST);
01056         /* Execute the game-start script */
01057         IConsoleCmdExec("exec scripts/game_start.scr 0");
01058         /* Decrease pause counter (was increased from opening load dialog) */
01059         DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
01060 #ifdef ENABLE_NETWORK
01061         if (_network_server) {
01062           snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Loaded game)", _file_to_saveload.title);
01063         }
01064 #endif /* ENABLE_NETWORK */
01065       }
01066       break;
01067     }
01068 
01069     case SM_START_HEIGHTMAP: // Load a heightmap and start a new game from it
01070 #ifdef ENABLE_NETWORK
01071       if (_network_server) {
01072         snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Heightmap)", _file_to_saveload.title);
01073       }
01074 #endif /* ENABLE_NETWORK */
01075       MakeNewGame(true, true);
01076       break;
01077 
01078     case SM_LOAD_HEIGHTMAP: // Load heightmap from scenario editor
01079       SetLocalCompany(OWNER_NONE);
01080 
01081       GenerateWorld(GWM_HEIGHTMAP, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
01082       MarkWholeScreenDirty();
01083       break;
01084 
01085     case SM_LOAD_SCENARIO: { // Load scenario from scenario editor
01086       if (SafeLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_EDITOR, NO_DIRECTORY)) {
01087         SetLocalCompany(OWNER_NONE);
01088         _settings_newgame.game_creation.starting_year = _cur_year;
01089         /* Cancel the saveload pausing */
01090         DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
01091       } else {
01092         SetDParamStr(0, GetSaveLoadErrorString());
01093         ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
01094       }
01095       break;
01096     }
01097 
01098     case SM_MENU: // Switch to game intro menu
01099       LoadIntroGame();
01100       if (BaseSounds::ini_set == NULL && BaseSounds::GetUsedSet()->fallback) {
01101         ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET, INVALID_STRING_ID, WL_CRITICAL);
01102         BaseSounds::ini_set = strdup(BaseSounds::GetUsedSet()->name);
01103       }
01104       break;
01105 
01106     case SM_SAVE_GAME: // Save game.
01107       /* Make network saved games on pause compatible to singleplayer */
01108       if (SaveOrLoad(_file_to_saveload.name, SL_SAVE, NO_DIRECTORY) != SL_OK) {
01109         SetDParamStr(0, GetSaveLoadErrorString());
01110         ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
01111       } else {
01112         DeleteWindowById(WC_SAVELOAD, 0);
01113       }
01114       break;
01115 
01116     case SM_SAVE_HEIGHTMAP: // Save heightmap.
01117       MakeHeightmapScreenshot(_file_to_saveload.name);
01118       DeleteWindowById(WC_SAVELOAD, 0);
01119       break;
01120 
01121     case SM_GENRANDLAND: // Generate random land within scenario editor
01122       SetLocalCompany(OWNER_NONE);
01123       GenerateWorld(GWM_RANDOM, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
01124       /* XXX: set date */
01125       MarkWholeScreenDirty();
01126       break;
01127 
01128     default: NOT_REACHED();
01129   }
01130 }
01131 
01132 
01139 static void CheckCaches()
01140 {
01141   /* Return here so it is easy to add checks that are run
01142    * always to aid testing of caches. */
01143   if (_debug_desync_level <= 1) return;
01144 
01145   /* Check company infrastructure cache. */
01146   SmallVector<CompanyInfrastructure, 4> old_infrastructure;
01147   Company *c;
01148   FOR_ALL_COMPANIES(c) MemCpyT(old_infrastructure.Append(), &c->infrastructure);
01149 
01150   extern void AfterLoadCompanyStats();
01151   AfterLoadCompanyStats();
01152 
01153   uint i = 0;
01154   FOR_ALL_COMPANIES(c) {
01155     if (MemCmpT(old_infrastructure.Get(i), &c->infrastructure) != 0) {
01156       DEBUG(desync, 2, "infrastructure cache mismatch: company %i", (int)c->index);
01157     }
01158     i++;
01159   }
01160 
01161   /* Strict checking of the road stop cache entries */
01162   const RoadStop *rs;
01163   FOR_ALL_ROADSTOPS(rs) {
01164     if (IsStandardRoadStopTile(rs->xy)) continue;
01165 
01166     assert(rs->GetEntry(DIAGDIR_NE) != rs->GetEntry(DIAGDIR_NW));
01167     rs->GetEntry(DIAGDIR_NE)->CheckIntegrity(rs);
01168     rs->GetEntry(DIAGDIR_NW)->CheckIntegrity(rs);
01169   }
01170 
01171   Vehicle *v;
01172   FOR_ALL_VEHICLES(v) {
01173     extern void FillNewGRFVehicleCache(const Vehicle *v);
01174     if (v != v->First() || v->vehstatus & VS_CRASHED || !v->IsPrimaryVehicle()) continue;
01175 
01176     uint length = 0;
01177     for (const Vehicle *u = v; u != NULL; u = u->Next()) length++;
01178 
01179     NewGRFCache        *grf_cache = CallocT<NewGRFCache>(length);
01180     VehicleCache       *veh_cache = CallocT<VehicleCache>(length);
01181     GroundVehicleCache *gro_cache = CallocT<GroundVehicleCache>(length);
01182     TrainCache         *tra_cache = CallocT<TrainCache>(length);
01183 
01184     length = 0;
01185     for (const Vehicle *u = v; u != NULL; u = u->Next()) {
01186       FillNewGRFVehicleCache(u);
01187       grf_cache[length] = u->grf_cache;
01188       veh_cache[length] = u->vcache;
01189       switch (u->type) {
01190         case VEH_TRAIN:
01191           gro_cache[length] = Train::From(u)->gcache;
01192           tra_cache[length] = Train::From(u)->tcache;
01193           break;
01194         case VEH_ROAD:
01195           gro_cache[length] = RoadVehicle::From(u)->gcache;
01196           break;
01197         default:
01198           break;
01199       }
01200       length++;
01201     }
01202 
01203     switch (v->type) {
01204       case VEH_TRAIN:    Train::From(v)->ConsistChanged(true);     break;
01205       case VEH_ROAD:     RoadVehUpdateCache(RoadVehicle::From(v)); break;
01206       case VEH_AIRCRAFT: UpdateAircraftCache(Aircraft::From(v));   break;
01207       case VEH_SHIP:     Ship::From(v)->UpdateCache();             break;
01208       default: break;
01209     }
01210 
01211     length = 0;
01212     for (const Vehicle *u = v; u != NULL; u = u->Next()) {
01213       FillNewGRFVehicleCache(u);
01214       if (memcmp(&grf_cache[length], &u->grf_cache, sizeof(NewGRFCache)) != 0) {
01215         DEBUG(desync, 2, "newgrf cache mismatch: type %i, vehicle %i, company %i, unit number %i, wagon %i", (int)v->type, v->index, (int)v->owner, v->unitnumber, length);
01216       }
01217       if (memcmp(&veh_cache[length], &u->vcache, sizeof(VehicleCache)) != 0) {
01218         DEBUG(desync, 2, "vehicle cache mismatch: type %i, vehicle %i, company %i, unit number %i, wagon %i", (int)v->type, v->index, (int)v->owner, v->unitnumber, length);
01219       }
01220       switch (u->type) {
01221         case VEH_TRAIN:
01222           if (memcmp(&gro_cache[length], &Train::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
01223             DEBUG(desync, 2, "train ground vehicle cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v->index, (int)v->owner, v->unitnumber, length);
01224           }
01225           if (memcmp(&tra_cache[length], &Train::From(u)->tcache, sizeof(TrainCache)) != 0) {
01226             DEBUG(desync, 2, "train cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v->index, (int)v->owner, v->unitnumber, length);
01227           }
01228           break;
01229         case VEH_ROAD:
01230           if (memcmp(&gro_cache[length], &RoadVehicle::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
01231             DEBUG(desync, 2, "road vehicle ground vehicle cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v->index, (int)v->owner, v->unitnumber, length);
01232           }
01233           break;
01234         default:
01235           break;
01236       }
01237       length++;
01238     }
01239 
01240     free(grf_cache);
01241     free(veh_cache);
01242     free(gro_cache);
01243     free(tra_cache);
01244   }
01245 
01246   /* Check whether the caches are still valid */
01247   FOR_ALL_VEHICLES(v) {
01248     byte buff[sizeof(VehicleCargoList)];
01249     memcpy(buff, &v->cargo, sizeof(VehicleCargoList));
01250     v->cargo.InvalidateCache();
01251     assert(memcmp(&v->cargo, buff, sizeof(VehicleCargoList)) == 0);
01252   }
01253 
01254   Station *st;
01255   FOR_ALL_STATIONS(st) {
01256     for (CargoID c = 0; c < NUM_CARGO; c++) {
01257       byte buff[sizeof(StationCargoList)];
01258       memcpy(buff, &st->goods[c].cargo, sizeof(StationCargoList));
01259       st->goods[c].cargo.InvalidateCache();
01260       assert(memcmp(&st->goods[c].cargo, buff, sizeof(StationCargoList)) == 0);
01261     }
01262   }
01263 }
01264 
01270 void StateGameLoop()
01271 {
01272   /* dont execute the state loop during pause */
01273   if (_pause_mode != PM_UNPAUSED) {
01274     UpdateLandscapingLimits();
01275     Game::GameLoop();
01276     CallWindowTickEvent();
01277     return;
01278   }
01279   if (HasModalProgress()) return;
01280 
01281   ClearStorageChanges(false);
01282 
01283   if (_game_mode == GM_EDITOR) {
01284     RunTileLoop();
01285     CallVehicleTicks();
01286     CallLandscapeTick();
01287     ClearStorageChanges(true);
01288     UpdateLandscapingLimits();
01289 
01290     CallWindowTickEvent();
01291     NewsLoop();
01292   } else {
01293     if (_debug_desync_level > 2 && _date_fract == 0 && (_date & 0x1F) == 0) {
01294       /* Save the desync savegame if needed. */
01295       char name[MAX_PATH];
01296       snprintf(name, lengthof(name), "dmp_cmds_%08x_%08x.sav", _settings_game.game_creation.generation_seed, _date);
01297       SaveOrLoad(name, SL_SAVE, AUTOSAVE_DIR, false);
01298     }
01299 
01300     CheckCaches();
01301 
01302     /* All these actions has to be done from OWNER_NONE
01303      *  for multiplayer compatibility */
01304     Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
01305 
01306     AnimateAnimatedTiles();
01307     IncreaseDate();
01308     RunTileLoop();
01309     CallVehicleTicks();
01310     CallLandscapeTick();
01311     ClearStorageChanges(true);
01312 
01313     AI::GameLoop();
01314     Game::GameLoop();
01315     UpdateLandscapingLimits();
01316 
01317     CallWindowTickEvent();
01318     NewsLoop();
01319     cur_company.Restore();
01320   }
01321 
01322   assert(IsLocalCompany());
01323 }
01324 
01329 static void DoAutosave()
01330 {
01331   char buf[MAX_PATH];
01332 
01333 #if defined(PSP)
01334   /* Autosaving in networking is too time expensive for the PSP */
01335   if (_networking) return;
01336 #endif /* PSP */
01337 
01338   if (_settings_client.gui.keep_all_autosave) {
01339     GenerateDefaultSaveName(buf, lastof(buf));
01340     strecat(buf, ".sav", lastof(buf));
01341   } else {
01342     static int _autosave_ctr = 0;
01343 
01344     /* generate a savegame name and number according to _settings_client.gui.max_num_autosaves */
01345     snprintf(buf, sizeof(buf), "autosave%d.sav", _autosave_ctr);
01346 
01347     if (++_autosave_ctr >= _settings_client.gui.max_num_autosaves) _autosave_ctr = 0;
01348   }
01349 
01350   DEBUG(sl, 2, "Autosaving to '%s'", buf);
01351   if (SaveOrLoad(buf, SL_SAVE, AUTOSAVE_DIR) != SL_OK) {
01352     ShowErrorMessage(STR_ERROR_AUTOSAVE_FAILED, INVALID_STRING_ID, WL_ERROR);
01353   }
01354 }
01355 
01356 void GameLoop()
01357 {
01358   if (_game_mode == GM_BOOTSTRAP) {
01359 #ifdef ENABLE_NETWORK
01360     /* Check for UDP stuff */
01361     if (_network_available) NetworkBackgroundLoop();
01362 #endif
01363     InputLoop();
01364     return;
01365   }
01366 
01367   ProcessAsyncSaveFinish();
01368 
01369   /* autosave game? */
01370   if (_do_autosave) {
01371     _do_autosave = false;
01372     DoAutosave();
01373     SetWindowDirty(WC_STATUS_BAR, 0);
01374   }
01375 
01376   /* switch game mode? */
01377   if (_switch_mode != SM_NONE && !HasModalProgress()) {
01378     SwitchToMode(_switch_mode);
01379     _switch_mode = SM_NONE;
01380   }
01381 
01382   IncreaseSpriteLRU();
01383   InteractiveRandom();
01384 
01385   extern int _caret_timer;
01386   _caret_timer += 3;
01387   CursorTick();
01388 
01389 #ifdef ENABLE_NETWORK
01390   /* Check for UDP stuff */
01391   if (_network_available) NetworkBackgroundLoop();
01392 
01393   if (_networking && !HasModalProgress()) {
01394     /* Multiplayer */
01395     NetworkGameLoop();
01396   } else {
01397     if (_network_reconnect > 0 && --_network_reconnect == 0) {
01398       /* This means that we want to reconnect to the last host
01399        * We do this here, because it means that the network is really closed */
01400       NetworkClientConnectGame(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port), COMPANY_SPECTATOR);
01401     }
01402     /* Singleplayer */
01403     StateGameLoop();
01404   }
01405 
01406   /* Check chat messages roughly once a second. */
01407   static uint check_message = 0;
01408   if (++check_message > 1000 / MILLISECONDS_PER_TICK) {
01409     check_message = 0;
01410     NetworkChatMessageLoop();
01411   }
01412 #else
01413   StateGameLoop();
01414 #endif /* ENABLE_NETWORK */
01415 
01416   if (!_pause_mode && HasBit(_display_opt, DO_FULL_ANIMATION)) DoPaletteAnimations();
01417 
01418   if (!_pause_mode || _game_mode == GM_EDITOR || _settings_game.construction.command_pause_level > CMDPL_NO_CONSTRUCTION) MoveAllTextEffects();
01419 
01420   InputLoop();
01421 
01422   _sound_driver->MainLoop();
01423   MusicLoop();
01424 }