openttd.cpp

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