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