openttd.cpp

Go to the documentation of this file.
00001 /* $Id: openttd.cpp 16804 2009-07-13 10:16:50Z rubidium $ */
00002 
00005 #include "stdafx.h"
00006 
00007 #define VARDEF
00008 #include "variables.h"
00009 #undef VARDEF
00010 
00011 #include "openttd.h"
00012 
00013 #include "blitter/factory.hpp"
00014 #include "sound/sound_driver.hpp"
00015 #include "music/music_driver.hpp"
00016 #include "video/video_driver.hpp"
00017 
00018 #include "fontcache.h"
00019 #include "gfxinit.h"
00020 #include "gui.h"
00021 #include "sound_func.h"
00022 #include "window_func.h"
00023 
00024 #include "saveload/saveload.h"
00025 #include "landscape.h"
00026 #include "company_func.h"
00027 #include "command_func.h"
00028 #include "news_func.h"
00029 #include "fileio_func.h"
00030 #include "fios.h"
00031 #include "aircraft.h"
00032 #include "console_func.h"
00033 #include "screenshot.h"
00034 #include "network/network.h"
00035 #include "network/network_func.h"
00036 #include "signs_base.h"
00037 #include "ai/ai.hpp"
00038 #include "ai/ai_config.hpp"
00039 #include "settings_func.h"
00040 #include "genworld.h"
00041 #include "group.h"
00042 #include "strings_func.h"
00043 #include "date_func.h"
00044 #include "vehicle_func.h"
00045 #include "gamelog.h"
00046 #include "cheat_type.h"
00047 #include "animated_tile_func.h"
00048 #include "functions.h"
00049 #include "elrail_func.h"
00050 #include "rev.h"
00051 #include "highscore.h"
00052 #include "thread.h"
00053 
00054 #include "newgrf_commons.h"
00055 
00056 #include "town.h"
00057 #include "industry.h"
00058 
00059 #include <stdarg.h>
00060 
00061 #include "table/strings.h"
00062 
00063 StringID _switch_mode_errorstr;
00064 
00065 void CallLandscapeTick();
00066 void IncreaseDate();
00067 void DoPaletteAnimations();
00068 void MusicLoop();
00069 void ResetMusic();
00070 void ProcessAsyncSaveFinish();
00071 void CallWindowTickEvent();
00072 
00073 extern void SetDifficultyLevel(int mode, DifficultySettings *gm_opt);
00074 extern Company *DoStartupNewCompany(bool is_ai);
00075 extern void ShowOSErrorBox(const char *buf, bool system);
00076 extern void InitializeRailGUI();
00077 
00083 void CDECL usererror(const char *s, ...)
00084 {
00085   va_list va;
00086   char buf[512];
00087 
00088   va_start(va, s);
00089   vsnprintf(buf, lengthof(buf), s, va);
00090   va_end(va);
00091 
00092   ShowOSErrorBox(buf, false);
00093   if (_video_driver != NULL) _video_driver->Stop();
00094 
00095   exit(1);
00096 }
00097 
00103 void CDECL error(const char *s, ...)
00104 {
00105   va_list va;
00106   char buf[512];
00107 
00108   va_start(va, s);
00109   vsnprintf(buf, lengthof(buf), s, va);
00110   va_end(va);
00111 
00112   ShowOSErrorBox(buf, true);
00113   if (_video_driver != NULL) _video_driver->Stop();
00114 
00115   assert(0);
00116   exit(1);
00117 }
00118 
00123 void CDECL ShowInfoF(const char *str, ...)
00124 {
00125   va_list va;
00126   char buf[1024];
00127   va_start(va, str);
00128   vsnprintf(buf, lengthof(buf), str, va);
00129   va_end(va);
00130   ShowInfo(buf);
00131 }
00132 
00136 static void ShowHelp()
00137 {
00138   char buf[8192];
00139   char *p = buf;
00140 
00141   p += seprintf(p, lastof(buf), "OpenTTD %s\n", _openttd_revision);
00142   p = strecpy(p,
00143     "\n"
00144     "\n"
00145     "Command line options:\n"
00146     "  -v drv              = Set video driver (see below)\n"
00147     "  -s drv              = Set sound driver (see below) (param bufsize,hz)\n"
00148     "  -m drv              = Set music driver (see below)\n"
00149     "  -b drv              = Set the blitter to use (see below)\n"
00150     "  -a ai               = Force use of specific AI (see below)\n"
00151     "  -r res              = Set resolution (for instance 800x600)\n"
00152     "  -h                  = Display this help text\n"
00153     "  -t year             = Set starting year\n"
00154     "  -d [[fac=]lvl[,...]]= Debug mode\n"
00155     "  -e                  = Start Editor\n"
00156     "  -g [savegame]       = Start new/save game immediately\n"
00157     "  -G seed             = Set random seed\n"
00158 #if defined(ENABLE_NETWORK)
00159     "  -n [ip:port#company]= Start networkgame\n"
00160     "  -D [ip][:port]      = Start dedicated server\n"
00161     "  -l ip[:port]        = Redirect DEBUG()\n"
00162 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
00163     "  -f                  = Fork into the background (dedicated only)\n"
00164 #endif
00165 #endif /* ENABLE_NETWORK */
00166     "  -i palette          = Force to use the DOS (0) or Windows (1) palette\n"
00167     "                          (defines default setting when adding newgrfs)\n"
00168     "                        Default value (2) lets OpenTTD use the palette\n"
00169     "                          specified in graphics set file (see below)\n"
00170     "  -I graphics_set     = Force the graphics set (see below)\n"
00171     "  -c config_file      = Use 'config_file' instead of 'openttd.cfg'\n"
00172     "  -x                  = Do not automatically save to config file on exit\n"
00173     "\n",
00174     lastof(buf)
00175   );
00176 
00177   /* List the graphics packs */
00178   p = GetGraphicsSetsList(p, lastof(buf));
00179 
00180   /* List the drivers */
00181   p = VideoDriverFactoryBase::GetDriversInfo(p, lastof(buf));
00182 
00183   /* List the blitters */
00184   p = BlitterFactoryBase::GetBlittersInfo(p, lastof(buf));
00185 
00186   /* We need to initialize the AI, so it finds the AIs */
00187   AI::Initialize();
00188   p = AI::GetConsoleList(p, lastof(buf));
00189   AI::Uninitialize(true);
00190 
00191   /* ShowInfo put output to stderr, but version information should go
00192    * to stdout; this is the only exception */
00193 #if !defined(WIN32) && !defined(WIN64)
00194   printf("%s\n", buf);
00195 #else
00196   ShowInfo(buf);
00197 #endif
00198 }
00199 
00200 
00201 struct MyGetOptData {
00202   char *opt;
00203   int numleft;
00204   char **argv;
00205   const char *options;
00206   const char *cont;
00207 
00208   MyGetOptData(int argc, char **argv, const char *options)
00209   {
00210     opt = NULL;
00211     numleft = argc;
00212     this->argv = argv;
00213     this->options = options;
00214     cont = NULL;
00215   }
00216 };
00217 
00218 static int MyGetOpt(MyGetOptData *md)
00219 {
00220   const char *s, *r, *t;
00221 
00222   s = md->cont;
00223   if (s != NULL)
00224     goto md_continue_here;
00225 
00226   for (;;) {
00227     if (--md->numleft < 0) return -1;
00228 
00229     s = *md->argv++;
00230     if (*s == '-') {
00231 md_continue_here:;
00232       s++;
00233       if (*s != 0) {
00234         /* Found argument, try to locate it in options. */
00235         if (*s == ':' || (r = strchr(md->options, *s)) == NULL) {
00236           /* ERROR! */
00237           return -2;
00238         }
00239         if (r[1] == ':') {
00240           /* Item wants an argument. Check if the argument follows, or if it comes as a separate arg. */
00241           if (!*(t = s + 1)) {
00242             /* It comes as a separate arg. Check if out of args? */
00243             if (--md->numleft < 0 || *(t = *md->argv) == '-') {
00244               /* Check if item is optional? */
00245               if (r[2] != ':')
00246                 return -2;
00247               md->numleft++;
00248               t = NULL;
00249             } else {
00250               md->argv++;
00251             }
00252           }
00253           md->opt = (char*)t;
00254           md->cont = NULL;
00255           return *s;
00256         }
00257         md->opt = NULL;
00258         md->cont = s;
00259         return *s;
00260       }
00261     } else {
00262       /* This is currently not supported. */
00263       return -2;
00264     }
00265   }
00266 }
00267 
00274 static void ParseResolution(Dimension *res, const char *s)
00275 {
00276   const char *t = strchr(s, 'x');
00277   if (t == NULL) {
00278     ShowInfoF("Invalid resolution '%s'", s);
00279     return;
00280   }
00281 
00282   res->width  = max(strtoul(s, NULL, 0), 64UL);
00283   res->height = max(strtoul(t + 1, NULL, 0), 64UL);
00284 }
00285 
00286 static void InitializeDynamicVariables()
00287 {
00288   /* Dynamic stuff needs to be initialized somewhere... */
00289   _engine_mngr.ResetToDefaultMapping();
00290   _house_mngr.ResetMapping();
00291   _industry_mngr.ResetMapping();
00292   _industile_mngr.ResetMapping();
00293   _Company_pool.AddBlockToPool();
00294 }
00295 
00296 
00300 static void ShutdownGame()
00301 {
00302   IConsoleFree();
00303 
00304   if (_network_available) NetworkShutDown(); // Shut down the network and close any open connections
00305 
00306   DriverFactoryBase::ShutdownDrivers();
00307 
00308   UnInitWindowSystem();
00309 
00310   /* stop the AI */
00311   AI::Uninitialize(false);
00312 
00313   /* Uninitialize airport state machines */
00314   UnInitializeAirports();
00315 
00316   /* Uninitialize variables that are allocated dynamically */
00317   GamelogReset();
00318   _Town_pool.CleanPool();
00319   _Industry_pool.CleanPool();
00320   _Station_pool.CleanPool();
00321   _Vehicle_pool.CleanPool();
00322   _Sign_pool.CleanPool();
00323   _Order_pool.CleanPool();
00324   _Group_pool.CleanPool();
00325   _CargoPacket_pool.CleanPool();
00326   _Engine_pool.CleanPool();
00327   _Company_pool.CleanPool();
00328 
00329   free(_config_file);
00330 
00331   /* Close all and any open filehandles */
00332   FioCloseAll();
00333 }
00334 
00335 static void LoadIntroGame()
00336 {
00337   _game_mode = GM_MENU;
00338 
00339   ResetGRFConfig(false);
00340 
00341   /* Setup main window */
00342   ResetWindowSystem();
00343   SetupColoursAndInitialWindow();
00344 
00345   /* Load the default opening screen savegame */
00346   if (SaveOrLoad("opntitle.dat", SL_LOAD, DATA_DIR) != SL_OK) {
00347     GenerateWorld(GW_EMPTY, 64, 64); // if failed loading, make empty world.
00348     WaitTillGeneratedWorld();
00349     SetLocalCompany(COMPANY_SPECTATOR);
00350   } else {
00351     SetLocalCompany(COMPANY_FIRST);
00352   }
00353 
00354   _pause_game = 0;
00355   _cursor.fix_at = false;
00356 
00357   CheckForMissingGlyphsInLoadedLanguagePack();
00358 
00359   /* Play main theme */
00360   if (_music_driver->IsSongPlaying()) ResetMusic();
00361 }
00362 
00363 void MakeNewgameSettingsLive()
00364 {
00365   for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
00366     if (_settings_game.ai_config[c] != NULL) {
00367       delete _settings_game.ai_config[c];
00368     }
00369   }
00370 
00371   _settings_game = _settings_newgame;
00372 
00373   for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
00374     _settings_game.ai_config[c] = NULL;
00375     if (_settings_newgame.ai_config[c] != NULL) {
00376       _settings_game.ai_config[c] = new AIConfig(_settings_newgame.ai_config[c]);
00377     }
00378   }
00379 }
00380 
00381 byte _savegame_sort_order;
00382 #if defined(UNIX) && !defined(__MORPHOS__)
00383 extern void DedicatedFork();
00384 #endif
00385 
00386 int ttd_main(int argc, char *argv[])
00387 {
00388   int i;
00389   const char *optformat;
00390   char *musicdriver = NULL;
00391   char *sounddriver = NULL;
00392   char *videodriver = NULL;
00393   char *blitter = NULL;
00394   char *graphics_set = NULL;
00395   Dimension resolution = {0, 0};
00396   Year startyear = INVALID_YEAR;
00397   uint generation_seed = GENERATE_NEW_SEED;
00398   bool save_config = true;
00399 #if defined(ENABLE_NETWORK)
00400   bool dedicated = false;
00401   bool network   = false;
00402   char *network_conn = NULL;
00403   char *debuglog_conn = NULL;
00404   char *dedicated_host = NULL;
00405   uint16 dedicated_port = 0;
00406 #endif /* ENABLE_NETWORK */
00407 
00408   _game_mode = GM_MENU;
00409   _switch_mode = SM_MENU;
00410   _switch_mode_errorstr = INVALID_STRING_ID;
00411   _dedicated_forks = false;
00412   _config_file = NULL;
00413 
00414   /* The last param of the following function means this:
00415    *   a letter means: it accepts that param (e.g.: -h)
00416    *   a ':' behind it means: it need a param (e.g.: -m<driver>)
00417    *   a '::' behind it means: it can optional have a param (e.g.: -d<debug>) */
00418   optformat = "m:s:v:b:hD::n::ei::I:t:d::r:g::G:c:xl:"
00419 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
00420     "f"
00421 #endif
00422   ;
00423 
00424   MyGetOptData mgo(argc - 1, argv + 1, optformat);
00425 
00426   while ((i = MyGetOpt(&mgo)) != -1) {
00427     switch (i) {
00428     case 'I': free(graphics_set); graphics_set = strdup(mgo.opt); break;
00429     case 'm': free(musicdriver); musicdriver = strdup(mgo.opt); break;
00430     case 's': free(sounddriver); sounddriver = strdup(mgo.opt); break;
00431     case 'v': free(videodriver); videodriver = strdup(mgo.opt); break;
00432     case 'b': free(blitter); blitter = strdup(mgo.opt); break;
00433 #if defined(ENABLE_NETWORK)
00434     case 'D':
00435       free(musicdriver);
00436       free(sounddriver);
00437       free(videodriver);
00438       free(blitter);
00439       musicdriver = strdup("null");
00440       sounddriver = strdup("null");
00441       videodriver = strdup("dedicated");
00442       blitter = strdup("null");
00443       dedicated = true;
00444       SetDebugString("net=6");
00445       if (mgo.opt != NULL) {
00446         /* Use the existing method for parsing (openttd -n).
00447          * However, we do ignore the #company part. */
00448         const char *temp = NULL;
00449         const char *port = NULL;
00450         ParseConnectionString(&temp, &port, mgo.opt);
00451         if (!StrEmpty(mgo.opt)) dedicated_host = mgo.opt;
00452         if (port != NULL) dedicated_port = atoi(port);
00453       }
00454       break;
00455     case 'f': _dedicated_forks = true; break;
00456     case 'n':
00457       network = true;
00458       network_conn = mgo.opt; // optional IP parameter, NULL if unset
00459       break;
00460     case 'l':
00461       debuglog_conn = mgo.opt;
00462       break;
00463 #endif /* ENABLE_NETWORK */
00464     case 'r': ParseResolution(&resolution, mgo.opt); break;
00465     case 't': startyear = atoi(mgo.opt); break;
00466     case 'd': {
00467 #if defined(WIN32)
00468         CreateConsole();
00469 #endif
00470         if (mgo.opt != NULL) SetDebugString(mgo.opt);
00471       } break;
00472     case 'e': _switch_mode = SM_EDITOR; break;
00473     case 'i':
00474       /* there is an argument, it is not empty, and it is exactly 1 char long */
00475       if (!StrEmpty(mgo.opt) && mgo.opt[1] == '\0') {
00476         _use_palette = (PaletteType)(mgo.opt[0] - '0');
00477         if (_use_palette <= MAX_PAL) break;
00478       }
00479       usererror("Valid value for '-i' is 0, 1 or 2");
00480     case 'g':
00481       if (mgo.opt != NULL) {
00482         strecpy(_file_to_saveload.name, mgo.opt, lastof(_file_to_saveload.name));
00483         _switch_mode = SM_LOAD;
00484         _file_to_saveload.mode = SL_LOAD;
00485 
00486         /* if the file doesn't exist or it is not a valid savegame, let the saveload code show an error */
00487         const char *t = strrchr(_file_to_saveload.name, '.');
00488         if (t != NULL) {
00489           FiosType ft = FiosGetSavegameListCallback(SLD_LOAD_GAME, _file_to_saveload.name, t, NULL, NULL);
00490           if (ft != FIOS_TYPE_INVALID) SetFiosType(ft);
00491         }
00492 
00493         break;
00494       }
00495 
00496       _switch_mode = SM_NEWGAME;
00497       /* Give a random map if no seed has been given */
00498       if (generation_seed == GENERATE_NEW_SEED) {
00499         generation_seed = InteractiveRandom();
00500       }
00501       break;
00502     case 'G': generation_seed = atoi(mgo.opt); break;
00503     case 'c': _config_file = strdup(mgo.opt); break;
00504     case 'x': save_config = false; break;
00505     case -2:
00506     case 'h':
00507       /* The next two functions are needed to list the graphics sets.
00508        * We can't do them earlier because then we can't show it on
00509        * the debug console as that hasn't been configured yet. */
00510       DeterminePaths(argv[0]);
00511       FindGraphicsSets();
00512       ShowHelp();
00513       return 0;
00514     }
00515   }
00516 
00517 #if defined(WINCE) && defined(_DEBUG)
00518   /* Switch on debug lvl 4 for WinCE if Debug release, as you can't give params, and you most likely do want this information */
00519   SetDebugString("4");
00520 #endif
00521 
00522   DeterminePaths(argv[0]);
00523   FindGraphicsSets();
00524 
00525 #if defined(UNIX) && !defined(__MORPHOS__)
00526   /* We must fork here, or we'll end up without some resources we need (like sockets) */
00527   if (_dedicated_forks)
00528     DedicatedFork();
00529 #endif
00530 
00531   AI::Initialize();
00532   LoadFromConfig();
00533   AI::Uninitialize(true);
00534   CheckConfig();
00535   LoadFromHighScore();
00536 
00537   if (resolution.width != 0) { _cur_resolution = resolution; }
00538   if (startyear != INVALID_YEAR) _settings_newgame.game_creation.starting_year = startyear;
00539   if (generation_seed != GENERATE_NEW_SEED) _settings_newgame.game_creation.generation_seed = generation_seed;
00540 
00541   /*
00542    * The width and height must be at least 1 pixel and width times
00543    * height must still fit within a 32 bits integer, this way all
00544    * internal drawing routines work correctly.
00545    */
00546   _cur_resolution.width  = ClampU(_cur_resolution.width,  1, UINT16_MAX);
00547   _cur_resolution.height = ClampU(_cur_resolution.height, 1, UINT16_MAX);
00548 
00549 #if defined(ENABLE_NETWORK)
00550   if (dedicated_host) snprintf(_settings_client.network.server_bind_ip, sizeof(_settings_client.network.server_bind_ip), "%s", dedicated_host);
00551   if (dedicated_port) _settings_client.network.server_port = dedicated_port;
00552   if (_dedicated_forks && !dedicated) _dedicated_forks = false;
00553 #endif /* ENABLE_NETWORK */
00554 
00555   /* enumerate language files */
00556   InitializeLanguagePacks();
00557 
00558   /* initialize screenshot formats */
00559   InitializeScreenshotFormats();
00560 
00561   /* initialize airport state machines */
00562   InitializeAirports();
00563 
00564   /* initialize all variables that are allocated dynamically */
00565   InitializeDynamicVariables();
00566 
00567   /* Sample catalogue */
00568   DEBUG(misc, 1, "Loading sound effects...");
00569   SoundInitialize("sample.cat");
00570 
00571   /* Initialize FreeType */
00572   InitFreeType();
00573 
00574   /* This must be done early, since functions use the InvalidateWindow* calls */
00575   InitWindowSystem();
00576 
00577   if (graphics_set == NULL) graphics_set = _ini_graphics_set;
00578   if (!SetGraphicsSet(graphics_set)) {
00579     StrEmpty(graphics_set) ?
00580       usererror("Failed to find a graphics set. Please acquire a graphics set for OpenTTD.") :
00581       usererror("Failed to select requested graphics set '%s'", graphics_set);
00582   }
00583 
00584   /* Initialize game palette */
00585   GfxInitPalettes();
00586 
00587   DEBUG(misc, 1, "Loading blitter...");
00588   if (blitter == NULL) blitter = _ini_blitter;
00589   if (BlitterFactoryBase::SelectBlitter(blitter) == NULL)
00590     StrEmpty(blitter) ?
00591       usererror("Failed to autoprobe blitter") :
00592       usererror("Failed to select requested blitter '%s'; does it exist?", blitter);
00593 
00594   DEBUG(driver, 1, "Loading drivers...");
00595 
00596   if (sounddriver == NULL) sounddriver = _ini_sounddriver;
00597   _sound_driver = (SoundDriver*)SoundDriverFactoryBase::SelectDriver(sounddriver, Driver::DT_SOUND);
00598   if (_sound_driver == NULL) {
00599     StrEmpty(sounddriver) ?
00600       usererror("Failed to autoprobe sound driver") :
00601       usererror("Failed to select requested sound driver '%s'", sounddriver);
00602   }
00603 
00604   if (musicdriver == NULL) musicdriver = _ini_musicdriver;
00605   _music_driver = (MusicDriver*)MusicDriverFactoryBase::SelectDriver(musicdriver, Driver::DT_MUSIC);
00606   if (_music_driver == NULL) {
00607     StrEmpty(musicdriver) ?
00608       usererror("Failed to autoprobe music driver") :
00609       usererror("Failed to select requested music driver '%s'", musicdriver);
00610   }
00611 
00612   if (videodriver == NULL) videodriver = _ini_videodriver;
00613   _video_driver = (VideoDriver*)VideoDriverFactoryBase::SelectDriver(videodriver, Driver::DT_VIDEO);
00614   if (_video_driver == NULL) {
00615     StrEmpty(videodriver) ?
00616       usererror("Failed to autoprobe video driver") :
00617       usererror("Failed to select requested video driver '%s'", videodriver);
00618   }
00619 
00620   _savegame_sort_order = SORT_BY_DATE | SORT_DESCENDING;
00621   /* Initialize the zoom level of the screen to normal */
00622   _screen.zoom = ZOOM_LVL_NORMAL;
00623 
00624   /* restore saved music volume */
00625   _music_driver->SetVolume(msf.music_vol);
00626 
00627   NetworkStartUp(); // initialize network-core
00628 
00629 #if defined(ENABLE_NETWORK)
00630   if (debuglog_conn != NULL && _network_available) {
00631     const char *not_used = NULL;
00632     const char *port = NULL;
00633     uint16 rport;
00634 
00635     rport = NETWORK_DEFAULT_DEBUGLOG_PORT;
00636 
00637     ParseConnectionString(&not_used, &port, debuglog_conn);
00638     if (port != NULL) rport = atoi(port);
00639 
00640     NetworkStartDebugLog(NetworkAddress(debuglog_conn, rport));
00641   }
00642 #endif /* ENABLE_NETWORK */
00643 
00644   ScanNewGRFFiles();
00645 
00646   ResetGRFConfig(false);
00647 
00648   /* Make sure _settings is filled with _settings_newgame if we switch to a game directly */
00649   if (_switch_mode != SM_NONE) MakeNewgameSettingsLive();
00650 
00651   /* initialize the ingame console */
00652   IConsoleInit();
00653   _cursor.in_window = true;
00654   InitializeGUI();
00655   IConsoleCmdExec("exec scripts/autoexec.scr 0");
00656 
00657   /* Take our initial lock on whatever we might want to do! */
00658   _genworld_paint_mutex->BeginCritical();
00659   _genworld_mapgen_mutex->BeginCritical();
00660 
00661   GenerateWorld(GW_EMPTY, 64, 64); // Make the viewport initialization happy
00662   WaitTillGeneratedWorld();
00663 
00664   CheckForMissingGlyphsInLoadedLanguagePack();
00665 
00666 #ifdef ENABLE_NETWORK
00667   if (network && _network_available) {
00668     if (network_conn != NULL) {
00669       const char *port = NULL;
00670       const char *company = NULL;
00671       uint16 rport;
00672 
00673       rport = NETWORK_DEFAULT_PORT;
00674       _network_playas = COMPANY_NEW_COMPANY;
00675 
00676       ParseConnectionString(&company, &port, network_conn);
00677 
00678       if (company != NULL) {
00679         _network_playas = (CompanyID)atoi(company);
00680 
00681         if (_network_playas != COMPANY_SPECTATOR) {
00682           _network_playas--;
00683           if (_network_playas >= MAX_COMPANIES) return false;
00684         }
00685       }
00686       if (port != NULL) rport = atoi(port);
00687 
00688       LoadIntroGame();
00689       _switch_mode = SM_NONE;
00690       NetworkClientConnectGame(NetworkAddress(network_conn, rport));
00691     }
00692   }
00693 #endif /* ENABLE_NETWORK */
00694 
00695   _video_driver->MainLoop();
00696 
00697   WaitTillSaved();
00698 
00699   /* only save config if we have to */
00700   if (save_config) {
00701     SaveToConfig();
00702     SaveToHighScore();
00703   }
00704 
00705   /* Reset windowing system, stop drivers, free used memory, ... */
00706   ShutdownGame();
00707 
00708   return 0;
00709 }
00710 
00711 void HandleExitGameRequest()
00712 {
00713   if (_game_mode == GM_MENU) { // do not ask to quit on the main screen
00714     _exit_game = true;
00715   } else if (_settings_client.gui.autosave_on_exit) {
00716     DoExitSave();
00717     _exit_game = true;
00718   } else {
00719     AskExitGame();
00720   }
00721 }
00722 
00723 static void ShowScreenshotResult(bool b)
00724 {
00725   if (b) {
00726     extern char _screenshot_name[];
00727     SetDParamStr(0, _screenshot_name);
00728     ShowErrorMessage(INVALID_STRING_ID, STR_031B_SCREENSHOT_SUCCESSFULLY, 0, 0);
00729   } else {
00730     ShowErrorMessage(INVALID_STRING_ID, STR_031C_SCREENSHOT_FAILED, 0, 0);
00731   }
00732 
00733 }
00734 
00735 static void MakeNewGameDone()
00736 {
00737   SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
00738 
00739   /* In a dedicated server, the server does not play */
00740   if (BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth() == 0) {
00741     SetLocalCompany(COMPANY_SPECTATOR);
00742     IConsoleCmdExec("exec scripts/game_start.scr 0");
00743     return;
00744   }
00745 
00746   /* Create a single company */
00747   DoStartupNewCompany(false);
00748 
00749   Company *c = GetCompany(COMPANY_FIRST);
00750   c->engine_renew = _settings_client.gui.autorenew;
00751   c->engine_renew_months = _settings_client.gui.autorenew_months;
00752   c->engine_renew_money = _settings_client.gui.autorenew_money;
00753 
00754   IConsoleCmdExec("exec scripts/game_start.scr 0");
00755 
00756   SetLocalCompany(COMPANY_FIRST);
00757   _current_company = _local_company;
00758   DoCommandP(0, (_settings_client.gui.autorenew << 15 ) | (_settings_client.gui.autorenew_months << 16) | 4, _settings_client.gui.autorenew_money, CMD_SET_AUTOREPLACE);
00759 
00760   InitializeRailGUI();
00761 
00762 #ifdef ENABLE_NETWORK
00763   /* We are the server, we start a new company (not dedicated),
00764    * so set the default password *if* needed. */
00765   if (_network_server && !StrEmpty(_settings_client.network.default_company_pass)) {
00766     char *password = _settings_client.network.default_company_pass;
00767     NetworkChangeCompanyPassword(1, &password);
00768   }
00769 #endif /* ENABLE_NETWORK */
00770 
00771   MarkWholeScreenDirty();
00772 }
00773 
00774 static void MakeNewGame(bool from_heightmap)
00775 {
00776   _game_mode = GM_NORMAL;
00777 
00778   ResetGRFConfig(true);
00779   _engine_mngr.ResetToDefaultMapping();
00780   _house_mngr.ResetMapping();
00781   _industile_mngr.ResetMapping();
00782   _industry_mngr.ResetMapping();
00783 
00784   GenerateWorldSetCallback(&MakeNewGameDone);
00785   GenerateWorld(from_heightmap ? GW_HEIGHTMAP : GW_NEWGAME, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
00786 }
00787 
00788 static void MakeNewEditorWorldDone()
00789 {
00790   SetLocalCompany(OWNER_NONE);
00791 }
00792 
00793 static void MakeNewEditorWorld()
00794 {
00795   _game_mode = GM_EDITOR;
00796 
00797   ResetGRFConfig(true);
00798 
00799   GenerateWorldSetCallback(&MakeNewEditorWorldDone);
00800   GenerateWorld(GW_EMPTY, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
00801 }
00802 
00803 void StartupCompanies();
00804 void StartupDisasters();
00805 extern void StartupEconomy();
00806 
00812 static void StartScenario()
00813 {
00814   _game_mode = GM_NORMAL;
00815 
00816   /* invalid type */
00817   if (_file_to_saveload.mode == SL_INVALID) {
00818     DEBUG(sl, 0, "Savegame is obsolete or invalid format: '%s'", _file_to_saveload.name);
00819     SetDParamStr(0, GetSaveLoadErrorString());
00820     ShowErrorMessage(INVALID_STRING_ID, STR_JUST_RAW_STRING, 0, 0);
00821     _game_mode = GM_MENU;
00822     return;
00823   }
00824 
00825   /* Reinitialize windows */
00826   ResetWindowSystem();
00827 
00828   SetupColoursAndInitialWindow();
00829 
00830   ResetGRFConfig(true);
00831 
00832   /* Load game */
00833   if (SaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode, SCENARIO_DIR) != SL_OK) {
00834     LoadIntroGame();
00835     SetDParamStr(0, GetSaveLoadErrorString());
00836     ShowErrorMessage(INVALID_STRING_ID, STR_JUST_RAW_STRING, 0, 0);
00837   }
00838 
00839   _settings_game.difficulty = _settings_newgame.difficulty;
00840 
00841   /* Inititalize data */
00842   StartupEconomy();
00843   StartupCompanies();
00844   StartupEngines();
00845   StartupDisasters();
00846 
00847   SetLocalCompany(COMPANY_FIRST);
00848   _current_company = _local_company;
00849   DoCommandP(0, (_settings_client.gui.autorenew << 15 ) | (_settings_client.gui.autorenew_months << 16) | 4, _settings_client.gui.autorenew_money, CMD_SET_AUTOREPLACE);
00850 
00851   MarkWholeScreenDirty();
00852 }
00853 
00862 bool SafeSaveOrLoad(const char *filename, int mode, GameMode newgm, Subdirectory subdir)
00863 {
00864   GameMode ogm = _game_mode;
00865 
00866   _game_mode = newgm;
00867   assert(mode == SL_LOAD || mode == SL_OLD_LOAD);
00868   switch (SaveOrLoad(filename, mode, subdir)) {
00869     case SL_OK: return true;
00870 
00871     case SL_REINIT:
00872       switch (ogm) {
00873         default:
00874         case GM_MENU:   LoadIntroGame();      break;
00875         case GM_EDITOR: MakeNewEditorWorld(); break;
00876       }
00877       return false;
00878 
00879     default:
00880       _game_mode = ogm;
00881       return false;
00882   }
00883 }
00884 
00885 void SwitchToMode(SwitchMode new_mode)
00886 {
00887 #ifdef ENABLE_NETWORK
00888   /* If we are saving something, the network stays in his current state */
00889   if (new_mode != SM_SAVE) {
00890     /* If the network is active, make it not-active */
00891     if (_networking) {
00892       if (_network_server && (new_mode == SM_LOAD || new_mode == SM_NEWGAME)) {
00893         NetworkReboot();
00894       } else {
00895         NetworkDisconnect();
00896       }
00897     }
00898 
00899     /* If we are a server, we restart the server */
00900     if (_is_network_server) {
00901       /* But not if we are going to the menu */
00902       if (new_mode != SM_MENU) {
00903         /* check if we should reload the config */
00904         if (_settings_client.network.reload_cfg) {
00905           LoadFromConfig();
00906           MakeNewgameSettingsLive();
00907           ResetGRFConfig(false);
00908         }
00909         NetworkServerStart();
00910       } else {
00911         /* This client no longer wants to be a network-server */
00912         _is_network_server = false;
00913       }
00914     }
00915   }
00916 #endif /* ENABLE_NETWORK */
00917   /* Make sure all AI controllers are gone at quiting game */
00918   if (new_mode != SM_SAVE) AI::KillAll();
00919 
00920   switch (new_mode) {
00921     case SM_EDITOR: // Switch to scenario editor
00922       MakeNewEditorWorld();
00923       break;
00924 
00925     case SM_NEWGAME: // New Game --> 'Random game'
00926 #ifdef ENABLE_NETWORK
00927       if (_network_server) {
00928         snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "Random Map");
00929       }
00930 #endif /* ENABLE_NETWORK */
00931       MakeNewGame(false);
00932       break;
00933 
00934     case SM_START_SCENARIO: // New Game --> Choose one of the preset scenarios
00935 #ifdef ENABLE_NETWORK
00936       if (_network_server) {
00937         snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Loaded scenario)", _file_to_saveload.title);
00938       }
00939 #endif /* ENABLE_NETWORK */
00940       StartScenario();
00941       break;
00942 
00943     case SM_LOAD: { // Load game, Play Scenario
00944       ResetGRFConfig(true);
00945       ResetWindowSystem();
00946 
00947       if (!SafeSaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_NORMAL, NO_DIRECTORY)) {
00948         LoadIntroGame();
00949         SetDParamStr(0, GetSaveLoadErrorString());
00950         ShowErrorMessage(INVALID_STRING_ID, STR_JUST_RAW_STRING, 0, 0);
00951       } else {
00952         if (_saveload_mode == SLD_LOAD_SCENARIO) {
00953           StartupEngines();
00954         }
00955         /* Update the local company for a loaded game. It is either always
00956          * company #1 (eg 0) or in the case of a dedicated server a spectator */
00957         SetLocalCompany(_network_dedicated ? COMPANY_SPECTATOR : COMPANY_FIRST);
00958         /* Execute the game-start script */
00959         IConsoleCmdExec("exec scripts/game_start.scr 0");
00960         /* Decrease pause counter (was increased from opening load dialog) */
00961         DoCommandP(0, 0, 0, CMD_PAUSE);
00962 #ifdef ENABLE_NETWORK
00963         if (_network_server) {
00964           snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Loaded game)", _file_to_saveload.title);
00965         }
00966 #endif /* ENABLE_NETWORK */
00967       }
00968       break;
00969     }
00970 
00971     case SM_START_HEIGHTMAP: // Load a heightmap and start a new game from it
00972 #ifdef ENABLE_NETWORK
00973       if (_network_server) {
00974         snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Heightmap)", _file_to_saveload.title);
00975       }
00976 #endif /* ENABLE_NETWORK */
00977       MakeNewGame(true);
00978       break;
00979 
00980     case SM_LOAD_HEIGHTMAP: // Load heightmap from scenario editor
00981       SetLocalCompany(OWNER_NONE);
00982 
00983       GenerateWorld(GW_HEIGHTMAP, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
00984       MarkWholeScreenDirty();
00985       break;
00986 
00987     case SM_LOAD_SCENARIO: { // Load scenario from scenario editor
00988       if (SafeSaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_EDITOR, NO_DIRECTORY)) {
00989         SetLocalCompany(OWNER_NONE);
00990         _settings_newgame.game_creation.starting_year = _cur_year;
00991       } else {
00992         SetDParamStr(0, GetSaveLoadErrorString());
00993         ShowErrorMessage(INVALID_STRING_ID, STR_JUST_RAW_STRING, 0, 0);
00994       }
00995       break;
00996     }
00997 
00998     case SM_MENU: // Switch to game intro menu
00999       LoadIntroGame();
01000       break;
01001 
01002     case SM_SAVE: // Save game
01003       /* Make network saved games on pause compatible to singleplayer */
01004       if (_networking && _pause_game == 1) _pause_game = 2;
01005       if (SaveOrLoad(_file_to_saveload.name, SL_SAVE, NO_DIRECTORY) != SL_OK) {
01006         SetDParamStr(0, GetSaveLoadErrorString());
01007         ShowErrorMessage(INVALID_STRING_ID, STR_JUST_RAW_STRING, 0, 0);
01008       } else {
01009         DeleteWindowById(WC_SAVELOAD, 0);
01010       }
01011       if (_networking && _pause_game == 2) _pause_game = 1;
01012       break;
01013 
01014     case SM_GENRANDLAND: // Generate random land within scenario editor
01015       SetLocalCompany(OWNER_NONE);
01016       GenerateWorld(GW_RANDOM, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
01017       /* XXX: set date */
01018       MarkWholeScreenDirty();
01019       break;
01020 
01021     default: NOT_REACHED();
01022   }
01023 
01024   if (_switch_mode_errorstr != INVALID_STRING_ID) {
01025     ShowErrorMessage(INVALID_STRING_ID, _switch_mode_errorstr, 0, 0);
01026   }
01027 }
01028 
01029 
01035 void StateGameLoop()
01036 {
01037   /* dont execute the state loop during pause */
01038   if (_pause_game) {
01039     CallWindowTickEvent();
01040     return;
01041   }
01042   if (IsGeneratingWorld()) return;
01043 
01044   ClearStorageChanges(false);
01045 
01046   if (_game_mode == GM_EDITOR) {
01047     RunTileLoop();
01048     CallVehicleTicks();
01049     CallLandscapeTick();
01050     ClearStorageChanges(true);
01051 
01052     CallWindowTickEvent();
01053     NewsLoop();
01054   } else {
01055     if (_debug_desync_level > 1) {
01056       Vehicle *v;
01057       FOR_ALL_VEHICLES(v) {
01058         if (v != v->First()) continue;
01059 
01060         switch (v->type) {
01061           case VEH_ROAD: {
01062             extern byte GetRoadVehLength(const Vehicle *v);
01063             if (GetRoadVehLength(v) != v->u.road.cached_veh_length) {
01064               DEBUG(desync, 2, "cache mismatch: vehicle %i, company %i, unit number %i\n", v->index, (int)v->owner, v->unitnumber);
01065             }
01066           } break;
01067 
01068           case VEH_TRAIN: {
01069             uint length = 0;
01070             for (Vehicle *u = v; u != NULL; u = u->Next()) length++;
01071 
01072             VehicleRail *wagons = MallocT<VehicleRail>(length);
01073             length = 0;
01074             for (Vehicle *u = v; u != NULL; u = u->Next()) wagons[length++] = u->u.rail;
01075 
01076             TrainConsistChanged(v, true);
01077 
01078             length = 0;
01079             for (Vehicle *u = v; u != NULL; u = u->Next()) {
01080               if (memcmp(&wagons[length], &u->u.rail, sizeof(VehicleRail)) != 0) {
01081                 DEBUG(desync, 2, "cache mismatch: vehicle %i, company %i, unit number %i, wagon %i\n", v->index, (int)v->owner, v->unitnumber, length);
01082               }
01083               length++;
01084             }
01085 
01086             free(wagons);
01087           } break;
01088 
01089           case VEH_AIRCRAFT: {
01090             uint speed = v->u.air.cached_max_speed;
01091             UpdateAircraftCache(v);
01092             if (speed != v->u.air.cached_max_speed) {
01093               DEBUG(desync, 2, "cache mismatch: vehicle %i, company %i, unit number %i\n", v->index, (int)v->owner, v->unitnumber);
01094             }
01095           } break;
01096 
01097           default:
01098             break;
01099         }
01100       }
01101     }
01102 
01103     /* All these actions has to be done from OWNER_NONE
01104      *  for multiplayer compatibility */
01105     CompanyID old_company = _current_company;
01106     _current_company = OWNER_NONE;
01107 
01108     AnimateAnimatedTiles();
01109     IncreaseDate();
01110     RunTileLoop();
01111     CallVehicleTicks();
01112     CallLandscapeTick();
01113     ClearStorageChanges(true);
01114 
01115     AI::GameLoop();
01116 
01117     CallWindowTickEvent();
01118     NewsLoop();
01119     _current_company = old_company;
01120   }
01121 }
01122 
01125 static void DoAutosave()
01126 {
01127   char buf[MAX_PATH];
01128 
01129 #if defined(PSP)
01130   /* Autosaving in networking is too time expensive for the PSP */
01131   if (_networking) return;
01132 #endif /* PSP */
01133 
01134   if (_settings_client.gui.keep_all_autosave) {
01135     GenerateDefaultSaveName(buf, lastof(buf));
01136     strecat(buf, ".sav", lastof(buf));
01137   } else {
01138     /* generate a savegame name and number according to _settings_client.gui.max_num_autosaves */
01139     snprintf(buf, sizeof(buf), "autosave%d.sav", _autosave_ctr);
01140 
01141     if (++_autosave_ctr >= _settings_client.gui.max_num_autosaves) _autosave_ctr = 0;
01142   }
01143 
01144   DEBUG(sl, 2, "Autosaving to '%s'", buf);
01145   if (SaveOrLoad(buf, SL_SAVE, AUTOSAVE_DIR) != SL_OK) {
01146     ShowErrorMessage(INVALID_STRING_ID, STR_AUTOSAVE_FAILED, 0, 0);
01147   }
01148 }
01149 
01150 void GameLoop()
01151 {
01152   ProcessAsyncSaveFinish();
01153 
01154   /* autosave game? */
01155   if (_do_autosave) {
01156     _do_autosave = false;
01157     DoAutosave();
01158     RedrawAutosave();
01159   }
01160 
01161   /* make a screenshot? */
01162   if (IsScreenshotRequested()) ShowScreenshotResult(MakeScreenshot());
01163 
01164   /* switch game mode? */
01165   if (_switch_mode != SM_NONE) {
01166     SwitchToMode(_switch_mode);
01167     _switch_mode = SM_NONE;
01168   }
01169 
01170   IncreaseSpriteLRU();
01171   InteractiveRandom();
01172 
01173   extern int _caret_timer;
01174   _caret_timer += 3;
01175   _palette_animation_counter += 8;
01176   CursorTick();
01177 
01178 #ifdef ENABLE_NETWORK
01179   /* Check for UDP stuff */
01180   if (_network_available) NetworkUDPGameLoop();
01181 
01182   if (_networking && !IsGeneratingWorld()) {
01183     /* Multiplayer */
01184     NetworkGameLoop();
01185   } else {
01186     if (_network_reconnect > 0 && --_network_reconnect == 0) {
01187       /* This means that we want to reconnect to the last host
01188        * We do this here, because it means that the network is really closed */
01189       _network_playas = COMPANY_SPECTATOR;
01190       NetworkClientConnectGame(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port));
01191     }
01192     /* Singleplayer */
01193     StateGameLoop();
01194   }
01195 #else
01196   StateGameLoop();
01197 #endif /* ENABLE_NETWORK */
01198 
01199   if (!_pause_game && HasBit(_display_opt, DO_FULL_ANIMATION)) DoPaletteAnimations();
01200 
01201   if (!_pause_game || _cheats.build_in_pause.value) MoveAllTextEffects();
01202 
01203   InputLoop();
01204 
01205   _sound_driver->MainLoop();
01206   MusicLoop();
01207 }

Generated on Fri Jul 31 22:33:16 2009 for OpenTTD by  doxygen 1.5.6