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 "error.h"
00021 #include "gui.h"
00022
00023 #include "base_media_base.h"
00024 #include "saveload/saveload.h"
00025 #include "company_func.h"
00026 #include "command_func.h"
00027 #include "news_func.h"
00028 #include "fios.h"
00029 #include "aircraft.h"
00030 #include "roadveh.h"
00031 #include "train.h"
00032 #include "ship.h"
00033 #include "console_func.h"
00034 #include "screenshot.h"
00035 #include "network/network.h"
00036 #include "network/network_func.h"
00037 #include "ai/ai.hpp"
00038 #include "ai/ai_config.hpp"
00039 #include "settings_func.h"
00040 #include "genworld.h"
00041 #include "progress.h"
00042 #include "strings_func.h"
00043 #include "date_func.h"
00044 #include "vehicle_func.h"
00045 #include "gamelog.h"
00046 #include "animated_tile_func.h"
00047 #include "roadstop_base.h"
00048 #include "elrail_func.h"
00049 #include "rev.h"
00050 #include "highscore.h"
00051 #include "station_base.h"
00052 #include "crashlog.h"
00053 #include "engine_func.h"
00054 #include "core/random_func.hpp"
00055 #include "rail_gui.h"
00056 #include "core/backup_type.hpp"
00057 #include "hotkeys.h"
00058 #include "newgrf.h"
00059 #include "misc/getoptdata.h"
00060 #include "game/game.hpp"
00061 #include "game/game_config.hpp"
00062 #include "town.h"
00063 #include "subsidy_func.h"
00064 #include "gfx_layout.h"
00065
00066
00067 #include "linkgraph/linkgraphschedule.h"
00068
00069 #include <stdarg.h>
00070
00071
00072 void CallLandscapeTick();
00073 void IncreaseDate();
00074 void DoPaletteAnimations();
00075 void MusicLoop();
00076 void ResetMusic();
00077 void CallWindowTickEvent();
00078 bool HandleBootstrap();
00079
00080 extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
00081 extern void ShowOSErrorBox(const char *buf, bool system);
00082 extern char *_config_file;
00083
00089 void CDECL usererror(const char *s, ...)
00090 {
00091 va_list va;
00092 char buf[512];
00093
00094 va_start(va, s);
00095 vsnprintf(buf, lengthof(buf), s, va);
00096 va_end(va);
00097
00098 ShowOSErrorBox(buf, false);
00099 if (_video_driver != NULL) _video_driver->Stop();
00100
00101 exit(1);
00102 }
00103
00109 void CDECL error(const char *s, ...)
00110 {
00111 va_list va;
00112 char buf[512];
00113
00114 va_start(va, s);
00115 vsnprintf(buf, lengthof(buf), s, va);
00116 va_end(va);
00117
00118 ShowOSErrorBox(buf, true);
00119
00120
00121 CrashLog::SetErrorMessage(buf);
00122 abort();
00123 }
00124
00129 void CDECL ShowInfoF(const char *str, ...)
00130 {
00131 va_list va;
00132 char buf[1024];
00133 va_start(va, str);
00134 vsnprintf(buf, lengthof(buf), str, va);
00135 va_end(va);
00136 ShowInfo(buf);
00137 }
00138
00142 static void ShowHelp()
00143 {
00144 char buf[8192];
00145 char *p = buf;
00146
00147 p += seprintf(p, lastof(buf), "OpenTTD %s\n", _openttd_revision);
00148 p = strecpy(p,
00149 "\n"
00150 "\n"
00151 "Command line options:\n"
00152 " -v drv = Set video driver (see below)\n"
00153 " -s drv = Set sound driver (see below) (param bufsize,hz)\n"
00154 " -m drv = Set music driver (see below)\n"
00155 " -b drv = Set the blitter to use (see below)\n"
00156 " -r res = Set resolution (for instance 800x600)\n"
00157 " -h = Display this help text\n"
00158 " -t year = Set starting year\n"
00159 " -d [[fac=]lvl[,...]]= Debug mode\n"
00160 " -e = Start Editor\n"
00161 " -g [savegame] = Start new/save game immediately\n"
00162 " -G seed = Set random seed\n"
00163 #if defined(ENABLE_NETWORK)
00164 " -n [ip:port#company]= Join network game\n"
00165 " -p password = Password to join server\n"
00166 " -P password = Password to join company\n"
00167 " -D [ip][:port] = Start dedicated server\n"
00168 " -l ip[:port] = Redirect DEBUG()\n"
00169 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
00170 " -f = Fork into the background (dedicated only)\n"
00171 #endif
00172 #endif
00173 " -I graphics_set = Force the graphics set (see below)\n"
00174 " -S sounds_set = Force the sounds set (see below)\n"
00175 " -M music_set = Force the music set (see below)\n"
00176 " -c config_file = Use 'config_file' instead of 'openttd.cfg'\n"
00177 " -x = Do not automatically save to config file on exit\n"
00178 " -q savegame = Write some information about the savegame and exit\n"
00179 "\n",
00180 lastof(buf)
00181 );
00182
00183
00184 p = BaseGraphics::GetSetsList(p, lastof(buf));
00185
00186
00187 p = BaseSounds::GetSetsList(p, lastof(buf));
00188
00189
00190 p = BaseMusic::GetSetsList(p, lastof(buf));
00191
00192
00193 p = DriverFactoryBase::GetDriversInfo(p, lastof(buf));
00194
00195
00196 p = BlitterFactoryBase::GetBlittersInfo(p, lastof(buf));
00197
00198
00199 p = DumpDebugFacilityNames(p, lastof(buf));
00200
00201
00202 AI::Initialize();
00203 p = AI::GetConsoleList(p, lastof(buf), true);
00204 AI::Uninitialize(true);
00205
00206
00207 Game::Initialize();
00208 p = Game::GetConsoleList(p, lastof(buf), true);
00209 Game::Uninitialize(true);
00210
00211
00212
00213 #if !defined(WIN32) && !defined(WIN64)
00214 printf("%s\n", buf);
00215 #else
00216 ShowInfo(buf);
00217 #endif
00218 }
00219
00220 static void WriteSavegameInfo(const char *name)
00221 {
00222 extern uint16 _sl_version;
00223 uint32 last_ottd_rev = 0;
00224 byte ever_modified = 0;
00225 bool removed_newgrfs = false;
00226
00227 GamelogInfo(_load_check_data.gamelog_action, _load_check_data.gamelog_actions, &last_ottd_rev, &ever_modified, &removed_newgrfs);
00228
00229 char buf[8192];
00230 char *p = buf;
00231 p += seprintf(p, lastof(buf), "Name: %s\n", name);
00232 p += seprintf(p, lastof(buf), "Savegame ver: %d\n", _sl_version);
00233 p += seprintf(p, lastof(buf), "NewGRF ver: 0x%08X\n", last_ottd_rev);
00234 p += seprintf(p, lastof(buf), "Modified: %d\n", ever_modified);
00235
00236 if (removed_newgrfs) {
00237 p += seprintf(p, lastof(buf), "NewGRFs have been removed\n");
00238 }
00239
00240 p = strecpy(p, "NewGRFs:\n", lastof(buf));
00241 if (_load_check_data.HasNewGrfs()) {
00242 for (GRFConfig *c = _load_check_data.grfconfig; c != NULL; c = c->next) {
00243 char md5sum[33];
00244 md5sumToString(md5sum, lastof(md5sum), HasBit(c->flags, GCF_COMPATIBLE) ? c->original_md5sum : c->ident.md5sum);
00245 p += seprintf(p, lastof(buf), "%08X %s %s\n", c->ident.grfid, md5sum, c->filename);
00246 }
00247 }
00248
00249
00250
00251 #if !defined(WIN32) && !defined(WIN64)
00252 printf("%s\n", buf);
00253 #else
00254 ShowInfo(buf);
00255 #endif
00256 }
00257
00258
00265 static void ParseResolution(Dimension *res, const char *s)
00266 {
00267 const char *t = strchr(s, 'x');
00268 if (t == NULL) {
00269 ShowInfoF("Invalid resolution '%s'", s);
00270 return;
00271 }
00272
00273 res->width = max(strtoul(s, NULL, 0), 64UL);
00274 res->height = max(strtoul(t + 1, NULL, 0), 64UL);
00275 }
00276
00277
00282 static void ShutdownGame()
00283 {
00284 IConsoleFree();
00285
00286 if (_network_available) NetworkShutDown();
00287
00288 DriverFactoryBase::ShutdownDrivers();
00289
00290 UnInitWindowSystem();
00291
00292
00293 AI::Uninitialize(false);
00294 Game::Uninitialize(false);
00295
00296
00297 GamelogReset();
00298
00299 #ifdef ENABLE_NETWORK
00300 free(_config_file);
00301 #endif
00302
00303 LinkGraphSchedule::Clear();
00304 PoolBase::Clean(PT_ALL);
00305
00306
00307 if (_game_mode != GM_BOOTSTRAP) ResetNewGRFData();
00308
00309
00310 FioCloseAll();
00311
00312 UninitFreeType();
00313 }
00314
00319 static void LoadIntroGame(bool load_newgrfs = true)
00320 {
00321 _game_mode = GM_MENU;
00322
00323 if (load_newgrfs) ResetGRFConfig(false);
00324
00325
00326 ResetWindowSystem();
00327 SetupColoursAndInitialWindow();
00328
00329
00330 if (SaveOrLoad("opntitle.dat", SL_LOAD, BASESET_DIR) != SL_OK) {
00331 GenerateWorld(GWM_EMPTY, 64, 64);
00332 WaitTillGeneratedWorld();
00333 SetLocalCompany(COMPANY_SPECTATOR);
00334 } else {
00335 SetLocalCompany(COMPANY_FIRST);
00336 }
00337
00338 _pause_mode = PM_UNPAUSED;
00339 _cursor.fix_at = false;
00340
00341 if (load_newgrfs) CheckForMissingSprites();
00342 CheckForMissingGlyphs();
00343
00344
00345 if (_music_driver->IsSongPlaying()) ResetMusic();
00346 }
00347
00348 void MakeNewgameSettingsLive()
00349 {
00350 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
00351 if (_settings_game.ai_config[c] != NULL) {
00352 delete _settings_game.ai_config[c];
00353 }
00354 }
00355 if (_settings_game.game_config != NULL) {
00356 delete _settings_game.game_config;
00357 }
00358
00359
00360
00361 _settings_game = _settings_newgame;
00362 _old_vds = _settings_client.company.vehicle;
00363
00364 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
00365 _settings_game.ai_config[c] = NULL;
00366 if (_settings_newgame.ai_config[c] != NULL) {
00367 _settings_game.ai_config[c] = new AIConfig(_settings_newgame.ai_config[c]);
00368 }
00369 }
00370 _settings_game.game_config = NULL;
00371 if (_settings_newgame.game_config != NULL) {
00372 _settings_game.game_config = new GameConfig(_settings_newgame.game_config);
00373 }
00374 }
00375
00376 void OpenBrowser(const char *url)
00377 {
00378
00379 if (strstr(url, "http://") != url && strstr(url, "https://") != url) return;
00380
00381 extern void OSOpenBrowser(const char *url);
00382 OSOpenBrowser(url);
00383 }
00384
00386 struct AfterNewGRFScan : NewGRFScanCallback {
00387 Year startyear;
00388 uint generation_seed;
00389 char *dedicated_host;
00390 uint16 dedicated_port;
00391 char *network_conn;
00392 const char *join_server_password;
00393 const char *join_company_password;
00394 bool *save_config_ptr;
00395 bool save_config;
00396
00402 AfterNewGRFScan(bool *save_config_ptr) :
00403 startyear(INVALID_YEAR), generation_seed(GENERATE_NEW_SEED),
00404 dedicated_host(NULL), dedicated_port(0), network_conn(NULL),
00405 join_server_password(NULL), join_company_password(NULL),
00406 save_config_ptr(save_config_ptr), save_config(true)
00407 {
00408 }
00409
00410 virtual void OnNewGRFsScanned()
00411 {
00412 ResetGRFConfig(false);
00413
00414 TarScanner::DoScan(TarScanner::SCENARIO);
00415
00416 AI::Initialize();
00417 Game::Initialize();
00418
00419
00420 uint last_newgrf_count = _settings_client.gui.last_newgrf_count;
00421 LoadFromConfig();
00422 _settings_client.gui.last_newgrf_count = last_newgrf_count;
00423
00424
00425 UpdateNewGRFConfigPalette();
00426
00427 Game::Uninitialize(true);
00428 AI::Uninitialize(true);
00429 CheckConfig();
00430 LoadFromHighScore();
00431 LoadHotkeysFromConfig();
00432 WindowDesc::LoadFromConfig();
00433
00434
00435 *save_config_ptr = save_config;
00436
00437
00438 _music_driver->SetVolume(_settings_client.music.music_vol);
00439
00440 if (startyear != INVALID_YEAR) _settings_newgame.game_creation.starting_year = startyear;
00441 if (generation_seed != GENERATE_NEW_SEED) _settings_newgame.game_creation.generation_seed = generation_seed;
00442
00443 #if defined(ENABLE_NETWORK)
00444 if (dedicated_host != NULL) {
00445 _network_bind_list.Clear();
00446 *_network_bind_list.Append() = strdup(dedicated_host);
00447 }
00448 if (dedicated_port != 0) _settings_client.network.server_port = dedicated_port;
00449 #endif
00450
00451
00452 IConsoleInit();
00453 InitializeGUI();
00454 IConsoleCmdExec("exec scripts/autoexec.scr 0");
00455
00456
00457 if (_switch_mode != SM_NONE) MakeNewgameSettingsLive();
00458
00459 #ifdef ENABLE_NETWORK
00460 if (_network_available && network_conn != NULL) {
00461 const char *port = NULL;
00462 const char *company = NULL;
00463 uint16 rport = NETWORK_DEFAULT_PORT;
00464 CompanyID join_as = COMPANY_NEW_COMPANY;
00465
00466 ParseConnectionString(&company, &port, network_conn);
00467
00468 if (company != NULL) {
00469 join_as = (CompanyID)atoi(company);
00470
00471 if (join_as != COMPANY_SPECTATOR) {
00472 join_as--;
00473 if (join_as >= MAX_COMPANIES) {
00474 delete this;
00475 return;
00476 }
00477 }
00478 }
00479 if (port != NULL) rport = atoi(port);
00480
00481 LoadIntroGame();
00482 _switch_mode = SM_NONE;
00483 NetworkClientConnectGame(NetworkAddress(network_conn, rport), join_as, join_server_password, join_company_password);
00484 }
00485 #endif
00486
00487
00488 delete this;
00489 }
00490 };
00491
00492 #if defined(UNIX) && !defined(__MORPHOS__)
00493 extern void DedicatedFork();
00494 #endif
00495
00497 static const OptionData _options[] = {
00498 GETOPT_SHORT_VALUE('I'),
00499 GETOPT_SHORT_VALUE('S'),
00500 GETOPT_SHORT_VALUE('M'),
00501 GETOPT_SHORT_VALUE('m'),
00502 GETOPT_SHORT_VALUE('s'),
00503 GETOPT_SHORT_VALUE('v'),
00504 GETOPT_SHORT_VALUE('b'),
00505 #if defined(ENABLE_NETWORK)
00506 GETOPT_SHORT_OPTVAL('D'),
00507 GETOPT_SHORT_OPTVAL('n'),
00508 GETOPT_SHORT_VALUE('l'),
00509 GETOPT_SHORT_VALUE('p'),
00510 GETOPT_SHORT_VALUE('P'),
00511 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
00512 GETOPT_SHORT_NOVAL('f'),
00513 #endif
00514 #endif
00515 GETOPT_SHORT_VALUE('r'),
00516 GETOPT_SHORT_VALUE('t'),
00517 GETOPT_SHORT_OPTVAL('d'),
00518 GETOPT_SHORT_NOVAL('e'),
00519 GETOPT_SHORT_OPTVAL('g'),
00520 GETOPT_SHORT_VALUE('G'),
00521 GETOPT_SHORT_VALUE('c'),
00522 GETOPT_SHORT_NOVAL('x'),
00523 GETOPT_SHORT_VALUE('q'),
00524 GETOPT_SHORT_NOVAL('h'),
00525 GETOPT_END()
00526 };
00527
00534 int openttd_main(int argc, char *argv[])
00535 {
00536 char *musicdriver = NULL;
00537 char *sounddriver = NULL;
00538 char *videodriver = NULL;
00539 char *blitter = NULL;
00540 char *graphics_set = NULL;
00541 char *sounds_set = NULL;
00542 char *music_set = NULL;
00543 Dimension resolution = {0, 0};
00544
00545 bool save_config = false;
00546 AfterNewGRFScan *scanner = new AfterNewGRFScan(&save_config);
00547 #if defined(ENABLE_NETWORK)
00548 bool dedicated = false;
00549 char *debuglog_conn = NULL;
00550
00551 extern bool _dedicated_forks;
00552 _dedicated_forks = false;
00553 #endif
00554
00555 _game_mode = GM_MENU;
00556 _switch_mode = SM_MENU;
00557 _config_file = NULL;
00558
00559 GetOptData mgo(argc - 1, argv + 1, _options);
00560 int ret = 0;
00561
00562 int i;
00563 while ((i = mgo.GetOpt()) != -1) {
00564 switch (i) {
00565 case 'I': free(graphics_set); graphics_set = strdup(mgo.opt); break;
00566 case 'S': free(sounds_set); sounds_set = strdup(mgo.opt); break;
00567 case 'M': free(music_set); music_set = strdup(mgo.opt); break;
00568 case 'm': free(musicdriver); musicdriver = strdup(mgo.opt); break;
00569 case 's': free(sounddriver); sounddriver = strdup(mgo.opt); break;
00570 case 'v': free(videodriver); videodriver = strdup(mgo.opt); break;
00571 case 'b': free(blitter); blitter = strdup(mgo.opt); break;
00572 #if defined(ENABLE_NETWORK)
00573 case 'D':
00574 free(musicdriver);
00575 free(sounddriver);
00576 free(videodriver);
00577 free(blitter);
00578 musicdriver = strdup("null");
00579 sounddriver = strdup("null");
00580 videodriver = strdup("dedicated");
00581 blitter = strdup("null");
00582 dedicated = true;
00583 SetDebugString("net=6");
00584 if (mgo.opt != NULL) {
00585
00586
00587 const char *temp = NULL;
00588 const char *port = NULL;
00589 ParseConnectionString(&temp, &port, mgo.opt);
00590 if (!StrEmpty(mgo.opt)) scanner->dedicated_host = mgo.opt;
00591 if (port != NULL) scanner->dedicated_port = atoi(port);
00592 }
00593 break;
00594 case 'f': _dedicated_forks = true; break;
00595 case 'n':
00596 scanner->network_conn = mgo.opt;
00597 break;
00598 case 'l':
00599 debuglog_conn = mgo.opt;
00600 break;
00601 case 'p':
00602 scanner->join_server_password = mgo.opt;
00603 break;
00604 case 'P':
00605 scanner->join_company_password = mgo.opt;
00606 break;
00607 #endif
00608 case 'r': ParseResolution(&resolution, mgo.opt); break;
00609 case 't': scanner->startyear = atoi(mgo.opt); break;
00610 case 'd': {
00611 #if defined(WIN32)
00612 CreateConsole();
00613 #endif
00614 if (mgo.opt != NULL) SetDebugString(mgo.opt);
00615 break;
00616 }
00617 case 'e': _switch_mode = (_switch_mode == SM_LOAD_GAME || _switch_mode == SM_LOAD_SCENARIO ? SM_LOAD_SCENARIO : SM_EDITOR); break;
00618 case 'g':
00619 if (mgo.opt != NULL) {
00620 strecpy(_file_to_saveload.name, mgo.opt, lastof(_file_to_saveload.name));
00621 _switch_mode = (_switch_mode == SM_EDITOR || _switch_mode == SM_LOAD_SCENARIO ? SM_LOAD_SCENARIO : SM_LOAD_GAME);
00622 _file_to_saveload.mode = SL_LOAD;
00623
00624
00625 const char *t = strrchr(_file_to_saveload.name, '.');
00626 if (t != NULL) {
00627 FiosType ft = FiosGetSavegameListCallback(SLD_LOAD_GAME, _file_to_saveload.name, t, NULL, NULL);
00628 if (ft != FIOS_TYPE_INVALID) SetFiosType(ft);
00629 }
00630
00631 break;
00632 }
00633
00634 _switch_mode = SM_NEWGAME;
00635
00636 if (scanner->generation_seed == GENERATE_NEW_SEED) {
00637 scanner->generation_seed = InteractiveRandom();
00638 }
00639 break;
00640 case 'q': {
00641 DeterminePaths(argv[0]);
00642 if (StrEmpty(mgo.opt)) {
00643 ret = 1;
00644 goto exit_noshutdown;
00645 }
00646
00647 char title[80];
00648 title[0] = '\0';
00649 FiosGetSavegameListCallback(SLD_LOAD_GAME, mgo.opt, strrchr(mgo.opt, '.'), title, lastof(title));
00650
00651 _load_check_data.Clear();
00652 SaveOrLoadResult res = SaveOrLoad(mgo.opt, SL_LOAD_CHECK, SAVE_DIR, false);
00653 if (res != SL_OK || _load_check_data.HasErrors()) {
00654 fprintf(stderr, "Failed to open savegame\n");
00655 if (_load_check_data.HasErrors()) {
00656 char buf[256];
00657 SetDParamStr(0, _load_check_data.error_data);
00658 GetString(buf, _load_check_data.error, lastof(buf));
00659 fprintf(stderr, "%s\n", buf);
00660 }
00661 goto exit_noshutdown;
00662 }
00663
00664 WriteSavegameInfo(title);
00665
00666 goto exit_noshutdown;
00667 }
00668 case 'G': scanner->generation_seed = atoi(mgo.opt); break;
00669 case 'c': _config_file = strdup(mgo.opt); break;
00670 case 'x': scanner->save_config = false; break;
00671 case 'h':
00672 i = -2;
00673 break;
00674 }
00675 if (i == -2) break;
00676 }
00677
00678 if (i == -2 || mgo.numleft > 0) {
00679
00680
00681
00682
00683
00684 DeterminePaths(argv[0]);
00685 TarScanner::DoScan(TarScanner::BASESET);
00686 BaseGraphics::FindSets();
00687 BaseSounds::FindSets();
00688 BaseMusic::FindSets();
00689 ShowHelp();
00690
00691 goto exit_noshutdown;
00692 }
00693
00694 #if defined(WINCE) && defined(_DEBUG)
00695
00696 SetDebugString("4");
00697 #endif
00698
00699 DeterminePaths(argv[0]);
00700 TarScanner::DoScan(TarScanner::BASESET);
00701
00702 #if defined(ENABLE_NETWORK)
00703 if (dedicated) DEBUG(net, 0, "Starting dedicated version %s", _openttd_revision);
00704 if (_dedicated_forks && !dedicated) _dedicated_forks = false;
00705
00706 #if defined(UNIX) && !defined(__MORPHOS__)
00707
00708 if (_dedicated_forks) DedicatedFork();
00709 #endif
00710 #endif
00711
00712 LoadFromConfig(true);
00713
00714 if (resolution.width != 0) _cur_resolution = resolution;
00715
00716
00717
00718
00719
00720
00721
00722 _cur_resolution.width = ClampU(_cur_resolution.width, 1, UINT16_MAX / 2);
00723 _cur_resolution.height = ClampU(_cur_resolution.height, 1, UINT16_MAX / 2);
00724
00725
00726
00727
00728
00729 _cursor.in_window = true;
00730
00731
00732 InitializeLanguagePacks();
00733
00734
00735 InitFreeType(false);
00736
00737
00738 InitWindowSystem();
00739
00740 BaseGraphics::FindSets();
00741 if (graphics_set == NULL && BaseGraphics::ini_set != NULL) graphics_set = strdup(BaseGraphics::ini_set);
00742 if (!BaseGraphics::SetSet(graphics_set)) {
00743 if (!StrEmpty(graphics_set)) {
00744 BaseGraphics::SetSet(NULL);
00745
00746 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_GRAPHICS_NOT_FOUND);
00747 msg.SetDParamStr(0, graphics_set);
00748 ScheduleErrorMessage(msg);
00749 }
00750 }
00751 free(graphics_set);
00752
00753
00754 GfxInitPalettes();
00755
00756 DEBUG(misc, 1, "Loading blitter...");
00757 if (blitter == NULL && _ini_blitter != NULL) blitter = strdup(_ini_blitter);
00758 _blitter_autodetected = StrEmpty(blitter);
00759
00760 if (!_blitter_autodetected || BaseGraphics::GetUsedSet() == NULL || BaseGraphics::GetUsedSet()->blitter == BLT_8BPP || BlitterFactoryBase::SelectBlitter("32bpp-anim") == NULL) {
00761 if (BlitterFactoryBase::SelectBlitter(blitter) == NULL) {
00762 StrEmpty(blitter) ?
00763 usererror("Failed to autoprobe blitter") :
00764 usererror("Failed to select requested blitter '%s'; does it exist?", blitter);
00765 }
00766 }
00767 free(blitter);
00768
00769 if (videodriver == NULL && _ini_videodriver != NULL) videodriver = strdup(_ini_videodriver);
00770 _video_driver = (VideoDriver*)DriverFactoryBase::SelectDriver(videodriver, Driver::DT_VIDEO);
00771 if (_video_driver == NULL) {
00772 StrEmpty(videodriver) ?
00773 usererror("Failed to autoprobe video driver") :
00774 usererror("Failed to select requested video driver '%s'", videodriver);
00775 }
00776 free(videodriver);
00777
00778
00779 _screen.zoom = ZOOM_LVL_NORMAL;
00780
00781 NetworkStartUp();
00782
00783 #if defined(ENABLE_NETWORK)
00784 if (debuglog_conn != NULL && _network_available) {
00785 const char *not_used = NULL;
00786 const char *port = NULL;
00787 uint16 rport;
00788
00789 rport = NETWORK_DEFAULT_DEBUGLOG_PORT;
00790
00791 ParseConnectionString(¬_used, &port, debuglog_conn);
00792 if (port != NULL) rport = atoi(port);
00793
00794 NetworkStartDebugLog(NetworkAddress(debuglog_conn, rport));
00795 }
00796 #endif
00797
00798 if (!HandleBootstrap()) {
00799 ShutdownGame();
00800
00801 goto exit_bootstrap;
00802 }
00803
00804 _video_driver->ClaimMousePointer();
00805
00806
00807 InitializeScreenshotFormats();
00808
00809 BaseSounds::FindSets();
00810 if (sounds_set == NULL && BaseSounds::ini_set != NULL) sounds_set = strdup(BaseSounds::ini_set);
00811 if (!BaseSounds::SetSet(sounds_set)) {
00812 if (StrEmpty(sounds_set) || !BaseSounds::SetSet(NULL)) {
00813 usererror("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 4.1 of readme.txt.");
00814 } else {
00815 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_SOUNDS_NOT_FOUND);
00816 msg.SetDParamStr(0, sounds_set);
00817 ScheduleErrorMessage(msg);
00818 }
00819 }
00820 free(sounds_set);
00821
00822 BaseMusic::FindSets();
00823 if (music_set == NULL && BaseMusic::ini_set != NULL) music_set = strdup(BaseMusic::ini_set);
00824 if (!BaseMusic::SetSet(music_set)) {
00825 if (StrEmpty(music_set) || !BaseMusic::SetSet(NULL)) {
00826 usererror("Failed to find a music set. Please acquire a music set for OpenTTD. See section 4.1 of readme.txt.");
00827 } else {
00828 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_MUSIC_NOT_FOUND);
00829 msg.SetDParamStr(0, music_set);
00830 ScheduleErrorMessage(msg);
00831 }
00832 }
00833 free(music_set);
00834
00835 if (sounddriver == NULL && _ini_sounddriver != NULL) sounddriver = strdup(_ini_sounddriver);
00836 _sound_driver = (SoundDriver*)DriverFactoryBase::SelectDriver(sounddriver, Driver::DT_SOUND);
00837 if (_sound_driver == NULL) {
00838 StrEmpty(sounddriver) ?
00839 usererror("Failed to autoprobe sound driver") :
00840 usererror("Failed to select requested sound driver '%s'", sounddriver);
00841 }
00842 free(sounddriver);
00843
00844 if (musicdriver == NULL && _ini_musicdriver != NULL) musicdriver = strdup(_ini_musicdriver);
00845 _music_driver = (MusicDriver*)DriverFactoryBase::SelectDriver(musicdriver, Driver::DT_MUSIC);
00846 if (_music_driver == NULL) {
00847 StrEmpty(musicdriver) ?
00848 usererror("Failed to autoprobe music driver") :
00849 usererror("Failed to select requested music driver '%s'", musicdriver);
00850 }
00851 free(musicdriver);
00852
00853
00854 _modal_progress_paint_mutex->BeginCritical();
00855 _modal_progress_work_mutex->BeginCritical();
00856
00857 GenerateWorld(GWM_EMPTY, 64, 64);
00858 WaitTillGeneratedWorld();
00859
00860 LoadIntroGame(false);
00861
00862 CheckForMissingGlyphs();
00863
00864
00865 ScanNewGRFFiles(scanner);
00866 scanner = NULL;
00867
00868 _video_driver->MainLoop();
00869
00870 WaitTillSaved();
00871
00872
00873 if (save_config) {
00874 SaveToConfig();
00875 SaveHotkeysToConfig();
00876 WindowDesc::SaveToConfig();
00877 SaveToHighScore();
00878 }
00879
00880
00881 ShutdownGame();
00882 goto exit_normal;
00883
00884 exit_noshutdown:
00885
00886 free(graphics_set);
00887 free(videodriver);
00888 free(blitter);
00889
00890 exit_bootstrap:
00891
00892 free(sounds_set);
00893 free(music_set);
00894 free(musicdriver);
00895 free(sounddriver);
00896
00897 exit_normal:
00898 free(BaseGraphics::ini_set);
00899 free(BaseSounds::ini_set);
00900 free(BaseMusic::ini_set);
00901
00902 free(_ini_musicdriver);
00903 free(_ini_sounddriver);
00904 free(_ini_videodriver);
00905 free(_ini_blitter);
00906
00907 delete scanner;
00908
00909 #ifdef ENABLE_NETWORK
00910 extern FILE *_log_fd;
00911 if (_log_fd != NULL) {
00912 fclose(_log_fd);
00913 }
00914 #endif
00915
00916 return ret;
00917 }
00918
00919 void HandleExitGameRequest()
00920 {
00921 if (_game_mode == GM_MENU || _game_mode == GM_BOOTSTRAP) {
00922 _exit_game = true;
00923 } else if (_settings_client.gui.autosave_on_exit) {
00924 DoExitSave();
00925 _exit_game = true;
00926 } else {
00927 AskExitGame();
00928 }
00929 }
00930
00931 static void MakeNewGameDone()
00932 {
00933 SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
00934
00935
00936 if (!_video_driver->HasGUI()) {
00937 SetLocalCompany(COMPANY_SPECTATOR);
00938 if (_settings_client.gui.pause_on_newgame) DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
00939 IConsoleCmdExec("exec scripts/game_start.scr 0");
00940 return;
00941 }
00942
00943
00944 DoStartupNewCompany(false);
00945
00946 Company *c = Company::Get(COMPANY_FIRST);
00947 c->settings = _settings_client.company;
00948
00949 IConsoleCmdExec("exec scripts/game_start.scr 0");
00950
00951 SetLocalCompany(COMPANY_FIRST);
00952
00953 InitializeRailGUI();
00954
00955 #ifdef ENABLE_NETWORK
00956
00957
00958 if (_network_server && !StrEmpty(_settings_client.network.default_company_pass)) {
00959 NetworkChangeCompanyPassword(_local_company, _settings_client.network.default_company_pass);
00960 }
00961 #endif
00962
00963 if (_settings_client.gui.pause_on_newgame) DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
00964
00965 CheckEngines();
00966 MarkWholeScreenDirty();
00967 }
00968
00969 static void MakeNewGame(bool from_heightmap, bool reset_settings)
00970 {
00971 _game_mode = GM_NORMAL;
00972
00973 ResetGRFConfig(true);
00974
00975 GenerateWorldSetCallback(&MakeNewGameDone);
00976 GenerateWorld(from_heightmap ? GWM_HEIGHTMAP : GWM_NEWGAME, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y, reset_settings);
00977 }
00978
00979 static void MakeNewEditorWorldDone()
00980 {
00981 SetLocalCompany(OWNER_NONE);
00982 }
00983
00984 static void MakeNewEditorWorld()
00985 {
00986 _game_mode = GM_EDITOR;
00987
00988 ResetGRFConfig(true);
00989
00990 GenerateWorldSetCallback(&MakeNewEditorWorldDone);
00991 GenerateWorld(GWM_EMPTY, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
00992 }
00993
01004 bool SafeLoad(const char *filename, int mode, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = NULL)
01005 {
01006 assert(mode == SL_LOAD || (lf == NULL && mode == SL_OLD_LOAD));
01007 GameMode ogm = _game_mode;
01008
01009 _game_mode = newgm;
01010
01011 switch (lf == NULL ? SaveOrLoad(filename, mode, subdir) : LoadWithFilter(lf)) {
01012 case SL_OK: return true;
01013
01014 case SL_REINIT:
01015 #ifdef ENABLE_NETWORK
01016 if (_network_dedicated) {
01017
01018
01019
01020
01021
01022
01023 DEBUG(net, 0, "Loading game failed, so a new (random) game will be started!");
01024 MakeNewGame(false, true);
01025 return false;
01026 }
01027 if (_network_server) {
01028
01029 NetworkDisconnect();
01030 }
01031 #endif
01032
01033 switch (ogm) {
01034 default:
01035 case GM_MENU: LoadIntroGame(); break;
01036 case GM_EDITOR: MakeNewEditorWorld(); break;
01037 }
01038 return false;
01039
01040 default:
01041 _game_mode = ogm;
01042 return false;
01043 }
01044 }
01045
01046 void SwitchToMode(SwitchMode new_mode)
01047 {
01048 #ifdef ENABLE_NETWORK
01049
01050 if (new_mode != SM_SAVE_GAME) {
01051
01052 if (_networking) {
01053 if (_network_server && (new_mode == SM_LOAD_GAME || new_mode == SM_NEWGAME || new_mode == SM_RESTARTGAME)) {
01054 NetworkReboot();
01055 } else {
01056 NetworkDisconnect();
01057 }
01058 }
01059
01060
01061 if (_is_network_server) {
01062
01063 if (new_mode != SM_MENU) {
01064
01065 if (_settings_client.network.reload_cfg) {
01066 LoadFromConfig();
01067 MakeNewgameSettingsLive();
01068 ResetGRFConfig(false);
01069 }
01070 NetworkServerStart();
01071 } else {
01072
01073 _is_network_server = false;
01074 }
01075 }
01076 }
01077 #endif
01078
01079 if (new_mode != SM_SAVE_GAME) AI::KillAll();
01080
01081 switch (new_mode) {
01082 case SM_EDITOR:
01083 MakeNewEditorWorld();
01084 break;
01085
01086 case SM_RESTARTGAME:
01087 case SM_NEWGAME:
01088 #ifdef ENABLE_NETWORK
01089 if (_network_server) {
01090 snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "Random Map");
01091 }
01092 #endif
01093 MakeNewGame(false, new_mode == SM_NEWGAME);
01094 break;
01095
01096 case SM_LOAD_GAME: {
01097 ResetGRFConfig(true);
01098 ResetWindowSystem();
01099
01100 if (!SafeLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_NORMAL, NO_DIRECTORY)) {
01101 SetDParamStr(0, GetSaveLoadErrorString());
01102 ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
01103 } else {
01104 if (_saveload_mode == SLD_LOAD_SCENARIO) {
01105
01106 EngineOverrideManager::ResetToCurrentNewGRFConfig();
01107 }
01108
01109
01110 SetLocalCompany(_network_dedicated ? COMPANY_SPECTATOR : COMPANY_FIRST);
01111
01112 IConsoleCmdExec("exec scripts/game_start.scr 0");
01113
01114 DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
01115 #ifdef ENABLE_NETWORK
01116 if (_network_server) {
01117 snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Loaded game)", _file_to_saveload.title);
01118 }
01119 #endif
01120 }
01121 break;
01122 }
01123
01124 case SM_START_HEIGHTMAP:
01125 #ifdef ENABLE_NETWORK
01126 if (_network_server) {
01127 snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Heightmap)", _file_to_saveload.title);
01128 }
01129 #endif
01130 MakeNewGame(true, true);
01131 break;
01132
01133 case SM_LOAD_HEIGHTMAP:
01134 SetLocalCompany(OWNER_NONE);
01135
01136 GenerateWorld(GWM_HEIGHTMAP, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
01137 MarkWholeScreenDirty();
01138 break;
01139
01140 case SM_LOAD_SCENARIO: {
01141 if (SafeLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_EDITOR, NO_DIRECTORY)) {
01142 SetLocalCompany(OWNER_NONE);
01143 _settings_newgame.game_creation.starting_year = _cur_year;
01144
01145 DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
01146 } else {
01147 SetDParamStr(0, GetSaveLoadErrorString());
01148 ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
01149 }
01150 break;
01151 }
01152
01153 case SM_MENU:
01154 LoadIntroGame();
01155 if (BaseSounds::ini_set == NULL && BaseSounds::GetUsedSet()->fallback) {
01156 ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET, INVALID_STRING_ID, WL_CRITICAL);
01157 BaseSounds::ini_set = strdup(BaseSounds::GetUsedSet()->name);
01158 }
01159 break;
01160
01161 case SM_SAVE_GAME:
01162
01163 if (SaveOrLoad(_file_to_saveload.name, SL_SAVE, NO_DIRECTORY) != SL_OK) {
01164 SetDParamStr(0, GetSaveLoadErrorString());
01165 ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
01166 } else {
01167 DeleteWindowById(WC_SAVELOAD, 0);
01168 }
01169 break;
01170
01171 case SM_SAVE_HEIGHTMAP:
01172 MakeHeightmapScreenshot(_file_to_saveload.name);
01173 DeleteWindowById(WC_SAVELOAD, 0);
01174 break;
01175
01176 case SM_GENRANDLAND:
01177 SetLocalCompany(OWNER_NONE);
01178 GenerateWorld(GWM_RANDOM, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
01179
01180 MarkWholeScreenDirty();
01181 break;
01182
01183 default: NOT_REACHED();
01184 }
01185 }
01186
01187
01194 static void CheckCaches()
01195 {
01196
01197
01198 if (_debug_desync_level <= 1) return;
01199
01200
01201 SmallVector<TownCache, 4> old_town_caches;
01202 Town *t;
01203 FOR_ALL_TOWNS(t) {
01204 MemCpyT(old_town_caches.Append(), &t->cache);
01205 }
01206
01207 extern void RebuildTownCaches();
01208 RebuildTownCaches();
01209 RebuildSubsidisedSourceAndDestinationCache();
01210
01211 uint i = 0;
01212 FOR_ALL_TOWNS(t) {
01213 if (MemCmpT(old_town_caches.Get(i), &t->cache) != 0) {
01214 DEBUG(desync, 2, "town cache mismatch: town %i", (int)t->index);
01215 }
01216 i++;
01217 }
01218
01219
01220 SmallVector<CompanyInfrastructure, 4> old_infrastructure;
01221 Company *c;
01222 FOR_ALL_COMPANIES(c) MemCpyT(old_infrastructure.Append(), &c->infrastructure);
01223
01224 extern void AfterLoadCompanyStats();
01225 AfterLoadCompanyStats();
01226
01227 i = 0;
01228 FOR_ALL_COMPANIES(c) {
01229 if (MemCmpT(old_infrastructure.Get(i), &c->infrastructure) != 0) {
01230 DEBUG(desync, 2, "infrastructure cache mismatch: company %i", (int)c->index);
01231 }
01232 i++;
01233 }
01234
01235
01236 const RoadStop *rs;
01237 FOR_ALL_ROADSTOPS(rs) {
01238 if (IsStandardRoadStopTile(rs->xy)) continue;
01239
01240 assert(rs->GetEntry(DIAGDIR_NE) != rs->GetEntry(DIAGDIR_NW));
01241 rs->GetEntry(DIAGDIR_NE)->CheckIntegrity(rs);
01242 rs->GetEntry(DIAGDIR_NW)->CheckIntegrity(rs);
01243 }
01244
01245 Vehicle *v;
01246 FOR_ALL_VEHICLES(v) {
01247 extern void FillNewGRFVehicleCache(const Vehicle *v);
01248 if (v != v->First() || v->vehstatus & VS_CRASHED || !v->IsPrimaryVehicle()) continue;
01249
01250 uint length = 0;
01251 for (const Vehicle *u = v; u != NULL; u = u->Next()) length++;
01252
01253 NewGRFCache *grf_cache = CallocT<NewGRFCache>(length);
01254 VehicleCache *veh_cache = CallocT<VehicleCache>(length);
01255 GroundVehicleCache *gro_cache = CallocT<GroundVehicleCache>(length);
01256 TrainCache *tra_cache = CallocT<TrainCache>(length);
01257
01258 length = 0;
01259 for (const Vehicle *u = v; u != NULL; u = u->Next()) {
01260 FillNewGRFVehicleCache(u);
01261 grf_cache[length] = u->grf_cache;
01262 veh_cache[length] = u->vcache;
01263 switch (u->type) {
01264 case VEH_TRAIN:
01265 gro_cache[length] = Train::From(u)->gcache;
01266 tra_cache[length] = Train::From(u)->tcache;
01267 break;
01268 case VEH_ROAD:
01269 gro_cache[length] = RoadVehicle::From(u)->gcache;
01270 break;
01271 default:
01272 break;
01273 }
01274 length++;
01275 }
01276
01277 switch (v->type) {
01278 case VEH_TRAIN: Train::From(v)->ConsistChanged(true); break;
01279 case VEH_ROAD: RoadVehUpdateCache(RoadVehicle::From(v)); break;
01280 case VEH_AIRCRAFT: UpdateAircraftCache(Aircraft::From(v)); break;
01281 case VEH_SHIP: Ship::From(v)->UpdateCache(); break;
01282 default: break;
01283 }
01284
01285 length = 0;
01286 for (const Vehicle *u = v; u != NULL; u = u->Next()) {
01287 FillNewGRFVehicleCache(u);
01288 if (memcmp(&grf_cache[length], &u->grf_cache, sizeof(NewGRFCache)) != 0) {
01289 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);
01290 }
01291 if (memcmp(&veh_cache[length], &u->vcache, sizeof(VehicleCache)) != 0) {
01292 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);
01293 }
01294 switch (u->type) {
01295 case VEH_TRAIN:
01296 if (memcmp(&gro_cache[length], &Train::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
01297 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);
01298 }
01299 if (memcmp(&tra_cache[length], &Train::From(u)->tcache, sizeof(TrainCache)) != 0) {
01300 DEBUG(desync, 2, "train cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v->index, (int)v->owner, v->unitnumber, length);
01301 }
01302 break;
01303 case VEH_ROAD:
01304 if (memcmp(&gro_cache[length], &RoadVehicle::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
01305 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);
01306 }
01307 break;
01308 default:
01309 break;
01310 }
01311 length++;
01312 }
01313
01314 free(grf_cache);
01315 free(veh_cache);
01316 free(gro_cache);
01317 free(tra_cache);
01318 }
01319
01320
01321 FOR_ALL_VEHICLES(v) {
01322 byte buff[sizeof(VehicleCargoList)];
01323 memcpy(buff, &v->cargo, sizeof(VehicleCargoList));
01324 v->cargo.InvalidateCache();
01325 assert(memcmp(&v->cargo, buff, sizeof(VehicleCargoList)) == 0);
01326 }
01327
01328 Station *st;
01329 FOR_ALL_STATIONS(st) {
01330 for (CargoID c = 0; c < NUM_CARGO; c++) {
01331 byte buff[sizeof(StationCargoList)];
01332 memcpy(buff, &st->goods[c].cargo, sizeof(StationCargoList));
01333 st->goods[c].cargo.InvalidateCache();
01334 assert(memcmp(&st->goods[c].cargo, buff, sizeof(StationCargoList)) == 0);
01335 }
01336 }
01337 }
01338
01344 void StateGameLoop()
01345 {
01346
01347 if (_pause_mode != PM_UNPAUSED) {
01348 UpdateLandscapingLimits();
01349 Game::GameLoop();
01350 CallWindowTickEvent();
01351 return;
01352 }
01353 if (HasModalProgress()) return;
01354
01355 ClearPersistentStorageChanges(false);
01356
01357 Layouter::ReduceLineCache();
01358
01359 if (_game_mode == GM_EDITOR) {
01360 RunTileLoop();
01361 CallVehicleTicks();
01362 CallLandscapeTick();
01363 ClearPersistentStorageChanges(true);
01364 UpdateLandscapingLimits();
01365
01366 CallWindowTickEvent();
01367 NewsLoop();
01368 } else {
01369 if (_debug_desync_level > 2 && _date_fract == 0 && (_date & 0x1F) == 0) {
01370
01371 char name[MAX_PATH];
01372 snprintf(name, lengthof(name), "dmp_cmds_%08x_%08x.sav", _settings_game.game_creation.generation_seed, _date);
01373 SaveOrLoad(name, SL_SAVE, AUTOSAVE_DIR, false);
01374 }
01375
01376 CheckCaches();
01377
01378
01379
01380 Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
01381
01382 AnimateAnimatedTiles();
01383 IncreaseDate();
01384 RunTileLoop();
01385 CallVehicleTicks();
01386 CallLandscapeTick();
01387 ClearPersistentStorageChanges(true);
01388
01389 AI::GameLoop();
01390 Game::GameLoop();
01391 UpdateLandscapingLimits();
01392
01393 CallWindowTickEvent();
01394 NewsLoop();
01395 cur_company.Restore();
01396 }
01397
01398 assert(IsLocalCompany());
01399 }
01400
01405 static void DoAutosave()
01406 {
01407 char buf[MAX_PATH];
01408
01409 #if defined(PSP)
01410
01411 if (_networking) return;
01412 #endif
01413
01414 if (_settings_client.gui.keep_all_autosave) {
01415 GenerateDefaultSaveName(buf, lastof(buf));
01416 strecat(buf, ".sav", lastof(buf));
01417 } else {
01418 static int _autosave_ctr = 0;
01419
01420
01421 snprintf(buf, sizeof(buf), "autosave%d.sav", _autosave_ctr);
01422
01423 if (++_autosave_ctr >= _settings_client.gui.max_num_autosaves) _autosave_ctr = 0;
01424 }
01425
01426 DEBUG(sl, 2, "Autosaving to '%s'", buf);
01427 if (SaveOrLoad(buf, SL_SAVE, AUTOSAVE_DIR) != SL_OK) {
01428 ShowErrorMessage(STR_ERROR_AUTOSAVE_FAILED, INVALID_STRING_ID, WL_ERROR);
01429 }
01430 }
01431
01432 void GameLoop()
01433 {
01434 if (_game_mode == GM_BOOTSTRAP) {
01435 #ifdef ENABLE_NETWORK
01436
01437 if (_network_available) NetworkBackgroundLoop();
01438 #endif
01439 InputLoop();
01440 return;
01441 }
01442
01443 ProcessAsyncSaveFinish();
01444
01445
01446 if (_do_autosave) {
01447 _do_autosave = false;
01448 DoAutosave();
01449 SetWindowDirty(WC_STATUS_BAR, 0);
01450 }
01451
01452
01453 if (_switch_mode != SM_NONE && !HasModalProgress()) {
01454 SwitchToMode(_switch_mode);
01455 _switch_mode = SM_NONE;
01456 }
01457
01458 IncreaseSpriteLRU();
01459 InteractiveRandom();
01460
01461 extern int _caret_timer;
01462 _caret_timer += 3;
01463 CursorTick();
01464
01465 #ifdef ENABLE_NETWORK
01466
01467 if (_network_available) NetworkBackgroundLoop();
01468
01469 if (_networking && !HasModalProgress()) {
01470
01471 NetworkGameLoop();
01472 } else {
01473 if (_network_reconnect > 0 && --_network_reconnect == 0) {
01474
01475
01476 NetworkClientConnectGame(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port), COMPANY_SPECTATOR);
01477 }
01478
01479 StateGameLoop();
01480 }
01481
01482
01483 static uint check_message = 0;
01484 if (++check_message > 1000 / MILLISECONDS_PER_TICK) {
01485 check_message = 0;
01486 NetworkChatMessageLoop();
01487 }
01488 #else
01489 StateGameLoop();
01490 #endif
01491
01492 if (!_pause_mode && HasBit(_display_opt, DO_FULL_ANIMATION)) DoPaletteAnimations();
01493
01494 if (!_pause_mode || _game_mode == GM_EDITOR || _settings_game.construction.command_pause_level > CMDPL_NO_CONSTRUCTION) MoveAllTextEffects();
01495
01496 InputLoop();
01497
01498 _sound_driver->MainLoop();
01499 MusicLoop();
01500 }