# openttd.cpp

Go to the documentation of this file.

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