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