openttd.cpp

Go to the documentation of this file.
00001 /* $Id: openttd.cpp 25583 2013-07-10 19:41:31Z rubidium $ */
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 #include "gfx_layout.h"
00065 
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 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     if (_settings_client.gui.pause_on_newgame) DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
00894     IConsoleCmdExec("exec scripts/game_start.scr 0");
00895     return;
00896   }
00897 
00898   /* Create a single company */
00899   DoStartupNewCompany(false);
00900 
00901   Company *c = Company::Get(COMPANY_FIRST);
00902   c->settings = _settings_client.company;
00903 
00904   IConsoleCmdExec("exec scripts/game_start.scr 0");
00905 
00906   SetLocalCompany(COMPANY_FIRST);
00907 
00908   InitializeRailGUI();
00909 
00910 #ifdef ENABLE_NETWORK
00911   /* We are the server, we start a new company (not dedicated),
00912    * so set the default password *if* needed. */
00913   if (_network_server && !StrEmpty(_settings_client.network.default_company_pass)) {
00914     NetworkChangeCompanyPassword(_local_company, _settings_client.network.default_company_pass);
00915   }
00916 #endif /* ENABLE_NETWORK */
00917 
00918   if (_settings_client.gui.pause_on_newgame) DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
00919 
00920   CheckEngines();
00921   MarkWholeScreenDirty();
00922 }
00923 
00924 static void MakeNewGame(bool from_heightmap, bool reset_settings)
00925 {
00926   _game_mode = GM_NORMAL;
00927 
00928   ResetGRFConfig(true);
00929 
00930   GenerateWorldSetCallback(&MakeNewGameDone);
00931   GenerateWorld(from_heightmap ? GWM_HEIGHTMAP : GWM_NEWGAME, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y, reset_settings);
00932 }
00933 
00934 static void MakeNewEditorWorldDone()
00935 {
00936   SetLocalCompany(OWNER_NONE);
00937 }
00938 
00939 static void MakeNewEditorWorld()
00940 {
00941   _game_mode = GM_EDITOR;
00942 
00943   ResetGRFConfig(true);
00944 
00945   GenerateWorldSetCallback(&MakeNewEditorWorldDone);
00946   GenerateWorld(GWM_EMPTY, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
00947 }
00948 
00959 bool SafeLoad(const char *filename, int mode, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = NULL)
00960 {
00961   assert(mode == SL_LOAD || (lf == NULL && mode == SL_OLD_LOAD));
00962   GameMode ogm = _game_mode;
00963 
00964   _game_mode = newgm;
00965 
00966   switch (lf == NULL ? SaveOrLoad(filename, mode, subdir) : LoadWithFilter(lf)) {
00967     case SL_OK: return true;
00968 
00969     case SL_REINIT:
00970 #ifdef ENABLE_NETWORK
00971       if (_network_dedicated) {
00972         /*
00973          * We need to reinit a network map...
00974          * We can't simply load the intro game here as that game has many
00975          * special cases which make clients desync immediately. So we fall
00976          * back to just generating a new game with the current settings.
00977          */
00978         DEBUG(net, 0, "Loading game failed, so a new (random) game will be started!");
00979         MakeNewGame(false, true);
00980         return false;
00981       }
00982       if (_network_server) {
00983         /* We can't load the intro game as server, so disconnect first. */
00984         NetworkDisconnect();
00985       }
00986 #endif /* ENABLE_NETWORK */
00987 
00988       switch (ogm) {
00989         default:
00990         case GM_MENU:   LoadIntroGame();      break;
00991         case GM_EDITOR: MakeNewEditorWorld(); break;
00992       }
00993       return false;
00994 
00995     default:
00996       _game_mode = ogm;
00997       return false;
00998   }
00999 }
01000 
01001 void SwitchToMode(SwitchMode new_mode)
01002 {
01003 #ifdef ENABLE_NETWORK
01004   /* If we are saving something, the network stays in his current state */
01005   if (new_mode != SM_SAVE_GAME) {
01006     /* If the network is active, make it not-active */
01007     if (_networking) {
01008       if (_network_server && (new_mode == SM_LOAD_GAME || new_mode == SM_NEWGAME || new_mode == SM_RESTARTGAME)) {
01009         NetworkReboot();
01010       } else {
01011         NetworkDisconnect();
01012       }
01013     }
01014 
01015     /* If we are a server, we restart the server */
01016     if (_is_network_server) {
01017       /* But not if we are going to the menu */
01018       if (new_mode != SM_MENU) {
01019         /* check if we should reload the config */
01020         if (_settings_client.network.reload_cfg) {
01021           LoadFromConfig();
01022           MakeNewgameSettingsLive();
01023           ResetGRFConfig(false);
01024         }
01025         NetworkServerStart();
01026       } else {
01027         /* This client no longer wants to be a network-server */
01028         _is_network_server = false;
01029       }
01030     }
01031   }
01032 #endif /* ENABLE_NETWORK */
01033   /* Make sure all AI controllers are gone at quitting game */
01034   if (new_mode != SM_SAVE_GAME) AI::KillAll();
01035 
01036   switch (new_mode) {
01037     case SM_EDITOR: // Switch to scenario editor
01038       MakeNewEditorWorld();
01039       break;
01040 
01041     case SM_RESTARTGAME: // Restart --> 'Random game' with current settings
01042     case SM_NEWGAME: // New Game --> 'Random game'
01043 #ifdef ENABLE_NETWORK
01044       if (_network_server) {
01045         snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "Random Map");
01046       }
01047 #endif /* ENABLE_NETWORK */
01048       MakeNewGame(false, new_mode == SM_NEWGAME);
01049       break;
01050 
01051     case SM_LOAD_GAME: { // Load game, Play Scenario
01052       ResetGRFConfig(true);
01053       ResetWindowSystem();
01054 
01055       if (!SafeLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_NORMAL, NO_DIRECTORY)) {
01056         SetDParamStr(0, GetSaveLoadErrorString());
01057         ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
01058       } else {
01059         if (_saveload_mode == SLD_LOAD_SCENARIO) {
01060           /* Reset engine pool to simplify changing engine NewGRFs in scenario editor. */
01061           EngineOverrideManager::ResetToCurrentNewGRFConfig();
01062         }
01063         /* Update the local company for a loaded game. It is either always
01064          * company #1 (eg 0) or in the case of a dedicated server a spectator */
01065         SetLocalCompany(_network_dedicated ? COMPANY_SPECTATOR : COMPANY_FIRST);
01066         /* Execute the game-start script */
01067         IConsoleCmdExec("exec scripts/game_start.scr 0");
01068         /* Decrease pause counter (was increased from opening load dialog) */
01069         DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
01070 #ifdef ENABLE_NETWORK
01071         if (_network_server) {
01072           snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Loaded game)", _file_to_saveload.title);
01073         }
01074 #endif /* ENABLE_NETWORK */
01075       }
01076       break;
01077     }
01078 
01079     case SM_START_HEIGHTMAP: // Load a heightmap and start a new game from it
01080 #ifdef ENABLE_NETWORK
01081       if (_network_server) {
01082         snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Heightmap)", _file_to_saveload.title);
01083       }
01084 #endif /* ENABLE_NETWORK */
01085       MakeNewGame(true, true);
01086       break;
01087 
01088     case SM_LOAD_HEIGHTMAP: // Load heightmap from scenario editor
01089       SetLocalCompany(OWNER_NONE);
01090 
01091       GenerateWorld(GWM_HEIGHTMAP, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
01092       MarkWholeScreenDirty();
01093       break;
01094 
01095     case SM_LOAD_SCENARIO: { // Load scenario from scenario editor
01096       if (SafeLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_EDITOR, NO_DIRECTORY)) {
01097         SetLocalCompany(OWNER_NONE);
01098         _settings_newgame.game_creation.starting_year = _cur_year;
01099         /* Cancel the saveload pausing */
01100         DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
01101       } else {
01102         SetDParamStr(0, GetSaveLoadErrorString());
01103         ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
01104       }
01105       break;
01106     }
01107 
01108     case SM_MENU: // Switch to game intro menu
01109       LoadIntroGame();
01110       if (BaseSounds::ini_set == NULL && BaseSounds::GetUsedSet()->fallback) {
01111         ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET, INVALID_STRING_ID, WL_CRITICAL);
01112         BaseSounds::ini_set = strdup(BaseSounds::GetUsedSet()->name);
01113       }
01114       break;
01115 
01116     case SM_SAVE_GAME: // Save game.
01117       /* Make network saved games on pause compatible to singleplayer */
01118       if (SaveOrLoad(_file_to_saveload.name, SL_SAVE, NO_DIRECTORY) != SL_OK) {
01119         SetDParamStr(0, GetSaveLoadErrorString());
01120         ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
01121       } else {
01122         DeleteWindowById(WC_SAVELOAD, 0);
01123       }
01124       break;
01125 
01126     case SM_SAVE_HEIGHTMAP: // Save heightmap.
01127       MakeHeightmapScreenshot(_file_to_saveload.name);
01128       DeleteWindowById(WC_SAVELOAD, 0);
01129       break;
01130 
01131     case SM_GENRANDLAND: // Generate random land within scenario editor
01132       SetLocalCompany(OWNER_NONE);
01133       GenerateWorld(GWM_RANDOM, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
01134       /* XXX: set date */
01135       MarkWholeScreenDirty();
01136       break;
01137 
01138     default: NOT_REACHED();
01139   }
01140 }
01141 
01142 
01149 static void CheckCaches()
01150 {
01151   /* Return here so it is easy to add checks that are run
01152    * always to aid testing of caches. */
01153   if (_debug_desync_level <= 1) return;
01154 
01155   /* Check the town caches. */
01156   SmallVector<TownCache, 4> old_town_caches;
01157   Town *t;
01158   FOR_ALL_TOWNS(t) {
01159     MemCpyT(old_town_caches.Append(), &t->cache);
01160   }
01161 
01162   extern void RebuildTownCaches();
01163   RebuildTownCaches();
01164   RebuildSubsidisedSourceAndDestinationCache();
01165 
01166   uint i = 0;
01167   FOR_ALL_TOWNS(t) {
01168     if (MemCmpT(old_town_caches.Get(i), &t->cache) != 0) {
01169       DEBUG(desync, 2, "town cache mismatch: town %i", (int)t->index);
01170     }
01171     i++;
01172   }
01173 
01174   /* Check company infrastructure cache. */
01175   SmallVector<CompanyInfrastructure, 4> old_infrastructure;
01176   Company *c;
01177   FOR_ALL_COMPANIES(c) MemCpyT(old_infrastructure.Append(), &c->infrastructure);
01178 
01179   extern void AfterLoadCompanyStats();
01180   AfterLoadCompanyStats();
01181 
01182   i = 0;
01183   FOR_ALL_COMPANIES(c) {
01184     if (MemCmpT(old_infrastructure.Get(i), &c->infrastructure) != 0) {
01185       DEBUG(desync, 2, "infrastructure cache mismatch: company %i", (int)c->index);
01186     }
01187     i++;
01188   }
01189 
01190   /* Strict checking of the road stop cache entries */
01191   const RoadStop *rs;
01192   FOR_ALL_ROADSTOPS(rs) {
01193     if (IsStandardRoadStopTile(rs->xy)) continue;
01194 
01195     assert(rs->GetEntry(DIAGDIR_NE) != rs->GetEntry(DIAGDIR_NW));
01196     rs->GetEntry(DIAGDIR_NE)->CheckIntegrity(rs);
01197     rs->GetEntry(DIAGDIR_NW)->CheckIntegrity(rs);
01198   }
01199 
01200   Vehicle *v;
01201   FOR_ALL_VEHICLES(v) {
01202     extern void FillNewGRFVehicleCache(const Vehicle *v);
01203     if (v != v->First() || v->vehstatus & VS_CRASHED || !v->IsPrimaryVehicle()) continue;
01204 
01205     uint length = 0;
01206     for (const Vehicle *u = v; u != NULL; u = u->Next()) length++;
01207 
01208     NewGRFCache        *grf_cache = CallocT<NewGRFCache>(length);
01209     VehicleCache       *veh_cache = CallocT<VehicleCache>(length);
01210     GroundVehicleCache *gro_cache = CallocT<GroundVehicleCache>(length);
01211     TrainCache         *tra_cache = CallocT<TrainCache>(length);
01212 
01213     length = 0;
01214     for (const Vehicle *u = v; u != NULL; u = u->Next()) {
01215       FillNewGRFVehicleCache(u);
01216       grf_cache[length] = u->grf_cache;
01217       veh_cache[length] = u->vcache;
01218       switch (u->type) {
01219         case VEH_TRAIN:
01220           gro_cache[length] = Train::From(u)->gcache;
01221           tra_cache[length] = Train::From(u)->tcache;
01222           break;
01223         case VEH_ROAD:
01224           gro_cache[length] = RoadVehicle::From(u)->gcache;
01225           break;
01226         default:
01227           break;
01228       }
01229       length++;
01230     }
01231 
01232     switch (v->type) {
01233       case VEH_TRAIN:    Train::From(v)->ConsistChanged(true);     break;
01234       case VEH_ROAD:     RoadVehUpdateCache(RoadVehicle::From(v)); break;
01235       case VEH_AIRCRAFT: UpdateAircraftCache(Aircraft::From(v));   break;
01236       case VEH_SHIP:     Ship::From(v)->UpdateCache();             break;
01237       default: break;
01238     }
01239 
01240     length = 0;
01241     for (const Vehicle *u = v; u != NULL; u = u->Next()) {
01242       FillNewGRFVehicleCache(u);
01243       if (memcmp(&grf_cache[length], &u->grf_cache, sizeof(NewGRFCache)) != 0) {
01244         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);
01245       }
01246       if (memcmp(&veh_cache[length], &u->vcache, sizeof(VehicleCache)) != 0) {
01247         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);
01248       }
01249       switch (u->type) {
01250         case VEH_TRAIN:
01251           if (memcmp(&gro_cache[length], &Train::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
01252             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);
01253           }
01254           if (memcmp(&tra_cache[length], &Train::From(u)->tcache, sizeof(TrainCache)) != 0) {
01255             DEBUG(desync, 2, "train cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v->index, (int)v->owner, v->unitnumber, length);
01256           }
01257           break;
01258         case VEH_ROAD:
01259           if (memcmp(&gro_cache[length], &RoadVehicle::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
01260             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);
01261           }
01262           break;
01263         default:
01264           break;
01265       }
01266       length++;
01267     }
01268 
01269     free(grf_cache);
01270     free(veh_cache);
01271     free(gro_cache);
01272     free(tra_cache);
01273   }
01274 
01275   /* Check whether the caches are still valid */
01276   FOR_ALL_VEHICLES(v) {
01277     byte buff[sizeof(VehicleCargoList)];
01278     memcpy(buff, &v->cargo, sizeof(VehicleCargoList));
01279     v->cargo.InvalidateCache();
01280     assert(memcmp(&v->cargo, buff, sizeof(VehicleCargoList)) == 0);
01281   }
01282 
01283   Station *st;
01284   FOR_ALL_STATIONS(st) {
01285     for (CargoID c = 0; c < NUM_CARGO; c++) {
01286       byte buff[sizeof(StationCargoList)];
01287       memcpy(buff, &st->goods[c].cargo, sizeof(StationCargoList));
01288       st->goods[c].cargo.InvalidateCache();
01289       assert(memcmp(&st->goods[c].cargo, buff, sizeof(StationCargoList)) == 0);
01290     }
01291   }
01292 }
01293 
01299 void StateGameLoop()
01300 {
01301   /* don't execute the state loop during pause */
01302   if (_pause_mode != PM_UNPAUSED) {
01303     UpdateLandscapingLimits();
01304     Game::GameLoop();
01305     CallWindowTickEvent();
01306     return;
01307   }
01308   if (HasModalProgress()) return;
01309 
01310   ClearStorageChanges(false);
01311 
01312   Layouter::ReduceLineCache();
01313 
01314   if (_game_mode == GM_EDITOR) {
01315     RunTileLoop();
01316     CallVehicleTicks();
01317     CallLandscapeTick();
01318     ClearStorageChanges(true);
01319     UpdateLandscapingLimits();
01320 
01321     CallWindowTickEvent();
01322     NewsLoop();
01323   } else {
01324     if (_debug_desync_level > 2 && _date_fract == 0 && (_date & 0x1F) == 0) {
01325       /* Save the desync savegame if needed. */
01326       char name[MAX_PATH];
01327       snprintf(name, lengthof(name), "dmp_cmds_%08x_%08x.sav", _settings_game.game_creation.generation_seed, _date);
01328       SaveOrLoad(name, SL_SAVE, AUTOSAVE_DIR, false);
01329     }
01330 
01331     CheckCaches();
01332 
01333     /* All these actions has to be done from OWNER_NONE
01334      *  for multiplayer compatibility */
01335     Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
01336 
01337     AnimateAnimatedTiles();
01338     IncreaseDate();
01339     RunTileLoop();
01340     CallVehicleTicks();
01341     CallLandscapeTick();
01342     ClearStorageChanges(true);
01343 
01344     AI::GameLoop();
01345     Game::GameLoop();
01346     UpdateLandscapingLimits();
01347 
01348     CallWindowTickEvent();
01349     NewsLoop();
01350     cur_company.Restore();
01351   }
01352 
01353   assert(IsLocalCompany());
01354 }
01355 
01360 static void DoAutosave()
01361 {
01362   char buf[MAX_PATH];
01363 
01364 #if defined(PSP)
01365   /* Autosaving in networking is too time expensive for the PSP */
01366   if (_networking) return;
01367 #endif /* PSP */
01368 
01369   if (_settings_client.gui.keep_all_autosave) {
01370     GenerateDefaultSaveName(buf, lastof(buf));
01371     strecat(buf, ".sav", lastof(buf));
01372   } else {
01373     static int _autosave_ctr = 0;
01374 
01375     /* generate a savegame name and number according to _settings_client.gui.max_num_autosaves */
01376     snprintf(buf, sizeof(buf), "autosave%d.sav", _autosave_ctr);
01377 
01378     if (++_autosave_ctr >= _settings_client.gui.max_num_autosaves) _autosave_ctr = 0;
01379   }
01380 
01381   DEBUG(sl, 2, "Autosaving to '%s'", buf);
01382   if (SaveOrLoad(buf, SL_SAVE, AUTOSAVE_DIR) != SL_OK) {
01383     ShowErrorMessage(STR_ERROR_AUTOSAVE_FAILED, INVALID_STRING_ID, WL_ERROR);
01384   }
01385 }
01386 
01387 void GameLoop()
01388 {
01389   if (_game_mode == GM_BOOTSTRAP) {
01390 #ifdef ENABLE_NETWORK
01391     /* Check for UDP stuff */
01392     if (_network_available) NetworkBackgroundLoop();
01393 #endif
01394     InputLoop();
01395     return;
01396   }
01397 
01398   ProcessAsyncSaveFinish();
01399 
01400   /* autosave game? */
01401   if (_do_autosave) {
01402     _do_autosave = false;
01403     DoAutosave();
01404     SetWindowDirty(WC_STATUS_BAR, 0);
01405   }
01406 
01407   /* switch game mode? */
01408   if (_switch_mode != SM_NONE && !HasModalProgress()) {
01409     SwitchToMode(_switch_mode);
01410     _switch_mode = SM_NONE;
01411   }
01412 
01413   IncreaseSpriteLRU();
01414   InteractiveRandom();
01415 
01416   extern int _caret_timer;
01417   _caret_timer += 3;
01418   CursorTick();
01419 
01420 #ifdef ENABLE_NETWORK
01421   /* Check for UDP stuff */
01422   if (_network_available) NetworkBackgroundLoop();
01423 
01424   if (_networking && !HasModalProgress()) {
01425     /* Multiplayer */
01426     NetworkGameLoop();
01427   } else {
01428     if (_network_reconnect > 0 && --_network_reconnect == 0) {
01429       /* This means that we want to reconnect to the last host
01430        * We do this here, because it means that the network is really closed */
01431       NetworkClientConnectGame(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port), COMPANY_SPECTATOR);
01432     }
01433     /* Singleplayer */
01434     StateGameLoop();
01435   }
01436 
01437   /* Check chat messages roughly once a second. */
01438   static uint check_message = 0;
01439   if (++check_message > 1000 / MILLISECONDS_PER_TICK) {
01440     check_message = 0;
01441     NetworkChatMessageLoop();
01442   }
01443 #else
01444   StateGameLoop();
01445 #endif /* ENABLE_NETWORK */
01446 
01447   if (!_pause_mode && HasBit(_display_opt, DO_FULL_ANIMATION)) DoPaletteAnimations();
01448 
01449   if (!_pause_mode || _game_mode == GM_EDITOR || _settings_game.construction.command_pause_level > CMDPL_NO_CONSTRUCTION) MoveAllTextEffects();
01450 
01451   InputLoop();
01452 
01453   _sound_driver->MainLoop();
01454   MusicLoop();
01455 }