# openttd.cpp

Go to the documentation of this file.

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