Codechange: Add support for verbose asserts
[openttd-github.git] / src / openttd.cpp
blob33f65314d1881df866aca3943d2aad3a9134da98
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /** @file openttd.cpp Functions related to starting OpenTTD. */
10 #include "stdafx.h"
12 #include "blitter/factory.hpp"
13 #include "sound/sound_driver.hpp"
14 #include "music/music_driver.hpp"
15 #include "video/video_driver.hpp"
17 #include "fontcache.h"
18 #include "error.h"
19 #include "gui.h"
21 #include "base_media_base.h"
22 #include "saveload/saveload.h"
23 #include "company_func.h"
24 #include "command_func.h"
25 #include "news_func.h"
26 #include "fios.h"
27 #include "aircraft.h"
28 #include "roadveh.h"
29 #include "train.h"
30 #include "ship.h"
31 #include "console_func.h"
32 #include "screenshot.h"
33 #include "network/network.h"
34 #include "network/network_func.h"
35 #include "ai/ai.hpp"
36 #include "ai/ai_config.hpp"
37 #include "settings_func.h"
38 #include "genworld.h"
39 #include "progress.h"
40 #include "strings_func.h"
41 #include "date_func.h"
42 #include "vehicle_func.h"
43 #include "gamelog.h"
44 #include "animated_tile_func.h"
45 #include "roadstop_base.h"
46 #include "elrail_func.h"
47 #include "rev.h"
48 #include "highscore.h"
49 #include "station_base.h"
50 #include "crashlog.h"
51 #include "engine_func.h"
52 #include "core/random_func.hpp"
53 #include "rail_gui.h"
54 #include "road_gui.h"
55 #include "core/backup_type.hpp"
56 #include "hotkeys.h"
57 #include "newgrf.h"
58 #include "misc/getoptdata.h"
59 #include "game/game.hpp"
60 #include "game/game_config.hpp"
61 #include "town.h"
62 #include "subsidy_func.h"
63 #include "gfx_layout.h"
64 #include "viewport_func.h"
65 #include "viewport_sprite_sorter.h"
66 #include "framerate_type.h"
67 #include "industry.h"
69 #include "linkgraph/linkgraphschedule.h"
71 #include <stdarg.h>
72 #include <system_error>
74 #include "safeguards.h"
76 #ifdef __EMSCRIPTEN__
77 # include <emscripten.h>
78 # include <emscripten/html5.h>
79 #endif
81 void CallLandscapeTick();
82 void IncreaseDate();
83 void DoPaletteAnimations();
84 void MusicLoop();
85 void ResetMusic();
86 void CallWindowGameTickEvent();
87 bool HandleBootstrap();
89 extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
90 extern void ShowOSErrorBox(const char *buf, bool system);
91 extern char *_config_file;
93 bool _save_config = false;
95 /**
96 * Error handling for fatal user errors.
97 * @param s the string to print.
98 * @note Does NEVER return.
100 void CDECL usererror(const char *s, ...)
102 va_list va;
103 char buf[512];
105 va_start(va, s);
106 vseprintf(buf, lastof(buf), s, va);
107 va_end(va);
109 ShowOSErrorBox(buf, false);
110 if (VideoDriver::GetInstance() != nullptr) VideoDriver::GetInstance()->Stop();
112 #ifdef __EMSCRIPTEN__
113 emscripten_exit_pointerlock();
114 /* In effect, the game ends here. As emscripten_set_main_loop() caused
115 * the stack to be unwound, the code after MainLoop() in
116 * openttd_main() is never executed. */
117 EM_ASM(if (window["openttd_syncfs"]) openttd_syncfs());
118 EM_ASM(if (window["openttd_abort"]) openttd_abort());
119 #endif
121 exit(1);
125 * Error handling for fatal non-user errors.
126 * @param s the string to print.
127 * @note Does NEVER return.
129 void CDECL error(const char *s, ...)
131 va_list va;
132 char buf[2048];
134 va_start(va, s);
135 vseprintf(buf, lastof(buf), s, va);
136 va_end(va);
138 if (VideoDriver::GetInstance() == nullptr || VideoDriver::GetInstance()->HasGUI()) {
139 ShowOSErrorBox(buf, true);
142 /* Set the error message for the crash log and then invoke it. */
143 CrashLog::SetErrorMessage(buf);
144 abort();
148 * Shows some information on the console/a popup box depending on the OS.
149 * @param str the text to show.
151 void CDECL ShowInfoF(const char *str, ...)
153 va_list va;
154 char buf[1024];
155 va_start(va, str);
156 vseprintf(buf, lastof(buf), str, va);
157 va_end(va);
158 ShowInfo(buf);
162 * Show the help message when someone passed a wrong parameter.
164 static void ShowHelp()
166 char buf[8192];
167 char *p = buf;
169 p += seprintf(p, lastof(buf), "OpenTTD %s\n", _openttd_revision);
170 p = strecpy(p,
171 "\n"
172 "\n"
173 "Command line options:\n"
174 " -v drv = Set video driver (see below)\n"
175 " -s drv = Set sound driver (see below) (param bufsize,hz)\n"
176 " -m drv = Set music driver (see below)\n"
177 " -b drv = Set the blitter to use (see below)\n"
178 " -r res = Set resolution (for instance 800x600)\n"
179 " -h = Display this help text\n"
180 " -t year = Set starting year\n"
181 " -d [[fac=]lvl[,...]]= Debug mode\n"
182 " -e = Start Editor\n"
183 " -g [savegame] = Start new/save game immediately\n"
184 " -G seed = Set random seed\n"
185 " -n [ip:port#company]= Join network game\n"
186 " -p password = Password to join server\n"
187 " -P password = Password to join company\n"
188 " -D [ip][:port] = Start dedicated server\n"
189 " -l ip[:port] = Redirect DEBUG()\n"
190 #if !defined(_WIN32)
191 " -f = Fork into the background (dedicated only)\n"
192 #endif
193 " -I graphics_set = Force the graphics set (see below)\n"
194 " -S sounds_set = Force the sounds set (see below)\n"
195 " -M music_set = Force the music set (see below)\n"
196 " -c config_file = Use 'config_file' instead of 'openttd.cfg'\n"
197 " -x = Never save configuration changes to disk\n"
198 " -q savegame = Write some information about the savegame and exit\n"
199 "\n",
200 lastof(buf)
203 /* List the graphics packs */
204 p = BaseGraphics::GetSetsList(p, lastof(buf));
206 /* List the sounds packs */
207 p = BaseSounds::GetSetsList(p, lastof(buf));
209 /* List the music packs */
210 p = BaseMusic::GetSetsList(p, lastof(buf));
212 /* List the drivers */
213 p = DriverFactoryBase::GetDriversInfo(p, lastof(buf));
215 /* List the blitters */
216 p = BlitterFactory::GetBlittersInfo(p, lastof(buf));
218 /* List the debug facilities. */
219 p = DumpDebugFacilityNames(p, lastof(buf));
221 /* We need to initialize the AI, so it finds the AIs */
222 AI::Initialize();
223 p = AI::GetConsoleList(p, lastof(buf), true);
224 AI::Uninitialize(true);
226 /* We need to initialize the GameScript, so it finds the GSs */
227 Game::Initialize();
228 p = Game::GetConsoleList(p, lastof(buf), true);
229 Game::Uninitialize(true);
231 /* ShowInfo put output to stderr, but version information should go
232 * to stdout; this is the only exception */
233 #if !defined(_WIN32)
234 printf("%s\n", buf);
235 #else
236 ShowInfo(buf);
237 #endif
240 static void WriteSavegameInfo(const char *name)
242 extern SaveLoadVersion _sl_version;
243 uint32 last_ottd_rev = 0;
244 byte ever_modified = 0;
245 bool removed_newgrfs = false;
247 GamelogInfo(_load_check_data.gamelog_action, _load_check_data.gamelog_actions, &last_ottd_rev, &ever_modified, &removed_newgrfs);
249 char buf[8192];
250 char *p = buf;
251 p += seprintf(p, lastof(buf), "Name: %s\n", name);
252 p += seprintf(p, lastof(buf), "Savegame ver: %d\n", _sl_version);
253 p += seprintf(p, lastof(buf), "NewGRF ver: 0x%08X\n", last_ottd_rev);
254 p += seprintf(p, lastof(buf), "Modified: %d\n", ever_modified);
256 if (removed_newgrfs) {
257 p += seprintf(p, lastof(buf), "NewGRFs have been removed\n");
260 p = strecpy(p, "NewGRFs:\n", lastof(buf));
261 if (_load_check_data.HasNewGrfs()) {
262 for (GRFConfig *c = _load_check_data.grfconfig; c != nullptr; c = c->next) {
263 char md5sum[33];
264 md5sumToString(md5sum, lastof(md5sum), HasBit(c->flags, GCF_COMPATIBLE) ? c->original_md5sum : c->ident.md5sum);
265 p += seprintf(p, lastof(buf), "%08X %s %s\n", c->ident.grfid, md5sum, c->filename);
269 /* ShowInfo put output to stderr, but version information should go
270 * to stdout; this is the only exception */
271 #if !defined(_WIN32)
272 printf("%s\n", buf);
273 #else
274 ShowInfo(buf);
275 #endif
280 * Extract the resolution from the given string and store
281 * it in the 'res' parameter.
282 * @param res variable to store the resolution in.
283 * @param s the string to decompose.
285 static void ParseResolution(Dimension *res, const char *s)
287 const char *t = strchr(s, 'x');
288 if (t == nullptr) {
289 ShowInfoF("Invalid resolution '%s'", s);
290 return;
293 res->width = max(strtoul(s, nullptr, 0), 64UL);
294 res->height = max(strtoul(t + 1, nullptr, 0), 64UL);
299 * Uninitializes drivers, frees allocated memory, cleans pools, ...
300 * Generally, prepares the game for shutting down
302 static void ShutdownGame()
304 IConsoleFree();
306 if (_network_available) NetworkShutDown(); // Shut down the network and close any open connections
308 DriverFactoryBase::ShutdownDrivers();
310 UnInitWindowSystem();
312 /* stop the scripts */
313 AI::Uninitialize(false);
314 Game::Uninitialize(false);
316 /* Uninitialize variables that are allocated dynamically */
317 GamelogReset();
319 free(_config_file);
321 LinkGraphSchedule::Clear();
322 PoolBase::Clean(PT_ALL);
324 /* No NewGRFs were loaded when it was still bootstrapping. */
325 if (_game_mode != GM_BOOTSTRAP) ResetNewGRFData();
327 /* Close all and any open filehandles */
328 FioCloseAll();
330 UninitFreeType();
334 * Load the introduction game.
335 * @param load_newgrfs Whether to load the NewGRFs or not.
337 static void LoadIntroGame(bool load_newgrfs = true)
339 _game_mode = GM_MENU;
341 if (load_newgrfs) ResetGRFConfig(false);
343 /* Setup main window */
344 ResetWindowSystem();
345 SetupColoursAndInitialWindow();
347 /* Load the default opening screen savegame */
348 if (SaveOrLoad("opntitle.dat", SLO_LOAD, DFT_GAME_FILE, BASESET_DIR) != SL_OK) {
349 GenerateWorld(GWM_EMPTY, 64, 64); // if failed loading, make empty world.
350 WaitTillGeneratedWorld();
351 SetLocalCompany(COMPANY_SPECTATOR);
352 } else {
353 SetLocalCompany(COMPANY_FIRST);
356 FixTitleGameZoom();
357 _pause_mode = PM_UNPAUSED;
358 _cursor.fix_at = false;
360 CheckForMissingGlyphs();
362 MusicLoop(); // ensure music is correct
365 void MakeNewgameSettingsLive()
367 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
368 if (_settings_game.ai_config[c] != nullptr) {
369 delete _settings_game.ai_config[c];
372 if (_settings_game.game_config != nullptr) {
373 delete _settings_game.game_config;
376 /* Copy newgame settings to active settings.
377 * Also initialise old settings needed for savegame conversion. */
378 _settings_game = _settings_newgame;
379 _old_vds = _settings_client.company.vehicle;
381 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
382 _settings_game.ai_config[c] = nullptr;
383 if (_settings_newgame.ai_config[c] != nullptr) {
384 _settings_game.ai_config[c] = new AIConfig(_settings_newgame.ai_config[c]);
385 if (!AIConfig::GetConfig(c, AIConfig::SSS_FORCE_GAME)->HasScript()) {
386 AIConfig::GetConfig(c, AIConfig::SSS_FORCE_GAME)->Change(nullptr);
390 _settings_game.game_config = nullptr;
391 if (_settings_newgame.game_config != nullptr) {
392 _settings_game.game_config = new GameConfig(_settings_newgame.game_config);
396 void OpenBrowser(const char *url)
398 /* Make sure we only accept urls that are sure to open a browser. */
399 if (strstr(url, "http://") != url && strstr(url, "https://") != url) return;
401 extern void OSOpenBrowser(const char *url);
402 OSOpenBrowser(url);
405 /** Callback structure of statements to be executed after the NewGRF scan. */
406 struct AfterNewGRFScan : NewGRFScanCallback {
407 Year startyear; ///< The start year.
408 uint32 generation_seed; ///< Seed for the new game.
409 char *dedicated_host; ///< Hostname for the dedicated server.
410 uint16 dedicated_port; ///< Port for the dedicated server.
411 char *network_conn; ///< Information about the server to connect to, or nullptr.
412 const char *join_server_password; ///< The password to join the server with.
413 const char *join_company_password; ///< The password to join the company with.
414 bool save_config; ///< The save config setting.
417 * Create a new callback.
419 AfterNewGRFScan() :
420 startyear(INVALID_YEAR), generation_seed(GENERATE_NEW_SEED),
421 dedicated_host(nullptr), dedicated_port(0), network_conn(nullptr),
422 join_server_password(nullptr), join_company_password(nullptr),
423 save_config(true)
425 /* Visual C++ 2015 fails compiling this line (AfterNewGRFScan::generation_seed undefined symbol)
426 * if it's placed outside a member function, directly in the struct body. */
427 assert_compile(sizeof(generation_seed) == sizeof(_settings_game.game_creation.generation_seed));
430 virtual void OnNewGRFsScanned()
432 ResetGRFConfig(false);
434 TarScanner::DoScan(TarScanner::SCENARIO);
436 AI::Initialize();
437 Game::Initialize();
439 /* We want the new (correct) NewGRF count to survive the loading. */
440 uint last_newgrf_count = _settings_client.gui.last_newgrf_count;
441 LoadFromConfig();
442 _settings_client.gui.last_newgrf_count = last_newgrf_count;
443 /* Since the default for the palette might have changed due to
444 * reading the configuration file, recalculate that now. */
445 UpdateNewGRFConfigPalette();
447 Game::Uninitialize(true);
448 AI::Uninitialize(true);
449 LoadFromHighScore();
450 LoadHotkeysFromConfig();
451 WindowDesc::LoadFromConfig();
453 /* We have loaded the config, so we may possibly save it. */
454 _save_config = save_config;
456 /* restore saved music volume */
457 MusicDriver::GetInstance()->SetVolume(_settings_client.music.music_vol);
459 if (startyear != INVALID_YEAR) _settings_newgame.game_creation.starting_year = startyear;
460 if (generation_seed != GENERATE_NEW_SEED) _settings_newgame.game_creation.generation_seed = generation_seed;
462 if (dedicated_host != nullptr) {
463 _network_bind_list.clear();
464 _network_bind_list.emplace_back(dedicated_host);
466 if (dedicated_port != 0) _settings_client.network.server_port = dedicated_port;
468 /* initialize the ingame console */
469 IConsoleInit();
470 InitializeGUI();
471 IConsoleCmdExec("exec scripts/autoexec.scr 0");
473 /* Make sure _settings is filled with _settings_newgame if we switch to a game directly */
474 if (_switch_mode != SM_NONE) MakeNewgameSettingsLive();
476 if (_network_available && network_conn != nullptr) {
477 const char *port = nullptr;
478 const char *company = nullptr;
479 uint16 rport = NETWORK_DEFAULT_PORT;
480 CompanyID join_as = COMPANY_NEW_COMPANY;
482 ParseConnectionString(&company, &port, network_conn);
484 if (company != nullptr) {
485 join_as = (CompanyID)atoi(company);
487 if (join_as != COMPANY_SPECTATOR) {
488 join_as--;
489 if (join_as >= MAX_COMPANIES) {
490 delete this;
491 return;
495 if (port != nullptr) rport = atoi(port);
497 LoadIntroGame();
498 _switch_mode = SM_NONE;
499 NetworkClientConnectGame(NetworkAddress(network_conn, rport), join_as, join_server_password, join_company_password);
502 /* After the scan we're not used anymore. */
503 delete this;
507 #if defined(UNIX)
508 extern void DedicatedFork();
509 #endif
511 /** Options of OpenTTD. */
512 static const OptionData _options[] = {
513 GETOPT_SHORT_VALUE('I'),
514 GETOPT_SHORT_VALUE('S'),
515 GETOPT_SHORT_VALUE('M'),
516 GETOPT_SHORT_VALUE('m'),
517 GETOPT_SHORT_VALUE('s'),
518 GETOPT_SHORT_VALUE('v'),
519 GETOPT_SHORT_VALUE('b'),
520 GETOPT_SHORT_OPTVAL('D'),
521 GETOPT_SHORT_OPTVAL('n'),
522 GETOPT_SHORT_VALUE('l'),
523 GETOPT_SHORT_VALUE('p'),
524 GETOPT_SHORT_VALUE('P'),
525 #if !defined(_WIN32)
526 GETOPT_SHORT_NOVAL('f'),
527 #endif
528 GETOPT_SHORT_VALUE('r'),
529 GETOPT_SHORT_VALUE('t'),
530 GETOPT_SHORT_OPTVAL('d'),
531 GETOPT_SHORT_NOVAL('e'),
532 GETOPT_SHORT_OPTVAL('g'),
533 GETOPT_SHORT_VALUE('G'),
534 GETOPT_SHORT_VALUE('c'),
535 GETOPT_SHORT_NOVAL('x'),
536 GETOPT_SHORT_VALUE('q'),
537 GETOPT_SHORT_NOVAL('h'),
538 GETOPT_END()
542 * Main entry point for this lovely game.
543 * @param argc The number of arguments passed to this game.
544 * @param argv The values of the arguments.
545 * @return 0 when there is no error.
547 int openttd_main(int argc, char *argv[])
549 std::string musicdriver;
550 std::string sounddriver;
551 std::string videodriver;
552 std::string blitter;
553 std::string graphics_set;
554 std::string sounds_set;
555 std::string music_set;
556 Dimension resolution = {0, 0};
557 std::unique_ptr<AfterNewGRFScan> scanner(new AfterNewGRFScan());
558 bool dedicated = false;
559 char *debuglog_conn = nullptr;
561 extern bool _dedicated_forks;
562 _dedicated_forks = false;
564 std::unique_lock<std::mutex> modal_work_lock(_modal_progress_work_mutex, std::defer_lock);
565 std::unique_lock<std::mutex> modal_paint_lock(_modal_progress_paint_mutex, std::defer_lock);
567 _game_mode = GM_MENU;
568 _switch_mode = SM_MENU;
569 _config_file = nullptr;
571 GetOptData mgo(argc - 1, argv + 1, _options);
572 int ret = 0;
574 int i;
575 while ((i = mgo.GetOpt()) != -1) {
576 switch (i) {
577 case 'I': graphics_set = mgo.opt; break;
578 case 'S': sounds_set = mgo.opt; break;
579 case 'M': music_set = mgo.opt; break;
580 case 'm': musicdriver = mgo.opt; break;
581 case 's': sounddriver = mgo.opt; break;
582 case 'v': videodriver = mgo.opt; break;
583 case 'b': blitter = mgo.opt; break;
584 case 'D':
585 musicdriver = "null";
586 sounddriver = "null";
587 videodriver = "dedicated";
588 blitter = "null";
589 dedicated = true;
590 SetDebugString("net=6");
591 if (mgo.opt != nullptr) {
592 /* Use the existing method for parsing (openttd -n).
593 * However, we do ignore the #company part. */
594 const char *temp = nullptr;
595 const char *port = nullptr;
596 ParseConnectionString(&temp, &port, mgo.opt);
597 if (!StrEmpty(mgo.opt)) scanner->dedicated_host = mgo.opt;
598 if (port != nullptr) scanner->dedicated_port = atoi(port);
600 break;
601 case 'f': _dedicated_forks = true; break;
602 case 'n':
603 scanner->network_conn = mgo.opt; // optional IP parameter, nullptr if unset
604 break;
605 case 'l':
606 debuglog_conn = mgo.opt;
607 break;
608 case 'p':
609 scanner->join_server_password = mgo.opt;
610 break;
611 case 'P':
612 scanner->join_company_password = mgo.opt;
613 break;
614 case 'r': ParseResolution(&resolution, mgo.opt); break;
615 case 't': scanner->startyear = atoi(mgo.opt); break;
616 case 'd': {
617 #if defined(_WIN32)
618 CreateConsole();
619 #endif
620 if (mgo.opt != nullptr) SetDebugString(mgo.opt);
621 break;
623 case 'e': _switch_mode = (_switch_mode == SM_LOAD_GAME || _switch_mode == SM_LOAD_SCENARIO ? SM_LOAD_SCENARIO : SM_EDITOR); break;
624 case 'g':
625 if (mgo.opt != nullptr) {
626 _file_to_saveload.SetName(mgo.opt);
627 bool is_scenario = _switch_mode == SM_EDITOR || _switch_mode == SM_LOAD_SCENARIO;
628 _switch_mode = is_scenario ? SM_LOAD_SCENARIO : SM_LOAD_GAME;
629 _file_to_saveload.SetMode(SLO_LOAD, is_scenario ? FT_SCENARIO : FT_SAVEGAME, DFT_GAME_FILE);
631 /* if the file doesn't exist or it is not a valid savegame, let the saveload code show an error */
632 const char *t = strrchr(_file_to_saveload.name, '.');
633 if (t != nullptr) {
634 FiosType ft = FiosGetSavegameListCallback(SLO_LOAD, _file_to_saveload.name, t, nullptr, nullptr);
635 if (ft != FIOS_TYPE_INVALID) _file_to_saveload.SetMode(ft);
638 break;
641 _switch_mode = SM_NEWGAME;
642 /* Give a random map if no seed has been given */
643 if (scanner->generation_seed == GENERATE_NEW_SEED) {
644 scanner->generation_seed = InteractiveRandom();
646 break;
647 case 'q': {
648 DeterminePaths(argv[0]);
649 if (StrEmpty(mgo.opt)) {
650 ret = 1;
651 return ret;
654 char title[80];
655 title[0] = '\0';
656 FiosGetSavegameListCallback(SLO_LOAD, mgo.opt, strrchr(mgo.opt, '.'), title, lastof(title));
658 _load_check_data.Clear();
659 SaveOrLoadResult res = SaveOrLoad(mgo.opt, SLO_CHECK, DFT_GAME_FILE, SAVE_DIR, false);
660 if (res != SL_OK || _load_check_data.HasErrors()) {
661 fprintf(stderr, "Failed to open savegame\n");
662 if (_load_check_data.HasErrors()) {
663 char buf[256];
664 SetDParamStr(0, _load_check_data.error_data);
665 GetString(buf, _load_check_data.error, lastof(buf));
666 fprintf(stderr, "%s\n", buf);
668 return ret;
671 WriteSavegameInfo(title);
672 return ret;
674 case 'G': scanner->generation_seed = strtoul(mgo.opt, nullptr, 10); break;
675 case 'c': free(_config_file); _config_file = stredup(mgo.opt); break;
676 case 'x': scanner->save_config = false; break;
677 case 'h':
678 i = -2; // Force printing of help.
679 break;
681 if (i == -2) break;
684 if (i == -2 || mgo.numleft > 0) {
685 /* Either the user typed '-h', he made an error, or he added unrecognized command line arguments.
686 * In all cases, print the help, and exit.
688 * The next two functions are needed to list the graphics sets. We can't do them earlier
689 * because then we cannot show it on the debug console as that hasn't been configured yet. */
690 DeterminePaths(argv[0]);
691 TarScanner::DoScan(TarScanner::BASESET);
692 BaseGraphics::FindSets();
693 BaseSounds::FindSets();
694 BaseMusic::FindSets();
695 ShowHelp();
696 return ret;
699 DeterminePaths(argv[0]);
700 TarScanner::DoScan(TarScanner::BASESET);
702 if (dedicated) DEBUG(net, 0, "Starting dedicated version %s", _openttd_revision);
703 if (_dedicated_forks && !dedicated) _dedicated_forks = false;
705 #if defined(UNIX)
706 /* We must fork here, or we'll end up without some resources we need (like sockets) */
707 if (_dedicated_forks) DedicatedFork();
708 #endif
710 LoadFromConfig(true);
712 if (resolution.width != 0) _cur_resolution = resolution;
715 * The width and height must be at least 1 pixel and width times
716 * height times bytes per pixel must still fit within a 32 bits
717 * integer, even for 32 bpp video modes. This way all internal
718 * drawing routines work correctly.
720 _cur_resolution.width = ClampU(_cur_resolution.width, 1, UINT16_MAX / 2);
721 _cur_resolution.height = ClampU(_cur_resolution.height, 1, UINT16_MAX / 2);
723 /* Assume the cursor starts within the game as not all video drivers
724 * get an event that the cursor is within the window when it is opened.
725 * Saying the cursor is there makes no visible difference as it would
726 * just be out of the bounds of the window. */
727 _cursor.in_window = true;
729 /* enumerate language files */
730 InitializeLanguagePacks();
732 /* Initialize the regular font for FreeType */
733 InitFreeType(false);
735 /* This must be done early, since functions use the SetWindowDirty* calls */
736 InitWindowSystem();
738 BaseGraphics::FindSets();
739 if (graphics_set.empty() && !BaseGraphics::ini_set.empty()) graphics_set = BaseGraphics::ini_set;
740 if (!BaseGraphics::SetSet(graphics_set)) {
741 if (!graphics_set.empty()) {
742 BaseGraphics::SetSet({});
744 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_GRAPHICS_NOT_FOUND);
745 msg.SetDParamStr(0, graphics_set.c_str());
746 ScheduleErrorMessage(msg);
750 /* Initialize game palette */
751 GfxInitPalettes();
753 DEBUG(misc, 1, "Loading blitter...");
754 if (blitter.empty() && !_ini_blitter.empty()) blitter = _ini_blitter;
755 _blitter_autodetected = blitter.empty();
756 /* Activate the initial blitter.
757 * This is only some initial guess, after NewGRFs have been loaded SwitchNewGRFBlitter may switch to a different one.
758 * - Never guess anything, if the user specified a blitter. (_blitter_autodetected)
759 * - Use 32bpp blitter if baseset or 8bpp-support settings says so.
760 * - Use 8bpp blitter otherwise.
762 if (!_blitter_autodetected ||
763 (_support8bpp != S8BPP_NONE && (BaseGraphics::GetUsedSet() == nullptr || BaseGraphics::GetUsedSet()->blitter == BLT_8BPP)) ||
764 BlitterFactory::SelectBlitter("32bpp-anim") == nullptr) {
765 if (BlitterFactory::SelectBlitter(blitter) == nullptr) {
766 blitter.empty() ?
767 usererror("Failed to autoprobe blitter") :
768 usererror("Failed to select requested blitter '%s'; does it exist?", blitter.c_str());
772 if (videodriver.empty() && !_ini_videodriver.empty()) videodriver = _ini_videodriver;
773 DriverFactoryBase::SelectDriver(videodriver, Driver::DT_VIDEO);
775 InitializeSpriteSorter();
777 /* Initialize the zoom level of the screen to normal */
778 _screen.zoom = ZOOM_LVL_NORMAL;
780 NetworkStartUp(); // initialize network-core
782 if (debuglog_conn != nullptr && _network_available) {
783 const char *not_used = nullptr;
784 const char *port = nullptr;
785 uint16 rport;
787 rport = NETWORK_DEFAULT_DEBUGLOG_PORT;
789 ParseConnectionString(&not_used, &port, debuglog_conn);
790 if (port != nullptr) rport = atoi(port);
792 NetworkStartDebugLog(NetworkAddress(debuglog_conn, rport));
795 if (!HandleBootstrap()) {
796 ShutdownGame();
797 return ret;
800 VideoDriver::GetInstance()->ClaimMousePointer();
802 /* initialize screenshot formats */
803 InitializeScreenshotFormats();
805 BaseSounds::FindSets();
806 if (sounds_set.empty() && !BaseSounds::ini_set.empty()) sounds_set = BaseSounds::ini_set;
807 if (!BaseSounds::SetSet(sounds_set)) {
808 if (sounds_set.empty() || !BaseSounds::SetSet({})) {
809 usererror("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 1.4 of README.md.");
810 } else {
811 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_SOUNDS_NOT_FOUND);
812 msg.SetDParamStr(0, sounds_set.c_str());
813 ScheduleErrorMessage(msg);
817 BaseMusic::FindSets();
818 if (music_set.empty() && !BaseMusic::ini_set.empty()) music_set = BaseMusic::ini_set;
819 if (!BaseMusic::SetSet(music_set)) {
820 if (music_set.empty() || !BaseMusic::SetSet({})) {
821 usererror("Failed to find a music set. Please acquire a music set for OpenTTD. See section 1.4 of README.md.");
822 } else {
823 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_MUSIC_NOT_FOUND);
824 msg.SetDParamStr(0, music_set.c_str());
825 ScheduleErrorMessage(msg);
829 if (sounddriver.empty() && !_ini_sounddriver.empty()) sounddriver = _ini_sounddriver;
830 DriverFactoryBase::SelectDriver(sounddriver, Driver::DT_SOUND);
832 if (musicdriver.empty() && !_ini_musicdriver.empty()) musicdriver = _ini_musicdriver;
833 DriverFactoryBase::SelectDriver(musicdriver, Driver::DT_MUSIC);
835 /* Take our initial lock on whatever we might want to do! */
836 try {
837 modal_work_lock.lock();
838 modal_paint_lock.lock();
839 } catch (const std::system_error&) {
840 /* If there is some error we assume that threads aren't usable on the system we run. */
841 extern bool _use_threaded_modal_progress; // From progress.cpp
842 _use_threaded_modal_progress = false;
845 GenerateWorld(GWM_EMPTY, 64, 64); // Make the viewport initialization happy
846 WaitTillGeneratedWorld();
848 LoadIntroGame(false);
850 CheckForMissingGlyphs();
852 /* ScanNewGRFFiles now has control over the scanner. */
853 ScanNewGRFFiles(scanner.release());
855 VideoDriver::GetInstance()->MainLoop();
857 WaitTillSaved();
858 WaitTillGeneratedWorld(); // Make sure any generate world threads have been joined.
860 /* only save config if we have to */
861 if (_save_config) {
862 SaveToConfig();
863 SaveHotkeysToConfig();
864 WindowDesc::SaveToConfig();
865 SaveToHighScore();
868 /* Reset windowing system, stop drivers, free used memory, ... */
869 ShutdownGame();
870 return ret;
873 void HandleExitGameRequest()
875 if (_game_mode == GM_MENU || _game_mode == GM_BOOTSTRAP) { // do not ask to quit on the main screen
876 _exit_game = true;
877 } else if (_settings_client.gui.autosave_on_exit) {
878 DoExitSave();
879 _exit_game = true;
880 } else {
881 AskExitGame();
885 static void MakeNewGameDone()
887 SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
889 /* In a dedicated server, the server does not play */
890 if (!VideoDriver::GetInstance()->HasGUI()) {
891 SetLocalCompany(COMPANY_SPECTATOR);
892 if (_settings_client.gui.pause_on_newgame) DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
893 IConsoleCmdExec("exec scripts/game_start.scr 0");
894 return;
897 /* Create a single company */
898 DoStartupNewCompany(false);
900 Company *c = Company::Get(COMPANY_FIRST);
901 c->settings = _settings_client.company;
903 /* Overwrite color from settings if needed
904 * COLOUR_END corresponds to Random colour */
905 if (_settings_client.gui.starting_colour != COLOUR_END) {
906 c->colour = _settings_client.gui.starting_colour;
907 ResetCompanyLivery(c);
908 _company_colours[c->index] = (Colours)c->colour;
911 IConsoleCmdExec("exec scripts/game_start.scr 0");
913 SetLocalCompany(COMPANY_FIRST);
915 InitializeRailGUI();
916 InitializeRoadGUI();
918 /* We are the server, we start a new company (not dedicated),
919 * so set the default password *if* needed. */
920 if (_network_server && !StrEmpty(_settings_client.network.default_company_pass)) {
921 NetworkChangeCompanyPassword(_local_company, _settings_client.network.default_company_pass);
924 if (_settings_client.gui.pause_on_newgame) DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
926 CheckEngines();
927 CheckIndustries();
928 MarkWholeScreenDirty();
931 static void MakeNewGame(bool from_heightmap, bool reset_settings)
933 _game_mode = GM_NORMAL;
935 ResetGRFConfig(true);
937 GenerateWorldSetCallback(&MakeNewGameDone);
938 GenerateWorld(from_heightmap ? GWM_HEIGHTMAP : GWM_NEWGAME, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y, reset_settings);
941 static void MakeNewEditorWorldDone()
943 SetLocalCompany(OWNER_NONE);
946 static void MakeNewEditorWorld()
948 _game_mode = GM_EDITOR;
950 ResetGRFConfig(true);
952 GenerateWorldSetCallback(&MakeNewEditorWorldDone);
953 GenerateWorld(GWM_EMPTY, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
957 * Load the specified savegame but on error do different things.
958 * If loading fails due to corrupt savegame, bad version, etc. go back to
959 * a previous correct state. In the menu for example load the intro game again.
960 * @param filename file to be loaded
961 * @param fop mode of loading, always SLO_LOAD
962 * @param newgm switch to this mode of loading fails due to some unknown error
963 * @param subdir default directory to look for filename, set to 0 if not needed
964 * @param lf Load filter to use, if nullptr: use filename + subdir.
966 bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = nullptr)
968 assert(fop == SLO_LOAD);
969 assert(dft == DFT_GAME_FILE || (lf == nullptr && dft == DFT_OLD_GAME_FILE));
970 GameMode ogm = _game_mode;
972 _game_mode = newgm;
974 switch (lf == nullptr ? SaveOrLoad(filename, fop, dft, subdir) : LoadWithFilter(lf)) {
975 case SL_OK: return true;
977 case SL_REINIT:
978 if (_network_dedicated) {
980 * We need to reinit a network map...
981 * We can't simply load the intro game here as that game has many
982 * special cases which make clients desync immediately. So we fall
983 * back to just generating a new game with the current settings.
985 DEBUG(net, 0, "Loading game failed, so a new (random) game will be started!");
986 MakeNewGame(false, true);
987 return false;
989 if (_network_server) {
990 /* We can't load the intro game as server, so disconnect first. */
991 NetworkDisconnect();
994 switch (ogm) {
995 default:
996 case GM_MENU: LoadIntroGame(); break;
997 case GM_EDITOR: MakeNewEditorWorld(); break;
999 return false;
1001 default:
1002 _game_mode = ogm;
1003 return false;
1007 void SwitchToMode(SwitchMode new_mode)
1009 /* If we are saving something, the network stays in his current state */
1010 if (new_mode != SM_SAVE_GAME) {
1011 /* If the network is active, make it not-active */
1012 if (_networking) {
1013 if (_network_server && (new_mode == SM_LOAD_GAME || new_mode == SM_NEWGAME || new_mode == SM_RESTARTGAME)) {
1014 NetworkReboot();
1015 } else {
1016 NetworkDisconnect();
1020 /* If we are a server, we restart the server */
1021 if (_is_network_server) {
1022 /* But not if we are going to the menu */
1023 if (new_mode != SM_MENU) {
1024 /* check if we should reload the config */
1025 if (_settings_client.network.reload_cfg) {
1026 LoadFromConfig();
1027 MakeNewgameSettingsLive();
1028 ResetGRFConfig(false);
1030 NetworkServerStart();
1031 } else {
1032 /* This client no longer wants to be a network-server */
1033 _is_network_server = false;
1038 /* Make sure all AI controllers are gone at quitting game */
1039 if (new_mode != SM_SAVE_GAME) AI::KillAll();
1041 switch (new_mode) {
1042 case SM_EDITOR: // Switch to scenario editor
1043 MakeNewEditorWorld();
1044 break;
1046 case SM_RESTARTGAME: // Restart --> Current settings preserved
1047 if (_file_to_saveload.abstract_ftype == FT_SAVEGAME || _file_to_saveload.abstract_ftype == FT_SCENARIO) {
1048 /* Restart current savegame/scenario */
1049 _switch_mode = _game_mode == GM_EDITOR ? SM_LOAD_SCENARIO : SM_LOAD_GAME;
1050 SwitchToMode(_switch_mode);
1051 break;
1052 } else if (_file_to_saveload.abstract_ftype == FT_HEIGHTMAP) {
1053 /* Restart current heightmap */
1054 _switch_mode = _game_mode == GM_EDITOR ? SM_LOAD_HEIGHTMAP : SM_RESTART_HEIGHTMAP;
1055 SwitchToMode(_switch_mode);
1056 break;
1058 /* No break here, to enter the next case:
1059 * Restart --> 'Random game' with current settings */
1060 FALLTHROUGH;
1062 case SM_NEWGAME: // New Game --> 'Random game'
1063 if (_network_server) {
1064 seprintf(_network_game_info.map_name, lastof(_network_game_info.map_name), "Random Map");
1066 MakeNewGame(false, new_mode == SM_NEWGAME);
1067 break;
1069 case SM_LOAD_GAME: { // Load game, Play Scenario
1070 ResetGRFConfig(true);
1071 ResetWindowSystem();
1073 if (!SafeLoad(_file_to_saveload.name, _file_to_saveload.file_op, _file_to_saveload.detail_ftype, GM_NORMAL, NO_DIRECTORY)) {
1074 SetDParamStr(0, GetSaveLoadErrorString());
1075 ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
1076 } else {
1077 if (_file_to_saveload.abstract_ftype == FT_SCENARIO) {
1078 /* Reset engine pool to simplify changing engine NewGRFs in scenario editor. */
1079 EngineOverrideManager::ResetToCurrentNewGRFConfig();
1081 /* Update the local company for a loaded game. It is either always
1082 * company #1 (eg 0) or in the case of a dedicated server a spectator */
1083 SetLocalCompany(_network_dedicated ? COMPANY_SPECTATOR : COMPANY_FIRST);
1084 /* Execute the game-start script */
1085 IConsoleCmdExec("exec scripts/game_start.scr 0");
1086 /* Decrease pause counter (was increased from opening load dialog) */
1087 DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
1088 if (_network_server) {
1089 seprintf(_network_game_info.map_name, lastof(_network_game_info.map_name), "%s (Loaded game)", _file_to_saveload.title);
1092 break;
1095 case SM_RESTART_HEIGHTMAP: // Load a heightmap and start a new game from it with current settings
1096 case SM_START_HEIGHTMAP: // Load a heightmap and start a new game from it
1097 if (_network_server) {
1098 seprintf(_network_game_info.map_name, lastof(_network_game_info.map_name), "%s (Heightmap)", _file_to_saveload.title);
1100 MakeNewGame(true, new_mode == SM_START_HEIGHTMAP);
1101 break;
1103 case SM_LOAD_HEIGHTMAP: // Load heightmap from scenario editor
1104 SetLocalCompany(OWNER_NONE);
1106 GenerateWorld(GWM_HEIGHTMAP, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
1107 MarkWholeScreenDirty();
1108 break;
1110 case SM_LOAD_SCENARIO: { // Load scenario from scenario editor
1111 if (SafeLoad(_file_to_saveload.name, _file_to_saveload.file_op, _file_to_saveload.detail_ftype, GM_EDITOR, NO_DIRECTORY)) {
1112 SetLocalCompany(OWNER_NONE);
1113 _settings_newgame.game_creation.starting_year = _cur_year;
1114 /* Cancel the saveload pausing */
1115 DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
1116 } else {
1117 SetDParamStr(0, GetSaveLoadErrorString());
1118 ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
1120 break;
1123 case SM_MENU: // Switch to game intro menu
1124 LoadIntroGame();
1125 if (BaseSounds::ini_set.empty() && BaseSounds::GetUsedSet()->fallback && SoundDriver::GetInstance()->HasOutput()) {
1126 ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET, INVALID_STRING_ID, WL_CRITICAL);
1127 BaseSounds::ini_set = BaseSounds::GetUsedSet()->name;
1129 break;
1131 case SM_SAVE_GAME: // Save game.
1132 /* Make network saved games on pause compatible to singleplayer */
1133 if (SaveOrLoad(_file_to_saveload.name, SLO_SAVE, DFT_GAME_FILE, NO_DIRECTORY) != SL_OK) {
1134 SetDParamStr(0, GetSaveLoadErrorString());
1135 ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
1136 } else {
1137 DeleteWindowById(WC_SAVELOAD, 0);
1139 break;
1141 case SM_SAVE_HEIGHTMAP: // Save heightmap.
1142 MakeHeightmapScreenshot(_file_to_saveload.name);
1143 DeleteWindowById(WC_SAVELOAD, 0);
1144 break;
1146 case SM_GENRANDLAND: // Generate random land within scenario editor
1147 SetLocalCompany(OWNER_NONE);
1148 GenerateWorld(GWM_RANDOM, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
1149 /* XXX: set date */
1150 MarkWholeScreenDirty();
1151 break;
1153 default: NOT_REACHED();
1159 * Check the validity of some of the caches.
1160 * Especially in the sense of desyncs between
1161 * the cached value and what the value would
1162 * be when calculated from the 'base' data.
1164 static void CheckCaches()
1166 /* Return here so it is easy to add checks that are run
1167 * always to aid testing of caches. */
1168 if (_debug_desync_level <= 1) return;
1170 /* Check the town caches. */
1171 std::vector<TownCache> old_town_caches;
1172 for (const Town *t : Town::Iterate()) {
1173 old_town_caches.push_back(t->cache);
1176 extern void RebuildTownCaches();
1177 RebuildTownCaches();
1178 RebuildSubsidisedSourceAndDestinationCache();
1180 uint i = 0;
1181 for (Town *t : Town::Iterate()) {
1182 if (MemCmpT(old_town_caches.data() + i, &t->cache) != 0) {
1183 DEBUG(desync, 2, "town cache mismatch: town %i", (int)t->index);
1185 i++;
1188 /* Check company infrastructure cache. */
1189 std::vector<CompanyInfrastructure> old_infrastructure;
1190 for (const Company *c : Company::Iterate()) old_infrastructure.push_back(c->infrastructure);
1192 extern void AfterLoadCompanyStats();
1193 AfterLoadCompanyStats();
1195 i = 0;
1196 for (const Company *c : Company::Iterate()) {
1197 if (MemCmpT(old_infrastructure.data() + i, &c->infrastructure) != 0) {
1198 DEBUG(desync, 2, "infrastructure cache mismatch: company %i", (int)c->index);
1200 i++;
1203 /* Strict checking of the road stop cache entries */
1204 for (const RoadStop *rs : RoadStop::Iterate()) {
1205 if (IsStandardRoadStopTile(rs->xy)) continue;
1207 assert(rs->GetEntry(DIAGDIR_NE) != rs->GetEntry(DIAGDIR_NW));
1208 rs->GetEntry(DIAGDIR_NE)->CheckIntegrity(rs);
1209 rs->GetEntry(DIAGDIR_NW)->CheckIntegrity(rs);
1212 for (Vehicle *v : Vehicle::Iterate()) {
1213 extern void FillNewGRFVehicleCache(const Vehicle *v);
1214 if (v != v->First() || v->vehstatus & VS_CRASHED || !v->IsPrimaryVehicle()) continue;
1216 uint length = 0;
1217 for (const Vehicle *u = v; u != nullptr; u = u->Next()) length++;
1219 NewGRFCache *grf_cache = CallocT<NewGRFCache>(length);
1220 VehicleCache *veh_cache = CallocT<VehicleCache>(length);
1221 GroundVehicleCache *gro_cache = CallocT<GroundVehicleCache>(length);
1222 TrainCache *tra_cache = CallocT<TrainCache>(length);
1224 length = 0;
1225 for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
1226 FillNewGRFVehicleCache(u);
1227 grf_cache[length] = u->grf_cache;
1228 veh_cache[length] = u->vcache;
1229 switch (u->type) {
1230 case VEH_TRAIN:
1231 gro_cache[length] = Train::From(u)->gcache;
1232 tra_cache[length] = Train::From(u)->tcache;
1233 break;
1234 case VEH_ROAD:
1235 gro_cache[length] = RoadVehicle::From(u)->gcache;
1236 break;
1237 default:
1238 break;
1240 length++;
1243 switch (v->type) {
1244 case VEH_TRAIN: Train::From(v)->ConsistChanged(CCF_TRACK); break;
1245 case VEH_ROAD: RoadVehUpdateCache(RoadVehicle::From(v)); break;
1246 case VEH_AIRCRAFT: UpdateAircraftCache(Aircraft::From(v)); break;
1247 case VEH_SHIP: Ship::From(v)->UpdateCache(); break;
1248 default: break;
1251 length = 0;
1252 for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
1253 FillNewGRFVehicleCache(u);
1254 if (memcmp(&grf_cache[length], &u->grf_cache, sizeof(NewGRFCache)) != 0) {
1255 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);
1257 if (memcmp(&veh_cache[length], &u->vcache, sizeof(VehicleCache)) != 0) {
1258 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);
1260 switch (u->type) {
1261 case VEH_TRAIN:
1262 if (memcmp(&gro_cache[length], &Train::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
1263 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);
1265 if (memcmp(&tra_cache[length], &Train::From(u)->tcache, sizeof(TrainCache)) != 0) {
1266 DEBUG(desync, 2, "train cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v->index, (int)v->owner, v->unitnumber, length);
1268 break;
1269 case VEH_ROAD:
1270 if (memcmp(&gro_cache[length], &RoadVehicle::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
1271 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);
1273 break;
1274 default:
1275 break;
1277 length++;
1280 free(grf_cache);
1281 free(veh_cache);
1282 free(gro_cache);
1283 free(tra_cache);
1286 /* Check whether the caches are still valid */
1287 for (Vehicle *v : Vehicle::Iterate()) {
1288 byte buff[sizeof(VehicleCargoList)];
1289 memcpy(buff, &v->cargo, sizeof(VehicleCargoList));
1290 v->cargo.InvalidateCache();
1291 assert(memcmp(&v->cargo, buff, sizeof(VehicleCargoList)) == 0);
1294 /* Backup stations_near */
1295 std::vector<StationList> old_town_stations_near;
1296 for (Town *t : Town::Iterate()) old_town_stations_near.push_back(t->stations_near);
1298 std::vector<StationList> old_industry_stations_near;
1299 for (Industry *ind : Industry::Iterate()) old_industry_stations_near.push_back(ind->stations_near);
1301 for (Station *st : Station::Iterate()) {
1302 for (CargoID c = 0; c < NUM_CARGO; c++) {
1303 byte buff[sizeof(StationCargoList)];
1304 memcpy(buff, &st->goods[c].cargo, sizeof(StationCargoList));
1305 st->goods[c].cargo.InvalidateCache();
1306 assert(memcmp(&st->goods[c].cargo, buff, sizeof(StationCargoList)) == 0);
1309 /* Check docking tiles */
1310 TileArea ta;
1311 std::map<TileIndex, bool> docking_tiles;
1312 TILE_AREA_LOOP(tile, st->docking_station) {
1313 ta.Add(tile);
1314 docking_tiles[tile] = IsDockingTile(tile);
1316 UpdateStationDockingTiles(st);
1317 if (ta.tile != st->docking_station.tile || ta.w != st->docking_station.w || ta.h != st->docking_station.h) {
1318 DEBUG(desync, 2, "station docking mismatch: station %i, company %i", st->index, (int)st->owner);
1320 TILE_AREA_LOOP(tile, ta) {
1321 if (docking_tiles[tile] != IsDockingTile(tile)) {
1322 DEBUG(desync, 2, "docking tile mismatch: tile %i", (int)tile);
1326 /* Check industries_near */
1327 IndustryList industries_near = st->industries_near;
1328 st->RecomputeCatchment();
1329 if (st->industries_near != industries_near) {
1330 DEBUG(desync, 2, "station industries near mismatch: station %i", st->index);
1334 /* Check stations_near */
1335 i = 0;
1336 for (Town *t : Town::Iterate()) {
1337 if (t->stations_near != old_town_stations_near[i]) {
1338 DEBUG(desync, 2, "town stations near mismatch: town %i", t->index);
1340 i++;
1342 i = 0;
1343 for (Industry *ind : Industry::Iterate()) {
1344 if (ind->stations_near != old_industry_stations_near[i]) {
1345 DEBUG(desync, 2, "industry stations near mismatch: industry %i", ind->index);
1347 i++;
1352 * State controlling game loop.
1353 * The state must not be changed from anywhere but here.
1354 * That check is enforced in DoCommand.
1356 void StateGameLoop()
1358 if (!_networking || _network_server) {
1359 StateGameLoop_LinkGraphPauseControl();
1362 /* don't execute the state loop during pause */
1363 if (_pause_mode != PM_UNPAUSED) {
1364 PerformanceMeasurer::Paused(PFE_GAMELOOP);
1365 PerformanceMeasurer::Paused(PFE_GL_ECONOMY);
1366 PerformanceMeasurer::Paused(PFE_GL_TRAINS);
1367 PerformanceMeasurer::Paused(PFE_GL_ROADVEHS);
1368 PerformanceMeasurer::Paused(PFE_GL_SHIPS);
1369 PerformanceMeasurer::Paused(PFE_GL_AIRCRAFT);
1370 PerformanceMeasurer::Paused(PFE_GL_LANDSCAPE);
1372 UpdateLandscapingLimits();
1373 #ifndef DEBUG_DUMP_COMMANDS
1374 Game::GameLoop();
1375 #endif
1376 return;
1379 PerformanceMeasurer framerate(PFE_GAMELOOP);
1380 PerformanceAccumulator::Reset(PFE_GL_LANDSCAPE);
1381 if (HasModalProgress()) return;
1383 Layouter::ReduceLineCache();
1385 if (_game_mode == GM_EDITOR) {
1386 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP);
1387 RunTileLoop();
1388 CallVehicleTicks();
1389 CallLandscapeTick();
1390 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP);
1391 UpdateLandscapingLimits();
1393 CallWindowGameTickEvent();
1394 NewsLoop();
1395 } else {
1396 if (_debug_desync_level > 2 && _date_fract == 0 && (_date & 0x1F) == 0) {
1397 /* Save the desync savegame if needed. */
1398 char name[MAX_PATH];
1399 seprintf(name, lastof(name), "dmp_cmds_%08x_%08x.sav", _settings_game.game_creation.generation_seed, _date);
1400 SaveOrLoad(name, SLO_SAVE, DFT_GAME_FILE, AUTOSAVE_DIR, false);
1403 CheckCaches();
1405 /* All these actions has to be done from OWNER_NONE
1406 * for multiplayer compatibility */
1407 Backup<CompanyID> cur_company(_current_company, OWNER_NONE, FILE_LINE);
1409 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP);
1410 AnimateAnimatedTiles();
1411 IncreaseDate();
1412 RunTileLoop();
1413 CallVehicleTicks();
1414 CallLandscapeTick();
1415 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP);
1417 #ifndef DEBUG_DUMP_COMMANDS
1419 PerformanceMeasurer framerate(PFE_ALLSCRIPTS);
1420 AI::GameLoop();
1421 Game::GameLoop();
1423 #endif
1424 UpdateLandscapingLimits();
1426 CallWindowGameTickEvent();
1427 NewsLoop();
1428 cur_company.Restore();
1431 assert(IsLocalCompany());
1435 * Create an autosave. The default name is "autosave#.sav". However with
1436 * the setting 'keep_all_autosave' the name defaults to company-name + date
1438 static void DoAutosave()
1440 char buf[MAX_PATH];
1442 if (_settings_client.gui.keep_all_autosave) {
1443 GenerateDefaultSaveName(buf, lastof(buf));
1444 strecat(buf, ".sav", lastof(buf));
1445 } else {
1446 static int _autosave_ctr = 0;
1448 /* generate a savegame name and number according to _settings_client.gui.max_num_autosaves */
1449 seprintf(buf, lastof(buf), "autosave%d.sav", _autosave_ctr);
1451 if (++_autosave_ctr >= _settings_client.gui.max_num_autosaves) _autosave_ctr = 0;
1454 DEBUG(sl, 2, "Autosaving to '%s'", buf);
1455 if (SaveOrLoad(buf, SLO_SAVE, DFT_GAME_FILE, AUTOSAVE_DIR) != SL_OK) {
1456 ShowErrorMessage(STR_ERROR_AUTOSAVE_FAILED, INVALID_STRING_ID, WL_ERROR);
1460 void GameLoop()
1462 if (_game_mode == GM_BOOTSTRAP) {
1463 /* Check for UDP stuff */
1464 if (_network_available) NetworkBackgroundLoop();
1465 InputLoop();
1466 return;
1469 ProcessAsyncSaveFinish();
1471 /* autosave game? */
1472 if (_do_autosave) {
1473 DoAutosave();
1474 _do_autosave = false;
1475 SetWindowDirty(WC_STATUS_BAR, 0);
1478 /* switch game mode? */
1479 if (_switch_mode != SM_NONE && !HasModalProgress()) {
1480 SwitchToMode(_switch_mode);
1481 _switch_mode = SM_NONE;
1484 IncreaseSpriteLRU();
1485 InteractiveRandom();
1487 /* Check for UDP stuff */
1488 if (_network_available) NetworkBackgroundLoop();
1490 if (_networking && !HasModalProgress()) {
1491 /* Multiplayer */
1492 NetworkGameLoop();
1493 } else {
1494 if (_network_reconnect > 0 && --_network_reconnect == 0) {
1495 /* This means that we want to reconnect to the last host
1496 * We do this here, because it means that the network is really closed */
1497 NetworkClientConnectGame(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port), COMPANY_SPECTATOR);
1499 /* Singleplayer */
1500 StateGameLoop();
1503 if (!_pause_mode && HasBit(_display_opt, DO_FULL_ANIMATION)) DoPaletteAnimations();
1505 InputLoop();
1507 SoundDriver::GetInstance()->MainLoop();
1508 MusicLoop();