openttd.cpp

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