Update: Translations from eints
[openttd-github.git] / src / openttd.cpp
blob25082be2c5b29804fa84961ca35acb95834e135b
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"
16 #include "mixer.h"
18 #include "fontcache.h"
19 #include "error.h"
20 #include "error_func.h"
21 #include "gui.h"
23 #include "base_media_base.h"
24 #include "saveload/saveload.h"
25 #include "company_cmd.h"
26 #include "company_func.h"
27 #include "command_func.h"
28 #include "news_func.h"
29 #include "fios.h"
30 #include "aircraft.h"
31 #include "roadveh.h"
32 #include "train.h"
33 #include "ship.h"
34 #include "console_func.h"
35 #include "screenshot.h"
36 #include "network/network.h"
37 #include "network/network_func.h"
38 #include "ai/ai.hpp"
39 #include "ai/ai_config.hpp"
40 #include "settings_func.h"
41 #include "genworld.h"
42 #include "progress.h"
43 #include "strings_func.h"
44 #include "vehicle_func.h"
45 #include "gamelog.h"
46 #include "animated_tile_func.h"
47 #include "roadstop_base.h"
48 #include "elrail_func.h"
49 #include "rev.h"
50 #include "highscore.h"
51 #include "station_base.h"
52 #include "crashlog.h"
53 #include "engine_func.h"
54 #include "core/random_func.hpp"
55 #include "rail_gui.h"
56 #include "road_gui.h"
57 #include "core/backup_type.hpp"
58 #include "hotkeys.h"
59 #include "newgrf.h"
60 #include "misc/getoptdata.h"
61 #include "game/game.hpp"
62 #include "game/game_config.hpp"
63 #include "town.h"
64 #include "subsidy_func.h"
65 #include "gfx_layout.h"
66 #include "viewport_func.h"
67 #include "viewport_sprite_sorter.h"
68 #include "framerate_type.h"
69 #include "industry.h"
70 #include "network/network_gui.h"
71 #include "network/network_survey.h"
72 #include "misc_cmd.h"
73 #include "timer/timer.h"
74 #include "timer/timer_game_calendar.h"
75 #include "timer/timer_game_economy.h"
76 #include "timer/timer_game_realtime.h"
77 #include "timer/timer_game_tick.h"
78 #include "social_integration.h"
80 #include "linkgraph/linkgraphschedule.h"
82 #include <system_error>
84 #include "safeguards.h"
86 #ifdef __EMSCRIPTEN__
87 # include <emscripten.h>
88 # include <emscripten/html5.h>
89 #endif
91 void CallLandscapeTick();
92 void DoPaletteAnimations();
93 void MusicLoop();
94 void CallWindowGameTickEvent();
95 bool HandleBootstrap();
97 extern void CheckCaches();
98 extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
99 extern void OSOpenBrowser(const std::string &url);
100 extern void ShowOSErrorBox(const char *buf, bool system);
101 extern std::string _config_file;
103 bool _save_config = false;
104 bool _request_newgrf_scan = false;
105 NewGRFScanCallback *_request_newgrf_scan_callback = nullptr;
108 * Error handling for fatal user errors.
109 * @param str the string to print.
110 * @note Does NEVER return.
112 void UserErrorI(const std::string &str)
114 ShowOSErrorBox(str.c_str(), false);
115 if (VideoDriver::GetInstance() != nullptr) VideoDriver::GetInstance()->Stop();
117 #ifdef __EMSCRIPTEN__
118 emscripten_exit_pointerlock();
119 /* In effect, the game ends here. As emscripten_set_main_loop() caused
120 * the stack to be unwound, the code after MainLoop() in
121 * openttd_main() is never executed. */
122 EM_ASM(if (window["openttd_abort"]) openttd_abort());
123 #endif
125 _exit(1);
129 * Error handling for fatal non-user errors.
130 * @param str the string to print.
131 * @note Does NEVER return.
133 void FatalErrorI(const std::string &str)
135 if (VideoDriver::GetInstance() == nullptr || VideoDriver::GetInstance()->HasGUI()) {
136 ShowOSErrorBox(str.c_str(), true);
139 /* Set the error message for the crash log and then invoke it. */
140 CrashLog::SetErrorMessage(str);
141 abort();
145 * Show the help message when someone passed a wrong parameter.
147 static void ShowHelp()
149 std::string str;
150 str.reserve(8192);
152 std::back_insert_iterator<std::string> output_iterator = std::back_inserter(str);
153 fmt::format_to(output_iterator, "OpenTTD {}\n", _openttd_revision);
154 str +=
155 "\n"
156 "\n"
157 "Command line options:\n"
158 " -v drv = Set video driver (see below)\n"
159 " -s drv = Set sound driver (see below)\n"
160 " -m drv = Set music driver (see below)\n"
161 " -b drv = Set the blitter to use (see below)\n"
162 " -r res = Set resolution (for instance 800x600)\n"
163 " -h = Display this help text\n"
164 " -t year = Set starting year\n"
165 " -d [[fac=]lvl[,...]]= Debug mode\n"
166 " -e = Start Editor\n"
167 " -g [savegame|scenario|heightmap] = Start new/savegame/scenario/heightmap immediately\n"
168 " -G seed = Set random seed\n"
169 " -n host[:port][#company]= Join network game\n"
170 " -p password = Password to join server\n"
171 " -D [host][:port] = Start dedicated server\n"
172 #if !defined(_WIN32)
173 " -f = Fork into the background (dedicated only)\n"
174 #endif
175 " -I graphics_set = Force the graphics set (see below)\n"
176 " -S sounds_set = Force the sounds set (see below)\n"
177 " -M music_set = Force the music set (see below)\n"
178 " -c config_file = Use 'config_file' instead of 'openttd.cfg'\n"
179 " -x = Never save configuration changes to disk\n"
180 " -X = Don't use global folders to search for files\n"
181 " -q savegame = Write some information about the savegame and exit\n"
182 " -Q = Don't scan for/load NewGRF files on startup\n"
183 " -QQ = Disable NewGRF scanning/loading entirely\n"
184 "\n";
186 /* List the graphics packs */
187 BaseGraphics::GetSetsList(output_iterator);
189 /* List the sounds packs */
190 BaseSounds::GetSetsList(output_iterator);
192 /* List the music packs */
193 BaseMusic::GetSetsList(output_iterator);
195 /* List the drivers */
196 DriverFactoryBase::GetDriversInfo(output_iterator);
198 /* List the blitters */
199 BlitterFactory::GetBlittersInfo(output_iterator);
201 /* List the debug facilities. */
202 DumpDebugFacilityNames(output_iterator);
204 /* We need to initialize the AI, so it finds the AIs */
205 AI::Initialize();
206 AI::GetConsoleList(output_iterator, true);
207 AI::Uninitialize(true);
209 /* We need to initialize the GameScript, so it finds the GSs */
210 Game::Initialize();
211 Game::GetConsoleList(output_iterator, true);
212 Game::Uninitialize(true);
214 /* ShowInfo put output to stderr, but version information should go
215 * to stdout; this is the only exception */
216 #if !defined(_WIN32)
217 fmt::print("{}\n", str);
218 #else
219 ShowInfoI(str);
220 #endif
223 static void WriteSavegameInfo(const std::string &name)
225 extern SaveLoadVersion _sl_version;
226 uint32_t last_ottd_rev = 0;
227 uint8_t ever_modified = 0;
228 bool removed_newgrfs = false;
230 _gamelog.Info(&last_ottd_rev, &ever_modified, &removed_newgrfs);
232 std::string message;
233 message.reserve(1024);
234 fmt::format_to(std::back_inserter(message), "Name: {}\n", name);
235 fmt::format_to(std::back_inserter(message), "Savegame ver: {}\n", _sl_version);
236 fmt::format_to(std::back_inserter(message), "NewGRF ver: 0x{:08X}\n", last_ottd_rev);
237 fmt::format_to(std::back_inserter(message), "Modified: {}\n", ever_modified);
239 if (removed_newgrfs) {
240 fmt::format_to(std::back_inserter(message), "NewGRFs have been removed\n");
243 message += "NewGRFs:\n";
244 if (_load_check_data.HasNewGrfs()) {
245 for (GRFConfig *c = _load_check_data.grfconfig; c != nullptr; c = c->next) {
246 fmt::format_to(std::back_inserter(message), "{:08X} {} {}\n", BSWAP32(c->ident.grfid),
247 FormatArrayAsHex(HasBit(c->flags, GCF_COMPATIBLE) ? c->original_md5sum : c->ident.md5sum), c->filename);
251 /* ShowInfo put output to stderr, but version information should go
252 * to stdout; this is the only exception */
253 #if !defined(_WIN32)
254 fmt::print("{}\n", message);
255 #else
256 ShowInfoI(message);
257 #endif
262 * Extract the resolution from the given string and store
263 * it in the 'res' parameter.
264 * @param res variable to store the resolution in.
265 * @param s the string to decompose.
267 static void ParseResolution(Dimension *res, const char *s)
269 const char *t = strchr(s, 'x');
270 if (t == nullptr) {
271 ShowInfo("Invalid resolution '{}'", s);
272 return;
275 res->width = std::max(std::strtoul(s, nullptr, 0), 64UL);
276 res->height = std::max(std::strtoul(t + 1, nullptr, 0), 64UL);
281 * Uninitializes drivers, frees allocated memory, cleans pools, ...
282 * Generally, prepares the game for shutting down
284 static void ShutdownGame()
286 IConsoleFree();
288 if (_network_available) NetworkShutDown(); // Shut down the network and close any open connections
290 SocialIntegration::Shutdown();
291 DriverFactoryBase::ShutdownDrivers();
293 UnInitWindowSystem();
295 /* stop the scripts */
296 AI::Uninitialize(false);
297 Game::Uninitialize(false);
299 /* Uninitialize variables that are allocated dynamically */
300 _gamelog.Reset();
302 LinkGraphSchedule::Clear();
303 PoolBase::Clean(PT_ALL);
305 /* No NewGRFs were loaded when it was still bootstrapping. */
306 if (_game_mode != GM_BOOTSTRAP) ResetNewGRFData();
308 UninitFontCache();
312 * Load the introduction game.
313 * @param load_newgrfs Whether to load the NewGRFs or not.
315 static void LoadIntroGame(bool load_newgrfs = true)
317 _game_mode = GM_MENU;
319 if (load_newgrfs) ResetGRFConfig(false);
321 /* Setup main window */
322 ResetWindowSystem();
323 SetupColoursAndInitialWindow();
325 /* Load the default opening screen savegame */
326 if (SaveOrLoad("opntitle.dat", SLO_LOAD, DFT_GAME_FILE, BASESET_DIR) != SL_OK) {
327 GenerateWorld(GWM_EMPTY, 64, 64); // if failed loading, make empty world.
328 SetLocalCompany(COMPANY_SPECTATOR);
329 } else {
330 SetLocalCompany(COMPANY_FIRST);
333 FixTitleGameZoom();
334 _pause_mode = PM_UNPAUSED;
335 _cursor.fix_at = false;
337 CheckForMissingGlyphs();
339 MusicLoop(); // ensure music is correct
342 void MakeNewgameSettingsLive()
344 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
345 if (_settings_game.ai_config[c] != nullptr) {
346 delete _settings_game.ai_config[c];
349 if (_settings_game.game_config != nullptr) {
350 delete _settings_game.game_config;
353 /* Copy newgame settings to active settings.
354 * Also initialise old settings needed for savegame conversion. */
355 _settings_game = _settings_newgame;
356 _old_vds = _settings_client.company.vehicle;
358 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
359 _settings_game.ai_config[c] = nullptr;
360 if (_settings_newgame.ai_config[c] != nullptr) {
361 _settings_game.ai_config[c] = new AIConfig(_settings_newgame.ai_config[c]);
364 _settings_game.game_config = nullptr;
365 if (_settings_newgame.game_config != nullptr) {
366 _settings_game.game_config = new GameConfig(_settings_newgame.game_config);
370 void OpenBrowser(const std::string &url)
372 /* Make sure we only accept urls that are sure to open a browser. */
373 if (url.starts_with("http://") || url.starts_with("https://")) {
374 OSOpenBrowser(url);
378 /** Callback structure of statements to be executed after the NewGRF scan. */
379 struct AfterNewGRFScan : NewGRFScanCallback {
380 TimerGameCalendar::Year startyear = CalendarTime::INVALID_YEAR; ///< The start year.
381 uint32_t generation_seed = GENERATE_NEW_SEED; ///< Seed for the new game.
382 std::string dedicated_host; ///< Hostname for the dedicated server.
383 uint16_t dedicated_port = 0; ///< Port for the dedicated server.
384 std::string connection_string; ///< Information about the server to connect to
385 std::string join_server_password; ///< The password to join the server with.
386 bool save_config = true; ///< The save config setting.
389 * Create a new callback.
391 AfterNewGRFScan()
393 /* Visual C++ 2015 fails compiling this line (AfterNewGRFScan::generation_seed undefined symbol)
394 * if it's placed outside a member function, directly in the struct body. */
395 static_assert(sizeof(generation_seed) == sizeof(_settings_game.game_creation.generation_seed));
398 void OnNewGRFsScanned() override
400 ResetGRFConfig(false);
402 TarScanner::DoScan(TarScanner::SCENARIO);
404 AI::Initialize();
405 Game::Initialize();
407 /* We want the new (correct) NewGRF count to survive the loading. */
408 uint last_newgrf_count = _settings_client.gui.last_newgrf_count;
409 LoadFromConfig();
410 _settings_client.gui.last_newgrf_count = last_newgrf_count;
411 /* Since the default for the palette might have changed due to
412 * reading the configuration file, recalculate that now. */
413 UpdateNewGRFConfigPalette();
415 Game::Uninitialize(true);
416 AI::Uninitialize(true);
417 LoadFromHighScore();
418 LoadHotkeysFromConfig();
419 WindowDesc::LoadFromConfig();
421 /* We have loaded the config, so we may possibly save it. */
422 _save_config = save_config;
424 /* restore saved music and effects volumes */
425 MusicDriver::GetInstance()->SetVolume(_settings_client.music.music_vol);
426 SetEffectVolume(_settings_client.music.effect_vol);
428 if (startyear != CalendarTime::INVALID_YEAR) IConsoleSetSetting("game_creation.starting_year", startyear.base());
429 _settings_newgame.game_creation.generation_seed = generation_seed;
431 if (!dedicated_host.empty()) {
432 _network_bind_list.clear();
433 _network_bind_list.emplace_back(dedicated_host);
435 if (dedicated_port != 0) _settings_client.network.server_port = dedicated_port;
437 /* initialize the ingame console */
438 IConsoleInit();
439 InitializeGUI();
440 IConsoleCmdExec("exec scripts/autoexec.scr 0");
442 /* Make sure _settings is filled with _settings_newgame if we switch to a game directly */
443 if (_switch_mode != SM_NONE) MakeNewgameSettingsLive();
445 if (_network_available && !connection_string.empty()) {
446 LoadIntroGame();
447 _switch_mode = SM_NONE;
449 NetworkClientConnectGame(connection_string, COMPANY_NEW_COMPANY, join_server_password);
452 /* After the scan we're not used anymore. */
453 delete this;
457 void PostMainLoop()
459 WaitTillSaved();
461 /* only save config if we have to */
462 if (_save_config) {
463 SaveToConfig();
464 SaveHotkeysToConfig();
465 WindowDesc::SaveToConfig();
466 SaveToHighScore();
469 /* Reset windowing system, stop drivers, free used memory, ... */
470 ShutdownGame();
473 #if defined(UNIX)
474 extern void DedicatedFork();
475 #endif
478 * Create all the options that OpenTTD supports. Each option is
479 * always a single character with no, an optional or a required value.
480 * @return The available options.
482 static std::vector<OptionData> CreateOptions()
484 std::vector<OptionData> options;
485 /* Options that require a parameter. */
486 for (char c : "GIMSbcmnpqrstv") options.push_back({ .type = ODF_HAS_VALUE, .id = c, .shortname = c });
487 #if !defined(_WIN32)
488 options.push_back({ .type = ODF_HAS_VALUE, .id = 'f', .shortname = 'f' });
489 #endif
491 /* Options with an optional parameter. */
492 for (char c : "Ddg") options.push_back({ .type = ODF_OPTIONAL_VALUE, .id = c, .shortname = c });
494 /* Options without a parameter. */
495 for (char c : "QXehx") options.push_back({ .type = ODF_NO_VALUE, .id = c, .shortname = c });
496 return options;
500 * Main entry point for this lovely game.
501 * @param arguments The command line arguments passed to the application.
502 * @return 0 when there is no error.
504 int openttd_main(std::span<char * const> arguments)
506 _game_session_stats.start_time = std::chrono::steady_clock::now();
507 _game_session_stats.savegame_size = std::nullopt;
509 std::string musicdriver;
510 std::string sounddriver;
511 std::string videodriver;
512 std::string blitter;
513 std::string graphics_set;
514 std::string sounds_set;
515 std::string music_set;
516 Dimension resolution = {0, 0};
517 std::unique_ptr<AfterNewGRFScan> scanner = std::make_unique<AfterNewGRFScan>();
518 bool dedicated = false;
519 bool only_local_path = false;
521 extern bool _dedicated_forks;
522 _dedicated_forks = false;
524 _game_mode = GM_MENU;
525 _switch_mode = SM_MENU;
527 auto options = CreateOptions();
528 GetOptData mgo(arguments.subspan(1), options);
529 int ret = 0;
531 int i;
532 while ((i = mgo.GetOpt()) != -1) {
533 switch (i) {
534 case 'I': graphics_set = mgo.opt; break;
535 case 'S': sounds_set = mgo.opt; break;
536 case 'M': music_set = mgo.opt; break;
537 case 'm': musicdriver = mgo.opt; break;
538 case 's': sounddriver = mgo.opt; break;
539 case 'v': videodriver = mgo.opt; break;
540 case 'b': blitter = mgo.opt; break;
541 case 'D':
542 musicdriver = "null";
543 sounddriver = "null";
544 videodriver = "dedicated";
545 blitter = "null";
546 dedicated = true;
547 SetDebugString("net=4", ShowInfoI);
548 if (mgo.opt != nullptr) {
549 scanner->dedicated_host = ParseFullConnectionString(mgo.opt, scanner->dedicated_port);
551 break;
552 case 'f': _dedicated_forks = true; break;
553 case 'n':
554 scanner->connection_string = mgo.opt; // host:port#company parameter
555 break;
556 case 'p':
557 scanner->join_server_password = mgo.opt;
558 break;
559 case 'r': ParseResolution(&resolution, mgo.opt); break;
560 case 't': scanner->startyear = atoi(mgo.opt); break;
561 case 'd': {
562 #if defined(_WIN32)
563 CreateConsole();
564 #endif
565 if (mgo.opt != nullptr) SetDebugString(mgo.opt, ShowInfoI);
566 break;
568 case 'e':
569 /* Allow for '-e' before or after '-g'. */
570 switch (_switch_mode) {
571 case SM_MENU: _switch_mode = SM_EDITOR; break;
572 case SM_LOAD_GAME: _switch_mode = SM_LOAD_SCENARIO; break;
573 case SM_START_HEIGHTMAP: _switch_mode = SM_LOAD_HEIGHTMAP; break;
574 default: break;
576 break;
577 case 'g':
578 if (mgo.opt != nullptr) {
579 _file_to_saveload.name = mgo.opt;
581 std::string extension = FS2OTTD(std::filesystem::path(OTTD2FS(_file_to_saveload.name)).extension());
582 auto [ft, _] = FiosGetSavegameListCallback(SLO_LOAD, _file_to_saveload.name, extension);
583 if (ft == FIOS_TYPE_INVALID) {
584 std::tie(ft, _) = FiosGetScenarioListCallback(SLO_LOAD, _file_to_saveload.name, extension);
586 if (ft == FIOS_TYPE_INVALID) {
587 std::tie(ft, _) = FiosGetHeightmapListCallback(SLO_LOAD, _file_to_saveload.name, extension);
590 /* Allow for '-e' before or after '-g'. */
591 switch (GetAbstractFileType(ft)) {
592 case FT_SAVEGAME: _switch_mode = (_switch_mode == SM_EDITOR ? SM_LOAD_SCENARIO : SM_LOAD_GAME); break;
593 case FT_SCENARIO: _switch_mode = (_switch_mode == SM_EDITOR ? SM_LOAD_SCENARIO : SM_LOAD_GAME); break;
594 case FT_HEIGHTMAP: _switch_mode = (_switch_mode == SM_EDITOR ? SM_LOAD_HEIGHTMAP : SM_START_HEIGHTMAP); break;
595 default: break;
598 _file_to_saveload.SetMode(SLO_LOAD, GetAbstractFileType(ft), GetDetailedFileType(ft));
599 break;
602 _switch_mode = SM_NEWGAME;
603 /* Give a random map if no seed has been given */
604 if (scanner->generation_seed == GENERATE_NEW_SEED) {
605 scanner->generation_seed = InteractiveRandom();
607 break;
608 case 'q': {
609 DeterminePaths(arguments[0], only_local_path);
610 if (StrEmpty(mgo.opt)) {
611 ret = 1;
612 return ret;
615 std::string extension = FS2OTTD(std::filesystem::path(OTTD2FS(mgo.opt)).extension());
616 auto [_, title] = FiosGetSavegameListCallback(SLO_LOAD, mgo.opt, extension);
618 _load_check_data.Clear();
619 SaveOrLoadResult res = SaveOrLoad(mgo.opt, SLO_CHECK, DFT_GAME_FILE, SAVE_DIR, false);
620 if (res != SL_OK || _load_check_data.HasErrors()) {
621 fmt::print(stderr, "Failed to open savegame\n");
622 if (_load_check_data.HasErrors()) {
623 InitializeLanguagePacks(); // A language pack is needed for GetString()
624 SetDParamStr(0, _load_check_data.error_msg);
625 fmt::print(stderr, "{}\n", GetString(_load_check_data.error));
627 return ret;
630 WriteSavegameInfo(title);
631 return ret;
633 case 'Q': {
634 extern int _skip_all_newgrf_scanning;
635 _skip_all_newgrf_scanning += 1;
636 break;
638 case 'G': scanner->generation_seed = std::strtoul(mgo.opt, nullptr, 10); break;
639 case 'c': _config_file = mgo.opt; break;
640 case 'x': scanner->save_config = false; break;
641 case 'X': only_local_path = true; break;
642 case 'h':
643 i = -2; // Force printing of help.
644 break;
646 if (i == -2) break;
649 if (i == -2 || !mgo.arguments.empty()) {
650 /* Either the user typed '-h', they made an error, or they added unrecognized command line arguments.
651 * In all cases, print the help, and exit.
653 * The next two functions are needed to list the graphics sets. We can't do them earlier
654 * because then we cannot show it on the debug console as that hasn't been configured yet. */
655 DeterminePaths(arguments[0], only_local_path);
656 TarScanner::DoScan(TarScanner::BASESET);
657 BaseGraphics::FindSets();
658 BaseSounds::FindSets();
659 BaseMusic::FindSets();
660 ShowHelp();
661 return ret;
664 DeterminePaths(arguments[0], only_local_path);
665 TarScanner::DoScan(TarScanner::BASESET);
667 if (dedicated) Debug(net, 3, "Starting dedicated server, version {}", _openttd_revision);
668 if (_dedicated_forks && !dedicated) _dedicated_forks = false;
670 #if defined(UNIX)
671 /* We must fork here, or we'll end up without some resources we need (like sockets) */
672 if (_dedicated_forks) DedicatedFork();
673 #endif
675 LoadFromConfig(true);
677 if (resolution.width != 0) _cur_resolution = resolution;
679 /* Limit width times height times bytes per pixel to fit a 32 bit
680 * integer, This way all internal drawing routines work correctly.
681 * A resolution that has one component as 0 is treated as a marker to
682 * auto-detect a good window size. */
683 _cur_resolution.width = std::min(_cur_resolution.width, UINT16_MAX / 2u);
684 _cur_resolution.height = std::min(_cur_resolution.height, UINT16_MAX / 2u);
686 /* Assume the cursor starts within the game as not all video drivers
687 * get an event that the cursor is within the window when it is opened.
688 * Saying the cursor is there makes no visible difference as it would
689 * just be out of the bounds of the window. */
690 _cursor.in_window = true;
692 /* enumerate language files */
693 InitializeLanguagePacks();
695 /* Initialize the font cache */
696 InitFontCache(false);
698 /* This must be done early, since functions use the SetWindowDirty* calls */
699 InitWindowSystem();
701 BaseGraphics::FindSets();
702 bool valid_graphics_set;
703 if (!graphics_set.empty()) {
704 valid_graphics_set = BaseGraphics::SetSetByName(graphics_set);
705 } else if (BaseGraphics::ini_data.shortname != 0) {
706 graphics_set = BaseGraphics::ini_data.name;
707 valid_graphics_set = BaseGraphics::SetSetByShortname(BaseGraphics::ini_data.shortname);
708 if (valid_graphics_set && !BaseGraphics::ini_data.extra_params.empty()) {
709 GRFConfig &extra_cfg = BaseGraphics::GetUsedSet()->GetOrCreateExtraConfig();
710 if (extra_cfg.IsCompatible(BaseGraphics::ini_data.extra_version)) {
711 extra_cfg.SetParams(BaseGraphics::ini_data.extra_params);
714 } else if (!BaseGraphics::ini_data.name.empty()) {
715 graphics_set = BaseGraphics::ini_data.name;
716 valid_graphics_set = BaseGraphics::SetSetByName(BaseGraphics::ini_data.name);
717 } else {
718 valid_graphics_set = true;
719 BaseGraphics::SetSet(nullptr); // ignore error, continue to bootstrap GUI
721 if (!valid_graphics_set) {
722 BaseGraphics::SetSet(nullptr);
724 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_GRAPHICS_NOT_FOUND);
725 msg.SetDParamStr(0, graphics_set);
726 ScheduleErrorMessage(msg);
729 /* Initialize game palette */
730 GfxInitPalettes();
732 Debug(misc, 1, "Loading blitter...");
733 if (blitter.empty() && !_ini_blitter.empty()) blitter = _ini_blitter;
734 _blitter_autodetected = blitter.empty();
735 /* Activate the initial blitter.
736 * This is only some initial guess, after NewGRFs have been loaded SwitchNewGRFBlitter may switch to a different one.
737 * - Never guess anything, if the user specified a blitter. (_blitter_autodetected)
738 * - Use 32bpp blitter if baseset or 8bpp-support settings says so.
739 * - Use 8bpp blitter otherwise.
741 if (!_blitter_autodetected ||
742 (_support8bpp != S8BPP_NONE && (BaseGraphics::GetUsedSet() == nullptr || BaseGraphics::GetUsedSet()->blitter == BLT_8BPP)) ||
743 BlitterFactory::SelectBlitter("32bpp-anim") == nullptr) {
744 if (BlitterFactory::SelectBlitter(blitter) == nullptr) {
745 blitter.empty() ?
746 UserError("Failed to autoprobe blitter") :
747 UserError("Failed to select requested blitter '{}'; does it exist?", blitter);
751 if (videodriver.empty() && !_ini_videodriver.empty()) videodriver = _ini_videodriver;
752 DriverFactoryBase::SelectDriver(videodriver, Driver::DT_VIDEO);
754 InitializeSpriteSorter();
756 /* Initialize the zoom level of the screen to normal */
757 _screen.zoom = ZOOM_LVL_MIN;
759 /* The video driver is now selected, now initialise GUI zoom */
760 UpdateGUIZoom();
762 SocialIntegration::Initialize();
763 NetworkStartUp(); // initialize network-core
765 if (!HandleBootstrap()) {
766 ShutdownGame();
767 return ret;
770 VideoDriver::GetInstance()->ClaimMousePointer();
772 /* initialize screenshot formats */
773 InitializeScreenshotFormats();
775 BaseSounds::FindSets();
776 if (sounds_set.empty() && !BaseSounds::ini_set.empty()) sounds_set = BaseSounds::ini_set;
777 if (!BaseSounds::SetSetByName(sounds_set)) {
778 if (sounds_set.empty() || !BaseSounds::SetSet({})) {
779 UserError("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 1.4 of README.md.");
780 } else {
781 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_SOUNDS_NOT_FOUND);
782 msg.SetDParamStr(0, sounds_set);
783 ScheduleErrorMessage(msg);
787 BaseMusic::FindSets();
788 if (music_set.empty() && !BaseMusic::ini_set.empty()) music_set = BaseMusic::ini_set;
789 if (!BaseMusic::SetSetByName(music_set)) {
790 if (music_set.empty() || !BaseMusic::SetSet({})) {
791 UserError("Failed to find a music set. Please acquire a music set for OpenTTD. See section 1.4 of README.md.");
792 } else {
793 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_MUSIC_NOT_FOUND);
794 msg.SetDParamStr(0, music_set);
795 ScheduleErrorMessage(msg);
799 if (sounddriver.empty() && !_ini_sounddriver.empty()) sounddriver = _ini_sounddriver;
800 DriverFactoryBase::SelectDriver(sounddriver, Driver::DT_SOUND);
802 if (musicdriver.empty() && !_ini_musicdriver.empty()) musicdriver = _ini_musicdriver;
803 DriverFactoryBase::SelectDriver(musicdriver, Driver::DT_MUSIC);
805 GenerateWorld(GWM_EMPTY, 64, 64); // Make the viewport initialization happy
806 LoadIntroGame(false);
808 /* ScanNewGRFFiles now has control over the scanner. */
809 RequestNewGRFScan(scanner.release());
811 VideoDriver::GetInstance()->MainLoop();
813 PostMainLoop();
814 return ret;
817 void HandleExitGameRequest()
819 if (_game_mode == GM_MENU || _game_mode == GM_BOOTSTRAP) { // do not ask to quit on the main screen
820 _exit_game = true;
821 } else if (_settings_client.gui.autosave_on_exit) {
822 DoExitSave();
823 _survey.Transmit(NetworkSurveyHandler::Reason::EXIT, true);
824 _exit_game = true;
825 } else {
826 AskExitGame();
831 * Triggers everything required to set up a saved scenario for a new game.
833 static void OnStartScenario()
835 /* Reset engine pool to simplify changing engine NewGRFs in scenario editor. */
836 EngineOverrideManager::ResetToCurrentNewGRFConfig();
838 /* Make sure all industries were built "this year", to avoid too early closures. (#9918) */
839 for (Industry *i : Industry::Iterate()) {
840 i->last_prod_year = TimerGameEconomy::year;
845 * Triggers everything that should be triggered when starting a game.
846 * @param dedicated_server Whether this is a dedicated server or not.
848 static void OnStartGame(bool dedicated_server)
850 /* Update the local company for a loaded game. It is either the first available company
851 * or in the case of a dedicated server, a spectator */
852 SetLocalCompany(dedicated_server ? COMPANY_SPECTATOR : GetFirstPlayableCompanyID());
854 NetworkOnGameStart();
856 /* Execute the game-start script */
857 IConsoleCmdExec("exec scripts/game_start.scr 0");
860 static void MakeNewGameDone()
862 SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
864 /* In a dedicated server, the server does not play */
865 if (!VideoDriver::GetInstance()->HasGUI()) {
866 OnStartGame(true);
867 if (_settings_client.gui.pause_on_newgame) Command<CMD_PAUSE>::Post(PM_PAUSED_NORMAL, true);
868 return;
871 /* Create a single company */
872 DoStartupNewCompany(false);
874 Company *c = Company::Get(COMPANY_FIRST);
875 c->settings = _settings_client.company;
877 /* Overwrite color from settings if needed
878 * COLOUR_END corresponds to Random colour */
880 if (_settings_client.gui.starting_colour != COLOUR_END) {
881 c->colour = _settings_client.gui.starting_colour;
882 ResetCompanyLivery(c);
883 _company_colours[c->index] = c->colour;
886 if (_settings_client.gui.starting_colour_secondary != COLOUR_END && HasBit(_loaded_newgrf_features.used_liveries, LS_DEFAULT)) {
887 Command<CMD_SET_COMPANY_COLOUR>::Post(LS_DEFAULT, false, _settings_client.gui.starting_colour_secondary);
890 OnStartGame(false);
892 InitializeRailGUI();
893 InitializeRoadGUI();
895 if (_settings_client.gui.pause_on_newgame) Command<CMD_PAUSE>::Post(PM_PAUSED_NORMAL, true);
897 CheckEngines();
898 CheckIndustries();
899 MarkWholeScreenDirty();
902 static void MakeNewGame(bool from_heightmap, bool reset_settings)
904 _game_mode = GM_NORMAL;
905 if (!from_heightmap) {
906 /* "reload" command needs to know what mode we were in. */
907 _file_to_saveload.SetMode(SLO_INVALID, FT_INVALID, DFT_INVALID);
910 ResetGRFConfig(true);
912 GenerateWorldSetCallback(&MakeNewGameDone);
913 GenerateWorld(from_heightmap ? GWM_HEIGHTMAP : GWM_NEWGAME, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y, reset_settings);
916 static void MakeNewEditorWorldDone()
918 SetLocalCompany(OWNER_NONE);
921 static void MakeNewEditorWorld()
923 _game_mode = GM_EDITOR;
924 /* "reload" command needs to know what mode we were in. */
925 _file_to_saveload.SetMode(SLO_INVALID, FT_INVALID, DFT_INVALID);
927 ResetGRFConfig(true);
929 GenerateWorldSetCallback(&MakeNewEditorWorldDone);
930 GenerateWorld(GWM_EMPTY, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
934 * Load the specified savegame but on error do different things.
935 * If loading fails due to corrupt savegame, bad version, etc. go back to
936 * a previous correct state. In the menu for example load the intro game again.
937 * @param filename file to be loaded
938 * @param fop mode of loading, always SLO_LOAD
939 * @param newgm switch to this mode of loading fails due to some unknown error
940 * @param subdir default directory to look for filename, set to 0 if not needed
941 * @param lf Load filter to use, if nullptr: use filename + subdir.
943 bool SafeLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, std::shared_ptr<LoadFilter> lf = nullptr)
945 assert(fop == SLO_LOAD);
946 assert(dft == DFT_GAME_FILE || (lf == nullptr && dft == DFT_OLD_GAME_FILE));
947 GameMode ogm = _game_mode;
949 _game_mode = newgm;
951 SaveOrLoadResult result = (lf == nullptr) ? SaveOrLoad(filename, fop, dft, subdir) : LoadWithFilter(lf);
952 if (result == SL_OK) return true;
954 if (_network_dedicated && ogm == GM_MENU) {
956 * If we are a dedicated server *and* we just were in the menu, then we
957 * are loading the first savegame. If that fails, not starting the
958 * server is a better reaction than starting the server with a newly
959 * generated map as it is quite likely to be started from a script.
961 Debug(net, 0, "Loading requested map failed; closing server.");
962 _exit_game = true;
963 return false;
966 if (result != SL_REINIT) {
967 _game_mode = ogm;
968 return false;
971 if (_network_dedicated) {
973 * If we are a dedicated server, have already loaded/started a game,
974 * and then loading the savegame fails in a manner that we need to
975 * reinitialize everything. We must not fall back into the menu mode
976 * with the intro game, as that is unjoinable by clients. So there is
977 * nothing else to do than start a new game, as it might have failed
978 * trying to reload the originally loaded savegame/scenario.
980 Debug(net, 0, "Loading game failed, so a new (random) game will be started");
981 MakeNewGame(false, true);
982 return false;
985 if (_network_server) {
986 /* We can't load the intro game as server, so disconnect first. */
987 NetworkDisconnect();
990 switch (ogm) {
991 default:
992 case GM_MENU: LoadIntroGame(); break;
993 case GM_EDITOR: MakeNewEditorWorld(); break;
995 return false;
998 static void UpdateSocialIntegration(GameMode game_mode)
1000 switch (game_mode) {
1001 case GM_BOOTSTRAP:
1002 case GM_MENU:
1003 SocialIntegration::EventEnterMainMenu();
1004 break;
1006 case GM_NORMAL:
1007 if (_networking) {
1008 SocialIntegration::EventEnterMultiplayer(Map::SizeX(), Map::SizeY());
1009 } else {
1010 SocialIntegration::EventEnterSingleplayer(Map::SizeX(), Map::SizeY());
1012 break;
1014 case GM_EDITOR:
1015 SocialIntegration::EventEnterScenarioEditor(Map::SizeX(), Map::SizeY());
1016 break;
1020 void SwitchToMode(SwitchMode new_mode)
1022 /* If we are saving something, the network stays in its current state */
1023 if (new_mode != SM_SAVE_GAME) {
1024 /* If the network is active, make it not-active */
1025 if (_networking) {
1026 if (_network_server && (new_mode == SM_LOAD_GAME || new_mode == SM_NEWGAME || new_mode == SM_RESTARTGAME)) {
1027 NetworkReboot();
1028 } else {
1029 NetworkDisconnect();
1033 /* If we are a server, we restart the server */
1034 if (_is_network_server) {
1035 /* But not if we are going to the menu */
1036 if (new_mode != SM_MENU) {
1037 /* check if we should reload the config */
1038 if (_settings_client.network.reload_cfg) {
1039 LoadFromConfig();
1040 MakeNewgameSettingsLive();
1041 ResetGRFConfig(false);
1043 NetworkServerStart();
1044 } else {
1045 /* This client no longer wants to be a network-server */
1046 _is_network_server = false;
1051 /* Make sure all AI controllers are gone at quitting game */
1052 if (new_mode != SM_SAVE_GAME) AI::KillAll();
1054 /* When we change mode, reset the autosave. */
1055 if (new_mode != SM_SAVE_GAME) ChangeAutosaveFrequency(true);
1057 /* Transmit the survey if we were in normal-mode and not saving. It always means we leaving the current game. */
1058 if (_game_mode == GM_NORMAL && new_mode != SM_SAVE_GAME) _survey.Transmit(NetworkSurveyHandler::Reason::LEAVE);
1060 /* Keep track when we last switch mode. Used for survey, to know how long someone was in a game. */
1061 if (new_mode != SM_SAVE_GAME) {
1062 _game_session_stats.start_time = std::chrono::steady_clock::now();
1063 _game_session_stats.savegame_size = std::nullopt;
1066 switch (new_mode) {
1067 case SM_EDITOR: // Switch to scenario editor
1068 MakeNewEditorWorld();
1069 GenerateSavegameId();
1071 UpdateSocialIntegration(GM_EDITOR);
1072 break;
1074 case SM_RELOADGAME: // Reload with what-ever started the game
1075 if (_file_to_saveload.abstract_ftype == FT_SAVEGAME || _file_to_saveload.abstract_ftype == FT_SCENARIO) {
1076 /* Reload current savegame/scenario */
1077 _switch_mode = _game_mode == GM_EDITOR ? SM_LOAD_SCENARIO : SM_LOAD_GAME;
1078 SwitchToMode(_switch_mode);
1079 break;
1080 } else if (_file_to_saveload.abstract_ftype == FT_HEIGHTMAP) {
1081 /* Restart current heightmap */
1082 _switch_mode = _game_mode == GM_EDITOR ? SM_LOAD_HEIGHTMAP : SM_RESTART_HEIGHTMAP;
1083 SwitchToMode(_switch_mode);
1084 break;
1087 MakeNewGame(false, new_mode == SM_NEWGAME);
1088 GenerateSavegameId();
1090 UpdateSocialIntegration(GM_NORMAL);
1091 break;
1093 case SM_RESTARTGAME: // Restart --> 'Random game' with current settings
1094 case SM_NEWGAME: // New Game --> 'Random game'
1095 MakeNewGame(false, new_mode == SM_NEWGAME);
1096 GenerateSavegameId();
1098 UpdateSocialIntegration(GM_NORMAL);
1099 break;
1101 case SM_LOAD_GAME: { // Load game, Play Scenario
1102 ResetGRFConfig(true);
1103 ResetWindowSystem();
1105 if (!SafeLoad(_file_to_saveload.name, _file_to_saveload.file_op, _file_to_saveload.detail_ftype, GM_NORMAL, NO_DIRECTORY)) {
1106 ShowErrorMessage(GetSaveLoadErrorType(), GetSaveLoadErrorMessage(), WL_CRITICAL);
1107 } else {
1108 if (_file_to_saveload.abstract_ftype == FT_SCENARIO) {
1109 OnStartScenario();
1111 OnStartGame(_network_dedicated);
1112 /* Decrease pause counter (was increased from opening load dialog) */
1113 Command<CMD_PAUSE>::Post(PM_PAUSED_SAVELOAD, false);
1116 UpdateSocialIntegration(GM_NORMAL);
1117 break;
1120 case SM_RESTART_HEIGHTMAP: // Load a heightmap and start a new game from it with current settings
1121 case SM_START_HEIGHTMAP: // Load a heightmap and start a new game from it
1122 MakeNewGame(true, new_mode == SM_START_HEIGHTMAP);
1123 GenerateSavegameId();
1125 UpdateSocialIntegration(GM_NORMAL);
1126 break;
1128 case SM_LOAD_HEIGHTMAP: // Load heightmap from scenario editor
1129 SetLocalCompany(OWNER_NONE);
1131 _game_mode = GM_EDITOR;
1133 GenerateWorld(GWM_HEIGHTMAP, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
1134 GenerateSavegameId();
1135 MarkWholeScreenDirty();
1137 UpdateSocialIntegration(GM_EDITOR);
1138 break;
1140 case SM_LOAD_SCENARIO: { // Load scenario from scenario editor
1141 if (SafeLoad(_file_to_saveload.name, _file_to_saveload.file_op, _file_to_saveload.detail_ftype, GM_EDITOR, NO_DIRECTORY)) {
1142 SetLocalCompany(OWNER_NONE);
1143 GenerateSavegameId();
1144 _settings_newgame.game_creation.starting_year = TimerGameCalendar::year;
1145 /* Cancel the saveload pausing */
1146 Command<CMD_PAUSE>::Post(PM_PAUSED_SAVELOAD, false);
1147 } else {
1148 ShowErrorMessage(GetSaveLoadErrorType(), GetSaveLoadErrorMessage(), WL_CRITICAL);
1151 UpdateSocialIntegration(GM_EDITOR);
1152 break;
1155 case SM_JOIN_GAME: // Join a multiplayer game
1156 LoadIntroGame();
1157 NetworkClientJoinGame();
1159 SocialIntegration::EventJoiningMultiplayer();
1160 break;
1162 case SM_MENU: // Switch to game intro menu
1163 LoadIntroGame();
1164 if (BaseSounds::ini_set.empty() && BaseSounds::GetUsedSet()->fallback && SoundDriver::GetInstance()->HasOutput()) {
1165 ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET, INVALID_STRING_ID, WL_CRITICAL);
1166 BaseSounds::ini_set = BaseSounds::GetUsedSet()->name;
1168 if (_settings_client.network.participate_survey == PS_ASK) {
1169 /* No matter how often you go back to the main menu, only ask the first time. */
1170 static bool asked_once = false;
1171 if (!asked_once) {
1172 asked_once = true;
1173 ShowNetworkAskSurvey();
1177 UpdateSocialIntegration(GM_MENU);
1178 break;
1180 case SM_SAVE_GAME: // Save game.
1181 /* Make network saved games on pause compatible to singleplayer mode */
1182 if (SaveOrLoad(_file_to_saveload.name, SLO_SAVE, DFT_GAME_FILE, NO_DIRECTORY) != SL_OK) {
1183 ShowErrorMessage(GetSaveLoadErrorType(), GetSaveLoadErrorMessage(), WL_ERROR);
1184 } else {
1185 CloseWindowById(WC_SAVELOAD, 0);
1187 break;
1189 case SM_SAVE_HEIGHTMAP: // Save heightmap.
1190 MakeHeightmapScreenshot(_file_to_saveload.name.c_str());
1191 CloseWindowById(WC_SAVELOAD, 0);
1192 break;
1194 case SM_GENRANDLAND: // Generate random land within scenario editor
1195 SetLocalCompany(OWNER_NONE);
1196 GenerateWorld(GWM_RANDOM, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
1197 /* XXX: set date */
1198 MarkWholeScreenDirty();
1199 break;
1201 default: NOT_REACHED();
1208 * State controlling game loop.
1209 * The state must not be changed from anywhere but here.
1210 * That check is enforced in DoCommand.
1212 void StateGameLoop()
1214 if (!_networking || _network_server) {
1215 StateGameLoop_LinkGraphPauseControl();
1218 /* Don't execute the state loop during pause or when modal windows are open. */
1219 if (_pause_mode != PM_UNPAUSED || HasModalProgress()) {
1220 PerformanceMeasurer::Paused(PFE_GAMELOOP);
1221 PerformanceMeasurer::Paused(PFE_GL_ECONOMY);
1222 PerformanceMeasurer::Paused(PFE_GL_TRAINS);
1223 PerformanceMeasurer::Paused(PFE_GL_ROADVEHS);
1224 PerformanceMeasurer::Paused(PFE_GL_SHIPS);
1225 PerformanceMeasurer::Paused(PFE_GL_AIRCRAFT);
1226 PerformanceMeasurer::Paused(PFE_GL_LANDSCAPE);
1228 if (!HasModalProgress()) UpdateLandscapingLimits();
1229 #ifndef DEBUG_DUMP_COMMANDS
1230 Game::GameLoop();
1231 #endif
1232 return;
1235 PerformanceMeasurer framerate(PFE_GAMELOOP);
1236 PerformanceAccumulator::Reset(PFE_GL_LANDSCAPE);
1238 Layouter::ReduceLineCache();
1240 if (_game_mode == GM_EDITOR) {
1241 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP);
1242 RunTileLoop();
1243 CallVehicleTicks();
1244 CallLandscapeTick();
1245 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP);
1246 UpdateLandscapingLimits();
1248 CallWindowGameTickEvent();
1249 NewsLoop();
1250 } else {
1251 if (_debug_desync_level > 2 && TimerGameEconomy::date_fract == 0 && (TimerGameEconomy::date.base() & 0x1F) == 0) {
1252 /* Save the desync savegame if needed. */
1253 std::string name = fmt::format("dmp_cmds_{:08x}_{:08x}.sav", _settings_game.game_creation.generation_seed, TimerGameEconomy::date);
1254 SaveOrLoad(name, SLO_SAVE, DFT_GAME_FILE, AUTOSAVE_DIR, false);
1257 CheckCaches();
1259 /* All these actions has to be done from OWNER_NONE
1260 * for multiplayer compatibility */
1261 Backup<CompanyID> cur_company(_current_company, OWNER_NONE);
1263 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP);
1264 AnimateAnimatedTiles();
1265 if (TimerManager<TimerGameCalendar>::Elapsed(1)) {
1266 RunVehicleCalendarDayProc();
1268 TimerManager<TimerGameEconomy>::Elapsed(1);
1269 TimerManager<TimerGameTick>::Elapsed(1);
1270 RunTileLoop();
1271 CallVehicleTicks();
1272 CallLandscapeTick();
1273 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP);
1275 #ifndef DEBUG_DUMP_COMMANDS
1277 PerformanceMeasurer script_framerate(PFE_ALLSCRIPTS);
1278 AI::GameLoop();
1279 Game::GameLoop();
1281 #endif
1282 UpdateLandscapingLimits();
1284 CallWindowGameTickEvent();
1285 NewsLoop();
1286 cur_company.Restore();
1289 assert(IsLocalCompany());
1292 /** Interval for regular autosaves. Initialized at zero to disable till settings are loaded. */
1293 static IntervalTimer<TimerGameRealtime> _autosave_interval({std::chrono::milliseconds::zero(), TimerGameRealtime::AUTOSAVE}, [](auto)
1295 /* We reset the command-during-pause mode here, so we don't continue
1296 * to make auto-saves when nothing more is changing. */
1297 _pause_mode &= ~PM_COMMAND_DURING_PAUSE;
1299 _do_autosave = true;
1300 SetWindowDirty(WC_STATUS_BAR, 0);
1302 static FiosNumberedSaveName _autosave_ctr("autosave");
1303 DoAutoOrNetsave(_autosave_ctr);
1305 _do_autosave = false;
1306 SetWindowDirty(WC_STATUS_BAR, 0);
1310 * Reset the interval of the autosave.
1312 * If reset is not set, this does not set the elapsed time on the timer,
1313 * so if the interval is smaller, it might result in an autosave being done
1314 * immediately.
1316 * @param reset Whether to reset the timer back to zero, or to continue.
1318 void ChangeAutosaveFrequency(bool reset)
1320 _autosave_interval.SetInterval({std::chrono::minutes(_settings_client.gui.autosave_interval), TimerGameRealtime::AUTOSAVE}, reset);
1324 * Request a new NewGRF scan. This will be executed on the next game-tick.
1325 * This is mostly needed to ensure NewGRF scans (which are blocking) are
1326 * done in the game-thread, and not in the draw-thread (which most often
1327 * triggers this request).
1328 * @param callback Optional callback to call when NewGRF scan is completed.
1329 * @return True when the NewGRF scan was actually requested, false when the scan was already running.
1331 bool RequestNewGRFScan(NewGRFScanCallback *callback)
1333 if (_request_newgrf_scan) return false;
1335 _request_newgrf_scan = true;
1336 _request_newgrf_scan_callback = callback;
1337 return true;
1340 void GameLoop()
1342 if (_game_mode == GM_BOOTSTRAP) {
1343 /* Check for UDP stuff */
1344 if (_network_available) NetworkBackgroundLoop();
1345 return;
1348 if (_request_newgrf_scan) {
1349 ScanNewGRFFiles(_request_newgrf_scan_callback);
1350 _request_newgrf_scan = false;
1351 _request_newgrf_scan_callback = nullptr;
1352 /* In case someone closed the game during our scan, don't do anything else. */
1353 if (_exit_game) return;
1356 ProcessAsyncSaveFinish();
1358 if (_game_mode == GM_NORMAL) {
1359 static auto last_time = std::chrono::steady_clock::now();
1360 auto now = std::chrono::steady_clock::now();
1361 auto delta_ms = std::chrono::duration_cast<std::chrono::milliseconds>(now - last_time);
1362 if (delta_ms.count() != 0) {
1363 TimerManager<TimerGameRealtime>::Elapsed(delta_ms);
1364 last_time = now;
1368 /* switch game mode? */
1369 if (_switch_mode != SM_NONE && !HasModalProgress()) {
1370 SwitchToMode(_switch_mode);
1371 _switch_mode = SM_NONE;
1372 if (_exit_game) return;
1375 IncreaseSpriteLRU();
1377 /* Check for UDP stuff */
1378 if (_network_available) NetworkBackgroundLoop();
1380 DebugSendRemoteMessages();
1382 if (_networking && !HasModalProgress()) {
1383 /* Multiplayer */
1384 NetworkGameLoop();
1385 } else {
1386 if (_network_reconnect > 0 && --_network_reconnect == 0) {
1387 /* This means that we want to reconnect to the last host
1388 * We do this here, because it means that the network is really closed */
1389 NetworkClientConnectGame(_settings_client.network.last_joined, COMPANY_SPECTATOR);
1391 /* Singleplayer */
1392 StateGameLoop();
1395 if (!_pause_mode && HasBit(_display_opt, DO_FULL_ANIMATION)) DoPaletteAnimations();
1397 SoundDriver::GetInstance()->MainLoop();
1398 MusicLoop();
1399 SocialIntegration::RunCallbacks();