4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
10 /** @file openttd.cpp Functions related to starting OpenTTD. */
14 #include "blitter/factory.hpp"
15 #include "sound/sound_driver.hpp"
16 #include "music/music_driver.hpp"
17 #include "video/video_driver.hpp"
19 #include "fontcache.h"
23 #include "base_media_base.h"
24 #include "saveload/saveload.h"
25 #include "company_func.h"
26 #include "command_func.h"
27 #include "news_func.h"
33 #include "console_func.h"
34 #include "screenshot.h"
35 #include "network/network.h"
36 #include "network/network_func.h"
38 #include "ai/ai_config.hpp"
39 #include "settings_func.h"
42 #include "strings_func.h"
43 #include "date_func.h"
44 #include "vehicle_func.h"
46 #include "animated_tile_func.h"
47 #include "roadstop_base.h"
48 #include "elrail_func.h"
50 #include "highscore.h"
51 #include "station_base.h"
53 #include "engine_func.h"
54 #include "core/random_func.hpp"
57 #include "core/backup_type.hpp"
60 #include "newgrf_commons.h"
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_sprite_sorter.h"
68 #include "smallmap_gui.h"
69 #include "viewport_func.h"
70 #include "bridge_signal_map.h"
73 #include "linkgraph/linkgraphschedule.h"
74 #include "tracerestrict.h"
78 #include "safeguards.h"
80 void CallLandscapeTick();
82 void DoPaletteAnimations();
85 void CallWindowTickEvent();
86 bool HandleBootstrap();
88 extern Company
*DoStartupNewCompany(bool is_ai
, CompanyID company
= INVALID_COMPANY
);
89 extern void ShowOSErrorBox(const char *buf
, bool system
);
90 extern char *_config_file
;
93 * Error handling for fatal user errors.
94 * @param s the string to print.
95 * @note Does NEVER return.
97 void CDECL
usererror(const char *s
, ...)
103 vseprintf(buf
, lastof(buf
), s
, va
);
106 ShowOSErrorBox(buf
, false);
107 if (VideoDriver::GetInstance() != nullptr) VideoDriver::GetInstance()->Stop();
113 * Error handling for fatal non-user errors.
114 * @param s the string to print.
115 * @note Does NEVER return.
117 void CDECL
error(const char *s
, ...)
123 vseprintf(buf
, lastof(buf
), s
, va
);
126 ShowOSErrorBox(buf
, true);
128 /* Set the error message for the crash log and then invoke it. */
129 CrashLog::SetErrorMessage(buf
);
133 void CDECL
assert_msg_error(int line
, const char *file
, const char *expr
, const char *str
, ...)
139 b
+= seprintf(b
, lastof(buf
), "Assertion failed at line %i of %s: %s\n\t", line
, file
, expr
);
142 vseprintf(b
, lastof(buf
), str
, va
);
145 ShowOSErrorBox(buf
, true);
147 /* Set the error message for the crash log and then invoke it. */
148 CrashLog::SetErrorMessage(buf
);
153 * Shows some information on the console/a popup box depending on the OS.
154 * @param str the text to show.
156 void CDECL
ShowInfoF(const char *str
, ...)
161 vseprintf(buf
, lastof(buf
), str
, va
);
167 * Show the help message when someone passed a wrong parameter.
169 static void ShowHelp()
174 p
+= seprintf(p
, lastof(buf
), "OpenTTD %s\n", _openttd_revision
);
178 "Command line options:\n"
179 " -v drv = Set video driver (see below)\n"
180 " -s drv = Set sound driver (see below) (param bufsize,hz)\n"
181 " -m drv = Set music driver (see below)\n"
182 " -b drv = Set the blitter to use (see below)\n"
183 " -r res = Set resolution (for instance 800x600)\n"
184 " -h = Display this help text\n"
185 " -t year = Set starting year\n"
186 " -d [[fac=]lvl[,...]]= Debug mode\n"
187 " -e = Start Editor\n"
188 " -g [savegame] = Start new/save game immediately\n"
189 " -G seed = Set random seed\n"
190 #if defined(ENABLE_NETWORK)
191 " -n [ip:port#company]= Join network game\n"
192 " -p password = Password to join server\n"
193 " -P password = Password to join company\n"
194 " -D [ip][:port] = Start dedicated server\n"
195 " -l ip[:port] = Redirect DEBUG()\n"
196 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
197 " -f = Fork into the background (dedicated only)\n"
199 #endif /* ENABLE_NETWORK */
200 " -I graphics_set = Force the graphics set (see below)\n"
201 " -S sounds_set = Force the sounds set (see below)\n"
202 " -M music_set = Force the music set (see below)\n"
203 " -c config_file = Use 'config_file' instead of 'openttd.cfg'\n"
204 " -x = Do not automatically save to config file on exit\n"
205 " -q savegame = Write some information about the savegame and exit\n"
210 /* List the graphics packs */
211 p
= BaseGraphics::GetSetsList(p
, lastof(buf
));
213 /* List the sounds packs */
214 p
= BaseSounds::GetSetsList(p
, lastof(buf
));
216 /* List the music packs */
217 p
= BaseMusic::GetSetsList(p
, lastof(buf
));
219 /* List the drivers */
220 p
= DriverFactoryBase::GetDriversInfo(p
, lastof(buf
));
222 /* List the blitters */
223 p
= BlitterFactory::GetBlittersInfo(p
, lastof(buf
));
225 /* List the debug facilities. */
226 p
= DumpDebugFacilityNames(p
, lastof(buf
));
228 /* We need to initialize the AI, so it finds the AIs */
230 p
= AI::GetConsoleList(p
, lastof(buf
), true);
231 AI::Uninitialize(true);
233 /* We need to initialize the GameScript, so it finds the GSs */
235 p
= Game::GetConsoleList(p
, lastof(buf
), true);
236 Game::Uninitialize(true);
238 /* ShowInfo put output to stderr, but version information should go
239 * to stdout; this is the only exception */
240 #if !defined(WIN32) && !defined(WIN64)
247 static void WriteSavegameInfo(const char *name
)
249 extern uint16 _sl_version
;
250 uint32 last_ottd_rev
= 0;
251 byte ever_modified
= 0;
252 bool removed_newgrfs
= false;
254 GamelogInfo(_load_check_data
.gamelog_action
, _load_check_data
.gamelog_actions
, &last_ottd_rev
, &ever_modified
, &removed_newgrfs
);
258 p
+= seprintf(p
, lastof(buf
), "Name: %s\n", name
);
259 p
+= seprintf(p
, lastof(buf
), "Savegame ver: %d\n", _sl_version
);
260 p
+= seprintf(p
, lastof(buf
), "NewGRF ver: 0x%08X\n", last_ottd_rev
);
261 p
+= seprintf(p
, lastof(buf
), "Modified: %d\n", ever_modified
);
263 if (removed_newgrfs
) {
264 p
+= seprintf(p
, lastof(buf
), "NewGRFs have been removed\n");
267 p
= strecpy(p
, "NewGRFs:\n", lastof(buf
));
268 if (_load_check_data
.HasNewGrfs()) {
269 for (GRFConfig
*c
= _load_check_data
.grfconfig
; c
!= nullptr; c
= c
->next
) {
271 md5sumToString(md5sum
, lastof(md5sum
), HasBit(c
->flags
, GCF_COMPATIBLE
) ? c
->original_md5sum
: c
->ident
.md5sum
);
272 p
+= seprintf(p
, lastof(buf
), "%08X %s %s\n", c
->ident
.grfid
, md5sum
, c
->filename
);
276 /* ShowInfo put output to stderr, but version information should go
277 * to stdout; this is the only exception */
278 #if !defined(WIN32) && !defined(WIN64)
287 * Extract the resolution from the given string and store
288 * it in the 'res' parameter.
289 * @param res variable to store the resolution in.
290 * @param s the string to decompose.
292 static void ParseResolution(Dimension
*res
, const char *s
)
294 const char *t
= strchr(s
, 'x');
296 ShowInfoF("Invalid resolution '%s'", s
);
300 res
->width
= max(strtoul(s
, nullptr, 0), 64UL);
301 res
->height
= max(strtoul(t
+ 1, nullptr, 0), 64UL);
306 * Unitializes drivers, frees allocated memory, cleans pools, ...
307 * Generally, prepares the game for shutting down
309 static void ShutdownGame()
313 if (_network_available
) NetworkShutDown(); // Shut down the network and close any open connections
315 DriverFactoryBase::ShutdownDrivers();
317 UnInitWindowSystem();
319 /* stop the scripts */
320 AI::Uninitialize(false);
321 Game::Uninitialize(false);
323 /* Uninitialize variables that are allocated dynamically */
326 #ifdef ENABLE_NETWORK
330 LinkGraphSchedule::Clear();
331 ClearBridgeSimulatedSignalMapping();
332 ClearTraceRestrictMapping();
333 PoolBase::Clean(PT_ALL
);
337 /* No NewGRFs were loaded when it was still bootstrapping. */
338 if (_game_mode
!= GM_BOOTSTRAP
) ResetNewGRFData();
340 /* Close all and any open filehandles */
347 ViewportMapClearTunnelCache();
351 * Load the introduction game.
352 * @param load_newgrfs Whether to load the NewGRFs or not.
354 static void LoadIntroGame(bool load_newgrfs
= true)
356 _game_mode
= GM_MENU
;
358 if (load_newgrfs
) ResetGRFConfig(false);
360 /* Setup main window */
362 SetupColoursAndInitialWindow();
364 /* Load the default opening screen savegame */
365 if (SaveOrLoad("opntitle.dat", SLO_LOAD
, DFT_GAME_FILE
, BASESET_DIR
) != SL_OK
) {
366 GenerateWorld(GWM_EMPTY
, 64, 64); // if failed loading, make empty world.
367 WaitTillGeneratedWorld();
368 SetLocalCompany(COMPANY_SPECTATOR
);
370 SetLocalCompany(COMPANY_FIRST
);
373 _pause_mode
= PM_UNPAUSED
;
374 _cursor
.fix_at
= false;
376 CheckForMissingGlyphs();
378 /* Play main theme */
379 if (MusicDriver::GetInstance()->IsSongPlaying()) ResetMusic();
382 void MakeNewgameSettingsLive()
384 for (CompanyID c
= COMPANY_FIRST
; c
< MAX_COMPANIES
; c
++) {
385 if (_settings_game
.ai_config
[c
] != nullptr) {
386 delete _settings_game
.ai_config
[c
];
389 if (_settings_game
.game_config
!= nullptr) {
390 delete _settings_game
.game_config
;
393 /* Copy newgame settings to active settings.
394 * Also initialise old settings needed for savegame conversion. */
395 _settings_game
= _settings_newgame
;
396 _old_vds
= _settings_client
.company
.vehicle
;
398 for (CompanyID c
= COMPANY_FIRST
; c
< MAX_COMPANIES
; c
++) {
399 _settings_game
.ai_config
[c
] = nullptr;
400 if (_settings_newgame
.ai_config
[c
] != nullptr) {
401 _settings_game
.ai_config
[c
] = new AIConfig(_settings_newgame
.ai_config
[c
]);
404 _settings_game
.game_config
= nullptr;
405 if (_settings_newgame
.game_config
!= nullptr) {
406 _settings_game
.game_config
= new GameConfig(_settings_newgame
.game_config
);
410 void OpenBrowser(const char *url
)
412 /* Make sure we only accept urls that are sure to open a browser. */
413 if (strstr(url
, "http://") != url
&& strstr(url
, "https://") != url
) return;
415 extern void OSOpenBrowser(const char *url
);
419 /** Callback structure of statements to be executed after the NewGRF scan. */
420 struct AfterNewGRFScan
: NewGRFScanCallback
{
421 Year startyear
; ///< The start year.
422 uint generation_seed
; ///< Seed for the new game.
423 char *dedicated_host
; ///< Hostname for the dedicated server.
424 uint16 dedicated_port
; ///< Port for the dedicated server.
425 char *network_conn
; ///< Information about the server to connect to, or nullptr.
426 const char *join_server_password
; ///< The password to join the server with.
427 const char *join_company_password
; ///< The password to join the company with.
428 bool *save_config_ptr
; ///< The pointer to the save config setting.
429 bool save_config
; ///< The save config setting.
432 * Create a new callback.
433 * @param save_config_ptr Pointer to the save_config local variable which
434 * decides whether to save of exit or not.
436 AfterNewGRFScan(bool *save_config_ptr
) :
437 startyear(INVALID_YEAR
), generation_seed(GENERATE_NEW_SEED
),
438 dedicated_host(nullptr), dedicated_port(0), network_conn(nullptr),
439 join_server_password(nullptr), join_company_password(nullptr),
440 save_config_ptr(save_config_ptr
), save_config(true)
444 virtual void OnNewGRFsScanned()
446 ResetGRFConfig(false);
448 TarScanner::DoScan(TarScanner::SCENARIO
);
453 /* We want the new (correct) NewGRF count to survive the loading. */
454 uint last_newgrf_count
= _settings_client
.gui
.last_newgrf_count
;
456 _settings_client
.gui
.last_newgrf_count
= last_newgrf_count
;
457 /* Since the default for the palette might have changed due to
458 * reading the configuration file, recalculate that now. */
459 UpdateNewGRFConfigPalette();
461 Game::Uninitialize(true);
462 AI::Uninitialize(true);
465 LoadHotkeysFromConfig();
466 WindowDesc::LoadFromConfig();
468 /* We have loaded the config, so we may possibly save it. */
469 *save_config_ptr
= save_config
;
471 /* restore saved music volume */
472 MusicDriver::GetInstance()->SetVolume(_settings_client
.music
.music_vol
);
474 if (startyear
!= INVALID_YEAR
) _settings_newgame
.game_creation
.starting_year
= startyear
;
475 if (generation_seed
!= GENERATE_NEW_SEED
) _settings_newgame
.game_creation
.generation_seed
= generation_seed
;
477 #if defined(ENABLE_NETWORK)
478 if (dedicated_host
!= nullptr) {
479 _network_bind_list
.Clear();
480 *_network_bind_list
.Append() = stredup(dedicated_host
);
482 if (dedicated_port
!= 0) _settings_client
.network
.server_port
= dedicated_port
;
483 #endif /* ENABLE_NETWORK */
485 /* initialize the ingame console */
488 IConsoleCmdExec("exec scripts/autoexec.scr 0");
490 /* Make sure _settings is filled with _settings_newgame if we switch to a game directly */
491 if (_switch_mode
!= SM_NONE
) MakeNewgameSettingsLive();
493 #ifdef ENABLE_NETWORK
494 if (_network_available
&& network_conn
!= nullptr) {
495 const char *port
= nullptr;
496 const char *company
= nullptr;
497 uint16 rport
= NETWORK_DEFAULT_PORT
;
498 CompanyID join_as
= COMPANY_NEW_COMPANY
;
500 ParseConnectionString(&company
, &port
, network_conn
);
502 if (company
!= nullptr) {
503 join_as
= (CompanyID
)atoi(company
);
505 if (join_as
!= COMPANY_SPECTATOR
) {
507 if (join_as
>= MAX_COMPANIES
) {
513 if (port
!= nullptr) rport
= atoi(port
);
516 _switch_mode
= SM_NONE
;
517 NetworkClientConnectGame(NetworkAddress(network_conn
, rport
), join_as
, join_server_password
, join_company_password
);
519 #endif /* ENABLE_NETWORK */
521 /* After the scan we're not used anymore. */
526 #if defined(UNIX) && !defined(__MORPHOS__)
527 extern void DedicatedFork();
530 /** Options of OpenTTD. */
531 static const OptionData _options
[] = {
532 GETOPT_SHORT_VALUE('I'),
533 GETOPT_SHORT_VALUE('S'),
534 GETOPT_SHORT_VALUE('M'),
535 GETOPT_SHORT_VALUE('m'),
536 GETOPT_SHORT_VALUE('s'),
537 GETOPT_SHORT_VALUE('v'),
538 GETOPT_SHORT_VALUE('b'),
539 #if defined(ENABLE_NETWORK)
540 GETOPT_SHORT_OPTVAL('D'),
541 GETOPT_SHORT_OPTVAL('n'),
542 GETOPT_SHORT_VALUE('l'),
543 GETOPT_SHORT_VALUE('p'),
544 GETOPT_SHORT_VALUE('P'),
545 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
546 GETOPT_SHORT_NOVAL('f'),
548 #endif /* ENABLE_NETWORK */
549 GETOPT_SHORT_VALUE('r'),
550 GETOPT_SHORT_VALUE('t'),
551 GETOPT_SHORT_OPTVAL('d'),
552 GETOPT_SHORT_NOVAL('e'),
553 GETOPT_SHORT_OPTVAL('g'),
554 GETOPT_SHORT_VALUE('G'),
555 GETOPT_SHORT_VALUE('c'),
556 GETOPT_SHORT_NOVAL('x'),
557 GETOPT_SHORT_VALUE('q'),
558 GETOPT_SHORT_NOVAL('h'),
563 * Main entry point for this lovely game.
564 * @param argc The number of arguments passed to this game.
565 * @param argv The values of the arguments.
566 * @return 0 when there is no error.
568 int openttd_main(int argc
, char *argv
[])
570 char *musicdriver
= nullptr;
571 char *sounddriver
= nullptr;
572 char *videodriver
= nullptr;
573 char *blitter
= nullptr;
574 char *graphics_set
= nullptr;
575 char *sounds_set
= nullptr;
576 char *music_set
= nullptr;
577 Dimension resolution
= {0, 0};
578 /* AfterNewGRFScan sets save_config to true after scanning completed. */
579 bool save_config
= false;
580 AfterNewGRFScan
*scanner
= new AfterNewGRFScan(&save_config
);
581 #if defined(ENABLE_NETWORK)
582 bool dedicated
= false;
583 char *debuglog_conn
= nullptr;
585 extern bool _dedicated_forks
;
586 _dedicated_forks
= false;
587 #endif /* ENABLE_NETWORK */
589 _game_mode
= GM_MENU
;
590 _switch_mode
= SM_MENU
;
591 _config_file
= nullptr;
593 GetOptData
mgo(argc
- 1, argv
+ 1, _options
);
597 while ((i
= mgo
.GetOpt()) != -1) {
599 case 'I': free(graphics_set
); graphics_set
= stredup(mgo
.opt
); break;
600 case 'S': free(sounds_set
); sounds_set
= stredup(mgo
.opt
); break;
601 case 'M': free(music_set
); music_set
= stredup(mgo
.opt
); break;
602 case 'm': free(musicdriver
); musicdriver
= stredup(mgo
.opt
); break;
603 case 's': free(sounddriver
); sounddriver
= stredup(mgo
.opt
); break;
604 case 'v': free(videodriver
); videodriver
= stredup(mgo
.opt
); break;
605 case 'b': free(blitter
); blitter
= stredup(mgo
.opt
); break;
606 #if defined(ENABLE_NETWORK)
612 musicdriver
= stredup("null");
613 sounddriver
= stredup("null");
614 videodriver
= stredup("dedicated");
615 blitter
= stredup("null");
617 SetDebugString("net=6");
618 if (mgo
.opt
!= nullptr) {
619 /* Use the existing method for parsing (openttd -n).
620 * However, we do ignore the #company part. */
621 const char *temp
= nullptr;
622 const char *port
= nullptr;
623 ParseConnectionString(&temp
, &port
, mgo
.opt
);
624 if (!StrEmpty(mgo
.opt
)) scanner
->dedicated_host
= mgo
.opt
;
625 if (port
!= nullptr) scanner
->dedicated_port
= atoi(port
);
628 case 'f': _dedicated_forks
= true; break;
630 scanner
->network_conn
= mgo
.opt
; // optional IP parameter, nullptr if unset
633 debuglog_conn
= mgo
.opt
;
636 scanner
->join_server_password
= mgo
.opt
;
639 scanner
->join_company_password
= mgo
.opt
;
641 #endif /* ENABLE_NETWORK */
642 case 'r': ParseResolution(&resolution
, mgo
.opt
); break;
643 case 't': scanner
->startyear
= atoi(mgo
.opt
); break;
648 if (mgo
.opt
!= nullptr) SetDebugString(mgo
.opt
);
651 case 'e': _switch_mode
= (_switch_mode
== SM_LOAD_GAME
|| _switch_mode
== SM_LOAD_SCENARIO
? SM_LOAD_SCENARIO
: SM_EDITOR
); break;
653 if (mgo
.opt
!= nullptr) {
654 _file_to_saveload
.SetName(mgo
.opt
);
655 bool is_scenario
= _switch_mode
== SM_EDITOR
|| _switch_mode
== SM_LOAD_SCENARIO
;
656 _switch_mode
= is_scenario
? SM_LOAD_SCENARIO
: SM_LOAD_GAME
;
657 _file_to_saveload
.SetMode(SLO_LOAD
, is_scenario
? FT_SCENARIO
: FT_SAVEGAME
, DFT_GAME_FILE
);
659 /* if the file doesn't exist or it is not a valid savegame, let the saveload code show an error */
660 const char *t
= strrchr(_file_to_saveload
.name
, '.');
662 FiosType ft
= FiosGetSavegameListCallback(SLO_LOAD
, _file_to_saveload
.name
, t
, nullptr, nullptr);
663 if (ft
!= FIOS_TYPE_INVALID
) _file_to_saveload
.SetMode(ft
);
669 _switch_mode
= SM_NEWGAME
;
670 /* Give a random map if no seed has been given */
671 if (scanner
->generation_seed
== GENERATE_NEW_SEED
) {
672 scanner
->generation_seed
= InteractiveRandom();
676 DeterminePaths(argv
[0]);
677 if (StrEmpty(mgo
.opt
)) {
679 goto exit_noshutdown
;
684 FiosGetSavegameListCallback(SLO_LOAD
, mgo
.opt
, strrchr(mgo
.opt
, '.'), title
, lastof(title
));
686 _load_check_data
.Clear();
687 SaveOrLoadResult res
= SaveOrLoad(mgo
.opt
, SLO_CHECK
, DFT_GAME_FILE
, SAVE_DIR
, false);
688 if (res
!= SL_OK
|| _load_check_data
.HasErrors()) {
689 fprintf(stderr
, "Failed to open savegame\n");
690 if (_load_check_data
.HasErrors()) {
692 SetDParamStr(0, _load_check_data
.error_data
);
693 GetString(buf
, _load_check_data
.error
, lastof(buf
));
694 fprintf(stderr
, "%s\n", buf
);
696 goto exit_noshutdown
;
699 WriteSavegameInfo(title
);
701 goto exit_noshutdown
;
703 case 'G': scanner
->generation_seed
= atoi(mgo
.opt
); break;
704 case 'c': free(_config_file
); _config_file
= stredup(mgo
.opt
); break;
705 case 'x': scanner
->save_config
= false; break;
707 i
= -2; // Force printing of help.
713 if (i
== -2 || mgo
.numleft
> 0) {
714 /* Either the user typed '-h', he made an error, or he added unrecognized command line arguments.
715 * In all cases, print the help, and exit.
717 * The next two functions are needed to list the graphics sets. We can't do them earlier
718 * because then we cannot show it on the debug console as that hasn't been configured yet. */
719 DeterminePaths(argv
[0]);
720 TarScanner::DoScan(TarScanner::BASESET
);
721 BaseGraphics::FindSets();
722 BaseSounds::FindSets();
723 BaseMusic::FindSets();
726 goto exit_noshutdown
;
729 #if defined(WINCE) && defined(_DEBUG)
730 /* Switch on debug lvl 4 for WinCE if Debug release, as you can't give params, and you most likely do want this information */
734 DeterminePaths(argv
[0]);
735 TarScanner::DoScan(TarScanner::BASESET
);
737 #if defined(ENABLE_NETWORK)
738 if (dedicated
) DEBUG(net
, 0, "Starting dedicated version %s", _openttd_revision
);
739 if (_dedicated_forks
&& !dedicated
) _dedicated_forks
= false;
741 #if defined(UNIX) && !defined(__MORPHOS__)
742 /* We must fork here, or we'll end up without some resources we need (like sockets) */
743 if (_dedicated_forks
) DedicatedFork();
747 LoadFromConfig(true);
749 if (resolution
.width
!= 0) _cur_resolution
= resolution
;
752 * The width and height must be at least 1 pixel and width times
753 * height times bytes per pixel must still fit within a 32 bits
754 * integer, even for 32 bpp video modes. This way all internal
755 * drawing routines work correctly.
757 _cur_resolution
.width
= ClampU(_cur_resolution
.width
, 1, UINT16_MAX
/ 2);
758 _cur_resolution
.height
= ClampU(_cur_resolution
.height
, 1, UINT16_MAX
/ 2);
760 /* Assume the cursor starts within the game as not all video drivers
761 * get an event that the cursor is within the window when it is opened.
762 * Saying the cursor is there makes no visible difference as it would
763 * just be out of the bounds of the window. */
764 _cursor
.in_window
= true;
766 /* enumerate language files */
767 InitializeLanguagePacks();
769 /* Initialize the regular font for FreeType */
772 /* This must be done early, since functions use the SetWindowDirty* calls */
775 BaseGraphics::FindSets();
776 if (graphics_set
== nullptr && BaseGraphics::ini_set
!= nullptr) graphics_set
= stredup(BaseGraphics::ini_set
);
777 if (!BaseGraphics::SetSet(graphics_set
)) {
778 if (!StrEmpty(graphics_set
)) {
779 BaseGraphics::SetSet(nullptr);
781 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_BASE_GRAPHICS_NOT_FOUND
);
782 msg
.SetDParamStr(0, graphics_set
);
783 ScheduleErrorMessage(msg
);
788 /* Initialize game palette */
791 DEBUG(misc
, 1, "Loading blitter...");
792 if (blitter
== nullptr && _ini_blitter
!= nullptr) blitter
= stredup(_ini_blitter
);
793 _blitter_autodetected
= StrEmpty(blitter
);
794 /* Activate the initial blitter.
795 * This is only some initial guess, after NewGRFs have been loaded SwitchNewGRFBlitter may switch to a different one.
796 * - Never guess anything, if the user specified a blitter. (_blitter_autodetected)
797 * - Use 32bpp blitter if baseset or 8bpp-support settings says so.
798 * - Use 8bpp blitter otherwise.
800 if (!_blitter_autodetected
||
801 (_support8bpp
!= S8BPP_NONE
&& (BaseGraphics::GetUsedSet() == nullptr || BaseGraphics::GetUsedSet()->blitter
== BLT_8BPP
)) ||
802 BlitterFactory::SelectBlitter("32bpp-anim") == nullptr) {
803 if (BlitterFactory::SelectBlitter(blitter
) == nullptr) {
805 usererror("Failed to autoprobe blitter") :
806 usererror("Failed to select requested blitter '%s'; does it exist?", blitter
);
811 if (videodriver
== nullptr && _ini_videodriver
!= nullptr) videodriver
= stredup(_ini_videodriver
);
812 DriverFactoryBase::SelectDriver(videodriver
, Driver::DT_VIDEO
);
815 InitializeSpriteSorter();
817 /* Initialize the zoom level of the screen to normal */
818 _screen
.zoom
= ZOOM_LVL_NORMAL
;
820 NetworkStartUp(); // initialize network-core
822 #if defined(ENABLE_NETWORK)
823 if (debuglog_conn
!= nullptr && _network_available
) {
824 const char *not_used
= nullptr;
825 const char *port
= nullptr;
828 rport
= NETWORK_DEFAULT_DEBUGLOG_PORT
;
830 ParseConnectionString(¬_used
, &port
, debuglog_conn
);
831 if (port
!= nullptr) rport
= atoi(port
);
833 NetworkStartDebugLog(NetworkAddress(debuglog_conn
, rport
));
835 #endif /* ENABLE_NETWORK */
837 if (!HandleBootstrap()) {
843 VideoDriver::GetInstance()->ClaimMousePointer();
845 /* initialize screenshot formats */
846 InitializeScreenshotFormats();
848 BaseSounds::FindSets();
849 if (sounds_set
== nullptr && BaseSounds::ini_set
!= nullptr) sounds_set
= stredup(BaseSounds::ini_set
);
850 if (!BaseSounds::SetSet(sounds_set
)) {
851 if (StrEmpty(sounds_set
) || !BaseSounds::SetSet(nullptr)) {
852 usererror("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 4.1 of readme.txt.");
854 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_BASE_SOUNDS_NOT_FOUND
);
855 msg
.SetDParamStr(0, sounds_set
);
856 ScheduleErrorMessage(msg
);
861 BaseMusic::FindSets();
862 if (music_set
== nullptr && BaseMusic::ini_set
!= nullptr) music_set
= stredup(BaseMusic::ini_set
);
863 if (!BaseMusic::SetSet(music_set
)) {
864 if (StrEmpty(music_set
) || !BaseMusic::SetSet(nullptr)) {
865 usererror("Failed to find a music set. Please acquire a music set for OpenTTD. See section 4.1 of readme.txt.");
867 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_BASE_MUSIC_NOT_FOUND
);
868 msg
.SetDParamStr(0, music_set
);
869 ScheduleErrorMessage(msg
);
874 if (sounddriver
== nullptr && _ini_sounddriver
!= nullptr) sounddriver
= stredup(_ini_sounddriver
);
875 DriverFactoryBase::SelectDriver(sounddriver
, Driver::DT_SOUND
);
878 if (musicdriver
== nullptr && _ini_musicdriver
!= nullptr) musicdriver
= stredup(_ini_musicdriver
);
879 DriverFactoryBase::SelectDriver(musicdriver
, Driver::DT_MUSIC
);
882 /* Take our initial lock on whatever we might want to do! */
883 _modal_progress_paint_mutex
->BeginCritical();
884 _modal_progress_work_mutex
->BeginCritical();
886 GenerateWorld(GWM_EMPTY
, 64, 64); // Make the viewport initialization happy
887 WaitTillGeneratedWorld();
889 LoadIntroGame(false);
891 CheckForMissingGlyphs();
893 /* ScanNewGRFFiles now has control over the scanner. */
894 ScanNewGRFFiles(scanner
);
897 VideoDriver::GetInstance()->MainLoop();
901 /* only save config if we have to */
904 SaveHotkeysToConfig();
905 WindowDesc::SaveToConfig();
909 /* Reset windowing system, stop drivers, free used memory, ... */
914 /* These three are normally freed before bootstrap. */
920 /* These are normally freed before exit, but after bootstrap. */
927 free(BaseGraphics::ini_set
);
928 free(BaseSounds::ini_set
);
929 free(BaseMusic::ini_set
);
931 free(_ini_musicdriver
);
932 free(_ini_sounddriver
);
933 free(_ini_videodriver
);
938 #ifdef ENABLE_NETWORK
939 extern FILE *_log_fd
;
940 if (_log_fd
!= nullptr) {
943 #endif /* ENABLE_NETWORK */
948 void HandleExitGameRequest()
950 if (_game_mode
== GM_MENU
|| _game_mode
== GM_BOOTSTRAP
) { // do not ask to quit on the main screen
952 } else if (_settings_client
.gui
.autosave_on_exit
) {
960 static void MakeNewGameDone()
962 SettingsDisableElrail(_settings_game
.vehicle
.disable_elrails
);
964 extern void PostCheckNewGRFLoadWarnings();
965 PostCheckNewGRFLoadWarnings();
967 /* In a dedicated server, the server does not play */
968 if (!VideoDriver::GetInstance()->HasGUI()) {
969 SetLocalCompany(COMPANY_SPECTATOR
);
970 if (_settings_client
.gui
.pause_on_newgame
) DoCommandP(0, PM_PAUSED_NORMAL
, 1, CMD_PAUSE
);
971 IConsoleCmdExec("exec scripts/game_start.scr 0");
975 /* Create a single company */
976 DoStartupNewCompany(false);
978 Company
*c
= Company::Get(COMPANY_FIRST
);
979 c
->settings
= _settings_client
.company
;
981 IConsoleCmdExec("exec scripts/game_start.scr 0");
983 SetLocalCompany(COMPANY_FIRST
);
988 #ifdef ENABLE_NETWORK
989 /* We are the server, we start a new company (not dedicated),
990 * so set the default password *if* needed. */
991 if (_network_server
&& !StrEmpty(_settings_client
.network
.default_company_pass
)) {
992 NetworkChangeCompanyPassword(_local_company
, _settings_client
.network
.default_company_pass
);
994 #endif /* ENABLE_NETWORK */
996 if (_settings_client
.gui
.pause_on_newgame
) DoCommandP(0, PM_PAUSED_NORMAL
, 1, CMD_PAUSE
);
1000 MarkWholeScreenDirty();
1003 static void MakeNewGame(bool from_heightmap
, bool reset_settings
)
1005 _game_mode
= GM_NORMAL
;
1007 ResetGRFConfig(true);
1009 GenerateWorldSetCallback(&MakeNewGameDone
);
1010 GenerateWorld(from_heightmap
? GWM_HEIGHTMAP
: GWM_NEWGAME
, 1 << _settings_game
.game_creation
.map_x
, 1 << _settings_game
.game_creation
.map_y
, reset_settings
);
1013 static void MakeNewEditorWorldDone()
1015 SetLocalCompany(OWNER_NONE
);
1017 extern void PostCheckNewGRFLoadWarnings();
1018 PostCheckNewGRFLoadWarnings();
1021 static void MakeNewEditorWorld()
1023 _game_mode
= GM_EDITOR
;
1025 ResetGRFConfig(true);
1027 GenerateWorldSetCallback(&MakeNewEditorWorldDone
);
1028 GenerateWorld(GWM_EMPTY
, 1 << _settings_game
.game_creation
.map_x
, 1 << _settings_game
.game_creation
.map_y
);
1032 * Load the specified savegame but on error do different things.
1033 * If loading fails due to corrupt savegame, bad version, etc. go back to
1034 * a previous correct state. In the menu for example load the intro game again.
1035 * @param mode mode of loading, either SL_LOAD or SL_OLD_LOAD
1036 * @param newgm switch to this mode of loading fails due to some unknown error
1037 * @param filename file to be loaded
1038 * @param subdir default directory to look for filename, set to 0 if not needed
1039 * @param lf Load filter to use, if nullptr: use filename + subdir.
1041 bool SafeLoad(const char *filename
, SaveLoadOperation fop
, DetailedFileType dft
, GameMode newgm
, Subdirectory subdir
, struct LoadFilter
*lf
= nullptr)
1043 assert(fop
== SLO_LOAD
);
1044 assert(dft
== DFT_GAME_FILE
|| (lf
== nullptr && dft
== DFT_OLD_GAME_FILE
));
1045 GameMode ogm
= _game_mode
;
1049 switch (lf
== nullptr ? SaveOrLoad(filename
, fop
, dft
, subdir
) : LoadWithFilter(lf
)) {
1050 case SL_OK
: return true;
1053 #ifdef ENABLE_NETWORK
1054 if (_network_dedicated
) {
1056 * We need to reinit a network map...
1057 * We can't simply load the intro game here as that game has many
1058 * special cases which make clients desync immediately. So we fall
1059 * back to just generating a new game with the current settings.
1061 DEBUG(net
, 0, "Loading game failed, so a new (random) game will be started!");
1062 MakeNewGame(false, true);
1065 if (_network_server
) {
1066 /* We can't load the intro game as server, so disconnect first. */
1067 NetworkDisconnect();
1069 #endif /* ENABLE_NETWORK */
1073 case GM_MENU
: LoadIntroGame(); break;
1074 case GM_EDITOR
: MakeNewEditorWorld(); break;
1084 void SwitchToMode(SwitchMode new_mode
)
1086 #ifdef ENABLE_NETWORK
1087 /* If we are saving something, the network stays in his current state */
1088 if (new_mode
!= SM_SAVE_GAME
) {
1089 /* If the network is active, make it not-active */
1091 if (_network_server
&& (new_mode
== SM_LOAD_GAME
|| new_mode
== SM_NEWGAME
|| new_mode
== SM_RESTARTGAME
)) {
1094 NetworkDisconnect();
1098 /* If we are a server, we restart the server */
1099 if (_is_network_server
) {
1100 /* But not if we are going to the menu */
1101 if (new_mode
!= SM_MENU
) {
1102 /* check if we should reload the config */
1103 if (_settings_client
.network
.reload_cfg
) {
1105 MakeNewgameSettingsLive();
1106 ResetGRFConfig(false);
1108 NetworkServerStart();
1110 /* This client no longer wants to be a network-server */
1111 _is_network_server
= false;
1115 #endif /* ENABLE_NETWORK */
1116 /* Make sure all AI controllers are gone at quitting game */
1117 if (new_mode
!= SM_SAVE_GAME
) AI::KillAll();
1120 case SM_EDITOR
: // Switch to scenario editor
1121 MakeNewEditorWorld();
1124 case SM_RESTARTGAME
: // Restart --> 'Random game' with current settings
1125 case SM_NEWGAME
: // New Game --> 'Random game'
1126 #ifdef ENABLE_NETWORK
1127 if (_network_server
) {
1128 seprintf(_network_game_info
.map_name
, lastof(_network_game_info
.map_name
), "Random Map");
1130 #endif /* ENABLE_NETWORK */
1131 MakeNewGame(false, new_mode
== SM_NEWGAME
);
1134 case SM_LOAD_GAME
: { // Load game, Play Scenario
1135 ResetGRFConfig(true);
1136 ResetWindowSystem();
1138 if (!SafeLoad(_file_to_saveload
.name
, _file_to_saveload
.file_op
, _file_to_saveload
.detail_ftype
, GM_NORMAL
, NO_DIRECTORY
)) {
1139 SetDParamStr(0, GetSaveLoadErrorString());
1140 ShowErrorMessage(STR_JUST_RAW_STRING
, INVALID_STRING_ID
, WL_ERROR
);
1142 if (_file_to_saveload
.abstract_ftype
== FT_SCENARIO
) {
1143 /* Reset engine pool to simplify changing engine NewGRFs in scenario editor. */
1144 EngineOverrideManager::ResetToCurrentNewGRFConfig();
1146 /* Update the local company for a loaded game. It is either always
1147 * company #1 (eg 0) or in the case of a dedicated server a spectator */
1148 SetLocalCompany(_network_dedicated
? COMPANY_SPECTATOR
: COMPANY_FIRST
);
1150 if (_ctrl_pressed
&& !_network_dedicated
) {
1151 DoCommandP(0, PM_PAUSED_NORMAL
, 1, CMD_PAUSE
);
1154 /* Execute the game-start script */
1155 IConsoleCmdExec("exec scripts/game_start.scr 0");
1156 /* Decrease pause counter (was increased from opening load dialog) */
1157 DoCommandP(0, PM_PAUSED_SAVELOAD
, 0, CMD_PAUSE
);
1158 #ifdef ENABLE_NETWORK
1159 if (_network_server
) {
1160 seprintf(_network_game_info
.map_name
, lastof(_network_game_info
.map_name
), "%s (Loaded game)", _file_to_saveload
.title
);
1162 #endif /* ENABLE_NETWORK */
1167 case SM_START_HEIGHTMAP
: // Load a heightmap and start a new game from it
1168 #ifdef ENABLE_NETWORK
1169 if (_network_server
) {
1170 seprintf(_network_game_info
.map_name
, lastof(_network_game_info
.map_name
), "%s (Heightmap)", _file_to_saveload
.title
);
1172 #endif /* ENABLE_NETWORK */
1173 MakeNewGame(true, true);
1176 case SM_LOAD_HEIGHTMAP
: // Load heightmap from scenario editor
1177 SetLocalCompany(OWNER_NONE
);
1179 GenerateWorld(GWM_HEIGHTMAP
, 1 << _settings_game
.game_creation
.map_x
, 1 << _settings_game
.game_creation
.map_y
);
1180 MarkWholeScreenDirty();
1183 case SM_LOAD_SCENARIO
: { // Load scenario from scenario editor
1184 if (SafeLoad(_file_to_saveload
.name
, _file_to_saveload
.file_op
, _file_to_saveload
.detail_ftype
, GM_EDITOR
, NO_DIRECTORY
)) {
1185 SetLocalCompany(OWNER_NONE
);
1186 _settings_newgame
.game_creation
.starting_year
= _cur_year
;
1187 /* Cancel the saveload pausing */
1188 DoCommandP(0, PM_PAUSED_SAVELOAD
, 0, CMD_PAUSE
);
1190 SetDParamStr(0, GetSaveLoadErrorString());
1191 ShowErrorMessage(STR_JUST_RAW_STRING
, INVALID_STRING_ID
, WL_ERROR
);
1196 case SM_MENU
: // Switch to game intro menu
1198 if (BaseSounds::ini_set
== nullptr && BaseSounds::GetUsedSet()->fallback
) {
1199 ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET
, INVALID_STRING_ID
, WL_CRITICAL
);
1200 BaseSounds::ini_set
= stredup(BaseSounds::GetUsedSet()->name
);
1204 case SM_SAVE_GAME
: // Save game.
1205 /* Make network saved games on pause compatible to singleplayer */
1206 if (SaveOrLoad(_file_to_saveload
.name
, SLO_SAVE
, DFT_GAME_FILE
, NO_DIRECTORY
) != SL_OK
) {
1207 SetDParamStr(0, GetSaveLoadErrorString());
1208 ShowErrorMessage(STR_JUST_RAW_STRING
, INVALID_STRING_ID
, WL_ERROR
);
1210 DeleteWindowById(WC_SAVELOAD
, 0);
1214 case SM_SAVE_HEIGHTMAP
: // Save heightmap.
1215 MakeHeightmapScreenshot(_file_to_saveload
.name
);
1216 DeleteWindowById(WC_SAVELOAD
, 0);
1219 case SM_GENRANDLAND
: // Generate random land within scenario editor
1220 SetLocalCompany(OWNER_NONE
);
1221 GenerateWorld(GWM_RANDOM
, 1 << _settings_game
.game_creation
.map_x
, 1 << _settings_game
.game_creation
.map_y
);
1223 MarkWholeScreenDirty();
1226 default: NOT_REACHED();
1229 SmallMapWindow::RebuildColourIndexIfNecessary();
1234 * Check the validity of some of the caches.
1235 * Especially in the sense of desyncs between
1236 * the cached value and what the value would
1237 * be when calculated from the 'base' data.
1239 void CheckCaches(bool force_check
)
1242 /* Return here so it is easy to add checks that are run
1243 * always to aid testing of caches. */
1244 if (_debug_desync_level
< 1) return;
1247 /* Check the town caches. */
1248 SmallVector
<TownCache
, 4> old_town_caches
;
1251 MemCpyT(old_town_caches
.Append(), &t
->cache
);
1254 extern void RebuildTownCaches();
1255 RebuildTownCaches();
1256 RebuildSubsidisedSourceAndDestinationCache();
1260 if (MemCmpT(old_town_caches
.Get(i
), &t
->cache
) != 0) {
1261 DEBUG(desync
, 2, "town cache mismatch: town %i", (int)t
->index
);
1266 /* Check company infrastructure cache. */
1267 SmallVector
<CompanyInfrastructure
, 4> old_infrastructure
;
1269 FOR_ALL_COMPANIES(c
) MemCpyT(old_infrastructure
.Append(), &c
->infrastructure
);
1271 extern void AfterLoadCompanyStats();
1272 AfterLoadCompanyStats();
1275 FOR_ALL_COMPANIES(c
) {
1276 if (MemCmpT(old_infrastructure
.Get(i
), &c
->infrastructure
) != 0) {
1277 DEBUG(desync
, 2, "infrastructure cache mismatch: company %i", (int)c
->index
);
1279 old_infrastructure
.Get(i
)->Dump(buffer
, lastof(buffer
));
1280 DEBUG(desync
, 0, "Previous:\n%s", buffer
);
1281 c
->infrastructure
.Dump(buffer
, lastof(buffer
));
1282 DEBUG(desync
, 0, "Recalculated:\n%s", buffer
);
1287 /* Strict checking of the road stop cache entries */
1289 FOR_ALL_ROADSTOPS(rs
) {
1290 if (IsStandardRoadStopTile(rs
->xy
)) continue;
1292 assert(rs
->GetEntry(DIAGDIR_NE
) != rs
->GetEntry(DIAGDIR_NW
));
1293 rs
->GetEntry(DIAGDIR_NE
)->CheckIntegrity(rs
);
1294 rs
->GetEntry(DIAGDIR_NW
)->CheckIntegrity(rs
);
1298 FOR_ALL_VEHICLES(v
) {
1299 extern void FillNewGRFVehicleCache(const Vehicle
*v
);
1300 if (v
!= v
->First() || v
->vehstatus
& VS_CRASHED
|| !v
->IsPrimaryVehicle()) continue;
1303 for (const Vehicle
*u
= v
; u
!= nullptr; u
= u
->Next()) length
++;
1305 NewGRFCache
*grf_cache
= CallocT
<NewGRFCache
>(length
);
1306 VehicleCache
*veh_cache
= CallocT
<VehicleCache
>(length
);
1307 GroundVehicleCache
*gro_cache
= CallocT
<GroundVehicleCache
>(length
);
1308 TrainCache
*tra_cache
= CallocT
<TrainCache
>(length
);
1311 for (const Vehicle
*u
= v
; u
!= nullptr; u
= u
->Next()) {
1312 FillNewGRFVehicleCache(u
);
1313 grf_cache
[length
] = u
->grf_cache
;
1314 veh_cache
[length
] = u
->vcache
;
1317 gro_cache
[length
] = Train::From(u
)->gcache
;
1318 tra_cache
[length
] = Train::From(u
)->tcache
;
1321 gro_cache
[length
] = RoadVehicle::From(u
)->gcache
;
1330 case VEH_TRAIN
: Train::From(v
)->ConsistChanged(CCF_TRACK
); break;
1331 case VEH_ROAD
: RoadVehUpdateCache(RoadVehicle::From(v
)); break;
1332 case VEH_AIRCRAFT
: UpdateAircraftCache(Aircraft::From(v
)); break;
1333 case VEH_SHIP
: Ship::From(v
)->UpdateCache(); break;
1338 for (const Vehicle
*u
= v
; u
!= nullptr; u
= u
->Next()) {
1339 FillNewGRFVehicleCache(u
);
1340 if (memcmp(&grf_cache
[length
], &u
->grf_cache
, sizeof(NewGRFCache
)) != 0) {
1341 DEBUG(desync
, 2, "newgrf cache mismatch: type %i, vehicle %i, company %i, unit number %i, wagon %i", (int)v
->type
, v
->index
, (int)v
->owner
, v
->unitnumber
, length
);
1343 if (memcmp(&veh_cache
[length
], &u
->vcache
, sizeof(VehicleCache
)) != 0) {
1344 DEBUG(desync
, 2, "vehicle cache mismatch: type %i, vehicle %i, company %i, unit number %i, wagon %i", (int)v
->type
, v
->index
, (int)v
->owner
, v
->unitnumber
, length
);
1348 if (memcmp(&gro_cache
[length
], &Train::From(u
)->gcache
, sizeof(GroundVehicleCache
)) != 0) {
1349 DEBUG(desync
, 2, "train ground vehicle cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v
->index
, (int)v
->owner
, v
->unitnumber
, length
);
1351 if (memcmp(&tra_cache
[length
], &Train::From(u
)->tcache
, sizeof(TrainCache
)) != 0) {
1352 DEBUG(desync
, 2, "train cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v
->index
, (int)v
->owner
, v
->unitnumber
, length
);
1356 if (memcmp(&gro_cache
[length
], &RoadVehicle::From(u
)->gcache
, sizeof(GroundVehicleCache
)) != 0) {
1357 DEBUG(desync
, 2, "road vehicle ground vehicle cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v
->index
, (int)v
->owner
, v
->unitnumber
, length
);
1372 /* Check whether the caches are still valid */
1373 FOR_ALL_VEHICLES(v
) {
1374 byte buff
[sizeof(VehicleCargoList
)];
1375 memcpy(buff
, &v
->cargo
, sizeof(VehicleCargoList
));
1376 v
->cargo
.InvalidateCache();
1377 assert(memcmp(&v
->cargo
, buff
, sizeof(VehicleCargoList
)) == 0);
1381 FOR_ALL_STATIONS(st
) {
1382 for (CargoID c
= 0; c
< NUM_CARGO
; c
++) {
1383 byte buff
[sizeof(StationCargoList
)];
1384 memcpy(buff
, &st
->goods
[c
].cargo
, sizeof(StationCargoList
));
1385 st
->goods
[c
].cargo
.InvalidateCache();
1386 assert(memcmp(&st
->goods
[c
].cargo
, buff
, sizeof(StationCargoList
)) == 0);
1392 * Network-safe forced desync check.
1393 * @param tile unused
1394 * @param flags operation to perform
1397 * @param text unused
1398 * @return the cost of this operation or an error
1400 CommandCost
CmdDesyncCheck(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1402 if (flags
& DC_EXEC
) {
1406 return CommandCost();
1410 * State controlling game loop.
1411 * The state must not be changed from anywhere but here.
1412 * That check is enforced in DoCommand.
1414 void StateGameLoop()
1416 if (!_networking
|| _network_server
) {
1417 extern void StateGameLoop_LinkGraphPauseControl();
1418 StateGameLoop_LinkGraphPauseControl();
1421 /* don't execute the state loop during pause */
1422 if (_pause_mode
!= PM_UNPAUSED
) {
1423 UpdateLandscapingLimits();
1424 #ifndef DEBUG_DUMP_COMMANDS
1427 CallWindowTickEvent();
1430 if (HasModalProgress()) return;
1432 Layouter::ReduceLineCache();
1434 if (_game_mode
== GM_EDITOR
) {
1435 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP
);
1438 CallLandscapeTick();
1439 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP
);
1440 UpdateLandscapingLimits();
1442 CallWindowTickEvent();
1445 if (_debug_desync_level
> 2 && _date_fract
== 0 && (_date
& 0x1F) == 0) {
1446 /* Save the desync savegame if needed. */
1447 char name
[MAX_PATH
];
1448 seprintf(name
, lastof(name
), "dmp_cmds_%08x_%08x.sav", _settings_game
.game_creation
.generation_seed
, _date
);
1449 SaveOrLoad(name
, SLO_SAVE
, DFT_GAME_FILE
, AUTOSAVE_DIR
, false);
1454 /* All these actions has to be done from OWNER_NONE
1455 * for multiplayer compatibility */
1456 Backup
<CompanyByte
> cur_company(_current_company
, OWNER_NONE
, FILE_LINE
);
1458 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP
);
1459 AnimateAnimatedTiles();
1463 CallLandscapeTick();
1464 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP
);
1466 #ifndef DEBUG_DUMP_COMMANDS
1470 UpdateLandscapingLimits();
1472 CallWindowTickEvent();
1474 cur_company
.Restore();
1477 assert(IsLocalCompany());
1481 * Create an autosave. The default name is "autosave#.sav". However with
1482 * the setting 'keep_all_autosave' the name defaults to company-name + date
1484 static void DoAutosave()
1489 /* Autosaving in networking is too time expensive for the PSP */
1490 if (_networking
) return;
1493 if (_settings_client
.gui
.keep_all_autosave
) {
1494 GenerateDefaultSaveName(buf
, lastof(buf
));
1495 strecat(buf
, ".sav", lastof(buf
));
1497 static int _autosave_ctr
= 0;
1499 /* generate a savegame name and number according to _settings_client.gui.max_num_autosaves */
1500 seprintf(buf
, lastof(buf
), "autosave%d.sav", _autosave_ctr
);
1502 if (++_autosave_ctr
>= _settings_client
.gui
.max_num_autosaves
) _autosave_ctr
= 0;
1505 DEBUG(sl
, 2, "Autosaving to '%s'", buf
);
1506 if (SaveOrLoad(buf
, SLO_SAVE
, DFT_GAME_FILE
, AUTOSAVE_DIR
) != SL_OK
) {
1507 ShowErrorMessage(STR_ERROR_AUTOSAVE_FAILED
, INVALID_STRING_ID
, WL_ERROR
);
1513 if (_game_mode
== GM_BOOTSTRAP
) {
1514 #ifdef ENABLE_NETWORK
1515 /* Check for UDP stuff */
1516 if (_network_available
) NetworkBackgroundLoop();
1522 ProcessAsyncSaveFinish();
1524 /* autosave game? */
1527 _do_autosave
= false;
1528 SetWindowDirty(WC_STATUS_BAR
, 0);
1531 /* switch game mode? */
1532 if (_switch_mode
!= SM_NONE
&& !HasModalProgress()) {
1533 SwitchToMode(_switch_mode
);
1534 _switch_mode
= SM_NONE
;
1537 IncreaseSpriteLRU();
1538 InteractiveRandom();
1540 extern int _caret_timer
;
1544 #ifdef ENABLE_NETWORK
1545 /* Check for UDP stuff */
1546 if (_network_available
) NetworkBackgroundLoop();
1548 if (_networking
&& !HasModalProgress()) {
1552 if (_network_reconnect
> 0 && --_network_reconnect
== 0) {
1553 /* This means that we want to reconnect to the last host
1554 * We do this here, because it means that the network is really closed */
1555 NetworkClientConnectGame(NetworkAddress(_settings_client
.network
.last_host
, _settings_client
.network
.last_port
), COMPANY_SPECTATOR
);
1561 /* Check chat messages roughly once a second. */
1562 static uint check_message
= 0;
1563 if (++check_message
> 1000 / MILLISECONDS_PER_TICK
) {
1565 NetworkChatMessageLoop();
1569 #endif /* ENABLE_NETWORK */
1571 if (!_pause_mode
&& HasBit(_display_opt
, DO_FULL_ANIMATION
)) DoPaletteAnimations();
1573 if (!_pause_mode
|| _game_mode
== GM_EDITOR
|| _settings_game
.construction
.command_pause_level
> CMDPL_NO_CONSTRUCTION
) MoveAllTextEffects();
1577 SoundDriver::GetInstance()->MainLoop();