00001
00002
00003
00004
00005
00006
00007
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 "functions.h"
00051 #include "elrail_func.h"
00052 #include "rev.h"
00053 #include "highscore.h"
00054 #include "thread/thread.h"
00055 #include "station_base.h"
00056 #include "crashlog.h"
00057 #include "engine_func.h"
00058 #include "core/random_func.hpp"
00059 #include "rail_gui.h"
00060 #include "core/backup_type.hpp"
00061 #include "hotkeys.h"
00062 #include "newgrf.h"
00063
00064
00065 #include "town.h"
00066 #include "industry.h"
00067
00068 #include <stdarg.h>
00069
00070 #include "table/strings.h"
00071
00072 StringID _switch_mode_errorstr;
00073
00074 void CallLandscapeTick();
00075 void IncreaseDate();
00076 void DoPaletteAnimations();
00077 void MusicLoop();
00078 void ResetMusic();
00079 void ProcessAsyncSaveFinish();
00080 void CallWindowTickEvent();
00081
00082 extern void SetDifficultyLevel(int mode, DifficultySettings *gm_opt);
00083 extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
00084 extern void ShowOSErrorBox(const char *buf, bool system);
00085 extern char *_config_file;
00086
00092 void CDECL usererror(const char *s, ...)
00093 {
00094 va_list va;
00095 char buf[512];
00096
00097 va_start(va, s);
00098 vsnprintf(buf, lengthof(buf), s, va);
00099 va_end(va);
00100
00101 ShowOSErrorBox(buf, false);
00102 if (_video_driver != NULL) _video_driver->Stop();
00103
00104 exit(1);
00105 }
00106
00112 void CDECL error(const char *s, ...)
00113 {
00114 va_list va;
00115 char buf[512];
00116
00117 va_start(va, s);
00118 vsnprintf(buf, lengthof(buf), s, va);
00119 va_end(va);
00120
00121 ShowOSErrorBox(buf, true);
00122
00123
00124 CrashLog::SetErrorMessage(buf);
00125 abort();
00126 }
00127
00132 void CDECL ShowInfoF(const char *str, ...)
00133 {
00134 va_list va;
00135 char buf[1024];
00136 va_start(va, str);
00137 vsnprintf(buf, lengthof(buf), str, va);
00138 va_end(va);
00139 ShowInfo(buf);
00140 }
00141
00145 static void ShowHelp()
00146 {
00147 char buf[8192];
00148 char *p = buf;
00149
00150 p += seprintf(p, lastof(buf), "OpenTTD %s\n", _openttd_revision);
00151 p = strecpy(p,
00152 "\n"
00153 "\n"
00154 "Command line options:\n"
00155 " -v drv = Set video driver (see below)\n"
00156 " -s drv = Set sound driver (see below) (param bufsize,hz)\n"
00157 " -m drv = Set music driver (see below)\n"
00158 " -b drv = Set the blitter to use (see below)\n"
00159 " -r res = Set resolution (for instance 800x600)\n"
00160 " -h = Display this help text\n"
00161 " -t year = Set starting year\n"
00162 " -d [[fac=]lvl[,...]]= Debug mode\n"
00163 " -e = Start Editor\n"
00164 " -g [savegame] = Start new/save game immediately\n"
00165 " -G seed = Set random seed\n"
00166 #if defined(ENABLE_NETWORK)
00167 " -n [ip:port#company]= Start networkgame\n"
00168 " -p password = Password to join server\n"
00169 " -P password = Password to join company\n"
00170 " -D [ip][:port] = Start dedicated server\n"
00171 " -l ip[:port] = Redirect DEBUG()\n"
00172 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
00173 " -f = Fork into the background (dedicated only)\n"
00174 #endif
00175 #endif
00176 " -i palette = Force to use the DOS (0) or Windows (1) palette\n"
00177 " (defines default setting when adding newgrfs)\n"
00178 " Default value (2) lets OpenTTD use the palette\n"
00179 " specified in graphics set file (see below)\n"
00180 " -I graphics_set = Force the graphics set (see below)\n"
00181 " -S sounds_set = Force the sounds set (see below)\n"
00182 " -M music_set = Force the music set (see below)\n"
00183 " -c config_file = Use 'config_file' instead of 'openttd.cfg'\n"
00184 " -x = Do not automatically save to config file on exit\n"
00185 "\n",
00186 lastof(buf)
00187 );
00188
00189
00190 p = BaseGraphics::GetSetsList(p, lastof(buf));
00191
00192
00193 p = BaseSounds::GetSetsList(p, lastof(buf));
00194
00195
00196 p = BaseMusic::GetSetsList(p, lastof(buf));
00197
00198
00199 p = VideoDriverFactoryBase::GetDriversInfo(p, lastof(buf));
00200
00201
00202 p = BlitterFactoryBase::GetBlittersInfo(p, lastof(buf));
00203
00204
00205 TarScanner::DoScan();
00206 AI::Initialize();
00207 p = AI::GetConsoleList(p, lastof(buf));
00208 AI::Uninitialize(true);
00209
00210
00211
00212 #if !defined(WIN32) && !defined(WIN64)
00213 printf("%s\n", buf);
00214 #else
00215 ShowInfo(buf);
00216 #endif
00217 }
00218
00219
00220 struct MyGetOptData {
00221 char *opt;
00222 int numleft;
00223 char **argv;
00224 const char *options;
00225 char *cont;
00226
00227 MyGetOptData(int argc, char **argv, const char *options)
00228 {
00229 opt = NULL;
00230 numleft = argc;
00231 this->argv = argv;
00232 this->options = options;
00233 cont = NULL;
00234 }
00235 };
00236
00237 static int MyGetOpt(MyGetOptData *md)
00238 {
00239 char *s = md->cont;
00240 if (s != NULL) {
00241 goto md_continue_here;
00242 }
00243
00244 for (;;) {
00245 if (--md->numleft < 0) return -1;
00246
00247 s = *md->argv++;
00248 if (*s == '-') {
00249 md_continue_here:;
00250 s++;
00251 if (*s != 0) {
00252 const char *r;
00253
00254 if (*s == ':' || (r = strchr(md->options, *s)) == NULL) {
00255
00256 return -2;
00257 }
00258 if (r[1] == ':') {
00259 char *t;
00260
00261 if (!*(t = s + 1)) {
00262
00263 if (--md->numleft < 0 || *(t = *md->argv) == '-') {
00264
00265 if (r[2] != ':') return -2;
00266 md->numleft++;
00267 t = NULL;
00268 } else {
00269 md->argv++;
00270 }
00271 }
00272 md->opt = t;
00273 md->cont = NULL;
00274 return *s;
00275 }
00276 md->opt = NULL;
00277 md->cont = s;
00278 return *s;
00279 }
00280 } else {
00281
00282 return -2;
00283 }
00284 }
00285 }
00286
00293 static void ParseResolution(Dimension *res, const char *s)
00294 {
00295 const char *t = strchr(s, 'x');
00296 if (t == NULL) {
00297 ShowInfoF("Invalid resolution '%s'", s);
00298 return;
00299 }
00300
00301 res->width = max(strtoul(s, NULL, 0), 64UL);
00302 res->height = max(strtoul(t + 1, NULL, 0), 64UL);
00303 }
00304
00305 static void InitializeDynamicVariables()
00306 {
00307
00308 _engine_mngr.ResetToDefaultMapping();
00309 _house_mngr.ResetMapping();
00310 _industry_mngr.ResetMapping();
00311 _industile_mngr.ResetMapping();
00312 _airport_mngr.ResetMapping();
00313 _airporttile_mngr.ResetMapping();
00314 }
00315
00316
00321 static void ShutdownGame()
00322 {
00323 IConsoleFree();
00324
00325 if (_network_available) NetworkShutDown();
00326
00327 DriverFactoryBase::ShutdownDrivers();
00328
00329 UnInitWindowSystem();
00330
00331
00332 AI::Uninitialize(false);
00333
00334
00335 GamelogReset();
00336 _town_pool.CleanPool();
00337 _industry_pool.CleanPool();
00338 _station_pool.CleanPool();
00339 _roadstop_pool.CleanPool();
00340 _vehicle_pool.CleanPool();
00341 _sign_pool.CleanPool();
00342 _order_pool.CleanPool();
00343 _group_pool.CleanPool();
00344 _cargopacket_pool.CleanPool();
00345 _engine_pool.CleanPool();
00346 _company_pool.CleanPool();
00347
00348 #ifdef ENABLE_NETWORK
00349 free(_config_file);
00350 #endif
00351
00352 ResetNewGRFData();
00353
00354
00355 FioCloseAll();
00356 }
00357
00358 static void LoadIntroGame()
00359 {
00360 _game_mode = GM_MENU;
00361
00362 ResetGRFConfig(false);
00363
00364
00365 ResetWindowSystem();
00366 SetupColoursAndInitialWindow();
00367
00368
00369 if (SaveOrLoad("opntitle.dat", SL_LOAD, DATA_DIR) != SL_OK) {
00370 GenerateWorld(GWM_EMPTY, 64, 64);
00371 WaitTillGeneratedWorld();
00372 SetLocalCompany(COMPANY_SPECTATOR);
00373 } else {
00374 SetLocalCompany(COMPANY_FIRST);
00375 }
00376
00377 _pause_mode = PM_UNPAUSED;
00378 _cursor.fix_at = false;
00379
00380 CheckForMissingSprites();
00381 CheckForMissingGlyphsInLoadedLanguagePack();
00382
00383
00384 if (_music_driver->IsSongPlaying()) ResetMusic();
00385 }
00386
00387 void MakeNewgameSettingsLive()
00388 {
00389 #ifdef ENABLE_AI
00390 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
00391 if (_settings_game.ai_config[c] != NULL) {
00392 delete _settings_game.ai_config[c];
00393 }
00394 }
00395 #endif
00396
00397 _settings_game = _settings_newgame;
00398
00399 #ifdef ENABLE_AI
00400 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
00401 _settings_game.ai_config[c] = NULL;
00402 if (_settings_newgame.ai_config[c] != NULL) {
00403 _settings_game.ai_config[c] = new AIConfig(_settings_newgame.ai_config[c]);
00404 }
00405 }
00406 #endif
00407 }
00408
00409 #if defined(UNIX) && !defined(__MORPHOS__)
00410 extern void DedicatedFork();
00411 #endif
00412
00413 int ttd_main(int argc, char *argv[])
00414 {
00415 int i;
00416 const char *optformat;
00417 char *musicdriver = NULL;
00418 char *sounddriver = NULL;
00419 char *videodriver = NULL;
00420 char *blitter = NULL;
00421 char *graphics_set = NULL;
00422 char *sounds_set = NULL;
00423 char *music_set = NULL;
00424 Dimension resolution = {0, 0};
00425 Year startyear = INVALID_YEAR;
00426 uint generation_seed = GENERATE_NEW_SEED;
00427 bool save_config = true;
00428 #if defined(ENABLE_NETWORK)
00429 bool dedicated = false;
00430 bool network = false;
00431 char *network_conn = NULL;
00432 char *debuglog_conn = NULL;
00433 char *dedicated_host = NULL;
00434 uint16 dedicated_port = 0;
00435 char *join_server_password = NULL;
00436 char *join_company_password = NULL;
00437
00438 extern bool _dedicated_forks;
00439 _dedicated_forks = false;
00440 #endif
00441
00442 _game_mode = GM_MENU;
00443 _switch_mode = SM_MENU;
00444 _switch_mode_errorstr = INVALID_STRING_ID;
00445 _config_file = NULL;
00446
00447
00448
00449
00450
00451 optformat = "m:s:v:b:hD::n::ei::I:S:M:t:d::r:g::G:c:xl:p:P:"
00452 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
00453 "f"
00454 #endif
00455 ;
00456
00457 MyGetOptData mgo(argc - 1, argv + 1, optformat);
00458
00459 while ((i = MyGetOpt(&mgo)) != -1) {
00460 switch (i) {
00461 case 'I': free(graphics_set); graphics_set = strdup(mgo.opt); break;
00462 case 'S': free(sounds_set); sounds_set = strdup(mgo.opt); break;
00463 case 'M': free(music_set); music_set = strdup(mgo.opt); break;
00464 case 'm': free(musicdriver); musicdriver = strdup(mgo.opt); break;
00465 case 's': free(sounddriver); sounddriver = strdup(mgo.opt); break;
00466 case 'v': free(videodriver); videodriver = strdup(mgo.opt); break;
00467 case 'b': free(blitter); blitter = strdup(mgo.opt); break;
00468 #if defined(ENABLE_NETWORK)
00469 case 'D':
00470 free(musicdriver);
00471 free(sounddriver);
00472 free(videodriver);
00473 free(blitter);
00474 musicdriver = strdup("null");
00475 sounddriver = strdup("null");
00476 videodriver = strdup("dedicated");
00477 blitter = strdup("null");
00478 dedicated = true;
00479 SetDebugString("net=6");
00480 if (mgo.opt != NULL) {
00481
00482
00483 const char *temp = NULL;
00484 const char *port = NULL;
00485 ParseConnectionString(&temp, &port, mgo.opt);
00486 if (!StrEmpty(mgo.opt)) dedicated_host = mgo.opt;
00487 if (port != NULL) dedicated_port = atoi(port);
00488 }
00489 break;
00490 case 'f': _dedicated_forks = true; break;
00491 case 'n':
00492 network = true;
00493 network_conn = mgo.opt;
00494 break;
00495 case 'l':
00496 debuglog_conn = mgo.opt;
00497 break;
00498 case 'p':
00499 join_server_password = mgo.opt;
00500 break;
00501 case 'P':
00502 join_company_password = mgo.opt;
00503 break;
00504 #endif
00505 case 'r': ParseResolution(&resolution, mgo.opt); break;
00506 case 't': startyear = atoi(mgo.opt); break;
00507 case 'd': {
00508 #if defined(WIN32)
00509 CreateConsole();
00510 #endif
00511 if (mgo.opt != NULL) SetDebugString(mgo.opt);
00512 break;
00513 }
00514 case 'e': _switch_mode = SM_EDITOR; break;
00515 case 'i':
00516
00517 if (!StrEmpty(mgo.opt) && mgo.opt[1] == '\0') {
00518 _use_palette = (PaletteType)(mgo.opt[0] - '0');
00519 if (_use_palette <= MAX_PAL) break;
00520 }
00521 usererror("Valid value for '-i' is 0, 1 or 2");
00522 case 'g':
00523 if (mgo.opt != NULL) {
00524 strecpy(_file_to_saveload.name, mgo.opt, lastof(_file_to_saveload.name));
00525 _switch_mode = SM_LOAD;
00526 _file_to_saveload.mode = SL_LOAD;
00527
00528
00529 const char *t = strrchr(_file_to_saveload.name, '.');
00530 if (t != NULL) {
00531 FiosType ft = FiosGetSavegameListCallback(SLD_LOAD_GAME, _file_to_saveload.name, t, NULL, NULL);
00532 if (ft != FIOS_TYPE_INVALID) SetFiosType(ft);
00533 }
00534
00535 break;
00536 }
00537
00538 _switch_mode = SM_NEWGAME;
00539
00540 if (generation_seed == GENERATE_NEW_SEED) {
00541 generation_seed = InteractiveRandom();
00542 }
00543 break;
00544 case 'G': generation_seed = atoi(mgo.opt); break;
00545 case 'c': _config_file = strdup(mgo.opt); break;
00546 case 'x': save_config = false; break;
00547 case -2:
00548 case 'h':
00549
00550
00551
00552 DeterminePaths(argv[0]);
00553 BaseGraphics::FindSets();
00554 BaseSounds::FindSets();
00555 BaseMusic::FindSets();
00556 ShowHelp();
00557 return 0;
00558 }
00559 }
00560
00561 #if defined(WINCE) && defined(_DEBUG)
00562
00563 SetDebugString("4");
00564 #endif
00565
00566 DeterminePaths(argv[0]);
00567 BaseGraphics::FindSets();
00568 BaseSounds::FindSets();
00569 BaseMusic::FindSets();
00570
00571 #if defined(ENABLE_NETWORK) && defined(UNIX) && !defined(__MORPHOS__)
00572
00573 if (_dedicated_forks) DedicatedFork();
00574 #endif
00575
00576 TarScanner::DoScan();
00577 AI::Initialize();
00578 LoadFromConfig();
00579 AI::Uninitialize(true);
00580 CheckConfig();
00581 LoadFromHighScore();
00582 LoadHotkeysFromConfig();
00583
00584 if (resolution.width != 0) { _cur_resolution = resolution; }
00585 if (startyear != INVALID_YEAR) _settings_newgame.game_creation.starting_year = startyear;
00586 if (generation_seed != GENERATE_NEW_SEED) _settings_newgame.game_creation.generation_seed = generation_seed;
00587
00588
00589
00590
00591
00592
00593 _cur_resolution.width = ClampU(_cur_resolution.width, 1, UINT16_MAX);
00594 _cur_resolution.height = ClampU(_cur_resolution.height, 1, UINT16_MAX);
00595
00596 #if defined(ENABLE_NETWORK)
00597 if (dedicated) DEBUG(net, 0, "Starting dedicated version %s", _openttd_revision);
00598 if (dedicated_host) {
00599 _network_bind_list.Clear();
00600 *_network_bind_list.Append() = strdup(dedicated_host);
00601 }
00602 if (dedicated_port) _settings_client.network.server_port = dedicated_port;
00603 if (_dedicated_forks && !dedicated) _dedicated_forks = false;
00604 #endif
00605
00606
00607 InitializeLanguagePacks();
00608
00609
00610 InitializeScreenshotFormats();
00611
00612
00613 InitializeDynamicVariables();
00614
00615
00616 InitFreeType();
00617
00618
00619 InitWindowSystem();
00620
00621
00622
00623
00624 if (sounds_set == NULL && BaseSounds::ini_set != NULL) sounds_set = strdup(BaseSounds::ini_set);
00625 if (!BaseSounds::SetSet(sounds_set)) {
00626 StrEmpty(sounds_set) ?
00627 usererror("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 4.1 of readme.txt.") :
00628 usererror("Failed to select requested sounds set '%s'", sounds_set);
00629 }
00630 free(sounds_set);
00631
00632 if (graphics_set == NULL && BaseGraphics::ini_set != NULL) graphics_set = strdup(BaseGraphics::ini_set);
00633 if (!BaseGraphics::SetSet(graphics_set)) {
00634 StrEmpty(graphics_set) ?
00635 usererror("Failed to find a graphics set. Please acquire a graphics set for OpenTTD. See section 4.1 of readme.txt.") :
00636 usererror("Failed to select requested graphics set '%s'", graphics_set);
00637 }
00638 free(graphics_set);
00639
00640 if (music_set == NULL && BaseMusic::ini_set != NULL) music_set = strdup(BaseMusic::ini_set);
00641 if (!BaseMusic::SetSet(music_set)) {
00642 StrEmpty(music_set) ?
00643 usererror("Failed to find a music set. Please acquire a music set for OpenTTD. See section 4.1 of readme.txt.") :
00644 usererror("Failed to select requested music set '%s'", music_set);
00645 }
00646 free(music_set);
00647
00648
00649 GfxInitPalettes();
00650
00651 DEBUG(misc, 1, "Loading blitter...");
00652 if (blitter == NULL && _ini_blitter != NULL) blitter = strdup(_ini_blitter);
00653 if (BlitterFactoryBase::SelectBlitter(blitter) == NULL) {
00654 StrEmpty(blitter) ?
00655 usererror("Failed to autoprobe blitter") :
00656 usererror("Failed to select requested blitter '%s'; does it exist?", blitter);
00657 }
00658 free(blitter);
00659
00660 DEBUG(driver, 1, "Loading drivers...");
00661
00662 if (sounddriver == NULL && _ini_sounddriver != NULL) sounddriver = strdup(_ini_sounddriver);
00663 _sound_driver = (SoundDriver*)SoundDriverFactoryBase::SelectDriver(sounddriver, Driver::DT_SOUND);
00664 if (_sound_driver == NULL) {
00665 StrEmpty(sounddriver) ?
00666 usererror("Failed to autoprobe sound driver") :
00667 usererror("Failed to select requested sound driver '%s'", sounddriver);
00668 }
00669 free(sounddriver);
00670
00671 if (videodriver == NULL && _ini_videodriver != NULL) videodriver = strdup(_ini_videodriver);
00672 _video_driver = (VideoDriver*)VideoDriverFactoryBase::SelectDriver(videodriver, Driver::DT_VIDEO);
00673 if (_video_driver == NULL) {
00674 StrEmpty(videodriver) ?
00675 usererror("Failed to autoprobe video driver") :
00676 usererror("Failed to select requested video driver '%s'", videodriver);
00677 }
00678 free(videodriver);
00679
00680 if (musicdriver == NULL && _ini_musicdriver != NULL) musicdriver = strdup(_ini_musicdriver);
00681 _music_driver = (MusicDriver*)MusicDriverFactoryBase::SelectDriver(musicdriver, Driver::DT_MUSIC);
00682 if (_music_driver == NULL) {
00683 StrEmpty(musicdriver) ?
00684 usererror("Failed to autoprobe music driver") :
00685 usererror("Failed to select requested music driver '%s'", musicdriver);
00686 }
00687 free(musicdriver);
00688
00689
00690 _screen.zoom = ZOOM_LVL_NORMAL;
00691
00692
00693 _music_driver->SetVolume(_msf.music_vol);
00694
00695 NetworkStartUp();
00696
00697 #if defined(ENABLE_NETWORK)
00698 if (debuglog_conn != NULL && _network_available) {
00699 const char *not_used = NULL;
00700 const char *port = NULL;
00701 uint16 rport;
00702
00703 rport = NETWORK_DEFAULT_DEBUGLOG_PORT;
00704
00705 ParseConnectionString(¬_used, &port, debuglog_conn);
00706 if (port != NULL) rport = atoi(port);
00707
00708 NetworkStartDebugLog(NetworkAddress(debuglog_conn, rport));
00709 }
00710 #endif
00711
00712 ScanNewGRFFiles();
00713
00714 ResetGRFConfig(false);
00715
00716
00717 if (_switch_mode != SM_NONE) MakeNewgameSettingsLive();
00718
00719
00720 IConsoleInit();
00721 _cursor.in_window = true;
00722 InitializeGUI();
00723 IConsoleCmdExec("exec scripts/autoexec.scr 0");
00724
00725
00726 _genworld_paint_mutex->BeginCritical();
00727 _genworld_mapgen_mutex->BeginCritical();
00728
00729 GenerateWorld(GWM_EMPTY, 64, 64);
00730 WaitTillGeneratedWorld();
00731
00732 CheckForMissingGlyphsInLoadedLanguagePack();
00733
00734 #ifdef ENABLE_NETWORK
00735 if (network && _network_available) {
00736 if (network_conn != NULL) {
00737 const char *port = NULL;
00738 const char *company = NULL;
00739 uint16 rport = NETWORK_DEFAULT_PORT;
00740 CompanyID join_as = COMPANY_NEW_COMPANY;
00741
00742 ParseConnectionString(&company, &port, network_conn);
00743
00744 if (company != NULL) {
00745 join_as = (CompanyID)atoi(company);
00746
00747 if (join_as != COMPANY_SPECTATOR) {
00748 join_as--;
00749 if (join_as >= MAX_COMPANIES) return false;
00750 }
00751 }
00752 if (port != NULL) rport = atoi(port);
00753
00754 LoadIntroGame();
00755 _switch_mode = SM_NONE;
00756 NetworkClientConnectGame(NetworkAddress(network_conn, rport), join_as, join_server_password, join_company_password);
00757 }
00758 }
00759 #endif
00760
00761 _video_driver->MainLoop();
00762
00763 WaitTillSaved();
00764
00765
00766 if (save_config) {
00767 SaveToConfig();
00768 SaveHotkeysToConfig();
00769 SaveToHighScore();
00770 }
00771
00772
00773 ShutdownGame();
00774
00775 free(const_cast<char *>(BaseGraphics::ini_set));
00776 free(const_cast<char *>(BaseSounds::ini_set));
00777 free(const_cast<char *>(BaseMusic::ini_set));
00778 free(_ini_musicdriver);
00779 free(_ini_sounddriver);
00780 free(_ini_videodriver);
00781 free(_ini_blitter);
00782
00783 return 0;
00784 }
00785
00786 void HandleExitGameRequest()
00787 {
00788 if (_game_mode == GM_MENU) {
00789 _exit_game = true;
00790 } else if (_settings_client.gui.autosave_on_exit) {
00791 DoExitSave();
00792 _exit_game = true;
00793 } else {
00794 AskExitGame();
00795 }
00796 }
00797
00798 static void MakeNewGameDone()
00799 {
00800 SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
00801
00802
00803 if (_network_dedicated || BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth() == 0) {
00804 SetLocalCompany(COMPANY_SPECTATOR);
00805 IConsoleCmdExec("exec scripts/game_start.scr 0");
00806 return;
00807 }
00808
00809
00810 DoStartupNewCompany(false);
00811
00812 Company *c = Company::Get(COMPANY_FIRST);
00813 c->settings = _settings_client.company;
00814
00815 IConsoleCmdExec("exec scripts/game_start.scr 0");
00816
00817 SetLocalCompany(COMPANY_FIRST);
00818
00819 InitializeRailGUI();
00820
00821 #ifdef ENABLE_NETWORK
00822
00823
00824 if (_network_server && !StrEmpty(_settings_client.network.default_company_pass)) {
00825 NetworkChangeCompanyPassword(_local_company, _settings_client.network.default_company_pass);
00826 }
00827 #endif
00828
00829 if (_settings_client.gui.pause_on_newgame) DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
00830
00831 MarkWholeScreenDirty();
00832 }
00833
00834 static void MakeNewGame(bool from_heightmap, bool reset_settings)
00835 {
00836 _game_mode = GM_NORMAL;
00837
00838 ResetGRFConfig(true);
00839 InitializeDynamicVariables();
00840
00841 GenerateWorldSetCallback(&MakeNewGameDone);
00842 GenerateWorld(from_heightmap ? GWM_HEIGHTMAP : GWM_NEWGAME, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y, reset_settings);
00843 }
00844
00845 static void MakeNewEditorWorldDone()
00846 {
00847 SetLocalCompany(OWNER_NONE);
00848 }
00849
00850 static void MakeNewEditorWorld()
00851 {
00852 _game_mode = GM_EDITOR;
00853
00854 ResetGRFConfig(true);
00855
00856 GenerateWorldSetCallback(&MakeNewEditorWorldDone);
00857 GenerateWorld(GWM_EMPTY, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
00858 }
00859
00870 bool SafeLoad(const char *filename, int mode, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = NULL)
00871 {
00872 assert(mode == SL_LOAD || (lf == NULL && mode == SL_OLD_LOAD));
00873 GameMode ogm = _game_mode;
00874
00875 _game_mode = newgm;
00876
00877 switch (lf == NULL ? SaveOrLoad(filename, mode, subdir) : LoadWithFilter(lf)) {
00878 case SL_OK: return true;
00879
00880 case SL_REINIT:
00881 #ifdef ENABLE_NETWORK
00882 if (_network_dedicated) {
00883
00884
00885
00886
00887
00888
00889 DEBUG(net, 0, "Loading game failed, so a new (random) game will be started!");
00890 MakeNewGame(false, true);
00891 return false;
00892 }
00893 if (_network_server) {
00894
00895 NetworkDisconnect();
00896 }
00897 #endif
00898
00899 switch (ogm) {
00900 default:
00901 case GM_MENU: LoadIntroGame(); break;
00902 case GM_EDITOR: MakeNewEditorWorld(); break;
00903 }
00904 return false;
00905
00906 default:
00907 _game_mode = ogm;
00908 return false;
00909 }
00910 }
00911
00912 void SwitchToMode(SwitchMode new_mode)
00913 {
00914 #ifdef ENABLE_NETWORK
00915
00916 if (new_mode != SM_SAVE) {
00917
00918 if (_networking) {
00919 if (_network_server && (new_mode == SM_LOAD || new_mode == SM_NEWGAME || new_mode == SM_RESTARTGAME)) {
00920 NetworkReboot();
00921 } else {
00922 NetworkDisconnect();
00923 }
00924 }
00925
00926
00927 if (_is_network_server) {
00928
00929 if (new_mode != SM_MENU) {
00930
00931 if (_settings_client.network.reload_cfg) {
00932 LoadFromConfig();
00933 MakeNewgameSettingsLive();
00934 ResetGRFConfig(false);
00935 }
00936 NetworkServerStart();
00937 } else {
00938
00939 _is_network_server = false;
00940 }
00941 }
00942 }
00943 #endif
00944
00945 if (new_mode != SM_SAVE) AI::KillAll();
00946
00947 switch (new_mode) {
00948 case SM_EDITOR:
00949 MakeNewEditorWorld();
00950 break;
00951
00952 case SM_RESTARTGAME:
00953 case SM_NEWGAME:
00954 #ifdef ENABLE_NETWORK
00955 if (_network_server) {
00956 snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "Random Map");
00957 }
00958 #endif
00959 MakeNewGame(false, new_mode == SM_NEWGAME);
00960 break;
00961
00962 case SM_LOAD: {
00963 ResetGRFConfig(true);
00964 ResetWindowSystem();
00965
00966 if (!SafeLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_NORMAL, NO_DIRECTORY)) {
00967 SetDParamStr(0, GetSaveLoadErrorString());
00968 ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
00969 } else {
00970 if (_saveload_mode == SLD_LOAD_SCENARIO) {
00971 StartupEngines();
00972 }
00973
00974
00975 SetLocalCompany(_network_dedicated ? COMPANY_SPECTATOR : COMPANY_FIRST);
00976
00977 IConsoleCmdExec("exec scripts/game_start.scr 0");
00978
00979 DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
00980 #ifdef ENABLE_NETWORK
00981 if (_network_server) {
00982 snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Loaded game)", _file_to_saveload.title);
00983 }
00984 #endif
00985 }
00986 break;
00987 }
00988
00989 case SM_START_HEIGHTMAP:
00990 #ifdef ENABLE_NETWORK
00991 if (_network_server) {
00992 snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Heightmap)", _file_to_saveload.title);
00993 }
00994 #endif
00995 MakeNewGame(true, true);
00996 break;
00997
00998 case SM_LOAD_HEIGHTMAP:
00999 SetLocalCompany(OWNER_NONE);
01000
01001 GenerateWorld(GWM_HEIGHTMAP, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
01002 MarkWholeScreenDirty();
01003 break;
01004
01005 case SM_LOAD_SCENARIO: {
01006 if (SafeLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_EDITOR, NO_DIRECTORY)) {
01007 SetLocalCompany(OWNER_NONE);
01008 _settings_newgame.game_creation.starting_year = _cur_year;
01009
01010 DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
01011 } else {
01012 SetDParamStr(0, GetSaveLoadErrorString());
01013 ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
01014 }
01015 break;
01016 }
01017
01018 case SM_MENU:
01019 LoadIntroGame();
01020 if (BaseSounds::ini_set == NULL && BaseSounds::GetUsedSet()->fallback) {
01021 ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET, INVALID_STRING_ID, WL_CRITICAL);
01022 BaseSounds::ini_set = strdup(BaseSounds::GetUsedSet()->name);
01023 }
01024 break;
01025
01026 case SM_SAVE:
01027
01028 if (SaveOrLoad(_file_to_saveload.name, SL_SAVE, NO_DIRECTORY) != SL_OK) {
01029 SetDParamStr(0, GetSaveLoadErrorString());
01030 ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
01031 } else {
01032 DeleteWindowById(WC_SAVELOAD, 0);
01033 }
01034 break;
01035
01036 case SM_GENRANDLAND:
01037 SetLocalCompany(OWNER_NONE);
01038 GenerateWorld(GWM_RANDOM, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
01039
01040 MarkWholeScreenDirty();
01041 break;
01042
01043 default: NOT_REACHED();
01044 }
01045
01046 if (_switch_mode_errorstr != INVALID_STRING_ID) {
01047 ShowErrorMessage(_switch_mode_errorstr, INVALID_STRING_ID, WL_CRITICAL);
01048 _switch_mode_errorstr = INVALID_STRING_ID;
01049 }
01050 }
01051
01052
01059 static void CheckCaches()
01060 {
01061
01062
01063 if (_debug_desync_level <= 1) return;
01064
01065
01066 const RoadStop *rs;
01067 FOR_ALL_ROADSTOPS(rs) {
01068 if (IsStandardRoadStopTile(rs->xy)) continue;
01069
01070 assert(rs->GetEntry(DIAGDIR_NE) != rs->GetEntry(DIAGDIR_NW));
01071 rs->GetEntry(DIAGDIR_NE)->CheckIntegrity(rs);
01072 rs->GetEntry(DIAGDIR_NW)->CheckIntegrity(rs);
01073 }
01074
01075 Vehicle *v;
01076 FOR_ALL_VEHICLES(v) {
01077 extern void FillNewGRFVehicleCache(const Vehicle *v);
01078 if (v != v->First() || v->vehstatus & VS_CRASHED || !v->IsPrimaryVehicle()) continue;
01079
01080 uint length = 0;
01081 for (const Vehicle *u = v; u != NULL; u = u->Next()) length++;
01082
01083 NewGRFCache *grf_cache = CallocT<NewGRFCache>(length);
01084 VehicleCache *veh_cache = CallocT<VehicleCache>(length);
01085 GroundVehicleCache *gro_cache = CallocT<GroundVehicleCache>(length);
01086 TrainCache *tra_cache = CallocT<TrainCache>(length);
01087
01088 length = 0;
01089 for (const Vehicle *u = v; u != NULL; u = u->Next()) {
01090 FillNewGRFVehicleCache(u);
01091 grf_cache[length] = u->grf_cache;
01092 veh_cache[length] = u->vcache;
01093 switch (u->type) {
01094 case VEH_TRAIN:
01095 gro_cache[length] = Train::From(u)->gcache;
01096 tra_cache[length] = Train::From(u)->tcache;
01097 break;
01098 case VEH_ROAD:
01099 gro_cache[length] = RoadVehicle::From(u)->gcache;
01100 break;
01101 default:
01102 break;
01103 }
01104 length++;
01105 }
01106
01107 switch (v->type) {
01108 case VEH_TRAIN: Train::From(v)->ConsistChanged(true); break;
01109 case VEH_ROAD: RoadVehUpdateCache(RoadVehicle::From(v)); break;
01110 case VEH_AIRCRAFT: UpdateAircraftCache(Aircraft::From(v)); break;
01111 case VEH_SHIP: Ship::From(v)->UpdateCache(); break;
01112 default: break;
01113 }
01114
01115 length = 0;
01116 for (const Vehicle *u = v; u != NULL; u = u->Next()) {
01117 FillNewGRFVehicleCache(u);
01118 if (memcmp(&grf_cache[length], &u->grf_cache, sizeof(NewGRFCache)) != 0) {
01119 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);
01120 }
01121 if (memcmp(&veh_cache[length], &u->vcache, sizeof(VehicleCache)) != 0) {
01122 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);
01123 }
01124 switch (u->type) {
01125 case VEH_TRAIN:
01126 if (memcmp(&gro_cache[length], &Train::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
01127 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);
01128 }
01129 if (memcmp(&tra_cache[length], &Train::From(u)->tcache, sizeof(TrainCache)) != 0) {
01130 DEBUG(desync, 2, "train cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v->index, (int)v->owner, v->unitnumber, length);
01131 }
01132 break;
01133 case VEH_ROAD:
01134 if (memcmp(&gro_cache[length], &RoadVehicle::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
01135 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);
01136 }
01137 break;
01138 default:
01139 break;
01140 }
01141 length++;
01142 }
01143
01144 free(grf_cache);
01145 free(veh_cache);
01146 free(gro_cache);
01147 free(tra_cache);
01148 }
01149
01150
01151 FOR_ALL_VEHICLES(v) {
01152 byte buff[sizeof(VehicleCargoList)];
01153 memcpy(buff, &v->cargo, sizeof(VehicleCargoList));
01154 v->cargo.InvalidateCache();
01155 assert(memcmp(&v->cargo, buff, sizeof(VehicleCargoList)) == 0);
01156 }
01157
01158 Station *st;
01159 FOR_ALL_STATIONS(st) {
01160 for (CargoID c = 0; c < NUM_CARGO; c++) {
01161 byte buff[sizeof(StationCargoList)];
01162 memcpy(buff, &st->goods[c].cargo, sizeof(StationCargoList));
01163 st->goods[c].cargo.InvalidateCache();
01164 assert(memcmp(&st->goods[c].cargo, buff, sizeof(StationCargoList)) == 0);
01165 }
01166 }
01167 }
01168
01174 void StateGameLoop()
01175 {
01176
01177 if (_pause_mode != PM_UNPAUSED) {
01178 UpdateLandscapingLimits();
01179 CallWindowTickEvent();
01180 return;
01181 }
01182 if (IsGeneratingWorld()) return;
01183
01184 ClearStorageChanges(false);
01185
01186 if (_game_mode == GM_EDITOR) {
01187 RunTileLoop();
01188 CallVehicleTicks();
01189 CallLandscapeTick();
01190 ClearStorageChanges(true);
01191 UpdateLandscapingLimits();
01192
01193 CallWindowTickEvent();
01194 NewsLoop();
01195 } else {
01196 if (_debug_desync_level > 2 && _date_fract == 0 && (_date & 0x1F) == 0) {
01197
01198 char name[MAX_PATH];
01199 snprintf(name, lengthof(name), "dmp_cmds_%08x_%08x.sav", _settings_game.game_creation.generation_seed, _date);
01200 SaveOrLoad(name, SL_SAVE, AUTOSAVE_DIR, false);
01201 }
01202
01203 CheckCaches();
01204
01205
01206
01207 Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
01208
01209 AnimateAnimatedTiles();
01210 IncreaseDate();
01211 RunTileLoop();
01212 CallVehicleTicks();
01213 CallLandscapeTick();
01214 ClearStorageChanges(true);
01215
01216 AI::GameLoop();
01217 UpdateLandscapingLimits();
01218
01219 CallWindowTickEvent();
01220 NewsLoop();
01221 cur_company.Restore();
01222 }
01223
01224 assert(IsLocalCompany());
01225 }
01226
01231 static void DoAutosave()
01232 {
01233 char buf[MAX_PATH];
01234
01235 #if defined(PSP)
01236
01237 if (_networking) return;
01238 #endif
01239
01240 if (_settings_client.gui.keep_all_autosave) {
01241 GenerateDefaultSaveName(buf, lastof(buf));
01242 strecat(buf, ".sav", lastof(buf));
01243 } else {
01244 static int _autosave_ctr = 0;
01245
01246
01247 snprintf(buf, sizeof(buf), "autosave%d.sav", _autosave_ctr);
01248
01249 if (++_autosave_ctr >= _settings_client.gui.max_num_autosaves) _autosave_ctr = 0;
01250 }
01251
01252 DEBUG(sl, 2, "Autosaving to '%s'", buf);
01253 if (SaveOrLoad(buf, SL_SAVE, AUTOSAVE_DIR) != SL_OK) {
01254 ShowErrorMessage(STR_ERROR_AUTOSAVE_FAILED, INVALID_STRING_ID, WL_ERROR);
01255 }
01256 }
01257
01258 void GameLoop()
01259 {
01260 ProcessAsyncSaveFinish();
01261
01262
01263 if (_do_autosave) {
01264 _do_autosave = false;
01265 DoAutosave();
01266 SetWindowDirty(WC_STATUS_BAR, 0);
01267 }
01268
01269
01270 if (_switch_mode != SM_NONE) {
01271 SwitchToMode(_switch_mode);
01272 _switch_mode = SM_NONE;
01273 }
01274
01275 IncreaseSpriteLRU();
01276 InteractiveRandom();
01277
01278 extern int _caret_timer;
01279 _caret_timer += 3;
01280 CursorTick();
01281
01282 #ifdef ENABLE_NETWORK
01283
01284 if (_network_available) NetworkUDPGameLoop();
01285
01286 if (_networking && !IsGeneratingWorld()) {
01287
01288 NetworkGameLoop();
01289 } else {
01290 if (_network_reconnect > 0 && --_network_reconnect == 0) {
01291
01292
01293 NetworkClientConnectGame(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port), COMPANY_SPECTATOR);
01294 }
01295
01296 StateGameLoop();
01297 }
01298
01299
01300 static uint check_message = 0;
01301 if (++check_message > 1000 / MILLISECONDS_PER_TICK) {
01302 check_message = 0;
01303 NetworkChatMessageLoop();
01304 }
01305 #else
01306 StateGameLoop();
01307 #endif
01308
01309 if (!_pause_mode && HasBit(_display_opt, DO_FULL_ANIMATION)) DoPaletteAnimations();
01310
01311 if (!_pause_mode || _game_mode == GM_EDITOR || _settings_game.construction.command_pause_level > CMDPL_NO_CONSTRUCTION) MoveAllTextEffects();
01312
01313 InputLoop();
01314
01315 _sound_driver->MainLoop();
01316 MusicLoop();
01317 }