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