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/>.
8 /** @file openttd.cpp Functions related to starting OpenTTD. */
12 #include "blitter/factory.hpp"
13 #include "sound/sound_driver.hpp"
14 #include "music/music_driver.hpp"
15 #include "video/video_driver.hpp"
18 #include "fontcache.h"
20 #include "error_func.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"
34 #include "console_func.h"
35 #include "screenshot.h"
36 #include "network/network.h"
37 #include "network/network_server.h"
38 #include "network/network_func.h"
40 #include "ai/ai_config.hpp"
41 #include "settings_func.h"
44 #include "strings_func.h"
45 #include "vehicle_func.h"
47 #include "animated_tile_func.h"
48 #include "roadstop_base.h"
49 #include "elrail_func.h"
51 #include "highscore.h"
52 #include "station_base.h"
54 #include "engine_func.h"
55 #include "core/random_func.hpp"
58 #include "core/backup_type.hpp"
61 #include "misc/getoptdata.h"
62 #include "game/game.hpp"
63 #include "game/game_config.hpp"
65 #include "subsidy_func.h"
66 #include "gfx_layout.h"
67 #include "viewport_func.h"
68 #include "viewport_sprite_sorter.h"
69 #include "framerate_type.h"
71 #include "network/network_gui.h"
72 #include "network/network_survey.h"
74 #include "timer/timer.h"
75 #include "timer/timer_game_calendar.h"
76 #include "timer/timer_game_economy.h"
77 #include "timer/timer_game_realtime.h"
78 #include "timer/timer_game_tick.h"
79 #include "social_integration.h"
81 #include "linkgraph/linkgraphschedule.h"
83 #include <system_error>
85 #include "safeguards.h"
88 # include <emscripten.h>
89 # include <emscripten/html5.h>
92 void CallLandscapeTick();
93 void DoPaletteAnimations();
95 void CallWindowGameTickEvent();
96 bool HandleBootstrap();
98 extern void AfterLoadCompanyStats();
99 extern Company
*DoStartupNewCompany(bool is_ai
, CompanyID company
= INVALID_COMPANY
);
100 extern void OSOpenBrowser(const std::string
&url
);
101 extern void RebuildTownCaches();
102 extern void ShowOSErrorBox(const char *buf
, bool system
);
103 extern std::string _config_file
;
105 bool _save_config
= false;
106 bool _request_newgrf_scan
= false;
107 NewGRFScanCallback
*_request_newgrf_scan_callback
= nullptr;
110 * Error handling for fatal user errors.
111 * @param str the string to print.
112 * @note Does NEVER return.
114 void UserErrorI(const std::string
&str
)
116 ShowOSErrorBox(str
.c_str(), false);
117 if (VideoDriver::GetInstance() != nullptr) VideoDriver::GetInstance()->Stop();
119 #ifdef __EMSCRIPTEN__
120 emscripten_exit_pointerlock();
121 /* In effect, the game ends here. As emscripten_set_main_loop() caused
122 * the stack to be unwound, the code after MainLoop() in
123 * openttd_main() is never executed. */
124 EM_ASM(if (window
["openttd_abort"]) openttd_abort());
131 * Error handling for fatal non-user errors.
132 * @param str the string to print.
133 * @note Does NEVER return.
135 void FatalErrorI(const std::string
&str
)
137 if (VideoDriver::GetInstance() == nullptr || VideoDriver::GetInstance()->HasGUI()) {
138 ShowOSErrorBox(str
.c_str(), true);
141 /* Set the error message for the crash log and then invoke it. */
142 CrashLog::SetErrorMessage(str
);
147 * Show the help message when someone passed a wrong parameter.
149 static void ShowHelp()
154 std::back_insert_iterator
<std::string
> output_iterator
= std::back_inserter(str
);
155 fmt::format_to(output_iterator
, "OpenTTD {}\n", _openttd_revision
);
159 "Command line options:\n"
160 " -v drv = Set video driver (see below)\n"
161 " -s drv = Set sound driver (see below)\n"
162 " -m drv = Set music driver (see below)\n"
163 " -b drv = Set the blitter to use (see below)\n"
164 " -r res = Set resolution (for instance 800x600)\n"
165 " -h = Display this help text\n"
166 " -t year = Set starting year\n"
167 " -d [[fac=]lvl[,...]]= Debug mode\n"
168 " -e = Start Editor\n"
169 " -g [savegame|scenario|heightmap] = Start new/savegame/scenario/heightmap immediately\n"
170 " -G seed = Set random seed\n"
171 " -n host[:port][#company]= Join network game\n"
172 " -p password = Password to join server\n"
173 " -P password = Password to join company\n"
174 " -D [host][:port] = Start dedicated server\n"
176 " -f = Fork into the background (dedicated only)\n"
178 " -I graphics_set = Force the graphics set (see below)\n"
179 " -S sounds_set = Force the sounds set (see below)\n"
180 " -M music_set = Force the music set (see below)\n"
181 " -c config_file = Use 'config_file' instead of 'openttd.cfg'\n"
182 " -x = Never save configuration changes to disk\n"
183 " -X = Don't use global folders to search for files\n"
184 " -q savegame = Write some information about the savegame and exit\n"
185 " -Q = Don't scan for/load NewGRF files on startup\n"
186 " -QQ = Disable NewGRF scanning/loading entirely\n"
189 /* List the graphics packs */
190 BaseGraphics::GetSetsList(output_iterator
);
192 /* List the sounds packs */
193 BaseSounds::GetSetsList(output_iterator
);
195 /* List the music packs */
196 BaseMusic::GetSetsList(output_iterator
);
198 /* List the drivers */
199 DriverFactoryBase::GetDriversInfo(output_iterator
);
201 /* List the blitters */
202 BlitterFactory::GetBlittersInfo(output_iterator
);
204 /* List the debug facilities. */
205 DumpDebugFacilityNames(output_iterator
);
207 /* We need to initialize the AI, so it finds the AIs */
209 AI::GetConsoleList(output_iterator
, true);
210 AI::Uninitialize(true);
212 /* We need to initialize the GameScript, so it finds the GSs */
214 Game::GetConsoleList(output_iterator
, true);
215 Game::Uninitialize(true);
217 /* ShowInfo put output to stderr, but version information should go
218 * to stdout; this is the only exception */
220 fmt::print("{}\n", str
);
226 static void WriteSavegameInfo(const std::string
&name
)
228 extern SaveLoadVersion _sl_version
;
229 uint32_t last_ottd_rev
= 0;
230 byte ever_modified
= 0;
231 bool removed_newgrfs
= false;
233 _gamelog
.Info(&last_ottd_rev
, &ever_modified
, &removed_newgrfs
);
236 message
.reserve(1024);
237 fmt::format_to(std::back_inserter(message
), "Name: {}\n", name
);
238 fmt::format_to(std::back_inserter(message
), "Savegame ver: {}\n", _sl_version
);
239 fmt::format_to(std::back_inserter(message
), "NewGRF ver: 0x{:08X}\n", last_ottd_rev
);
240 fmt::format_to(std::back_inserter(message
), "Modified: {}\n", ever_modified
);
242 if (removed_newgrfs
) {
243 fmt::format_to(std::back_inserter(message
), "NewGRFs have been removed\n");
246 message
+= "NewGRFs:\n";
247 if (_load_check_data
.HasNewGrfs()) {
248 for (GRFConfig
*c
= _load_check_data
.grfconfig
; c
!= nullptr; c
= c
->next
) {
249 fmt::format_to(std::back_inserter(message
), "{:08X} {} {}\n", c
->ident
.grfid
,
250 FormatArrayAsHex(HasBit(c
->flags
, GCF_COMPATIBLE
) ? c
->original_md5sum
: c
->ident
.md5sum
), c
->filename
);
254 /* ShowInfo put output to stderr, but version information should go
255 * to stdout; this is the only exception */
257 fmt::print("{}\n", message
);
265 * Extract the resolution from the given string and store
266 * it in the 'res' parameter.
267 * @param res variable to store the resolution in.
268 * @param s the string to decompose.
270 static void ParseResolution(Dimension
*res
, const char *s
)
272 const char *t
= strchr(s
, 'x');
274 ShowInfo("Invalid resolution '{}'", s
);
278 res
->width
= std::max(std::strtoul(s
, nullptr, 0), 64UL);
279 res
->height
= std::max(std::strtoul(t
+ 1, nullptr, 0), 64UL);
284 * Uninitializes drivers, frees allocated memory, cleans pools, ...
285 * Generally, prepares the game for shutting down
287 static void ShutdownGame()
291 if (_network_available
) NetworkShutDown(); // Shut down the network and close any open connections
293 SocialIntegration::Shutdown();
294 DriverFactoryBase::ShutdownDrivers();
296 UnInitWindowSystem();
298 /* stop the scripts */
299 AI::Uninitialize(false);
300 Game::Uninitialize(false);
302 /* Uninitialize variables that are allocated dynamically */
305 LinkGraphSchedule::Clear();
306 PoolBase::Clean(PT_ALL
);
308 /* No NewGRFs were loaded when it was still bootstrapping. */
309 if (_game_mode
!= GM_BOOTSTRAP
) ResetNewGRFData();
315 * Load the introduction game.
316 * @param load_newgrfs Whether to load the NewGRFs or not.
318 static void LoadIntroGame(bool load_newgrfs
= true)
320 _game_mode
= GM_MENU
;
322 if (load_newgrfs
) ResetGRFConfig(false);
324 /* Setup main window */
326 SetupColoursAndInitialWindow();
328 /* Load the default opening screen savegame */
329 if (SaveOrLoad("opntitle.dat", SLO_LOAD
, DFT_GAME_FILE
, BASESET_DIR
) != SL_OK
) {
330 GenerateWorld(GWM_EMPTY
, 64, 64); // if failed loading, make empty world.
331 SetLocalCompany(COMPANY_SPECTATOR
);
333 SetLocalCompany(COMPANY_FIRST
);
337 _pause_mode
= PM_UNPAUSED
;
338 _cursor
.fix_at
= false;
340 CheckForMissingGlyphs();
342 MusicLoop(); // ensure music is correct
345 void MakeNewgameSettingsLive()
347 for (CompanyID c
= COMPANY_FIRST
; c
< MAX_COMPANIES
; c
++) {
348 if (_settings_game
.ai_config
[c
] != nullptr) {
349 delete _settings_game
.ai_config
[c
];
352 if (_settings_game
.game_config
!= nullptr) {
353 delete _settings_game
.game_config
;
356 /* Copy newgame settings to active settings.
357 * Also initialise old settings needed for savegame conversion. */
358 _settings_game
= _settings_newgame
;
359 _old_vds
= _settings_client
.company
.vehicle
;
361 for (CompanyID c
= COMPANY_FIRST
; c
< MAX_COMPANIES
; c
++) {
362 _settings_game
.ai_config
[c
] = nullptr;
363 if (_settings_newgame
.ai_config
[c
] != nullptr) {
364 _settings_game
.ai_config
[c
] = new AIConfig(_settings_newgame
.ai_config
[c
]);
367 _settings_game
.game_config
= nullptr;
368 if (_settings_newgame
.game_config
!= nullptr) {
369 _settings_game
.game_config
= new GameConfig(_settings_newgame
.game_config
);
373 void OpenBrowser(const std::string
&url
)
375 /* Make sure we only accept urls that are sure to open a browser. */
376 if (url
.starts_with("http://") || url
.starts_with("https://")) {
381 /** Callback structure of statements to be executed after the NewGRF scan. */
382 struct AfterNewGRFScan
: NewGRFScanCallback
{
383 TimerGameCalendar::Year startyear
= CalendarTime::INVALID_YEAR
; ///< The start year.
384 uint32_t generation_seed
= GENERATE_NEW_SEED
; ///< Seed for the new game.
385 std::string dedicated_host
; ///< Hostname for the dedicated server.
386 uint16_t dedicated_port
= 0; ///< Port for the dedicated server.
387 std::string connection_string
; ///< Information about the server to connect to
388 std::string join_server_password
; ///< The password to join the server with.
389 std::string join_company_password
; ///< The password to join the company with.
390 bool save_config
= true; ///< The save config setting.
393 * Create a new callback.
397 /* Visual C++ 2015 fails compiling this line (AfterNewGRFScan::generation_seed undefined symbol)
398 * if it's placed outside a member function, directly in the struct body. */
399 static_assert(sizeof(generation_seed
) == sizeof(_settings_game
.game_creation
.generation_seed
));
402 void OnNewGRFsScanned() override
404 ResetGRFConfig(false);
406 TarScanner::DoScan(TarScanner::SCENARIO
);
411 /* We want the new (correct) NewGRF count to survive the loading. */
412 uint last_newgrf_count
= _settings_client
.gui
.last_newgrf_count
;
414 _settings_client
.gui
.last_newgrf_count
= last_newgrf_count
;
415 /* Since the default for the palette might have changed due to
416 * reading the configuration file, recalculate that now. */
417 UpdateNewGRFConfigPalette();
419 Game::Uninitialize(true);
420 AI::Uninitialize(true);
422 LoadHotkeysFromConfig();
423 WindowDesc::LoadFromConfig();
425 /* We have loaded the config, so we may possibly save it. */
426 _save_config
= save_config
;
428 /* restore saved music and effects volumes */
429 MusicDriver::GetInstance()->SetVolume(_settings_client
.music
.music_vol
);
430 SetEffectVolume(_settings_client
.music
.effect_vol
);
432 if (startyear
!= CalendarTime::INVALID_YEAR
) IConsoleSetSetting("game_creation.starting_year", startyear
.base());
433 _settings_newgame
.game_creation
.generation_seed
= generation_seed
;
435 if (!dedicated_host
.empty()) {
436 _network_bind_list
.clear();
437 _network_bind_list
.emplace_back(dedicated_host
);
439 if (dedicated_port
!= 0) _settings_client
.network
.server_port
= dedicated_port
;
441 /* initialize the ingame console */
444 IConsoleCmdExec("exec scripts/autoexec.scr 0");
446 /* Make sure _settings is filled with _settings_newgame if we switch to a game directly */
447 if (_switch_mode
!= SM_NONE
) MakeNewgameSettingsLive();
449 if (_network_available
&& !connection_string
.empty()) {
451 _switch_mode
= SM_NONE
;
453 NetworkClientConnectGame(connection_string
, COMPANY_NEW_COMPANY
, join_server_password
, join_company_password
);
456 /* After the scan we're not used anymore. */
465 /* only save config if we have to */
468 SaveHotkeysToConfig();
469 WindowDesc::SaveToConfig();
473 /* Reset windowing system, stop drivers, free used memory, ... */
478 extern void DedicatedFork();
481 /** Options of OpenTTD. */
482 static const OptionData _options
[] = {
483 GETOPT_SHORT_VALUE('I'),
484 GETOPT_SHORT_VALUE('S'),
485 GETOPT_SHORT_VALUE('M'),
486 GETOPT_SHORT_VALUE('m'),
487 GETOPT_SHORT_VALUE('s'),
488 GETOPT_SHORT_VALUE('v'),
489 GETOPT_SHORT_VALUE('b'),
490 GETOPT_SHORT_OPTVAL('D'),
491 GETOPT_SHORT_VALUE('n'),
492 GETOPT_SHORT_VALUE('p'),
493 GETOPT_SHORT_VALUE('P'),
495 GETOPT_SHORT_NOVAL('f'),
497 GETOPT_SHORT_VALUE('r'),
498 GETOPT_SHORT_VALUE('t'),
499 GETOPT_SHORT_OPTVAL('d'),
500 GETOPT_SHORT_NOVAL('e'),
501 GETOPT_SHORT_OPTVAL('g'),
502 GETOPT_SHORT_VALUE('G'),
503 GETOPT_SHORT_VALUE('c'),
504 GETOPT_SHORT_NOVAL('x'),
505 GETOPT_SHORT_NOVAL('X'),
506 GETOPT_SHORT_VALUE('q'),
507 GETOPT_SHORT_NOVAL('h'),
508 GETOPT_SHORT_NOVAL('Q'),
513 * Main entry point for this lovely game.
514 * @param argc The number of arguments passed to this game.
515 * @param argv The values of the arguments.
516 * @return 0 when there is no error.
518 int openttd_main(int argc
, char *argv
[])
520 std::string musicdriver
;
521 std::string sounddriver
;
522 std::string videodriver
;
524 std::string graphics_set
;
525 std::string sounds_set
;
526 std::string music_set
;
527 Dimension resolution
= {0, 0};
528 std::unique_ptr
<AfterNewGRFScan
> scanner(new AfterNewGRFScan());
529 bool dedicated
= false;
530 bool only_local_path
= false;
532 extern bool _dedicated_forks
;
533 _dedicated_forks
= false;
535 _game_mode
= GM_MENU
;
536 _switch_mode
= SM_MENU
;
538 GetOptData
mgo(argc
- 1, argv
+ 1, _options
);
542 while ((i
= mgo
.GetOpt()) != -1) {
544 case 'I': graphics_set
= mgo
.opt
; break;
545 case 'S': sounds_set
= mgo
.opt
; break;
546 case 'M': music_set
= mgo
.opt
; break;
547 case 'm': musicdriver
= mgo
.opt
; break;
548 case 's': sounddriver
= mgo
.opt
; break;
549 case 'v': videodriver
= mgo
.opt
; break;
550 case 'b': blitter
= mgo
.opt
; break;
552 musicdriver
= "null";
553 sounddriver
= "null";
554 videodriver
= "dedicated";
557 SetDebugString("net=4", ShowInfoI
);
558 if (mgo
.opt
!= nullptr) {
559 scanner
->dedicated_host
= ParseFullConnectionString(mgo
.opt
, scanner
->dedicated_port
);
562 case 'f': _dedicated_forks
= true; break;
564 scanner
->connection_string
= mgo
.opt
; // host:port#company parameter
567 scanner
->join_server_password
= mgo
.opt
;
570 scanner
->join_company_password
= mgo
.opt
;
572 case 'r': ParseResolution(&resolution
, mgo
.opt
); break;
573 case 't': scanner
->startyear
= atoi(mgo
.opt
); break;
578 if (mgo
.opt
!= nullptr) SetDebugString(mgo
.opt
, ShowInfoI
);
582 /* Allow for '-e' before or after '-g'. */
583 switch (_switch_mode
) {
584 case SM_MENU
: _switch_mode
= SM_EDITOR
; break;
585 case SM_LOAD_GAME
: _switch_mode
= SM_LOAD_SCENARIO
; break;
586 case SM_START_HEIGHTMAP
: _switch_mode
= SM_LOAD_HEIGHTMAP
; break;
591 if (mgo
.opt
!= nullptr) {
592 _file_to_saveload
.name
= mgo
.opt
;
594 std::string extension
= std::filesystem::path(_file_to_saveload
.name
).extension().string();
595 auto [ft
, _
] = FiosGetSavegameListCallback(SLO_LOAD
, _file_to_saveload
.name
, extension
);
596 if (ft
== FIOS_TYPE_INVALID
) {
597 std::tie(ft
, _
) = FiosGetScenarioListCallback(SLO_LOAD
, _file_to_saveload
.name
, extension
);
599 if (ft
== FIOS_TYPE_INVALID
) {
600 std::tie(ft
, _
) = FiosGetHeightmapListCallback(SLO_LOAD
, _file_to_saveload
.name
, extension
);
603 /* Allow for '-e' before or after '-g'. */
604 switch (GetAbstractFileType(ft
)) {
605 case FT_SAVEGAME
: _switch_mode
= (_switch_mode
== SM_EDITOR
? SM_LOAD_SCENARIO
: SM_LOAD_GAME
); break;
606 case FT_SCENARIO
: _switch_mode
= (_switch_mode
== SM_EDITOR
? SM_LOAD_SCENARIO
: SM_LOAD_GAME
); break;
607 case FT_HEIGHTMAP
: _switch_mode
= (_switch_mode
== SM_EDITOR
? SM_LOAD_HEIGHTMAP
: SM_START_HEIGHTMAP
); break;
611 _file_to_saveload
.SetMode(SLO_LOAD
, GetAbstractFileType(ft
), GetDetailedFileType(ft
));
615 _switch_mode
= SM_NEWGAME
;
616 /* Give a random map if no seed has been given */
617 if (scanner
->generation_seed
== GENERATE_NEW_SEED
) {
618 scanner
->generation_seed
= InteractiveRandom();
622 DeterminePaths(argv
[0], only_local_path
);
623 if (StrEmpty(mgo
.opt
)) {
628 auto [_
, title
] = FiosGetSavegameListCallback(SLO_LOAD
, mgo
.opt
, strrchr(mgo
.opt
, '.'));
630 _load_check_data
.Clear();
631 SaveOrLoadResult res
= SaveOrLoad(mgo
.opt
, SLO_CHECK
, DFT_GAME_FILE
, SAVE_DIR
, false);
632 if (res
!= SL_OK
|| _load_check_data
.HasErrors()) {
633 fmt::print(stderr
, "Failed to open savegame\n");
634 if (_load_check_data
.HasErrors()) {
635 InitializeLanguagePacks(); // A language pack is needed for GetString()
636 SetDParamStr(0, _load_check_data
.error_msg
);
637 fmt::print(stderr
, "{}\n", GetString(_load_check_data
.error
));
642 WriteSavegameInfo(title
);
646 extern int _skip_all_newgrf_scanning
;
647 _skip_all_newgrf_scanning
+= 1;
650 case 'G': scanner
->generation_seed
= std::strtoul(mgo
.opt
, nullptr, 10); break;
651 case 'c': _config_file
= mgo
.opt
; break;
652 case 'x': scanner
->save_config
= false; break;
653 case 'X': only_local_path
= true; break;
655 i
= -2; // Force printing of help.
661 if (i
== -2 || mgo
.numleft
> 0) {
662 /* Either the user typed '-h', they made an error, or they added unrecognized command line arguments.
663 * In all cases, print the help, and exit.
665 * The next two functions are needed to list the graphics sets. We can't do them earlier
666 * because then we cannot show it on the debug console as that hasn't been configured yet. */
667 DeterminePaths(argv
[0], only_local_path
);
668 TarScanner::DoScan(TarScanner::BASESET
);
669 BaseGraphics::FindSets();
670 BaseSounds::FindSets();
671 BaseMusic::FindSets();
676 DeterminePaths(argv
[0], only_local_path
);
677 TarScanner::DoScan(TarScanner::BASESET
);
679 if (dedicated
) Debug(net
, 3, "Starting dedicated server, version {}", _openttd_revision
);
680 if (_dedicated_forks
&& !dedicated
) _dedicated_forks
= false;
683 /* We must fork here, or we'll end up without some resources we need (like sockets) */
684 if (_dedicated_forks
) DedicatedFork();
687 LoadFromConfig(true);
689 if (resolution
.width
!= 0) _cur_resolution
= resolution
;
691 /* Limit width times height times bytes per pixel to fit a 32 bit
692 * integer, This way all internal drawing routines work correctly.
693 * A resolution that has one component as 0 is treated as a marker to
694 * auto-detect a good window size. */
695 _cur_resolution
.width
= std::min(_cur_resolution
.width
, UINT16_MAX
/ 2u);
696 _cur_resolution
.height
= std::min(_cur_resolution
.height
, UINT16_MAX
/ 2u);
698 /* Assume the cursor starts within the game as not all video drivers
699 * get an event that the cursor is within the window when it is opened.
700 * Saying the cursor is there makes no visible difference as it would
701 * just be out of the bounds of the window. */
702 _cursor
.in_window
= true;
704 /* enumerate language files */
705 InitializeLanguagePacks();
707 /* Initialize the font cache */
708 InitFontCache(false);
710 /* This must be done early, since functions use the SetWindowDirty* calls */
713 BaseGraphics::FindSets();
714 bool valid_graphics_set
;
715 if (!graphics_set
.empty()) {
716 valid_graphics_set
= BaseGraphics::SetSetByName(graphics_set
);
717 } else if (BaseGraphics::ini_data
.shortname
!= 0) {
718 graphics_set
= BaseGraphics::ini_data
.name
;
719 valid_graphics_set
= BaseGraphics::SetSetByShortname(BaseGraphics::ini_data
.shortname
);
720 if (valid_graphics_set
&& !BaseGraphics::ini_data
.extra_params
.empty()) {
721 GRFConfig
&extra_cfg
= BaseGraphics::GetUsedSet()->GetOrCreateExtraConfig();
722 if (extra_cfg
.IsCompatible(BaseGraphics::ini_data
.extra_version
)) {
723 extra_cfg
.SetParams(BaseGraphics::ini_data
.extra_params
);
726 } else if (!BaseGraphics::ini_data
.name
.empty()) {
727 graphics_set
= BaseGraphics::ini_data
.name
;
728 valid_graphics_set
= BaseGraphics::SetSetByName(BaseGraphics::ini_data
.name
);
730 valid_graphics_set
= true;
731 BaseGraphics::SetSet(nullptr); // ignore error, continue to bootstrap GUI
733 if (!valid_graphics_set
) {
734 BaseGraphics::SetSet(nullptr);
736 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_BASE_GRAPHICS_NOT_FOUND
);
737 msg
.SetDParamStr(0, graphics_set
);
738 ScheduleErrorMessage(msg
);
741 /* Initialize game palette */
744 Debug(misc
, 1, "Loading blitter...");
745 if (blitter
.empty() && !_ini_blitter
.empty()) blitter
= _ini_blitter
;
746 _blitter_autodetected
= blitter
.empty();
747 /* Activate the initial blitter.
748 * This is only some initial guess, after NewGRFs have been loaded SwitchNewGRFBlitter may switch to a different one.
749 * - Never guess anything, if the user specified a blitter. (_blitter_autodetected)
750 * - Use 32bpp blitter if baseset or 8bpp-support settings says so.
751 * - Use 8bpp blitter otherwise.
753 if (!_blitter_autodetected
||
754 (_support8bpp
!= S8BPP_NONE
&& (BaseGraphics::GetUsedSet() == nullptr || BaseGraphics::GetUsedSet()->blitter
== BLT_8BPP
)) ||
755 BlitterFactory::SelectBlitter("32bpp-anim") == nullptr) {
756 if (BlitterFactory::SelectBlitter(blitter
) == nullptr) {
758 UserError("Failed to autoprobe blitter") :
759 UserError("Failed to select requested blitter '{}'; does it exist?", blitter
);
763 if (videodriver
.empty() && !_ini_videodriver
.empty()) videodriver
= _ini_videodriver
;
764 DriverFactoryBase::SelectDriver(videodriver
, Driver::DT_VIDEO
);
766 InitializeSpriteSorter();
768 /* Initialize the zoom level of the screen to normal */
769 _screen
.zoom
= ZOOM_LVL_NORMAL
;
771 /* The video driver is now selected, now initialise GUI zoom */
772 AdjustGUIZoom(false);
774 SocialIntegration::Initialize();
775 NetworkStartUp(); // initialize network-core
777 if (!HandleBootstrap()) {
782 VideoDriver::GetInstance()->ClaimMousePointer();
784 /* initialize screenshot formats */
785 InitializeScreenshotFormats();
787 BaseSounds::FindSets();
788 if (sounds_set
.empty() && !BaseSounds::ini_set
.empty()) sounds_set
= BaseSounds::ini_set
;
789 if (!BaseSounds::SetSetByName(sounds_set
)) {
790 if (sounds_set
.empty() || !BaseSounds::SetSet({})) {
791 UserError("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 1.4 of README.md.");
793 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_BASE_SOUNDS_NOT_FOUND
);
794 msg
.SetDParamStr(0, sounds_set
);
795 ScheduleErrorMessage(msg
);
799 BaseMusic::FindSets();
800 if (music_set
.empty() && !BaseMusic::ini_set
.empty()) music_set
= BaseMusic::ini_set
;
801 if (!BaseMusic::SetSetByName(music_set
)) {
802 if (music_set
.empty() || !BaseMusic::SetSet({})) {
803 UserError("Failed to find a music set. Please acquire a music set for OpenTTD. See section 1.4 of README.md.");
805 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_BASE_MUSIC_NOT_FOUND
);
806 msg
.SetDParamStr(0, music_set
);
807 ScheduleErrorMessage(msg
);
811 if (sounddriver
.empty() && !_ini_sounddriver
.empty()) sounddriver
= _ini_sounddriver
;
812 DriverFactoryBase::SelectDriver(sounddriver
, Driver::DT_SOUND
);
814 if (musicdriver
.empty() && !_ini_musicdriver
.empty()) musicdriver
= _ini_musicdriver
;
815 DriverFactoryBase::SelectDriver(musicdriver
, Driver::DT_MUSIC
);
817 GenerateWorld(GWM_EMPTY
, 64, 64); // Make the viewport initialization happy
818 LoadIntroGame(false);
820 CheckForMissingGlyphs();
822 /* ScanNewGRFFiles now has control over the scanner. */
823 RequestNewGRFScan(scanner
.release());
825 VideoDriver::GetInstance()->MainLoop();
831 void HandleExitGameRequest()
833 if (_game_mode
== GM_MENU
|| _game_mode
== GM_BOOTSTRAP
) { // do not ask to quit on the main screen
835 } else if (_settings_client
.gui
.autosave_on_exit
) {
837 _survey
.Transmit(NetworkSurveyHandler::Reason::EXIT
, true);
845 * Triggers everything required to set up a saved scenario for a new game.
847 static void OnStartScenario()
849 /* Reset engine pool to simplify changing engine NewGRFs in scenario editor. */
850 EngineOverrideManager::ResetToCurrentNewGRFConfig();
852 /* Make sure all industries were built "this year", to avoid too early closures. (#9918) */
853 for (Industry
*i
: Industry::Iterate()) {
854 i
->last_prod_year
= TimerGameEconomy::year
;
859 * Triggers everything that should be triggered when starting a game.
860 * @param dedicated_server Whether this is a dedicated server or not.
862 static void OnStartGame(bool dedicated_server
)
864 /* Update the local company for a loaded game. It is either the first available company
865 * or in the case of a dedicated server, a spectator */
866 SetLocalCompany(dedicated_server
? COMPANY_SPECTATOR
: GetFirstPlayableCompanyID());
868 /* Update the static game info to set the values from the new game. */
869 NetworkServerUpdateGameInfo();
870 /* Execute the game-start script */
871 IConsoleCmdExec("exec scripts/game_start.scr 0");
874 static void MakeNewGameDone()
876 SettingsDisableElrail(_settings_game
.vehicle
.disable_elrails
);
878 /* In a dedicated server, the server does not play */
879 if (!VideoDriver::GetInstance()->HasGUI()) {
881 if (_settings_client
.gui
.pause_on_newgame
) Command
<CMD_PAUSE
>::Post(PM_PAUSED_NORMAL
, true);
885 /* Create a single company */
886 DoStartupNewCompany(false);
888 Company
*c
= Company::Get(COMPANY_FIRST
);
889 c
->settings
= _settings_client
.company
;
891 /* Overwrite color from settings if needed
892 * COLOUR_END corresponds to Random colour */
894 if (_settings_client
.gui
.starting_colour
!= COLOUR_END
) {
895 c
->colour
= _settings_client
.gui
.starting_colour
;
896 ResetCompanyLivery(c
);
897 _company_colours
[c
->index
] = c
->colour
;
900 if (_settings_client
.gui
.starting_colour_secondary
!= COLOUR_END
&& HasBit(_loaded_newgrf_features
.used_liveries
, LS_DEFAULT
)) {
901 Command
<CMD_SET_COMPANY_COLOUR
>::Post(LS_DEFAULT
, false, _settings_client
.gui
.starting_colour_secondary
);
909 /* We are the server, we start a new company (not dedicated),
910 * so set the default password *if* needed. */
911 if (_network_server
&& !_settings_client
.network
.default_company_pass
.empty()) {
912 NetworkChangeCompanyPassword(_local_company
, _settings_client
.network
.default_company_pass
);
915 if (_settings_client
.gui
.pause_on_newgame
) Command
<CMD_PAUSE
>::Post(PM_PAUSED_NORMAL
, true);
919 MarkWholeScreenDirty();
921 if (_network_server
) {
922 ChangeNetworkRestartTime(true);
924 if (!_network_dedicated
) ShowClientList();
928 static void MakeNewGame(bool from_heightmap
, bool reset_settings
)
930 _game_mode
= GM_NORMAL
;
931 if (!from_heightmap
) {
932 /* "reload" command needs to know what mode we were in. */
933 _file_to_saveload
.SetMode(SLO_INVALID
, FT_INVALID
, DFT_INVALID
);
936 ResetGRFConfig(true);
938 GenerateWorldSetCallback(&MakeNewGameDone
);
939 GenerateWorld(from_heightmap
? GWM_HEIGHTMAP
: GWM_NEWGAME
, 1 << _settings_game
.game_creation
.map_x
, 1 << _settings_game
.game_creation
.map_y
, reset_settings
);
942 static void MakeNewEditorWorldDone()
944 SetLocalCompany(OWNER_NONE
);
947 static void MakeNewEditorWorld()
949 _game_mode
= GM_EDITOR
;
950 /* "reload" command needs to know what mode we were in. */
951 _file_to_saveload
.SetMode(SLO_INVALID
, FT_INVALID
, DFT_INVALID
);
953 ResetGRFConfig(true);
955 GenerateWorldSetCallback(&MakeNewEditorWorldDone
);
956 GenerateWorld(GWM_EMPTY
, 1 << _settings_game
.game_creation
.map_x
, 1 << _settings_game
.game_creation
.map_y
);
960 * Load the specified savegame but on error do different things.
961 * If loading fails due to corrupt savegame, bad version, etc. go back to
962 * a previous correct state. In the menu for example load the intro game again.
963 * @param filename file to be loaded
964 * @param fop mode of loading, always SLO_LOAD
965 * @param newgm switch to this mode of loading fails due to some unknown error
966 * @param subdir default directory to look for filename, set to 0 if not needed
967 * @param lf Load filter to use, if nullptr: use filename + subdir.
969 bool SafeLoad(const std::string
&filename
, SaveLoadOperation fop
, DetailedFileType dft
, GameMode newgm
, Subdirectory subdir
, std::shared_ptr
<LoadFilter
> lf
= nullptr)
971 assert(fop
== SLO_LOAD
);
972 assert(dft
== DFT_GAME_FILE
|| (lf
== nullptr && dft
== DFT_OLD_GAME_FILE
));
973 GameMode ogm
= _game_mode
;
977 SaveOrLoadResult result
= (lf
== nullptr) ? SaveOrLoad(filename
, fop
, dft
, subdir
) : LoadWithFilter(lf
);
978 if (result
== SL_OK
) return true;
980 if (_network_dedicated
&& ogm
== GM_MENU
) {
982 * If we are a dedicated server *and* we just were in the menu, then we
983 * are loading the first savegame. If that fails, not starting the
984 * server is a better reaction than starting the server with a newly
985 * generated map as it is quite likely to be started from a script.
987 Debug(net
, 0, "Loading requested map failed; closing server.");
992 if (result
!= SL_REINIT
) {
997 if (_network_dedicated
) {
999 * If we are a dedicated server, have already loaded/started a game,
1000 * and then loading the savegame fails in a manner that we need to
1001 * reinitialize everything. We must not fall back into the menu mode
1002 * with the intro game, as that is unjoinable by clients. So there is
1003 * nothing else to do than start a new game, as it might have failed
1004 * trying to reload the originally loaded savegame/scenario.
1006 Debug(net
, 0, "Loading game failed, so a new (random) game will be started");
1007 MakeNewGame(false, true);
1011 if (_network_server
) {
1012 /* We can't load the intro game as server, so disconnect first. */
1013 NetworkDisconnect();
1018 case GM_MENU
: LoadIntroGame(); break;
1019 case GM_EDITOR
: MakeNewEditorWorld(); break;
1024 static void UpdateSocialIntegration(GameMode game_mode
)
1026 switch (game_mode
) {
1029 SocialIntegration::EventEnterMainMenu();
1034 SocialIntegration::EventEnterMultiplayer(Map::SizeX(), Map::SizeY());
1036 SocialIntegration::EventEnterSingleplayer(Map::SizeX(), Map::SizeY());
1041 SocialIntegration::EventEnterScenarioEditor(Map::SizeX(), Map::SizeY());
1046 void SwitchToMode(SwitchMode new_mode
)
1048 /* If we are saving something, the network stays in its current state */
1049 if (new_mode
!= SM_SAVE_GAME
) {
1050 /* If the network is active, make it not-active */
1052 if (_network_server
&& (new_mode
== SM_LOAD_GAME
|| new_mode
== SM_NEWGAME
|| new_mode
== SM_RESTARTGAME
)) {
1055 NetworkDisconnect();
1059 /* If we are a server, we restart the server */
1060 if (_is_network_server
) {
1061 /* But not if we are going to the menu */
1062 if (new_mode
!= SM_MENU
) {
1063 /* check if we should reload the config */
1064 if (_settings_client
.network
.reload_cfg
) {
1066 MakeNewgameSettingsLive();
1067 ResetGRFConfig(false);
1069 NetworkServerStart();
1071 /* This client no longer wants to be a network-server */
1072 _is_network_server
= false;
1077 /* Make sure all AI controllers are gone at quitting game */
1078 if (new_mode
!= SM_SAVE_GAME
) AI::KillAll();
1080 /* When we change mode, reset the autosave. */
1081 if (new_mode
!= SM_SAVE_GAME
) ChangeAutosaveFrequency(true);
1083 /* Transmit the survey if we were in normal-mode and not saving. It always means we leaving the current game. */
1084 if (_game_mode
== GM_NORMAL
&& new_mode
!= SM_SAVE_GAME
) _survey
.Transmit(NetworkSurveyHandler::Reason::LEAVE
);
1086 /* Keep track when we last switch mode. Used for survey, to know how long someone was in a game. */
1087 if (new_mode
!= SM_SAVE_GAME
) _switch_mode_time
= std::chrono::steady_clock::now();
1090 case SM_EDITOR
: // Switch to scenario editor
1091 MakeNewEditorWorld();
1092 GenerateSavegameId();
1094 UpdateSocialIntegration(GM_EDITOR
);
1097 case SM_RELOADGAME
: // Reload with what-ever started the game
1098 if (_file_to_saveload
.abstract_ftype
== FT_SAVEGAME
|| _file_to_saveload
.abstract_ftype
== FT_SCENARIO
) {
1099 /* Reload current savegame/scenario */
1100 _switch_mode
= _game_mode
== GM_EDITOR
? SM_LOAD_SCENARIO
: SM_LOAD_GAME
;
1101 SwitchToMode(_switch_mode
);
1103 } else if (_file_to_saveload
.abstract_ftype
== FT_HEIGHTMAP
) {
1104 /* Restart current heightmap */
1105 _switch_mode
= _game_mode
== GM_EDITOR
? SM_LOAD_HEIGHTMAP
: SM_RESTART_HEIGHTMAP
;
1106 SwitchToMode(_switch_mode
);
1110 MakeNewGame(false, new_mode
== SM_NEWGAME
);
1111 GenerateSavegameId();
1113 UpdateSocialIntegration(GM_NORMAL
);
1116 case SM_RESTARTGAME
: // Restart --> 'Random game' with current settings
1117 case SM_NEWGAME
: // New Game --> 'Random game'
1118 MakeNewGame(false, new_mode
== SM_NEWGAME
);
1119 GenerateSavegameId();
1121 UpdateSocialIntegration(GM_NORMAL
);
1124 case SM_LOAD_GAME
: { // Load game, Play Scenario
1125 ResetGRFConfig(true);
1126 ResetWindowSystem();
1128 if (!SafeLoad(_file_to_saveload
.name
, _file_to_saveload
.file_op
, _file_to_saveload
.detail_ftype
, GM_NORMAL
, NO_DIRECTORY
)) {
1129 SetDParamStr(0, GetSaveLoadErrorString());
1130 ShowErrorMessage(STR_JUST_RAW_STRING
, INVALID_STRING_ID
, WL_CRITICAL
);
1132 if (_file_to_saveload
.abstract_ftype
== FT_SCENARIO
) {
1135 OnStartGame(_network_dedicated
);
1136 /* Decrease pause counter (was increased from opening load dialog) */
1137 Command
<CMD_PAUSE
>::Post(PM_PAUSED_SAVELOAD
, false);
1140 UpdateSocialIntegration(GM_NORMAL
);
1144 case SM_RESTART_HEIGHTMAP
: // Load a heightmap and start a new game from it with current settings
1145 case SM_START_HEIGHTMAP
: // Load a heightmap and start a new game from it
1146 MakeNewGame(true, new_mode
== SM_START_HEIGHTMAP
);
1147 GenerateSavegameId();
1149 UpdateSocialIntegration(GM_NORMAL
);
1152 case SM_LOAD_HEIGHTMAP
: // Load heightmap from scenario editor
1153 SetLocalCompany(OWNER_NONE
);
1155 _game_mode
= GM_EDITOR
;
1157 GenerateWorld(GWM_HEIGHTMAP
, 1 << _settings_game
.game_creation
.map_x
, 1 << _settings_game
.game_creation
.map_y
);
1158 GenerateSavegameId();
1159 MarkWholeScreenDirty();
1161 UpdateSocialIntegration(GM_EDITOR
);
1164 case SM_LOAD_SCENARIO
: { // Load scenario from scenario editor
1165 if (SafeLoad(_file_to_saveload
.name
, _file_to_saveload
.file_op
, _file_to_saveload
.detail_ftype
, GM_EDITOR
, NO_DIRECTORY
)) {
1166 SetLocalCompany(OWNER_NONE
);
1167 GenerateSavegameId();
1168 _settings_newgame
.game_creation
.starting_year
= TimerGameCalendar::year
;
1169 /* Cancel the saveload pausing */
1170 Command
<CMD_PAUSE
>::Post(PM_PAUSED_SAVELOAD
, false);
1172 SetDParamStr(0, GetSaveLoadErrorString());
1173 ShowErrorMessage(STR_JUST_RAW_STRING
, INVALID_STRING_ID
, WL_CRITICAL
);
1176 UpdateSocialIntegration(GM_EDITOR
);
1180 case SM_JOIN_GAME
: // Join a multiplayer game
1182 NetworkClientJoinGame();
1184 SocialIntegration::EventJoiningMultiplayer();
1187 case SM_MENU
: // Switch to game intro menu
1189 if (BaseSounds::ini_set
.empty() && BaseSounds::GetUsedSet()->fallback
&& SoundDriver::GetInstance()->HasOutput()) {
1190 ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET
, INVALID_STRING_ID
, WL_CRITICAL
);
1191 BaseSounds::ini_set
= BaseSounds::GetUsedSet()->name
;
1193 if (_settings_client
.network
.participate_survey
== PS_ASK
) {
1194 /* No matter how often you go back to the main menu, only ask the first time. */
1195 static bool asked_once
= false;
1198 ShowNetworkAskSurvey();
1202 UpdateSocialIntegration(GM_MENU
);
1205 case SM_SAVE_GAME
: // Save game.
1206 /* Make network saved games on pause compatible to singleplayer mode */
1207 if (SaveOrLoad(_file_to_saveload
.name
, SLO_SAVE
, DFT_GAME_FILE
, NO_DIRECTORY
) != SL_OK
) {
1208 SetDParamStr(0, GetSaveLoadErrorString());
1209 ShowErrorMessage(STR_JUST_RAW_STRING
, INVALID_STRING_ID
, WL_ERROR
);
1211 CloseWindowById(WC_SAVELOAD
, 0);
1215 case SM_SAVE_HEIGHTMAP
: // Save heightmap.
1216 MakeHeightmapScreenshot(_file_to_saveload
.name
.c_str());
1217 CloseWindowById(WC_SAVELOAD
, 0);
1220 case SM_GENRANDLAND
: // Generate random land within scenario editor
1221 SetLocalCompany(OWNER_NONE
);
1222 GenerateWorld(GWM_RANDOM
, 1 << _settings_game
.game_creation
.map_x
, 1 << _settings_game
.game_creation
.map_y
);
1224 MarkWholeScreenDirty();
1227 default: NOT_REACHED();
1233 * Check the validity of some of the caches.
1234 * Especially in the sense of desyncs between
1235 * the cached value and what the value would
1236 * be when calculated from the 'base' data.
1238 static void CheckCaches()
1240 /* Return here so it is easy to add checks that are run
1241 * always to aid testing of caches. */
1242 if (_debug_desync_level
<= 1) return;
1244 /* Check the town caches. */
1245 std::vector
<TownCache
> old_town_caches
;
1246 for (const Town
*t
: Town::Iterate()) {
1247 old_town_caches
.push_back(t
->cache
);
1250 RebuildTownCaches();
1251 RebuildSubsidisedSourceAndDestinationCache();
1254 for (Town
*t
: Town::Iterate()) {
1255 if (MemCmpT(old_town_caches
.data() + i
, &t
->cache
) != 0) {
1256 Debug(desync
, 2, "town cache mismatch: town {}", t
->index
);
1261 /* Check company infrastructure cache. */
1262 std::vector
<CompanyInfrastructure
> old_infrastructure
;
1263 for (const Company
*c
: Company::Iterate()) old_infrastructure
.push_back(c
->infrastructure
);
1265 AfterLoadCompanyStats();
1268 for (const Company
*c
: Company::Iterate()) {
1269 if (MemCmpT(old_infrastructure
.data() + i
, &c
->infrastructure
) != 0) {
1270 Debug(desync
, 2, "infrastructure cache mismatch: company {}", c
->index
);
1275 /* Strict checking of the road stop cache entries */
1276 for (const RoadStop
*rs
: RoadStop::Iterate()) {
1277 if (IsBayRoadStopTile(rs
->xy
)) continue;
1279 assert(rs
->GetEntry(DIAGDIR_NE
) != rs
->GetEntry(DIAGDIR_NW
));
1280 rs
->GetEntry(DIAGDIR_NE
)->CheckIntegrity(rs
);
1281 rs
->GetEntry(DIAGDIR_NW
)->CheckIntegrity(rs
);
1284 for (Vehicle
*v
: Vehicle::Iterate()) {
1285 if (v
!= v
->First() || v
->vehstatus
& VS_CRASHED
|| !v
->IsPrimaryVehicle()) continue;
1288 for (const Vehicle
*u
= v
; u
!= nullptr; u
= u
->Next()) length
++;
1290 NewGRFCache
*grf_cache
= CallocT
<NewGRFCache
>(length
);
1291 VehicleCache
*veh_cache
= CallocT
<VehicleCache
>(length
);
1292 GroundVehicleCache
*gro_cache
= CallocT
<GroundVehicleCache
>(length
);
1293 TrainCache
*tra_cache
= CallocT
<TrainCache
>(length
);
1296 for (const Vehicle
*u
= v
; u
!= nullptr; u
= u
->Next()) {
1297 FillNewGRFVehicleCache(u
);
1298 grf_cache
[length
] = u
->grf_cache
;
1299 veh_cache
[length
] = u
->vcache
;
1302 gro_cache
[length
] = Train::From(u
)->gcache
;
1303 tra_cache
[length
] = Train::From(u
)->tcache
;
1306 gro_cache
[length
] = RoadVehicle::From(u
)->gcache
;
1315 case VEH_TRAIN
: Train::From(v
)->ConsistChanged(CCF_TRACK
); break;
1316 case VEH_ROAD
: RoadVehUpdateCache(RoadVehicle::From(v
)); break;
1317 case VEH_AIRCRAFT
: UpdateAircraftCache(Aircraft::From(v
)); break;
1318 case VEH_SHIP
: Ship::From(v
)->UpdateCache(); break;
1323 for (const Vehicle
*u
= v
; u
!= nullptr; u
= u
->Next()) {
1324 FillNewGRFVehicleCache(u
);
1325 if (memcmp(&grf_cache
[length
], &u
->grf_cache
, sizeof(NewGRFCache
)) != 0) {
1326 Debug(desync
, 2, "newgrf cache mismatch: type {}, vehicle {}, company {}, unit number {}, wagon {}", v
->type
, v
->index
, v
->owner
, v
->unitnumber
, length
);
1328 if (memcmp(&veh_cache
[length
], &u
->vcache
, sizeof(VehicleCache
)) != 0) {
1329 Debug(desync
, 2, "vehicle cache mismatch: type {}, vehicle {}, company {}, unit number {}, wagon {}", v
->type
, v
->index
, v
->owner
, v
->unitnumber
, length
);
1333 if (memcmp(&gro_cache
[length
], &Train::From(u
)->gcache
, sizeof(GroundVehicleCache
)) != 0) {
1334 Debug(desync
, 2, "train ground vehicle cache mismatch: vehicle {}, company {}, unit number {}, wagon {}", v
->index
, v
->owner
, v
->unitnumber
, length
);
1336 if (memcmp(&tra_cache
[length
], &Train::From(u
)->tcache
, sizeof(TrainCache
)) != 0) {
1337 Debug(desync
, 2, "train cache mismatch: vehicle {}, company {}, unit number {}, wagon {}", v
->index
, v
->owner
, v
->unitnumber
, length
);
1341 if (memcmp(&gro_cache
[length
], &RoadVehicle::From(u
)->gcache
, sizeof(GroundVehicleCache
)) != 0) {
1342 Debug(desync
, 2, "road vehicle ground vehicle cache mismatch: vehicle {}, company {}, unit number {}, wagon {}", v
->index
, v
->owner
, v
->unitnumber
, length
);
1357 /* Check whether the caches are still valid */
1358 for (Vehicle
*v
: Vehicle::Iterate()) {
1359 byte buff
[sizeof(VehicleCargoList
)];
1360 memcpy(buff
, &v
->cargo
, sizeof(VehicleCargoList
));
1361 v
->cargo
.InvalidateCache();
1362 assert(memcmp(&v
->cargo
, buff
, sizeof(VehicleCargoList
)) == 0);
1365 /* Backup stations_near */
1366 std::vector
<StationList
> old_town_stations_near
;
1367 for (Town
*t
: Town::Iterate()) old_town_stations_near
.push_back(t
->stations_near
);
1369 std::vector
<StationList
> old_industry_stations_near
;
1370 for (Industry
*ind
: Industry::Iterate()) old_industry_stations_near
.push_back(ind
->stations_near
);
1372 for (Station
*st
: Station::Iterate()) {
1373 for (GoodsEntry
&ge
: st
->goods
) {
1374 byte buff
[sizeof(StationCargoList
)];
1375 memcpy(buff
, &ge
.cargo
, sizeof(StationCargoList
));
1376 ge
.cargo
.InvalidateCache();
1377 assert(memcmp(&ge
.cargo
, buff
, sizeof(StationCargoList
)) == 0);
1380 /* Check docking tiles */
1382 std::map
<TileIndex
, bool> docking_tiles
;
1383 for (TileIndex tile
: st
->docking_station
) {
1385 docking_tiles
[tile
] = IsDockingTile(tile
);
1387 UpdateStationDockingTiles(st
);
1388 if (ta
.tile
!= st
->docking_station
.tile
|| ta
.w
!= st
->docking_station
.w
|| ta
.h
!= st
->docking_station
.h
) {
1389 Debug(desync
, 2, "station docking mismatch: station {}, company {}", st
->index
, st
->owner
);
1391 for (TileIndex tile
: ta
) {
1392 if (docking_tiles
[tile
] != IsDockingTile(tile
)) {
1393 Debug(desync
, 2, "docking tile mismatch: tile {}", tile
);
1397 /* Check industries_near */
1398 IndustryList industries_near
= st
->industries_near
;
1399 st
->RecomputeCatchment();
1400 if (st
->industries_near
!= industries_near
) {
1401 Debug(desync
, 2, "station industries near mismatch: station {}", st
->index
);
1405 /* Check stations_near */
1407 for (Town
*t
: Town::Iterate()) {
1408 if (t
->stations_near
!= old_town_stations_near
[i
]) {
1409 Debug(desync
, 2, "town stations near mismatch: town {}", t
->index
);
1414 for (Industry
*ind
: Industry::Iterate()) {
1415 if (ind
->stations_near
!= old_industry_stations_near
[i
]) {
1416 Debug(desync
, 2, "industry stations near mismatch: industry {}", ind
->index
);
1423 * State controlling game loop.
1424 * The state must not be changed from anywhere but here.
1425 * That check is enforced in DoCommand.
1427 void StateGameLoop()
1429 if (!_networking
|| _network_server
) {
1430 StateGameLoop_LinkGraphPauseControl();
1433 /* Don't execute the state loop during pause or when modal windows are open. */
1434 if (_pause_mode
!= PM_UNPAUSED
|| HasModalProgress()) {
1435 PerformanceMeasurer::Paused(PFE_GAMELOOP
);
1436 PerformanceMeasurer::Paused(PFE_GL_ECONOMY
);
1437 PerformanceMeasurer::Paused(PFE_GL_TRAINS
);
1438 PerformanceMeasurer::Paused(PFE_GL_ROADVEHS
);
1439 PerformanceMeasurer::Paused(PFE_GL_SHIPS
);
1440 PerformanceMeasurer::Paused(PFE_GL_AIRCRAFT
);
1441 PerformanceMeasurer::Paused(PFE_GL_LANDSCAPE
);
1443 if (!HasModalProgress()) UpdateLandscapingLimits();
1444 #ifndef DEBUG_DUMP_COMMANDS
1450 PerformanceMeasurer
framerate(PFE_GAMELOOP
);
1451 PerformanceAccumulator::Reset(PFE_GL_LANDSCAPE
);
1453 Layouter::ReduceLineCache();
1455 if (_game_mode
== GM_EDITOR
) {
1456 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP
);
1459 CallLandscapeTick();
1460 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP
);
1461 UpdateLandscapingLimits();
1463 CallWindowGameTickEvent();
1466 if (_debug_desync_level
> 2 && TimerGameEconomy::date_fract
== 0 && (TimerGameEconomy::date
.base() & 0x1F) == 0) {
1467 /* Save the desync savegame if needed. */
1468 std::string name
= fmt::format("dmp_cmds_{:08x}_{:08x}.sav", _settings_game
.game_creation
.generation_seed
, TimerGameEconomy::date
);
1469 SaveOrLoad(name
, SLO_SAVE
, DFT_GAME_FILE
, AUTOSAVE_DIR
, false);
1474 /* All these actions has to be done from OWNER_NONE
1475 * for multiplayer compatibility */
1476 Backup
<CompanyID
> cur_company(_current_company
, OWNER_NONE
, FILE_LINE
);
1478 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP
);
1479 AnimateAnimatedTiles();
1480 if (TimerManager
<TimerGameCalendar
>::Elapsed(1)) {
1481 RunVehicleCalendarDayProc();
1483 TimerManager
<TimerGameEconomy
>::Elapsed(1);
1484 TimerManager
<TimerGameTick
>::Elapsed(1);
1487 CallLandscapeTick();
1488 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP
);
1490 #ifndef DEBUG_DUMP_COMMANDS
1492 PerformanceMeasurer
script_framerate(PFE_ALLSCRIPTS
);
1497 UpdateLandscapingLimits();
1499 CallWindowGameTickEvent();
1501 cur_company
.Restore();
1504 assert(IsLocalCompany());
1507 /** Interval for regular autosaves. Initialized at zero to disable till settings are loaded. */
1508 static IntervalTimer
<TimerGameRealtime
> _autosave_interval({std::chrono::milliseconds::zero(), TimerGameRealtime::AUTOSAVE
}, [](auto)
1510 /* We reset the command-during-pause mode here, so we don't continue
1511 * to make auto-saves when nothing more is changing. */
1512 _pause_mode
&= ~PM_COMMAND_DURING_PAUSE
;
1514 _do_autosave
= true;
1515 SetWindowDirty(WC_STATUS_BAR
, 0);
1517 static FiosNumberedSaveName
_autosave_ctr("autosave");
1518 DoAutoOrNetsave(_autosave_ctr
);
1520 _do_autosave
= false;
1521 SetWindowDirty(WC_STATUS_BAR
, 0);
1525 * Reset the interval of the autosave.
1527 * If reset is not set, this does not set the elapsed time on the timer,
1528 * so if the interval is smaller, it might result in an autosave being done
1531 * @param reset Whether to reset the timer back to zero, or to continue.
1533 void ChangeAutosaveFrequency(bool reset
)
1535 _autosave_interval
.SetInterval({std::chrono::minutes(_settings_client
.gui
.autosave_interval
), TimerGameRealtime::AUTOSAVE
}, reset
);
1539 * Request a new NewGRF scan. This will be executed on the next game-tick.
1540 * This is mostly needed to ensure NewGRF scans (which are blocking) are
1541 * done in the game-thread, and not in the draw-thread (which most often
1542 * triggers this request).
1543 * @param callback Optional callback to call when NewGRF scan is completed.
1544 * @return True when the NewGRF scan was actually requested, false when the scan was already running.
1546 bool RequestNewGRFScan(NewGRFScanCallback
*callback
)
1548 if (_request_newgrf_scan
) return false;
1550 _request_newgrf_scan
= true;
1551 _request_newgrf_scan_callback
= callback
;
1557 if (_game_mode
== GM_BOOTSTRAP
) {
1558 /* Check for UDP stuff */
1559 if (_network_available
) NetworkBackgroundLoop();
1563 if (_request_newgrf_scan
) {
1564 ScanNewGRFFiles(_request_newgrf_scan_callback
);
1565 _request_newgrf_scan
= false;
1566 _request_newgrf_scan_callback
= nullptr;
1567 /* In case someone closed the game during our scan, don't do anything else. */
1568 if (_exit_game
) return;
1571 ProcessAsyncSaveFinish();
1573 if (_game_mode
== GM_NORMAL
) {
1574 static auto last_time
= std::chrono::steady_clock::now();
1575 auto now
= std::chrono::steady_clock::now();
1576 auto delta_ms
= std::chrono::duration_cast
<std::chrono::milliseconds
>(now
- last_time
);
1577 if (delta_ms
.count() != 0) {
1578 TimerManager
<TimerGameRealtime
>::Elapsed(delta_ms
);
1583 /* switch game mode? */
1584 if (_switch_mode
!= SM_NONE
&& !HasModalProgress()) {
1585 SwitchToMode(_switch_mode
);
1586 _switch_mode
= SM_NONE
;
1587 if (_exit_game
) return;
1590 IncreaseSpriteLRU();
1592 /* Check for UDP stuff */
1593 if (_network_available
) NetworkBackgroundLoop();
1595 DebugSendRemoteMessages();
1597 if (_networking
&& !HasModalProgress()) {
1601 if (_network_reconnect
> 0 && --_network_reconnect
== 0) {
1602 /* This means that we want to reconnect to the last host
1603 * We do this here, because it means that the network is really closed */
1604 NetworkClientConnectGame(_settings_client
.network
.last_joined
, COMPANY_SPECTATOR
);
1610 if (!_pause_mode
&& HasBit(_display_opt
, DO_FULL_ANIMATION
)) DoPaletteAnimations();
1612 SoundDriver::GetInstance()->MainLoop();
1614 SocialIntegration::RunCallbacks();