openttd.cpp

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